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