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