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