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