xref: /netbsd-src/sys/net/if_tap.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*	$NetBSD: if_tap.c,v 1.82 2015/08/20 14:40:19 christos Exp $	*/
2 
3 /*
4  *  Copyright (c) 2003, 2004, 2008, 2009 The NetBSD Foundation.
5  *  All rights reserved.
6  *
7  *  Redistribution and use in source and binary forms, with or without
8  *  modification, are permitted provided that the following conditions
9  *  are met:
10  *  1. Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  *  2. Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17  *  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  *  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  *  PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20  *  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  *  POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * tap(4) is a virtual Ethernet interface.  It appears as a real Ethernet
31  * device to the system, but can also be accessed by userland through a
32  * character device interface, which allows reading and injecting frames.
33  */
34 
35 #include <sys/cdefs.h>
36 __KERNEL_RCSID(0, "$NetBSD: if_tap.c,v 1.82 2015/08/20 14:40:19 christos Exp $");
37 
38 #if defined(_KERNEL_OPT)
39 
40 #include "opt_modular.h"
41 #include "opt_compat_netbsd.h"
42 #endif
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/conf.h>
49 #include <sys/cprng.h>
50 #include <sys/device.h>
51 #include <sys/file.h>
52 #include <sys/filedesc.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/intr.h>
63 #include <sys/stat.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 #if defined(COMPAT_40) || defined(MODULAR)
77 /*
78  * sysctl node management
79  *
80  * It's not really possible to use a SYSCTL_SETUP block with
81  * current module implementation, so it is easier to just define
82  * our own function.
83  *
84  * The handler function is a "helper" in Andrew Brown's sysctl
85  * framework terminology.  It is used as a gateway for sysctl
86  * requests over the nodes.
87  *
88  * tap_log allows the module to log creations of nodes and
89  * destroy them all at once using sysctl_teardown.
90  */
91 static int tap_node;
92 static int	tap_sysctl_handler(SYSCTLFN_PROTO);
93 SYSCTL_SETUP_PROTO(sysctl_tap_setup);
94 #endif
95 
96 /*
97  * Since we're an Ethernet device, we need the 2 following
98  * components: a struct ethercom and a struct ifmedia
99  * since we don't attach a PHY to ourselves.
100  * We could emulate one, but there's no real 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 	kmutex_t	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 static int	tap_match(device_t, cfdata_t, void *);
125 static void	tap_attach(device_t, device_t, void *);
126 static int	tap_detach(device_t, int);
127 
128 CFATTACH_DECL_NEW(tap, sizeof(struct tap_softc),
129     tap_match, tap_attach, tap_detach, NULL);
130 extern struct cfdriver tap_cd;
131 
132 /* Real device access routines */
133 static int	tap_dev_close(struct tap_softc *);
134 static int	tap_dev_read(int, struct uio *, int);
135 static int	tap_dev_write(int, struct uio *, int);
136 static int	tap_dev_ioctl(int, u_long, void *, struct lwp *);
137 static int	tap_dev_poll(int, int, struct lwp *);
138 static int	tap_dev_kqfilter(int, struct knote *);
139 
140 /* Fileops access routines */
141 static int	tap_fops_close(file_t *);
142 static int	tap_fops_read(file_t *, off_t *, struct uio *,
143     kauth_cred_t, int);
144 static int	tap_fops_write(file_t *, off_t *, struct uio *,
145     kauth_cred_t, int);
146 static int	tap_fops_ioctl(file_t *, u_long, void *);
147 static int	tap_fops_poll(file_t *, int);
148 static int	tap_fops_stat(file_t *, struct stat *);
149 static int	tap_fops_kqfilter(file_t *, struct knote *);
150 
151 static const struct fileops tap_fileops = {
152 	.fo_read = tap_fops_read,
153 	.fo_write = tap_fops_write,
154 	.fo_ioctl = tap_fops_ioctl,
155 	.fo_fcntl = fnullop_fcntl,
156 	.fo_poll = tap_fops_poll,
157 	.fo_stat = tap_fops_stat,
158 	.fo_close = tap_fops_close,
159 	.fo_kqfilter = tap_fops_kqfilter,
160 	.fo_restart = fnullop_restart,
161 };
162 
163 /* Helper for cloning open() */
164 static int	tap_dev_cloner(struct lwp *);
165 
166 /* Character device routines */
167 static int	tap_cdev_open(dev_t, int, int, struct lwp *);
168 static int	tap_cdev_close(dev_t, int, int, struct lwp *);
169 static int	tap_cdev_read(dev_t, struct uio *, int);
170 static int	tap_cdev_write(dev_t, struct uio *, int);
171 static int	tap_cdev_ioctl(dev_t, u_long, void *, int, struct lwp *);
172 static int	tap_cdev_poll(dev_t, int, struct lwp *);
173 static int	tap_cdev_kqfilter(dev_t, struct knote *);
174 
175 const struct cdevsw tap_cdevsw = {
176 	.d_open = tap_cdev_open,
177 	.d_close = tap_cdev_close,
178 	.d_read = tap_cdev_read,
179 	.d_write = tap_cdev_write,
180 	.d_ioctl = tap_cdev_ioctl,
181 	.d_stop = nostop,
182 	.d_tty = notty,
183 	.d_poll = tap_cdev_poll,
184 	.d_mmap = nommap,
185 	.d_kqfilter = tap_cdev_kqfilter,
186 	.d_discard = nodiscard,
187 	.d_flag = D_OTHER
188 };
189 
190 #define TAP_CLONER	0xfffff		/* Maximal minor value */
191 
192 /* kqueue-related routines */
193 static void	tap_kqdetach(struct knote *);
194 static int	tap_kqread(struct knote *, long);
195 
196 /*
197  * Those are needed by the if_media interface.
198  */
199 
200 static int	tap_mediachange(struct ifnet *);
201 static void	tap_mediastatus(struct ifnet *, struct ifmediareq *);
202 
203 /*
204  * Those are needed by the ifnet interface, and would typically be
205  * there for any network interface driver.
206  * Some other routines are optional: watchdog and drain.
207  */
208 
209 static void	tap_start(struct ifnet *);
210 static void	tap_stop(struct ifnet *, int);
211 static int	tap_init(struct ifnet *);
212 static int	tap_ioctl(struct ifnet *, u_long, void *);
213 
214 /* Internal functions */
215 #if defined(COMPAT_40) || defined(MODULAR)
216 static int	tap_lifaddr(struct ifnet *, u_long, struct ifaliasreq *);
217 #endif
218 static void	tap_softintr(void *);
219 
220 /*
221  * tap is a clonable interface, although it is highly unrealistic for
222  * an Ethernet device.
223  *
224  * Here are the bits needed for a clonable interface.
225  */
226 static int	tap_clone_create(struct if_clone *, int);
227 static int	tap_clone_destroy(struct ifnet *);
228 
229 struct if_clone tap_cloners = IF_CLONE_INITIALIZER("tap",
230 					tap_clone_create,
231 					tap_clone_destroy);
232 
233 /* Helper functionis shared by the two cloning code paths */
234 static struct tap_softc *	tap_clone_creator(int);
235 int	tap_clone_destroyer(device_t);
236 
237 void
238 tapattach(int n)
239 {
240 	int error;
241 
242 	error = config_cfattach_attach(tap_cd.cd_name, &tap_ca);
243 	if (error) {
244 		aprint_error("%s: unable to register cfattach\n",
245 		    tap_cd.cd_name);
246 		(void)config_cfdriver_detach(&tap_cd);
247 		return;
248 	}
249 
250 	if_clone_attach(&tap_cloners);
251 }
252 
253 /* Pretty much useless for a pseudo-device */
254 static int
255 tap_match(device_t parent, cfdata_t cfdata, void *arg)
256 {
257 
258 	return (1);
259 }
260 
261 void
262 tap_attach(device_t parent, device_t self, void *aux)
263 {
264 	struct tap_softc *sc = device_private(self);
265 	struct ifnet *ifp;
266 #if defined(COMPAT_40) || defined(MODULAR)
267 	const struct sysctlnode *node;
268 	int error;
269 #endif
270 	uint8_t enaddr[ETHER_ADDR_LEN] =
271 	    { 0xf2, 0x0b, 0xa4, 0xff, 0xff, 0xff };
272 	char enaddrstr[3 * ETHER_ADDR_LEN];
273 
274 	sc->sc_dev = self;
275 	sc->sc_sih = NULL;
276 	getnanotime(&sc->sc_btime);
277 	sc->sc_atime = sc->sc_mtime = sc->sc_btime;
278 	sc->sc_flags = 0;
279 	selinit(&sc->sc_rsel);
280 
281 	/*
282 	 * Initialize the two locks for the device.
283 	 *
284 	 * We need a lock here because even though the tap device can be
285 	 * opened only once, the file descriptor might be passed to another
286 	 * process, say a fork(2)ed child.
287 	 *
288 	 * The Giant saves us from most of the hassle, but since the read
289 	 * operation can sleep, we don't want two processes to wake up at
290 	 * the same moment and both try and dequeue a single packet.
291 	 *
292 	 * The queue for event listeners (used by kqueue(9), see below) has
293 	 * to be protected too, so use a spin lock.
294 	 */
295 	mutex_init(&sc->sc_rdlock, MUTEX_DEFAULT, IPL_NONE);
296 	mutex_init(&sc->sc_kqlock, MUTEX_DEFAULT, IPL_VM);
297 
298 	if (!pmf_device_register(self, NULL, NULL))
299 		aprint_error_dev(self, "couldn't establish power handler\n");
300 
301 	/*
302 	 * In order to obtain unique initial Ethernet address on a host,
303 	 * do some randomisation.  It's not meant for anything but avoiding
304 	 * hard-coding an address.
305 	 */
306 	cprng_fast(&enaddr[3], 3);
307 
308 	aprint_verbose_dev(self, "Ethernet address %s\n",
309 	    ether_snprintf(enaddrstr, sizeof(enaddrstr), enaddr));
310 
311 	/*
312 	 * Why 1000baseT? Why not? You can add more.
313 	 *
314 	 * Note that there are 3 steps: init, one or several additions to
315 	 * list of supported media, and in the end, the selection of one
316 	 * of them.
317 	 */
318 	ifmedia_init(&sc->sc_im, 0, tap_mediachange, tap_mediastatus);
319 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_1000_T, 0, NULL);
320 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_1000_T|IFM_FDX, 0, NULL);
321 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_100_TX, 0, NULL);
322 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_100_TX|IFM_FDX, 0, NULL);
323 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_10_T, 0, NULL);
324 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_10_T|IFM_FDX, 0, NULL);
325 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_AUTO, 0, NULL);
326 	ifmedia_set(&sc->sc_im, IFM_ETHER|IFM_AUTO);
327 
328 	/*
329 	 * One should note that an interface must do multicast in order
330 	 * to support IPv6.
331 	 */
332 	ifp = &sc->sc_ec.ec_if;
333 	strcpy(ifp->if_xname, device_xname(self));
334 	ifp->if_softc	= sc;
335 	ifp->if_flags	= IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
336 	ifp->if_ioctl	= tap_ioctl;
337 	ifp->if_start	= tap_start;
338 	ifp->if_stop	= tap_stop;
339 	ifp->if_init	= tap_init;
340 	IFQ_SET_READY(&ifp->if_snd);
341 
342 	sc->sc_ec.ec_capabilities = ETHERCAP_VLAN_MTU | ETHERCAP_JUMBO_MTU;
343 
344 	/* Those steps are mandatory for an Ethernet driver. */
345 	if_initialize(ifp);
346 	ether_ifattach(ifp, enaddr);
347 	if_register(ifp);
348 
349 #if defined(COMPAT_40) || defined(MODULAR)
350 	/*
351 	 * Add a sysctl node for that interface.
352 	 *
353 	 * The pointer transmitted is not a string, but instead a pointer to
354 	 * the softc structure, which we can use to build the string value on
355 	 * the fly in the helper function of the node.  See the comments for
356 	 * tap_sysctl_handler for details.
357 	 *
358 	 * Usually sysctl_createv is called with CTL_CREATE as the before-last
359 	 * component.  However, we can allocate a number ourselves, as we are
360 	 * the only consumer of the net.link.<iface> node.  In this case, the
361 	 * unit number is conveniently used to number the node.  CTL_CREATE
362 	 * would just work, too.
363 	 */
364 	if ((error = sysctl_createv(NULL, 0, NULL,
365 	    &node, CTLFLAG_READWRITE,
366 	    CTLTYPE_STRING, device_xname(self), NULL,
367 	    tap_sysctl_handler, 0, (void *)sc, 18,
368 	    CTL_NET, AF_LINK, tap_node, device_unit(sc->sc_dev),
369 	    CTL_EOL)) != 0)
370 		aprint_error_dev(self, "sysctl_createv returned %d, ignoring\n",
371 		    error);
372 #endif
373 }
374 
375 /*
376  * When detaching, we do the inverse of what is done in the attach
377  * routine, in reversed order.
378  */
379 static int
380 tap_detach(device_t self, int flags)
381 {
382 	struct tap_softc *sc = device_private(self);
383 	struct ifnet *ifp = &sc->sc_ec.ec_if;
384 #if defined(COMPAT_40) || defined(MODULAR)
385 	int error;
386 #endif
387 	int s;
388 
389 	sc->sc_flags |= TAP_GOING;
390 	s = splnet();
391 	tap_stop(ifp, 1);
392 	if_down(ifp);
393 	splx(s);
394 
395 	if (sc->sc_sih != NULL) {
396 		softint_disestablish(sc->sc_sih);
397 		sc->sc_sih = NULL;
398 	}
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 	mutex_destroy(&sc->sc_kqlock);
417 
418 	pmf_device_deregister(self);
419 
420 	return (0);
421 }
422 
423 /*
424  * This function is called by the ifmedia layer to notify the driver
425  * that the user requested a media change.  A real driver would
426  * reconfigure the hardware.
427  */
428 static int
429 tap_mediachange(struct ifnet *ifp)
430 {
431 	return (0);
432 }
433 
434 /*
435  * Here the user asks for the currently used media.
436  */
437 static void
438 tap_mediastatus(struct ifnet *ifp, struct ifmediareq *imr)
439 {
440 	struct tap_softc *sc = (struct tap_softc *)ifp->if_softc;
441 	imr->ifm_active = sc->sc_im.ifm_cur->ifm_media;
442 }
443 
444 /*
445  * This is the function where we SEND packets.
446  *
447  * There is no 'receive' equivalent.  A typical driver will get
448  * interrupts from the hardware, and from there will inject new packets
449  * into the network stack.
450  *
451  * Once handled, a packet must be freed.  A real driver might not be able
452  * to fit all the pending packets into the hardware, and is allowed to
453  * return before having sent all the packets.  It should then use the
454  * if_flags flag IFF_OACTIVE to notify the upper layer.
455  *
456  * There are also other flags one should check, such as IFF_PAUSE.
457  *
458  * It is our duty to make packets available to BPF listeners.
459  *
460  * You should be aware that this function is called by the Ethernet layer
461  * at splnet().
462  *
463  * When the device is opened, we have to pass the packet(s) to the
464  * userland.  For that we stay in OACTIVE mode while the userland gets
465  * the packets, and we send a signal to the processes waiting to read.
466  *
467  * wakeup(sc) is the counterpart to the tsleep call in
468  * tap_dev_read, while selnotify() is used for kevent(2) and
469  * poll(2) (which includes select(2)) listeners.
470  */
471 static void
472 tap_start(struct ifnet *ifp)
473 {
474 	struct tap_softc *sc = (struct tap_softc *)ifp->if_softc;
475 	struct mbuf *m0;
476 
477 	if ((sc->sc_flags & TAP_INUSE) == 0) {
478 		/* Simply drop packets */
479 		for(;;) {
480 			IFQ_DEQUEUE(&ifp->if_snd, m0);
481 			if (m0 == NULL)
482 				return;
483 
484 			ifp->if_opackets++;
485 			bpf_mtap(ifp, 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_devunit 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 = fp->f_devunit;
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 			bpf_mtap(ifp, m);
855 			m_freem(m);
856 		}
857 	}
858 	splx(s);
859 
860 	if (sc->sc_sih != NULL) {
861 		softint_disestablish(sc->sc_sih);
862 		sc->sc_sih = NULL;
863 	}
864 	sc->sc_flags &= ~(TAP_INUSE | TAP_ASYNCIO);
865 
866 	return (0);
867 }
868 
869 static int
870 tap_cdev_read(dev_t dev, struct uio *uio, int flags)
871 {
872 	return tap_dev_read(minor(dev), uio, flags);
873 }
874 
875 static int
876 tap_fops_read(file_t *fp, off_t *offp, struct uio *uio,
877     kauth_cred_t cred, int flags)
878 {
879 	int error;
880 
881 	KERNEL_LOCK(1, NULL);
882 	error = tap_dev_read(fp->f_devunit, uio, flags);
883 	KERNEL_UNLOCK_ONE(NULL);
884 	return error;
885 }
886 
887 static int
888 tap_dev_read(int unit, struct uio *uio, int flags)
889 {
890 	struct tap_softc *sc = device_lookup_private(&tap_cd, unit);
891 	struct ifnet *ifp;
892 	struct mbuf *m, *n;
893 	int error = 0, s;
894 
895 	if (sc == NULL)
896 		return (ENXIO);
897 
898 	getnanotime(&sc->sc_atime);
899 
900 	ifp = &sc->sc_ec.ec_if;
901 	if ((ifp->if_flags & IFF_UP) == 0)
902 		return (EHOSTDOWN);
903 
904 	/*
905 	 * In the TAP_NBIO case, we have to make sure we won't be sleeping
906 	 */
907 	if ((sc->sc_flags & TAP_NBIO) != 0) {
908 		if (!mutex_tryenter(&sc->sc_rdlock))
909 			return (EWOULDBLOCK);
910 	} else {
911 		mutex_enter(&sc->sc_rdlock);
912 	}
913 
914 	s = splnet();
915 	if (IFQ_IS_EMPTY(&ifp->if_snd)) {
916 		ifp->if_flags &= ~IFF_OACTIVE;
917 		/*
918 		 * We must release the lock before sleeping, and re-acquire it
919 		 * after.
920 		 */
921 		mutex_exit(&sc->sc_rdlock);
922 		if (sc->sc_flags & TAP_NBIO)
923 			error = EWOULDBLOCK;
924 		else
925 			error = tsleep(sc, PSOCK|PCATCH, "tap", 0);
926 		splx(s);
927 
928 		if (error != 0)
929 			return (error);
930 		/* The device might have been downed */
931 		if ((ifp->if_flags & IFF_UP) == 0)
932 			return (EHOSTDOWN);
933 		if ((sc->sc_flags & TAP_NBIO)) {
934 			if (!mutex_tryenter(&sc->sc_rdlock))
935 				return (EWOULDBLOCK);
936 		} else {
937 			mutex_enter(&sc->sc_rdlock);
938 		}
939 		s = splnet();
940 	}
941 
942 	IFQ_DEQUEUE(&ifp->if_snd, m);
943 	ifp->if_flags &= ~IFF_OACTIVE;
944 	splx(s);
945 	if (m == NULL) {
946 		error = 0;
947 		goto out;
948 	}
949 
950 	ifp->if_opackets++;
951 	bpf_mtap(ifp, m);
952 
953 	/*
954 	 * One read is one packet.
955 	 */
956 	do {
957 		error = uiomove(mtod(m, void *),
958 		    min(m->m_len, uio->uio_resid), uio);
959 		MFREE(m, n);
960 		m = n;
961 	} while (m != NULL && uio->uio_resid > 0 && error == 0);
962 
963 	if (m != NULL)
964 		m_freem(m);
965 
966 out:
967 	mutex_exit(&sc->sc_rdlock);
968 	return (error);
969 }
970 
971 static int
972 tap_fops_stat(file_t *fp, struct stat *st)
973 {
974 	int error = 0;
975 	struct tap_softc *sc;
976 	int unit = fp->f_devunit;
977 
978 	(void)memset(st, 0, sizeof(*st));
979 
980 	KERNEL_LOCK(1, NULL);
981 	sc = device_lookup_private(&tap_cd, unit);
982 	if (sc == NULL) {
983 		error = ENXIO;
984 		goto out;
985 	}
986 
987 	st->st_dev = makedev(cdevsw_lookup_major(&tap_cdevsw), unit);
988 	st->st_atimespec = sc->sc_atime;
989 	st->st_mtimespec = sc->sc_mtime;
990 	st->st_ctimespec = st->st_birthtimespec = sc->sc_btime;
991 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
992 	st->st_gid = kauth_cred_getegid(fp->f_cred);
993 out:
994 	KERNEL_UNLOCK_ONE(NULL);
995 	return error;
996 }
997 
998 static int
999 tap_cdev_write(dev_t dev, struct uio *uio, int flags)
1000 {
1001 	return tap_dev_write(minor(dev), uio, flags);
1002 }
1003 
1004 static int
1005 tap_fops_write(file_t *fp, off_t *offp, struct uio *uio,
1006     kauth_cred_t cred, int flags)
1007 {
1008 	int error;
1009 
1010 	KERNEL_LOCK(1, NULL);
1011 	error = tap_dev_write(fp->f_devunit, uio, flags);
1012 	KERNEL_UNLOCK_ONE(NULL);
1013 	return error;
1014 }
1015 
1016 static int
1017 tap_dev_write(int unit, struct uio *uio, int flags)
1018 {
1019 	struct tap_softc *sc =
1020 	    device_lookup_private(&tap_cd, unit);
1021 	struct ifnet *ifp;
1022 	struct mbuf *m, **mp;
1023 	int error = 0;
1024 	int s;
1025 
1026 	if (sc == NULL)
1027 		return (ENXIO);
1028 
1029 	getnanotime(&sc->sc_mtime);
1030 	ifp = &sc->sc_ec.ec_if;
1031 
1032 	/* One write, one packet, that's the rule */
1033 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1034 	if (m == NULL) {
1035 		ifp->if_ierrors++;
1036 		return (ENOBUFS);
1037 	}
1038 	m->m_pkthdr.len = uio->uio_resid;
1039 
1040 	mp = &m;
1041 	while (error == 0 && uio->uio_resid > 0) {
1042 		if (*mp != m) {
1043 			MGET(*mp, M_DONTWAIT, MT_DATA);
1044 			if (*mp == NULL) {
1045 				error = ENOBUFS;
1046 				break;
1047 			}
1048 		}
1049 		(*mp)->m_len = min(MHLEN, uio->uio_resid);
1050 		error = uiomove(mtod(*mp, void *), (*mp)->m_len, uio);
1051 		mp = &(*mp)->m_next;
1052 	}
1053 	if (error) {
1054 		ifp->if_ierrors++;
1055 		m_freem(m);
1056 		return (error);
1057 	}
1058 
1059 	ifp->if_ipackets++;
1060 	m->m_pkthdr.rcvif = ifp;
1061 
1062 	bpf_mtap(ifp, 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(fp->f_devunit, 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 = device_lookup_private(&tap_cd, unit);
1087 
1088 	if (sc == NULL)
1089 		return ENXIO;
1090 
1091 	switch (cmd) {
1092 	case FIONREAD:
1093 		{
1094 			struct ifnet *ifp = &sc->sc_ec.ec_if;
1095 			struct mbuf *m;
1096 			int s;
1097 
1098 			s = splnet();
1099 			IFQ_POLL(&ifp->if_snd, m);
1100 
1101 			if (m == NULL)
1102 				*(int *)data = 0;
1103 			else
1104 				*(int *)data = m->m_pkthdr.len;
1105 			splx(s);
1106 			return 0;
1107 		}
1108 	case TIOCSPGRP:
1109 	case FIOSETOWN:
1110 		return fsetown(&sc->sc_pgid, cmd, data);
1111 	case TIOCGPGRP:
1112 	case FIOGETOWN:
1113 		return fgetown(sc->sc_pgid, cmd, data);
1114 	case FIOASYNC:
1115 		if (*(int *)data) {
1116 			if (sc->sc_sih == NULL) {
1117 				sc->sc_sih = softint_establish(SOFTINT_CLOCK,
1118 				    tap_softintr, sc);
1119 				if (sc->sc_sih == NULL)
1120 					return EBUSY; /* XXX */
1121 			}
1122 			sc->sc_flags |= TAP_ASYNCIO;
1123 		} else {
1124 			sc->sc_flags &= ~TAP_ASYNCIO;
1125 			if (sc->sc_sih != NULL) {
1126 				softint_disestablish(sc->sc_sih);
1127 				sc->sc_sih = NULL;
1128 			}
1129 		}
1130 		return 0;
1131 	case FIONBIO:
1132 		if (*(int *)data)
1133 			sc->sc_flags |= TAP_NBIO;
1134 		else
1135 			sc->sc_flags &= ~TAP_NBIO;
1136 		return 0;
1137 #ifdef OTAPGIFNAME
1138 	case OTAPGIFNAME:
1139 #endif
1140 	case TAPGIFNAME:
1141 		{
1142 			struct ifreq *ifr = (struct ifreq *)data;
1143 			struct ifnet *ifp = &sc->sc_ec.ec_if;
1144 
1145 			strlcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
1146 			return 0;
1147 		}
1148 	default:
1149 		return ENOTTY;
1150 	}
1151 }
1152 
1153 static int
1154 tap_cdev_poll(dev_t dev, int events, struct lwp *l)
1155 {
1156 	return tap_dev_poll(minor(dev), events, l);
1157 }
1158 
1159 static int
1160 tap_fops_poll(file_t *fp, int events)
1161 {
1162 	return tap_dev_poll(fp->f_devunit, events, curlwp);
1163 }
1164 
1165 static int
1166 tap_dev_poll(int unit, int events, struct lwp *l)
1167 {
1168 	struct tap_softc *sc =
1169 	    device_lookup_private(&tap_cd, unit);
1170 	int revents = 0;
1171 
1172 	if (sc == NULL)
1173 		return POLLERR;
1174 
1175 	if (events & (POLLIN|POLLRDNORM)) {
1176 		struct ifnet *ifp = &sc->sc_ec.ec_if;
1177 		struct mbuf *m;
1178 		int s;
1179 
1180 		s = splnet();
1181 		IFQ_POLL(&ifp->if_snd, m);
1182 
1183 		if (m != NULL)
1184 			revents |= events & (POLLIN|POLLRDNORM);
1185 		else {
1186 			mutex_spin_enter(&sc->sc_kqlock);
1187 			selrecord(l, &sc->sc_rsel);
1188 			mutex_spin_exit(&sc->sc_kqlock);
1189 		}
1190 		splx(s);
1191 	}
1192 	revents |= events & (POLLOUT|POLLWRNORM);
1193 
1194 	return (revents);
1195 }
1196 
1197 static struct filterops tap_read_filterops = { 1, NULL, tap_kqdetach,
1198 	tap_kqread };
1199 static struct filterops tap_seltrue_filterops = { 1, NULL, tap_kqdetach,
1200 	filt_seltrue };
1201 
1202 static int
1203 tap_cdev_kqfilter(dev_t dev, struct knote *kn)
1204 {
1205 	return tap_dev_kqfilter(minor(dev), kn);
1206 }
1207 
1208 static int
1209 tap_fops_kqfilter(file_t *fp, struct knote *kn)
1210 {
1211 	return tap_dev_kqfilter(fp->f_devunit, kn);
1212 }
1213 
1214 static int
1215 tap_dev_kqfilter(int unit, struct knote *kn)
1216 {
1217 	struct tap_softc *sc =
1218 	    device_lookup_private(&tap_cd, unit);
1219 
1220 	if (sc == NULL)
1221 		return (ENXIO);
1222 
1223 	KERNEL_LOCK(1, NULL);
1224 	switch(kn->kn_filter) {
1225 	case EVFILT_READ:
1226 		kn->kn_fop = &tap_read_filterops;
1227 		break;
1228 	case EVFILT_WRITE:
1229 		kn->kn_fop = &tap_seltrue_filterops;
1230 		break;
1231 	default:
1232 		KERNEL_UNLOCK_ONE(NULL);
1233 		return (EINVAL);
1234 	}
1235 
1236 	kn->kn_hook = sc;
1237 	mutex_spin_enter(&sc->sc_kqlock);
1238 	SLIST_INSERT_HEAD(&sc->sc_rsel.sel_klist, kn, kn_selnext);
1239 	mutex_spin_exit(&sc->sc_kqlock);
1240 	KERNEL_UNLOCK_ONE(NULL);
1241 	return (0);
1242 }
1243 
1244 static void
1245 tap_kqdetach(struct knote *kn)
1246 {
1247 	struct tap_softc *sc = (struct tap_softc *)kn->kn_hook;
1248 
1249 	KERNEL_LOCK(1, NULL);
1250 	mutex_spin_enter(&sc->sc_kqlock);
1251 	SLIST_REMOVE(&sc->sc_rsel.sel_klist, kn, knote, kn_selnext);
1252 	mutex_spin_exit(&sc->sc_kqlock);
1253 	KERNEL_UNLOCK_ONE(NULL);
1254 }
1255 
1256 static int
1257 tap_kqread(struct knote *kn, long hint)
1258 {
1259 	struct tap_softc *sc = (struct tap_softc *)kn->kn_hook;
1260 	struct ifnet *ifp = &sc->sc_ec.ec_if;
1261 	struct mbuf *m;
1262 	int s, rv;
1263 
1264 	KERNEL_LOCK(1, NULL);
1265 	s = splnet();
1266 	IFQ_POLL(&ifp->if_snd, m);
1267 
1268 	if (m == NULL)
1269 		kn->kn_data = 0;
1270 	else
1271 		kn->kn_data = m->m_pkthdr.len;
1272 	splx(s);
1273 	rv = (kn->kn_data != 0 ? 1 : 0);
1274 	KERNEL_UNLOCK_ONE(NULL);
1275 	return rv;
1276 }
1277 
1278 #if defined(COMPAT_40) || defined(MODULAR)
1279 /*
1280  * sysctl management routines
1281  * You can set the address of an interface through:
1282  * net.link.tap.tap<number>
1283  *
1284  * Note the consistent use of tap_log in order to use
1285  * sysctl_teardown at unload time.
1286  *
1287  * In the kernel you will find a lot of SYSCTL_SETUP blocks.  Those
1288  * blocks register a function in a special section of the kernel
1289  * (called a link set) which is used at init_sysctl() time to cycle
1290  * through all those functions to create the kernel's sysctl tree.
1291  *
1292  * It is not possible to use link sets in a module, so the
1293  * easiest is to simply call our own setup routine at load time.
1294  *
1295  * In the SYSCTL_SETUP blocks you find in the kernel, nodes have the
1296  * CTLFLAG_PERMANENT flag, meaning they cannot be removed.  Once the
1297  * whole kernel sysctl tree is built, it is not possible to add any
1298  * permanent node.
1299  *
1300  * It should be noted that we're not saving the sysctlnode pointer
1301  * we are returned when creating the "tap" node.  That structure
1302  * cannot be trusted once out of the calling function, as it might
1303  * get reused.  So we just save the MIB number, and always give the
1304  * full path starting from the root for later calls to sysctl_createv
1305  * and sysctl_destroyv.
1306  */
1307 SYSCTL_SETUP(sysctl_tap_setup, "sysctl net.link.tap subtree setup")
1308 {
1309 	const struct sysctlnode *node;
1310 	int error = 0;
1311 
1312 	if ((error = sysctl_createv(clog, 0, NULL, NULL,
1313 	    CTLFLAG_PERMANENT,
1314 	    CTLTYPE_NODE, "link", NULL,
1315 	    NULL, 0, NULL, 0,
1316 	    CTL_NET, AF_LINK, CTL_EOL)) != 0)
1317 		return;
1318 
1319 	/*
1320 	 * The first four parameters of sysctl_createv are for management.
1321 	 *
1322 	 * The four that follows, here starting with a '0' for the flags,
1323 	 * describe the node.
1324 	 *
1325 	 * The next series of four set its value, through various possible
1326 	 * means.
1327 	 *
1328 	 * Last but not least, the path to the node is described.  That path
1329 	 * is relative to the given root (third argument).  Here we're
1330 	 * starting from the root.
1331 	 */
1332 	if ((error = sysctl_createv(clog, 0, NULL, &node,
1333 	    CTLFLAG_PERMANENT,
1334 	    CTLTYPE_NODE, "tap", NULL,
1335 	    NULL, 0, NULL, 0,
1336 	    CTL_NET, AF_LINK, CTL_CREATE, CTL_EOL)) != 0)
1337 		return;
1338 	tap_node = node->sysctl_num;
1339 }
1340 
1341 /*
1342  * The helper functions make Andrew Brown's interface really
1343  * shine.  It makes possible to create value on the fly whether
1344  * the sysctl value is read or written.
1345  *
1346  * As shown as an example in the man page, the first step is to
1347  * create a copy of the node to have sysctl_lookup work on it.
1348  *
1349  * Here, we have more work to do than just a copy, since we have
1350  * to create the string.  The first step is to collect the actual
1351  * value of the node, which is a convenient pointer to the softc
1352  * of the interface.  From there we create the string and use it
1353  * as the value, but only for the *copy* of the node.
1354  *
1355  * Then we let sysctl_lookup do the magic, which consists in
1356  * setting oldp and newp as required by the operation.  When the
1357  * value is read, that means that the string will be copied to
1358  * the user, and when it is written, the new value will be copied
1359  * over in the addr array.
1360  *
1361  * If newp is NULL, the user was reading the value, so we don't
1362  * have anything else to do.  If a new value was written, we
1363  * have to check it.
1364  *
1365  * If it is incorrect, we can return an error and leave 'node' as
1366  * it is:  since it is a copy of the actual node, the change will
1367  * be forgotten.
1368  *
1369  * Upon a correct input, we commit the change to the ifnet
1370  * structure of our interface.
1371  */
1372 static int
1373 tap_sysctl_handler(SYSCTLFN_ARGS)
1374 {
1375 	struct sysctlnode node;
1376 	struct tap_softc *sc;
1377 	struct ifnet *ifp;
1378 	int error;
1379 	size_t len;
1380 	char addr[3 * ETHER_ADDR_LEN];
1381 	uint8_t enaddr[ETHER_ADDR_LEN];
1382 
1383 	node = *rnode;
1384 	sc = node.sysctl_data;
1385 	ifp = &sc->sc_ec.ec_if;
1386 	(void)ether_snprintf(addr, sizeof(addr), CLLADDR(ifp->if_sadl));
1387 	node.sysctl_data = addr;
1388 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1389 	if (error || newp == NULL)
1390 		return (error);
1391 
1392 	len = strlen(addr);
1393 	if (len < 11 || len > 17)
1394 		return (EINVAL);
1395 
1396 	/* Commit change */
1397 	if (ether_aton_r(enaddr, sizeof(enaddr), addr) != 0)
1398 		return (EINVAL);
1399 	if_set_sadl(ifp, enaddr, ETHER_ADDR_LEN, false);
1400 	return (error);
1401 }
1402 #endif
1403