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