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