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