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