9a6ffb7b771a9cf0de34685c4ebde21adaf1fec8
[dragonfly.git] / sys / net / tap / if_tap.c
1 /*
2  * Copyright (C) 1999-2000 by Maksim Yevmenkin <m_evmenkin@yahoo.com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * BASED ON:
27  * -------------------------------------------------------------------------
28  *
29  * Copyright (c) 1988, Julian Onions <jpo@cs.nott.ac.uk>
30  * Nottingham University 1987.
31  */
32
33 /*
34  * $FreeBSD: src/sys/net/if_tap.c,v 1.3.2.3 2002/04/14 21:41:48 luigi Exp $
35  * $Id: if_tap.c,v 0.21 2000/07/23 21:46:02 max Exp $
36  */
37
38 #include "opt_inet.h"
39 #include "use_tap.h"
40
41 #include <sys/param.h>
42 #include <sys/conf.h>
43 #include <sys/device.h>
44 #include <sys/filedesc.h>
45 #include <sys/filio.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/proc.h>
50 #include <sys/priv.h>
51 #include <sys/signalvar.h>
52 #include <sys/socket.h>
53 #include <sys/sockio.h>
54 #include <sys/sysctl.h>
55 #include <sys/systm.h>
56 #include <sys/ttycom.h>
57 #include <sys/uio.h>
58 #include <sys/vnode.h>
59 #include <sys/serialize.h>
60 #include <sys/thread2.h>
61 #include <sys/mplock2.h>
62 #include <sys/devfs.h>
63 #include <sys/queue.h>
64
65 #include <net/bpf.h>
66 #include <net/ethernet.h>
67 #include <net/if.h>
68 #include <net/if_var.h>  /* for IF_LLADDR */
69 #include <net/if_dl.h>  /* for LLADDR used by IF_LLADDR */
70 #include <net/if_types.h>  /* for IFT_ETHER */
71 #include <net/if_arp.h>
72 #include <net/if_clone.h>
73 #include <net/if_media.h>
74 #include <net/ifq_var.h>
75 #include <net/route.h>
76
77 #include <netinet/in.h>
78
79 #include "if_tapvar.h"
80 #include "if_tap.h"
81
82 #define TAP_IFFLAGS     (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST)
83
84 #if NTAP <= 1
85 #define TAP_PREALLOCATED_UNITS  4
86 #else
87 #define TAP_PREALLOCATED_UNITS  NTAP
88 #endif
89
90 #define TAP             "tap"
91 #define TAPDEBUG        if (tapdebug) if_printf
92
93 /* module */
94 static int              tapmodevent(module_t, int, void *);
95
96 /* device */
97 static struct tap_softc *tapcreate(cdev_t, int);
98 static void             tapdestroy(struct tap_softc *);
99
100 /* clone */
101 static int              tap_clone_create(struct if_clone *, int, caddr_t);
102 static int              tap_clone_destroy(struct ifnet *);
103
104 /* network interface */
105 static void             tapifinit(void *);
106 static void             tapifstart(struct ifnet *, struct ifaltq_subque *);
107 static int              tapifioctl(struct ifnet *, u_long, caddr_t,
108                                    struct ucred *);
109 static void             tapifstop(struct tap_softc *, int);
110 static void             tapifflags(struct tap_softc *);
111
112 /* character device */
113 static d_open_t         tapopen;
114 static d_clone_t        tapclone;
115 static d_close_t        tapclose;
116 static d_read_t         tapread;
117 static d_write_t        tapwrite;
118 static d_ioctl_t        tapioctl;
119 static d_kqfilter_t     tapkqfilter;
120
121 static struct dev_ops   tap_ops = {
122         { TAP, 0, 0 },
123         .d_open =       tapopen,
124         .d_close =      tapclose,
125         .d_read =       tapread,
126         .d_write =      tapwrite,
127         .d_ioctl =      tapioctl,
128         .d_kqfilter =   tapkqfilter
129 };
130
131 /* kqueue support */
132 static void             tap_filter_detach(struct knote *);
133 static int              tap_filter_read(struct knote *, long);
134 static int              tap_filter_write(struct knote *, long);
135
136 static struct filterops tapread_filtops = {
137         FILTEROP_ISFD,
138         NULL,
139         tap_filter_detach,
140         tap_filter_read
141 };
142 static struct filterops tapwrite_filtops = {
143         FILTEROP_ISFD,
144         NULL,
145         tap_filter_detach,
146         tap_filter_write
147 };
148
149 static int              tapdebug = 0;           /* debug flag */
150 static int              taprefcnt = 0;          /* module ref. counter */
151 static int              tapuopen = 0;           /* allow user open() */
152 static int              tapuponopen = 0;        /* IFF_UP when opened */
153
154 static MALLOC_DEFINE(M_TAP, TAP, "Ethernet tunnel interface");
155
156 static DEVFS_DEFINE_CLONE_BITMAP(tap);
157
158 struct if_clone tap_cloner = IF_CLONE_INITIALIZER(
159         TAP, tap_clone_create, tap_clone_destroy, 0, IF_MAXUNIT);
160
161 static SLIST_HEAD(,tap_softc) tap_listhead =
162         SLIST_HEAD_INITIALIZER(&tap_listhead);
163
164 SYSCTL_INT(_debug, OID_AUTO, if_tap_debug, CTLFLAG_RW, &tapdebug, 0, "");
165 SYSCTL_DECL(_net_link);
166 SYSCTL_NODE(_net_link, OID_AUTO, tap, CTLFLAG_RW, 0,
167             "Ethernet tunnel software network interface");
168 SYSCTL_INT(_net_link_tap, OID_AUTO, user_open, CTLFLAG_RW, &tapuopen, 0,
169            "Allow user to open /dev/tap (based on node permissions)");
170 SYSCTL_INT(_net_link_tap, OID_AUTO, up_on_open, CTLFLAG_RW, &tapuponopen, 0,
171            "Bring interface up when /dev/tap is opened");
172 SYSCTL_INT(_net_link_tap, OID_AUTO, debug, CTLFLAG_RW, &tapdebug, 0, "");
173 SYSCTL_INT(_net_link_tap, OID_AUTO, refcnt, CTLFLAG_RD, &taprefcnt, 0,
174            "Number of opened devices");
175
176 DEV_MODULE(if_tap, tapmodevent, NULL);
177
178 /*
179  * tapmodevent
180  *
181  * module event handler
182  */
183 static int
184 tapmodevent(module_t mod, int type, void *data)
185 {
186         static cdev_t dev = NULL;
187         struct tap_softc *sc, *sc_tmp;
188         int i;
189
190         switch (type) {
191         case MOD_LOAD:
192                 dev = make_autoclone_dev(&tap_ops, &DEVFS_CLONE_BITMAP(tap),
193                                          tapclone, UID_ROOT, GID_WHEEL,
194                                          0600, TAP);
195                 SLIST_INIT(&tap_listhead);
196                 if_clone_attach(&tap_cloner);
197
198                 for (i = 0; i < TAP_PREALLOCATED_UNITS; ++i) {
199                         make_dev(&tap_ops, i, UID_ROOT, GID_WHEEL,
200                                  0600, "%s%d", TAP, i);
201                         devfs_clone_bitmap_set(&DEVFS_CLONE_BITMAP(tap), i);
202                 }
203                 break;
204
205         case MOD_UNLOAD:
206                 if (taprefcnt > 0)
207                         return (EBUSY);
208
209                 if_clone_detach(&tap_cloner);
210
211                 SLIST_FOREACH_MUTABLE(sc, &tap_listhead, tap_link, sc_tmp)
212                         tapdestroy(sc);
213
214                 dev_ops_remove_all(&tap_ops);
215                 destroy_autoclone_dev(dev, &DEVFS_CLONE_BITMAP(tap));
216                 break;
217
218         default:
219                 return (EOPNOTSUPP);
220         }
221
222         return (0);
223 }
224
225
226 /*
227  * tapcreate - create or clone an interface
228  */
229 static struct tap_softc *
230 tapcreate(cdev_t dev, int flags)
231 {
232         struct tap_softc *sc;
233         struct ifnet *ifp;
234         uint8_t ether_addr[ETHER_ADDR_LEN];
235         int unit = minor(dev);
236
237         sc = kmalloc(sizeof(*sc), M_TAP, M_WAITOK | M_ZERO);
238         dev->si_drv1 = sc;
239         sc->tap_dev = dev;
240         sc->tap_flags |= flags;
241
242         reference_dev(dev); /* device association */
243
244         /* generate fake MAC address: 00 bd xx xx xx unit_no */
245         ether_addr[0] = 0x00;
246         ether_addr[1] = 0xbd;
247         bcopy(&ticks, &ether_addr[2], 3);
248         ether_addr[5] = (u_char)unit;
249
250         /* fill the rest and attach interface */
251         ifp = sc->tap_ifp = if_alloc(IFT_ETHER);
252         if (ifp == NULL) {
253                 kprintf("%s: failed to if_alloc() interface for %s%d",
254                         __func__, TAP, unit);
255                 return (NULL);
256         }
257
258         if_initname(ifp, TAP, unit);
259         ifp->if_init = tapifinit;
260         ifp->if_start = tapifstart;
261         ifp->if_ioctl = tapifioctl;
262         ifp->if_mtu = ETHERMTU;
263         ifp->if_flags = TAP_IFFLAGS;
264         ifp->if_softc = sc;
265         ifq_set_maxlen(&ifp->if_snd, ifqmaxlen);
266         ifq_set_ready(&ifp->if_snd);
267
268         ether_ifattach(ifp, ether_addr, NULL);
269
270         sc->tap_flags |= TAP_INITED;
271         sc->tap_devq.ifq_maxlen = ifqmaxlen;
272
273         SLIST_INSERT_HEAD(&tap_listhead, sc, tap_link);
274
275         TAPDEBUG(ifp, "created, minor = %#x, flags = 0x%x\n",
276                  unit, sc->tap_flags);
277         return (sc);
278 }
279
280 static
281 struct tap_softc *
282 tapfind(int unit)
283 {
284         struct tap_softc *sc;
285
286         SLIST_FOREACH(sc, &tap_listhead, tap_link) {
287                 if (minor(sc->tap_dev) == unit)
288                         return (sc);
289         }
290         return (NULL);
291 }
292
293 /*
294  * tap_clone_create:
295  *
296  * Create a new tap instance via ifconfig.
297  */
298 static int
299 tap_clone_create(struct if_clone *ifc __unused, int unit,
300                  caddr_t param __unused)
301 {
302         struct tap_softc *sc;
303         cdev_t dev;
304
305         sc = tapfind(unit);
306         if (sc == NULL) {
307                 if (!devfs_clone_bitmap_chk(&DEVFS_CLONE_BITMAP(tap), unit)) {
308                         devfs_clone_bitmap_set(&DEVFS_CLONE_BITMAP(tap), unit);
309                         dev = make_dev(&tap_ops, unit, UID_ROOT, GID_WHEEL,
310                                        0600, "%s%d", TAP, unit);
311                 } else {
312                         dev = devfs_find_device_by_name("%s%d", TAP, unit);
313                 }
314
315                 if (dev == NULL)
316                         return (ENODEV);
317                 if ((sc = tapcreate(dev, TAP_MANUALMAKE)) == NULL)
318                         return (ENOMEM);
319         } else {
320                 dev = sc->tap_dev;
321         }
322
323         sc->tap_flags |= TAP_CLONE;
324         TAPDEBUG(sc->tap_ifp, "clone created, minor = %#x, flags = 0x%x\n",
325                  minor(dev), sc->tap_flags);
326
327         return (0);
328 }
329
330 /*
331  * tapopen
332  *
333  * to open tunnel. must be superuser
334  */
335 static int
336 tapopen(struct dev_open_args *ap)
337 {
338         cdev_t dev = NULL;
339         struct tap_softc *sc = NULL;
340         struct ifnet *ifp = NULL;
341         int error;
342
343         if (tapuopen == 0 &&
344             (error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0)) != 0)
345                 return (error);
346
347         get_mplock();
348         dev = ap->a_head.a_dev;
349         sc = dev->si_drv1;
350         if (sc == NULL && (sc = tapcreate(dev, TAP_MANUALMAKE)) == NULL) {
351                 rel_mplock();
352                 return (ENOMEM);
353         }
354         if (sc->tap_flags & TAP_OPEN) {
355                 rel_mplock();
356                 return (EBUSY);
357         }
358         ifp = sc->tap_ifp;
359
360         if ((sc->tap_flags & TAP_CLONE) == 0) {
361                 EVENTHANDLER_INVOKE(ifnet_attach_event, ifp);
362
363                 /* Announce the return of the interface. */
364                 rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
365         }
366
367         bcopy(IF_LLADDR(ifp), sc->ether_addr, sizeof(sc->ether_addr));
368
369         if (curthread->td_proc)
370                 fsetown(curthread->td_proc->p_pid, &sc->tap_sigtd);
371         sc->tap_flags |= TAP_OPEN;
372         taprefcnt++;
373
374         if (tapuponopen && (ifp->if_flags & IFF_UP) == 0) {
375                 crit_enter();
376                 if_up(ifp);
377                 crit_exit();
378
379                 ifnet_serialize_all(ifp);
380                 tapifflags(sc);
381                 ifnet_deserialize_all(ifp);
382
383                 sc->tap_flags |= TAP_CLOSEDOWN;
384         }
385
386         TAPDEBUG(ifp, "opened, minor = %#x. Module refcnt = %d\n",
387                  minor(dev), taprefcnt);
388
389         rel_mplock();
390         return (0);
391 }
392
393 static int
394 tapclone(struct dev_clone_args *ap)
395 {
396         int unit;
397
398         unit = devfs_clone_bitmap_get(&DEVFS_CLONE_BITMAP(tap), 0);
399         ap->a_dev = make_only_dev(&tap_ops, unit, UID_ROOT, GID_WHEEL,
400                                   0600, "%s%d", TAP, unit);
401         if (tapcreate(ap->a_dev, 0) == NULL)
402                 return (ENOMEM);
403         else
404                 return (0);
405 }
406
407 /*
408  * tapclose
409  *
410  * close the device - mark i/f down & delete routing info
411  */
412 static int
413 tapclose(struct dev_close_args *ap)
414 {
415         cdev_t dev = ap->a_head.a_dev;
416         struct tap_softc *sc = dev->si_drv1;
417         struct ifnet *ifp = sc->tap_ifp;
418         int unit = minor(dev);
419         int clear_flags = 0;
420
421         get_mplock();
422
423         /* Junk all pending output */
424         ifq_purge_all(&ifp->if_snd);
425
426         /*
427          * If the interface is not cloned, we always bring it down.
428          *
429          * If the interface is cloned, then we bring it down during
430          * closing only if it was brought up during opening.
431          */
432         if ((sc->tap_flags & TAP_CLONE) == 0 ||
433             (sc->tap_flags & TAP_CLOSEDOWN)) {
434                 if (ifp->if_flags & IFF_UP)
435                         if_down(ifp);
436                 clear_flags = 1;
437         }
438         ifnet_serialize_all(ifp);
439         tapifstop(sc, clear_flags);
440         ifnet_deserialize_all(ifp);
441
442         if ((sc->tap_flags & TAP_CLONE) == 0) {
443                 if_purgeaddrs_nolink(ifp);
444
445                 EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
446
447                 /* Announce the departure of the interface. */
448                 rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
449         }
450
451         funsetown(&sc->tap_sigio);
452         sc->tap_sigio = NULL;
453         KNOTE(&sc->tap_rkq.ki_note, 0);
454
455         sc->tap_flags &= ~TAP_OPEN;
456         funsetown(&sc->tap_sigtd);
457         sc->tap_sigtd = NULL;
458
459         taprefcnt--;
460         if (taprefcnt < 0) {
461                 taprefcnt = 0;
462                 if_printf(ifp, ". Module refcnt = %d is out of sync! "
463                           "Force refcnt to be 0.\n", taprefcnt);
464         }
465
466         TAPDEBUG(ifp, "closed, minor = %#x. Module refcnt = %d\n",
467                  unit, taprefcnt);
468
469         /* Only auto-destroy if the interface was not manually created. */
470         if ((sc->tap_flags & TAP_MANUALMAKE) == 0 &&
471             unit >= TAP_PREALLOCATED_UNITS) {
472                 tapdestroy(sc);
473                 dev->si_drv1 = NULL;
474         }
475
476         rel_mplock();
477         return (0);
478 }
479
480
481 /*
482  * tapdestroy:
483  *
484  *      Destroy a tap instance.
485  */
486 static void
487 tapdestroy(struct tap_softc *sc)
488 {
489         struct ifnet *ifp = sc->tap_ifp;
490         cdev_t dev = sc->tap_dev;
491         int unit = minor(dev);
492
493         TAPDEBUG(ifp, "destroyed, minor = %#x. Module refcnt = %d\n",
494                  unit, taprefcnt);
495
496         ifnet_serialize_all(ifp);
497         tapifstop(sc, 1);
498         ifnet_deserialize_all(ifp);
499
500         ether_ifdetach(ifp);
501         if_free(ifp);
502
503         sc->tap_dev = NULL;
504         dev->si_drv1 = NULL;
505         release_dev(dev); /* device disassociation */
506
507         /* Also destroy the cloned device */
508         if (unit >= TAP_PREALLOCATED_UNITS) {
509                 destroy_dev(dev);
510                 devfs_clone_bitmap_put(&DEVFS_CLONE_BITMAP(tap), unit);
511         }
512
513         SLIST_REMOVE(&tap_listhead, sc, tap_softc, tap_link);
514         kfree(sc, M_TAP);
515 }
516
517
518 /*
519  * tap_clone_destroy:
520  *
521  *      Destroy a tap instance.
522  */
523 static int
524 tap_clone_destroy(struct ifnet *ifp)
525 {
526         struct tap_softc *sc = ifp->if_softc;
527
528         if ((sc->tap_flags & TAP_CLONE) == 0)
529                 return (ENXIO);
530
531         TAPDEBUG(ifp, "clone destroyed, minor = %#x, flags = 0x%x\n",
532                  minor(sc->tap_dev), sc->tap_flags);
533         tapdestroy(sc);
534
535         return (0);
536 }
537
538
539 /*
540  * tapifinit
541  *
542  * Network interface initialization function (called with if serializer held)
543  *
544  * MPSAFE
545  */
546 static void
547 tapifinit(void *xtp)
548 {
549         struct tap_softc *sc = xtp;
550         struct ifnet *ifp = sc->tap_ifp;
551         struct ifaltq_subque *ifsq = ifq_get_subq_default(&ifp->if_snd);
552
553         TAPDEBUG(ifp, "initializing, minor = %#x, flags = 0x%x\n",
554                  minor(sc->tap_dev), sc->tap_flags);
555
556         ASSERT_IFNET_SERIALIZED_ALL(ifp);
557
558         tapifstop(sc, 1);
559
560         ifp->if_flags |= IFF_RUNNING;
561         ifsq_clr_oactive(ifsq);
562
563         /* attempt to start output */
564         tapifstart(ifp, ifsq);
565 }
566
567 static void
568 tapifflags(struct tap_softc *sc)
569 {
570         struct ifnet *ifp = sc->tap_ifp;
571
572         ASSERT_IFNET_SERIALIZED_ALL(ifp);
573
574         if (ifp->if_flags & IFF_UP) {
575                 if ((ifp->if_flags & IFF_RUNNING) == 0)
576                         tapifinit(sc);
577         } else {
578                 tapifstop(sc, 1);
579         }
580 }
581
582 /*
583  * tapifioctl
584  *
585  * Process an ioctl request on network interface (called with if serializer
586  * held).
587  *
588  * MPSAFE
589  */
590 static int
591 tapifioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
592 {
593         struct tap_softc *sc = ifp->if_softc;
594         struct ifstat *ifs = NULL;
595         struct ifmediareq *ifmr = NULL;
596         int error = 0;
597         int dummy;
598
599         switch (cmd) {
600         case SIOCADDMULTI:
601         case SIOCDELMULTI:
602                 break;
603
604         case SIOCSIFADDR:
605         case SIOCGIFADDR:
606         case SIOCSIFMTU:
607                 error = ether_ioctl(ifp, cmd, data);
608                 break;
609
610         case SIOCSIFFLAGS:
611                 tapifflags(sc);
612                 break;
613
614         case SIOCGIFMEDIA:
615                 /*
616                  * The bridge code needs this when running the
617                  * spanning tree protocol.
618                  */
619                 ifmr = (struct ifmediareq *)data;
620                 dummy = ifmr->ifm_count;
621                 ifmr->ifm_count = 1;
622                 ifmr->ifm_status = IFM_AVALID;
623                 ifmr->ifm_active = IFM_ETHER;
624                 if (sc->tap_flags & TAP_OPEN)
625                         ifmr->ifm_status |= IFM_ACTIVE;
626                 ifmr->ifm_current = ifmr->ifm_active;
627                 if (dummy >= 1) {
628                         int media = IFM_ETHER;
629                         error = copyout(&media, ifmr->ifm_ulist, sizeof(int));
630                 }
631                 break;
632
633         case SIOCGIFSTATUS:
634                 ifs = (struct ifstat *)data;
635                 dummy = strlen(ifs->ascii);
636                 if ((sc->tap_flags & TAP_OPEN) && dummy < sizeof(ifs->ascii)) {
637                         if (sc->tap_sigtd && sc->tap_sigtd->sio_proc) {
638                                 ksnprintf(ifs->ascii + dummy,
639                                     sizeof(ifs->ascii) - dummy,
640                                     "\tOpened by pid %d\n",
641                                     (int)sc->tap_sigtd->sio_proc->p_pid);
642                         } else {
643                                 ksnprintf(ifs->ascii + dummy,
644                                     sizeof(ifs->ascii) - dummy,
645                                     "\tOpened by <unknown>\n");
646                         }
647                 }
648                 break;
649
650         default:
651                 error = EINVAL;
652                 break;
653         }
654
655         return (error);
656 }
657
658 /*
659  * tapifstart
660  *
661  * Queue packets from higher level ready to put out (called with if serializer
662  * held)
663  *
664  * MPSAFE
665  */
666 static void
667 tapifstart(struct ifnet *ifp, struct ifaltq_subque *ifsq)
668 {
669         struct tap_softc *sc = ifp->if_softc;
670         struct ifqueue *ifq;
671         struct mbuf *m;
672         int has_data = 0;
673
674         ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq);
675         TAPDEBUG(ifp, "starting, minor = %#x\n", minor(sc->tap_dev));
676
677         if ((sc->tap_flags & TAP_READY) != TAP_READY) {
678                 TAPDEBUG(ifp, "not ready, minor = %#x, flags = 0x%x\n",
679                          minor(sc->tap_dev), sc->tap_flags);
680                 ifsq_purge(ifsq);
681                 return;
682         }
683
684         ifsq_set_oactive(ifsq);
685
686         ifq = &sc->tap_devq;
687         while ((m = ifsq_dequeue(ifsq)) != NULL) {
688                 if (IF_QFULL(ifq)) {
689                         IF_DROP(ifq);
690                         IFNET_STAT_INC(ifp, oerrors, 1);
691                         m_freem(m);
692                 } else {
693                         IF_ENQUEUE(ifq, m);
694                         IFNET_STAT_INC(ifp, opackets, 1);
695                         has_data = 1;
696                 }
697         }
698
699         if (has_data) {
700                 if (sc->tap_flags & TAP_RWAIT) {
701                         sc->tap_flags &= ~TAP_RWAIT;
702                         wakeup((caddr_t)sc);
703                 }
704
705                 KNOTE(&sc->tap_rkq.ki_note, 0);
706
707                 if ((sc->tap_flags & TAP_ASYNC) && (sc->tap_sigio != NULL)) {
708                         get_mplock();
709                         pgsigio(sc->tap_sigio, SIGIO, 0);
710                         rel_mplock();
711                 }
712         }
713
714         ifsq_clr_oactive(ifsq);
715 }
716
717 static void
718 tapifstop(struct tap_softc *sc, int clear_flags)
719 {
720         struct ifnet *ifp = sc->tap_ifp;
721
722         ASSERT_IFNET_SERIALIZED_ALL(ifp);
723         IF_DRAIN(&sc->tap_devq);
724         sc->tap_flags &= ~TAP_CLOSEDOWN;
725         if (clear_flags) {
726                 ifp->if_flags &= ~IFF_RUNNING;
727                 ifsq_clr_oactive(ifq_get_subq_default(&ifp->if_snd));
728         }
729 }
730
731 /*
732  * tapioctl
733  *
734  * The ops interface is now pretty minimal.  Called via fileops with nothing
735  * held.
736  *
737  * MPSAFE
738  */
739 static int
740 tapioctl(struct dev_ioctl_args *ap)
741 {
742         cdev_t dev = ap->a_head.a_dev;
743         caddr_t data = ap->a_data;
744         struct tap_softc *sc = dev->si_drv1;
745         struct ifnet *ifp = sc->tap_ifp;
746         struct ifreq *ifr;
747         struct tapinfo *tapp = NULL;
748         struct mbuf *mb;
749         int error;
750
751         ifnet_serialize_all(ifp);
752         error = 0;
753
754         switch (ap->a_cmd) {
755         case TAPSIFINFO:
756                 tapp = (struct tapinfo *)data;
757                 ifp->if_mtu = tapp->mtu;
758                 ifp->if_type = tapp->type;
759                 ifp->if_baudrate = tapp->baudrate;
760                 break;
761
762         case TAPGIFINFO:
763                 tapp = (struct tapinfo *)data;
764                 tapp->mtu = ifp->if_mtu;
765                 tapp->type = ifp->if_type;
766                 tapp->baudrate = ifp->if_baudrate;
767                 break;
768
769         case TAPGIFNAME:
770                 ifr = (struct ifreq *)data;
771                 strlcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
772                 break;
773
774         case TAPSDEBUG:
775                 tapdebug = *(int *)data;
776                 break;
777
778         case TAPGDEBUG:
779                 *(int *)data = tapdebug;
780                 break;
781
782         case FIOASYNC:
783                 if (*(int *)data)
784                         sc->tap_flags |= TAP_ASYNC;
785                 else
786                         sc->tap_flags &= ~TAP_ASYNC;
787                 break;
788
789         case FIONREAD:
790                 /* Take a look at devq first */
791                 IF_POLL(&sc->tap_devq, mb);
792                 if (mb != NULL) {
793                         *(int *)data = 0;
794                         for(; mb != NULL; mb = mb->m_next)
795                                 *(int *)data += mb->m_len;
796                 } else {
797                         *(int *)data = ifsq_poll_pktlen(
798                             ifq_get_subq_default(&ifp->if_snd));
799                 }
800                 break;
801
802         case FIOSETOWN:
803                 error = fsetown(*(int *)data, &sc->tap_sigio);
804                 break;
805
806         case FIOGETOWN:
807                 *(int *)data = fgetown(&sc->tap_sigio);
808                 break;
809
810         /* this is deprecated, FIOSETOWN should be used instead */
811         case TIOCSPGRP:
812                 error = fsetown(-(*(int *)data), &sc->tap_sigio);
813                 break;
814
815         /* this is deprecated, FIOGETOWN should be used instead */
816         case TIOCGPGRP:
817                 *(int *)data = -fgetown(&sc->tap_sigio);
818                 break;
819
820         default:
821                 error = ENOTTY;
822                 break;
823         }
824
825         ifnet_deserialize_all(ifp);
826         return (error);
827 }
828
829
830 /*
831  * tapread
832  *
833  * The ops read interface - reads a packet at a time, or at
834  * least as much of a packet as can be read.
835  *
836  * Called from the fileops interface with nothing held.
837  *
838  * MPSAFE
839  */
840 static int
841 tapread(struct dev_read_args *ap)
842 {
843         cdev_t dev = ap->a_head.a_dev;
844         struct uio *uio = ap->a_uio;
845         struct tap_softc *sc = dev->si_drv1;
846         struct ifnet *ifp = sc->tap_ifp;
847         struct mbuf *m0 = NULL;
848         int error = 0, len;
849
850         TAPDEBUG(ifp, "reading, minor = %#x\n", minor(dev));
851
852         if ((sc->tap_flags & TAP_READY) != TAP_READY) {
853                 TAPDEBUG(ifp, "not ready, minor = %#x, flags = 0x%x\n",
854                          minor(dev), sc->tap_flags);
855
856                 return (EHOSTDOWN);
857         }
858
859         sc->tap_flags &= ~TAP_RWAIT;
860
861         /* sleep until we get a packet */
862         do {
863                 ifnet_serialize_all(ifp);
864                 IF_DEQUEUE(&sc->tap_devq, m0);
865                 if (m0 == NULL) {
866                         if (ap->a_ioflag & IO_NDELAY) {
867                                 ifnet_deserialize_all(ifp);
868                                 return (EWOULDBLOCK);
869                         }
870                         sc->tap_flags |= TAP_RWAIT;
871                         tsleep_interlock(sc, PCATCH);
872                         ifnet_deserialize_all(ifp);
873                         error = tsleep(sc, PCATCH | PINTERLOCKED, "taprd", 0);
874                         if (error)
875                                 return (error);
876                 } else {
877                         ifnet_deserialize_all(ifp);
878                 }
879         } while (m0 == NULL);
880
881         BPF_MTAP(ifp, m0);
882
883         /* xfer packet to user space */
884         while ((m0 != NULL) && (uio->uio_resid > 0) && (error == 0)) {
885                 len = (int)szmin(uio->uio_resid, m0->m_len);
886                 if (len == 0)
887                         break;
888
889                 error = uiomove(mtod(m0, caddr_t), (size_t)len, uio);
890                 m0 = m_free(m0);
891         }
892
893         if (m0 != NULL) {
894                 TAPDEBUG(ifp, "dropping mbuf, minor = %#x\n", minor(dev));
895                 m_freem(m0);
896         }
897
898         return (error);
899 }
900
901 /*
902  * tapwrite
903  *
904  * The ops write interface - an atomic write is a packet - or else!
905  *
906  * Called from the fileops interface with nothing held.
907  *
908  * MPSAFE
909  */
910 static int
911 tapwrite(struct dev_write_args *ap)
912 {
913         cdev_t dev = ap->a_head.a_dev;
914         struct uio *uio = ap->a_uio;
915         struct tap_softc *sc = dev->si_drv1;
916         struct ifnet *ifp = sc->tap_ifp;
917         struct mbuf *top = NULL, **mp = NULL, *m = NULL;
918         int error;
919         size_t tlen, mlen;
920
921         TAPDEBUG(ifp, "writing, minor = %#x\n", minor(dev));
922
923         if ((sc->tap_flags & TAP_READY) != TAP_READY) {
924                 TAPDEBUG(ifp, "not ready, minor = %#x, flags = 0x%x\n",
925                          minor(dev), sc->tap_flags);
926                 return (EHOSTDOWN);
927         }
928
929         if (uio->uio_resid == 0)
930                 return (0);
931
932         if (uio->uio_resid > TAPMRU) {
933                 TAPDEBUG(ifp, "invalid packet len = %zu, minor = %#x\n",
934                          uio->uio_resid, minor(dev));
935
936                 return (EIO);
937         }
938         tlen = uio->uio_resid;
939
940         /* get a header mbuf */
941         MGETHDR(m, M_WAITOK, MT_DATA);
942         if (m == NULL)
943                 return (ENOBUFS);
944         mlen = MHLEN;
945
946         top = NULL;
947         mp = &top;
948         error = 0;
949
950         while (error == 0 && uio->uio_resid > 0) {
951                 m->m_len = (int)szmin(mlen, uio->uio_resid);
952                 error = uiomove(mtod(m, caddr_t), (size_t)m->m_len, uio);
953                 *mp = m;
954                 mp = &m->m_next;
955                 if (uio->uio_resid > 0) {
956                         MGET(m, M_WAITOK, MT_DATA);
957                         if (m == NULL) {
958                                 error = ENOBUFS;
959                                 break;
960                         }
961                         mlen = MLEN;
962                 }
963         }
964         if (error) {
965                 IFNET_STAT_INC(ifp, ierrors, 1);
966                 if (top)
967                         m_freem(top);
968                 return (error);
969         }
970
971         top->m_pkthdr.len = (int)tlen;
972         top->m_pkthdr.rcvif = ifp;
973
974         /*
975          * Ethernet bridge and bpf are handled in ether_input
976          *
977          * adjust mbuf and give packet to the ether_input
978          */
979         ifnet_serialize_all(ifp);
980         ifp->if_input(ifp, top, NULL, -1);
981         IFNET_STAT_INC(ifp, ipackets, 1); /* ibytes are counted in ether_input */
982         ifnet_deserialize_all(ifp);
983
984         return (0);
985 }
986
987
988 /*
989  * tapkqfilter - called from the fileops interface with nothing held
990  *
991  * MPSAFE
992  */
993 static int
994 tapkqfilter(struct dev_kqfilter_args *ap)
995 {
996         cdev_t dev = ap->a_head.a_dev;
997         struct knote *kn = ap->a_kn;
998         struct tap_softc *sc = dev->si_drv1;
999         struct klist *list;
1000
1001         list = &sc->tap_rkq.ki_note;
1002         ap->a_result =0;
1003
1004         switch (kn->kn_filter) {
1005         case EVFILT_READ:
1006                 kn->kn_fop = &tapread_filtops;
1007                 kn->kn_hook = (void *)sc;
1008                 break;
1009         case EVFILT_WRITE:
1010                 kn->kn_fop = &tapwrite_filtops;
1011                 kn->kn_hook = (void *)sc;
1012                 break;
1013         default:
1014                 ap->a_result = EOPNOTSUPP;
1015                 return (0);
1016         }
1017
1018         knote_insert(list, kn);
1019         return (0);
1020 }
1021
1022 static int
1023 tap_filter_read(struct knote *kn, long hint)
1024 {
1025         struct tap_softc *sc = (struct tap_softc *)kn->kn_hook;
1026
1027         if (IF_QEMPTY(&sc->tap_devq) == 0)      /* XXX serializer */
1028                 return (1);
1029         else
1030                 return (0);
1031 }
1032
1033 static int
1034 tap_filter_write(struct knote *kn, long hint)
1035 {
1036         /* Always ready for a write */
1037         return (1);
1038 }
1039
1040 static void
1041 tap_filter_detach(struct knote *kn)
1042 {
1043         struct tap_softc *sc = (struct tap_softc *)kn->kn_hook;
1044
1045         knote_remove(&sc->tap_rkq.ki_note, kn);
1046 }