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