MASSIVE reorganization of the device operations vector. Change cdevsw
[dragonfly.git] / sys / net / bpf.c
1 /*
2  * Copyright (c) 1990, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from the Stanford/CMU enet packet filter,
6  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
7  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
8  * Berkeley Laboratory.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)bpf.c       8.2 (Berkeley) 3/28/94
39  *
40  * $FreeBSD: src/sys/net/bpf.c,v 1.59.2.12 2002/04/14 21:41:48 luigi Exp $
41  * $DragonFly: src/sys/net/bpf.c,v 1.31 2006/07/28 02:17:40 dillon Exp $
42  */
43
44 #include "use_bpf.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/conf.h>
49 #include <sys/device.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/time.h>
53 #include <sys/proc.h>
54 #include <sys/signalvar.h>
55 #include <sys/filio.h>
56 #include <sys/sockio.h>
57 #include <sys/ttycom.h>
58 #include <sys/filedesc.h>
59
60 #include <sys/poll.h>
61
62 #include <sys/socket.h>
63 #include <sys/vnode.h>
64
65 #include <sys/thread2.h>
66
67 #include <net/if.h>
68 #include <net/bpf.h>
69 #include <net/bpfdesc.h>
70
71 #include <netinet/in.h>
72 #include <netinet/if_ether.h>
73 #include <sys/kernel.h>
74 #include <sys/sysctl.h>
75
76 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
77
78 #if NBPF > 0
79
80 /*
81  * The default read buffer size is patchable.
82  */
83 static int bpf_bufsize = BPF_DEFAULTBUFSIZE;
84 SYSCTL_INT(_debug, OID_AUTO, bpf_bufsize, CTLFLAG_RW,
85            &bpf_bufsize, 0, "");
86 static int bpf_maxbufsize = BPF_MAXBUFSIZE;
87 SYSCTL_INT(_debug, OID_AUTO, bpf_maxbufsize, CTLFLAG_RW,
88            &bpf_maxbufsize, 0, "");
89
90 /*
91  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
92  */
93 static struct bpf_if    *bpf_iflist;
94
95 static int      bpf_allocbufs(struct bpf_d *);
96 static void     bpf_attachd(struct bpf_d *d, struct bpf_if *bp);
97 static void     bpf_detachd(struct bpf_d *d);
98 static void     bpf_freed(struct bpf_d *);
99 static void     bpf_mcopy(const void *, void *, size_t);
100 static int      bpf_movein(struct uio *, int, struct mbuf **,
101                            struct sockaddr *, int *);
102 static int      bpf_setif(struct bpf_d *, struct ifreq *);
103 static void     bpf_timed_out(void *);
104 static void     bpf_wakeup(struct bpf_d *);
105 static void     catchpacket(struct bpf_d *, u_char *, u_int, u_int,
106                             void (*)(const void *, void *, size_t));
107 static void     reset_d(struct bpf_d *);
108 static int      bpf_setf(struct bpf_d *, struct bpf_program *);
109 static int      bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
110 static int      bpf_setdlt(struct bpf_d *, u_int);
111 static void     bpf_drvinit(void *unused);
112
113 static d_open_t         bpfopen;
114 static d_close_t        bpfclose;
115 static d_read_t         bpfread;
116 static d_write_t        bpfwrite;
117 static d_ioctl_t        bpfioctl;
118 static d_poll_t         bpfpoll;
119
120 #define CDEV_MAJOR 23
121 static struct dev_ops bpf_ops = {
122         { "bpf", CDEV_MAJOR, 0 },
123         .d_open =       bpfopen,
124         .d_close =      bpfclose,
125         .d_read =       bpfread,
126         .d_write =      bpfwrite,
127         .d_ioctl =      bpfioctl,
128         .d_poll =       bpfpoll,
129 };
130
131
132 static int
133 bpf_movein(struct uio *uio, int linktype, struct mbuf **mp,
134            struct sockaddr *sockp, int *datlen)
135 {
136         struct mbuf *m;
137         int error;
138         int len;
139         int hlen;
140
141         /*
142          * Build a sockaddr based on the data link layer type.
143          * We do this at this level because the ethernet header
144          * is copied directly into the data field of the sockaddr.
145          * In the case of SLIP, there is no header and the packet
146          * is forwarded as is.
147          * Also, we are careful to leave room at the front of the mbuf
148          * for the link level header.
149          */
150         switch (linktype) {
151
152         case DLT_SLIP:
153                 sockp->sa_family = AF_INET;
154                 hlen = 0;
155                 break;
156
157         case DLT_EN10MB:
158                 sockp->sa_family = AF_UNSPEC;
159                 /* XXX Would MAXLINKHDR be better? */
160                 hlen = sizeof(struct ether_header);
161                 break;
162
163         case DLT_FDDI:
164                 sockp->sa_family = AF_IMPLINK;
165                 hlen = 0;
166                 break;
167
168         case DLT_RAW:
169         case DLT_NULL:
170                 sockp->sa_family = AF_UNSPEC;
171                 hlen = 0;
172                 break;
173
174         case DLT_ATM_RFC1483:
175                 /*
176                  * en atm driver requires 4-byte atm pseudo header.
177                  * though it isn't standard, vpi:vci needs to be
178                  * specified anyway.
179                  */
180                 sockp->sa_family = AF_UNSPEC;
181                 hlen = 12;      /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
182                 break;
183
184         case DLT_PPP:
185                 sockp->sa_family = AF_UNSPEC;
186                 hlen = 4;       /* This should match PPP_HDRLEN */
187                 break;
188
189         default:
190                 return(EIO);
191         }
192
193         len = uio->uio_resid;
194         *datlen = len - hlen;
195         if ((unsigned)len > MCLBYTES)
196                 return(EIO);
197
198         MGETHDR(m, MB_WAIT, MT_DATA);
199         if (m == NULL)
200                 return(ENOBUFS);
201         if (len > MHLEN) {
202                 MCLGET(m, MB_WAIT);
203                 if (!(m->m_flags & M_EXT)) {
204                         error = ENOBUFS;
205                         goto bad;
206                 }
207         }
208         m->m_pkthdr.len = m->m_len = len;
209         m->m_pkthdr.rcvif = NULL;
210         *mp = m;
211         /*
212          * Make room for link header.
213          */
214         if (hlen != 0) {
215                 m->m_pkthdr.len -= hlen;
216                 m->m_len -= hlen;
217                 m->m_data += hlen; /* XXX */
218                 error = uiomove(sockp->sa_data, hlen, uio);
219                 if (error)
220                         goto bad;
221         }
222         error = uiomove(mtod(m, caddr_t), len - hlen, uio);
223         if (!error)
224                 return(0);
225 bad:
226         m_freem(m);
227         return(error);
228 }
229
230 /*
231  * Attach file to the bpf interface, i.e. make d listen on bp.
232  * Must be called at splimp.
233  */
234 static void
235 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
236 {
237         /*
238          * Point d at bp, and add d to the interface's list of listeners.
239          * Finally, point the driver's bpf cookie at the interface so
240          * it will divert packets to bpf.
241          */
242         d->bd_bif = bp;
243         SLIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
244         *bp->bif_driverp = bp;
245 }
246
247 /*
248  * Detach a file from its interface.
249  */
250 static void
251 bpf_detachd(struct bpf_d *d)
252 {
253         int error;
254         struct bpf_if *bp;
255         struct ifnet *ifp;
256
257         bp = d->bd_bif;
258         ifp = bp->bif_ifp;
259
260         /* Remove d from the interface's descriptor list. */
261         SLIST_REMOVE(&bp->bif_dlist, d, bpf_d, bd_next);
262
263         if (SLIST_EMPTY(&bp->bif_dlist)) {
264                 /*
265                  * Let the driver know that there are no more listeners.
266                  */
267                 *bp->bif_driverp = NULL;
268         }
269         d->bd_bif = NULL;
270         /*
271          * Check if this descriptor had requested promiscuous mode.
272          * If so, turn it off.
273          */
274         if (d->bd_promisc) {
275                 d->bd_promisc = 0;
276                 error = ifpromisc(ifp, 0);
277                 if (error != 0 && error != ENXIO) {
278                         /*
279                          * ENXIO can happen if a pccard is unplugged,
280                          * Something is really wrong if we were able to put
281                          * the driver into promiscuous mode, but can't
282                          * take it out.
283                          */
284                         if_printf(ifp, "bpf_detach: ifpromisc failed(%d)\n",
285                                   error);
286                 }
287         }
288 }
289
290 /*
291  * Open ethernet device.  Returns ENXIO for illegal minor device number,
292  * EBUSY if file is open by another process.
293  */
294 /* ARGSUSED */
295 static int
296 bpfopen(struct dev_open_args *ap)
297 {
298         dev_t dev = ap->a_head.a_dev;
299         struct bpf_d *d;
300
301         if (ap->a_cred->cr_prison)
302                 return(EPERM);
303
304         d = dev->si_drv1;
305         /*
306          * Each minor can be opened by only one process.  If the requested
307          * minor is in use, return EBUSY.
308          */
309         if (d != NULL)
310                 return(EBUSY);
311         make_dev(&bpf_ops, minor(dev), 0, 0, 0600, "bpf%d", lminor(dev));
312         MALLOC(d, struct bpf_d *, sizeof *d, M_BPF, M_WAITOK | M_ZERO);
313         dev->si_drv1 = d;
314         d->bd_bufsize = bpf_bufsize;
315         d->bd_sig = SIGIO;
316         d->bd_seesent = 1;
317         callout_init(&d->bd_callout);
318         return(0);
319 }
320
321 /*
322  * Close the descriptor by detaching it from its interface,
323  * deallocating its buffers, and marking it free.
324  */
325 /* ARGSUSED */
326 static int
327 bpfclose(struct dev_close_args *ap)
328 {
329         dev_t dev = ap->a_head.a_dev;
330         struct bpf_d *d = dev->si_drv1;
331
332         funsetown(d->bd_sigio);
333         crit_enter();
334         if (d->bd_state == BPF_WAITING)
335                 callout_stop(&d->bd_callout);
336         d->bd_state = BPF_IDLE;
337         if (d->bd_bif != NULL)
338                 bpf_detachd(d);
339         crit_exit();
340         bpf_freed(d);
341         dev->si_drv1 = NULL;
342         free(d, M_BPF);
343
344         return(0);
345 }
346
347 /*
348  * Rotate the packet buffers in descriptor d.  Move the store buffer
349  * into the hold slot, and the free buffer into the store slot.
350  * Zero the length of the new store buffer.
351  */
352 #define ROTATE_BUFFERS(d) \
353         (d)->bd_hbuf = (d)->bd_sbuf; \
354         (d)->bd_hlen = (d)->bd_slen; \
355         (d)->bd_sbuf = (d)->bd_fbuf; \
356         (d)->bd_slen = 0; \
357         (d)->bd_fbuf = NULL;
358 /*
359  *  bpfread - read next chunk of packets from buffers
360  */
361 static int
362 bpfread(struct dev_read_args *ap)
363 {
364         dev_t dev = ap->a_head.a_dev;
365         struct bpf_d *d = dev->si_drv1;
366         int timed_out;
367         int error;
368
369         /*
370          * Restrict application to use a buffer the same size as
371          * as kernel buffers.
372          */
373         if (ap->a_uio->uio_resid != d->bd_bufsize)
374                 return(EINVAL);
375
376         crit_enter();
377         if (d->bd_state == BPF_WAITING)
378                 callout_stop(&d->bd_callout);
379         timed_out = (d->bd_state == BPF_TIMED_OUT);
380         d->bd_state = BPF_IDLE;
381         /*
382          * If the hold buffer is empty, then do a timed sleep, which
383          * ends when the timeout expires or when enough packets
384          * have arrived to fill the store buffer.
385          */
386         while (d->bd_hbuf == NULL) {
387                 if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
388                         /*
389                          * A packet(s) either arrived since the previous
390                          * read or arrived while we were asleep.
391                          * Rotate the buffers and return what's here.
392                          */
393                         ROTATE_BUFFERS(d);
394                         break;
395                 }
396
397                 /*
398                  * No data is available, check to see if the bpf device
399                  * is still pointed at a real interface.  If not, return
400                  * ENXIO so that the userland process knows to rebind
401                  * it before using it again.
402                  */
403                 if (d->bd_bif == NULL) {
404                         crit_exit();
405                         return(ENXIO);
406                 }
407
408                 if (ap->a_ioflag & IO_NDELAY) {
409                         crit_exit();
410                         return(EWOULDBLOCK);
411                 }
412                 error = tsleep(d, PCATCH, "bpf", d->bd_rtout);
413                 if (error == EINTR || error == ERESTART) {
414                         crit_exit();
415                         return(error);
416                 }
417                 if (error == EWOULDBLOCK) {
418                         /*
419                          * On a timeout, return what's in the buffer,
420                          * which may be nothing.  If there is something
421                          * in the store buffer, we can rotate the buffers.
422                          */
423                         if (d->bd_hbuf)
424                                 /*
425                                  * We filled up the buffer in between
426                                  * getting the timeout and arriving
427                                  * here, so we don't need to rotate.
428                                  */
429                                 break;
430
431                         if (d->bd_slen == 0) {
432                                 crit_exit();
433                                 return(0);
434                         }
435                         ROTATE_BUFFERS(d);
436                         break;
437                 }
438         }
439         /*
440          * At this point, we know we have something in the hold slot.
441          */
442         crit_exit();
443
444         /*
445          * Move data from hold buffer into user space.
446          * We know the entire buffer is transferred since
447          * we checked above that the read buffer is bpf_bufsize bytes.
448          */
449         error = uiomove(d->bd_hbuf, d->bd_hlen, ap->a_uio);
450
451         crit_enter();
452         d->bd_fbuf = d->bd_hbuf;
453         d->bd_hbuf = NULL;
454         d->bd_hlen = 0;
455         crit_exit();
456
457         return(error);
458 }
459
460
461 /*
462  * If there are processes sleeping on this descriptor, wake them up.
463  */
464 static void
465 bpf_wakeup(struct bpf_d *d)
466 {
467         if (d->bd_state == BPF_WAITING) {
468                 callout_stop(&d->bd_callout);
469                 d->bd_state = BPF_IDLE;
470         }
471         wakeup(d);
472         if (d->bd_async && d->bd_sig && d->bd_sigio)
473                 pgsigio(d->bd_sigio, d->bd_sig, 0);
474
475         get_mplock();
476         selwakeup(&d->bd_sel);
477         rel_mplock();
478         /* XXX */
479         d->bd_sel.si_pid = 0;
480 }
481
482 static void
483 bpf_timed_out(void *arg)
484 {
485         struct bpf_d *d = (struct bpf_d *)arg;
486
487         crit_enter();
488         if (d->bd_state == BPF_WAITING) {
489                 d->bd_state = BPF_TIMED_OUT;
490                 if (d->bd_slen != 0)
491                         bpf_wakeup(d);
492         }
493         crit_exit();
494 }
495
496 static  int
497 bpfwrite(struct dev_write_args *ap)
498 {
499         dev_t dev = ap->a_head.a_dev;
500         struct bpf_d *d = dev->si_drv1;
501         struct ifnet *ifp;
502         struct mbuf *m;
503         int error;
504         static struct sockaddr dst;
505         int datlen;
506
507         if (d->bd_bif == NULL)
508                 return(ENXIO);
509
510         ifp = d->bd_bif->bif_ifp;
511
512         if (ap->a_uio->uio_resid == 0)
513                 return(0);
514
515         error = bpf_movein(ap->a_uio, (int)d->bd_bif->bif_dlt, &m,
516                            &dst, &datlen);
517         if (error)
518                 return(error);
519
520         if (datlen > ifp->if_mtu) {
521                 m_freem(m);
522                 return(EMSGSIZE);
523         }
524
525         if (d->bd_hdrcmplt)
526                 dst.sa_family = pseudo_AF_HDRCMPLT;
527
528         crit_enter();
529         lwkt_serialize_enter(ifp->if_serializer);
530         error = (*ifp->if_output)(ifp, m, &dst, (struct rtentry *)NULL);
531         lwkt_serialize_exit(ifp->if_serializer);
532         crit_exit();
533         /*
534          * The driver frees the mbuf.
535          */
536         return(error);
537 }
538
539 /*
540  * Reset a descriptor by flushing its packet buffer and clearing the
541  * receive and drop counts.  Should be called at splimp.
542  */
543 static void
544 reset_d(struct bpf_d *d)
545 {
546         if (d->bd_hbuf) {
547                 /* Free the hold buffer. */
548                 d->bd_fbuf = d->bd_hbuf;
549                 d->bd_hbuf = NULL;
550         }
551         d->bd_slen = 0;
552         d->bd_hlen = 0;
553         d->bd_rcount = 0;
554         d->bd_dcount = 0;
555 }
556
557 /*
558  *  FIONREAD            Check for read packet available.
559  *  SIOCGIFADDR         Get interface address - convenient hook to driver.
560  *  BIOCGBLEN           Get buffer len [for read()].
561  *  BIOCSETF            Set ethernet read filter.
562  *  BIOCFLUSH           Flush read packet buffer.
563  *  BIOCPROMISC         Put interface into promiscuous mode.
564  *  BIOCGDLT            Get link layer type.
565  *  BIOCGETIF           Get interface name.
566  *  BIOCSETIF           Set interface.
567  *  BIOCSRTIMEOUT       Set read timeout.
568  *  BIOCGRTIMEOUT       Get read timeout.
569  *  BIOCGSTATS          Get packet stats.
570  *  BIOCIMMEDIATE       Set immediate mode.
571  *  BIOCVERSION         Get filter language version.
572  *  BIOCGHDRCMPLT       Get "header already complete" flag
573  *  BIOCSHDRCMPLT       Set "header already complete" flag
574  *  BIOCGSEESENT        Get "see packets sent" flag
575  *  BIOCSSEESENT        Set "see packets sent" flag
576  */
577 /* ARGSUSED */
578 static int
579 bpfioctl(struct dev_ioctl_args *ap)
580 {
581         dev_t dev = ap->a_head.a_dev;
582         struct bpf_d *d = dev->si_drv1;
583         int error = 0;
584
585         crit_enter();
586         if (d->bd_state == BPF_WAITING)
587                 callout_stop(&d->bd_callout);
588         d->bd_state = BPF_IDLE;
589         crit_exit();
590
591         switch (ap->a_cmd) {
592         default:
593                 error = EINVAL;
594                 break;
595
596         /*
597          * Check for read packet available.
598          */
599         case FIONREAD:
600                 {
601                         int n;
602
603                         crit_enter();
604                         n = d->bd_slen;
605                         if (d->bd_hbuf)
606                                 n += d->bd_hlen;
607                         crit_exit();
608
609                         *(int *)ap->a_data = n;
610                         break;
611                 }
612
613         case SIOCGIFADDR:
614                 {
615                         struct ifnet *ifp;
616
617                         if (d->bd_bif == NULL)
618                                 error = EINVAL;
619                         else {
620                                 ifp = d->bd_bif->bif_ifp;
621                                 lwkt_serialize_enter(ifp->if_serializer);
622                                 error = ifp->if_ioctl(ifp, ap->a_cmd,
623                                                       ap->a_data, ap->a_cred);
624                                 lwkt_serialize_exit(ifp->if_serializer);
625                         }
626                         break;
627                 }
628
629         /*
630          * Get buffer len [for read()].
631          */
632         case BIOCGBLEN:
633                 *(u_int *)ap->a_data = d->bd_bufsize;
634                 break;
635
636         /*
637          * Set buffer length.
638          */
639         case BIOCSBLEN:
640                 if (d->bd_bif != 0)
641                         error = EINVAL;
642                 else {
643                         u_int size = *(u_int *)ap->a_data;
644
645                         if (size > bpf_maxbufsize)
646                                 *(u_int *)ap->a_data = size = bpf_maxbufsize;
647                         else if (size < BPF_MINBUFSIZE)
648                                 *(u_int *)ap->a_data = size = BPF_MINBUFSIZE;
649                         d->bd_bufsize = size;
650                 }
651                 break;
652
653         /*
654          * Set link layer read filter.
655          */
656         case BIOCSETF:
657                 error = bpf_setf(d, (struct bpf_program *)ap->a_data);
658                 break;
659
660         /*
661          * Flush read packet buffer.
662          */
663         case BIOCFLUSH:
664                 crit_enter();
665                 reset_d(d);
666                 crit_exit();
667                 break;
668
669         /*
670          * Put interface into promiscuous mode.
671          */
672         case BIOCPROMISC:
673                 if (d->bd_bif == NULL) {
674                         /*
675                          * No interface attached yet.
676                          */
677                         error = EINVAL;
678                         break;
679                 }
680                 crit_enter();
681                 if (d->bd_promisc == 0) {
682                         error = ifpromisc(d->bd_bif->bif_ifp, 1);
683                         if (error == 0)
684                                 d->bd_promisc = 1;
685                 }
686                 crit_exit();
687                 break;
688
689         /*
690          * Get device parameters.
691          */
692         case BIOCGDLT:
693                 if (d->bd_bif == NULL)
694                         error = EINVAL;
695                 else
696                         *(u_int *)ap->a_data = d->bd_bif->bif_dlt;
697                 break;
698
699         /*
700          * Get a list of supported data link types.
701          */
702         case BIOCGDLTLIST:
703                 if (d->bd_bif == NULL)
704                         error = EINVAL;
705                 else
706                         error = bpf_getdltlist(d, (struct bpf_dltlist *)ap->a_data);
707                 break;
708
709         /*
710          * Set data link type.
711          */
712         case BIOCSDLT:
713                 if (d->bd_bif == NULL)
714                         error = EINVAL;
715                 else
716                         error = bpf_setdlt(d, *(u_int *)ap->a_data);
717                 break;
718
719         /*
720          * Get interface name.
721          */
722         case BIOCGETIF:
723                 if (d->bd_bif == NULL) {
724                         error = EINVAL;
725                 } else {
726                         struct ifnet *const ifp = d->bd_bif->bif_ifp;
727                         struct ifreq *const ifr = (struct ifreq *)ap->a_data;
728
729                         strlcpy(ifr->ifr_name, ifp->if_xname,
730                                 sizeof ifr->ifr_name);
731                 }
732                 break;
733
734         /*
735          * Set interface.
736          */
737         case BIOCSETIF:
738                 error = bpf_setif(d, (struct ifreq *)ap->a_data);
739                 break;
740
741         /*
742          * Set read timeout.
743          */
744         case BIOCSRTIMEOUT:
745                 {
746                         struct timeval *tv = (struct timeval *)ap->a_data;
747
748                         /*
749                          * Subtract 1 tick from tvtohz() since this isn't
750                          * a one-shot timer.
751                          */
752                         if ((error = itimerfix(tv)) == 0)
753                                 d->bd_rtout = tvtohz_low(tv);
754                         break;
755                 }
756
757         /*
758          * Get read timeout.
759          */
760         case BIOCGRTIMEOUT:
761                 {
762                         struct timeval *tv = (struct timeval *)ap->a_data;
763
764                         tv->tv_sec = d->bd_rtout / hz;
765                         tv->tv_usec = (d->bd_rtout % hz) * tick;
766                         break;
767                 }
768
769         /*
770          * Get packet stats.
771          */
772         case BIOCGSTATS:
773                 {
774                         struct bpf_stat *bs = (struct bpf_stat *)ap->a_data;
775
776                         bs->bs_recv = d->bd_rcount;
777                         bs->bs_drop = d->bd_dcount;
778                         break;
779                 }
780
781         /*
782          * Set immediate mode.
783          */
784         case BIOCIMMEDIATE:
785                 d->bd_immediate = *(u_int *)ap->a_data;
786                 break;
787
788         case BIOCVERSION:
789                 {
790                         struct bpf_version *bv = (struct bpf_version *)ap->a_data;
791
792                         bv->bv_major = BPF_MAJOR_VERSION;
793                         bv->bv_minor = BPF_MINOR_VERSION;
794                         break;
795                 }
796
797         /*
798          * Get "header already complete" flag
799          */
800         case BIOCGHDRCMPLT:
801                 *(u_int *)ap->a_data = d->bd_hdrcmplt;
802                 break;
803
804         /*
805          * Set "header already complete" flag
806          */
807         case BIOCSHDRCMPLT:
808                 d->bd_hdrcmplt = *(u_int *)ap->a_data ? 1 : 0;
809                 break;
810
811         /*
812          * Get "see sent packets" flag
813          */
814         case BIOCGSEESENT:
815                 *(u_int *)ap->a_data = d->bd_seesent;
816                 break;
817
818         /*
819          * Set "see sent packets" flag
820          */
821         case BIOCSSEESENT:
822                 d->bd_seesent = *(u_int *)ap->a_data;
823                 break;
824
825         case FIOASYNC:          /* Send signal on receive packets */
826                 d->bd_async = *(int *)ap->a_data;
827                 break;
828
829         case FIOSETOWN:
830                 error = fsetown(*(int *)ap->a_data, &d->bd_sigio);
831                 break;
832
833         case FIOGETOWN:
834                 *(int *)ap->a_data = fgetown(d->bd_sigio);
835                 break;
836
837         /* This is deprecated, FIOSETOWN should be used instead. */
838         case TIOCSPGRP:
839                 error = fsetown(-(*(int *)ap->a_data), &d->bd_sigio);
840                 break;
841
842         /* This is deprecated, FIOGETOWN should be used instead. */
843         case TIOCGPGRP:
844                 *(int *)ap->a_data = -fgetown(d->bd_sigio);
845                 break;
846
847         case BIOCSRSIG:         /* Set receive signal */
848                 {
849                         u_int sig;
850
851                         sig = *(u_int *)ap->a_data;
852
853                         if (sig >= NSIG)
854                                 error = EINVAL;
855                         else
856                                 d->bd_sig = sig;
857                         break;
858                 }
859         case BIOCGRSIG:
860                 *(u_int *)ap->a_data = d->bd_sig;
861                 break;
862         }
863         return(error);
864 }
865
866 /*
867  * Set d's packet filter program to fp.  If this file already has a filter,
868  * free it and replace it.  Returns EINVAL for bogus requests.
869  */
870 static int
871 bpf_setf(struct bpf_d *d, struct bpf_program *fp)
872 {
873         struct bpf_insn *fcode, *old;
874         u_int flen, size;
875
876         old = d->bd_filter;
877         if (fp->bf_insns == NULL) {
878                 if (fp->bf_len != 0)
879                         return(EINVAL);
880                 crit_enter();
881                 d->bd_filter = NULL;
882                 reset_d(d);
883                 crit_exit();
884                 if (old != 0)
885                         free(old, M_BPF);
886                 return(0);
887         }
888         flen = fp->bf_len;
889         if (flen > BPF_MAXINSNS)
890                 return(EINVAL);
891
892         size = flen * sizeof *fp->bf_insns;
893         fcode = (struct bpf_insn *)malloc(size, M_BPF, M_WAITOK);
894         if (copyin(fp->bf_insns, fcode, size) == 0 &&
895             bpf_validate(fcode, (int)flen)) {
896                 crit_enter();
897                 d->bd_filter = fcode;
898                 reset_d(d);
899                 crit_exit();
900                 if (old != 0)
901                         free(old, M_BPF);
902
903                 return(0);
904         }
905         free(fcode, M_BPF);
906         return(EINVAL);
907 }
908
909 /*
910  * Detach a file from its current interface (if attached at all) and attach
911  * to the interface indicated by the name stored in ifr.
912  * Return an errno or 0.
913  */
914 static int
915 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
916 {
917         struct bpf_if *bp;
918         int error;
919         struct ifnet *theywant;
920
921         theywant = ifunit(ifr->ifr_name);
922         if (theywant == NULL)
923                 return(ENXIO);
924
925         /*
926          * Look through attached interfaces for the named one.
927          */
928         for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
929                 struct ifnet *ifp = bp->bif_ifp;
930
931                 if (ifp == NULL || ifp != theywant)
932                         continue;
933                 /* skip additional entry */
934                 if (bp->bif_driverp != &ifp->if_bpf)
935                         continue;
936                 /*
937                  * We found the requested interface.
938                  * If it's not up, return an error.
939                  * Allocate the packet buffers if we need to.
940                  * If we're already attached to requested interface,
941                  * just flush the buffer.
942                  */
943                 if (!(ifp->if_flags & IFF_UP))
944                         return(ENETDOWN);
945
946                 if (d->bd_sbuf == NULL) {
947                         error = bpf_allocbufs(d);
948                         if (error != 0)
949                                 return(error);
950                 }
951                 crit_enter();
952                 if (bp != d->bd_bif) {
953                         if (d->bd_bif != NULL) {
954                                 /*
955                                  * Detach if attached to something else.
956                                  */
957                                 bpf_detachd(d);
958                         }
959
960                         bpf_attachd(d, bp);
961                 }
962                 reset_d(d);
963                 crit_exit();
964                 return(0);
965         }
966
967         /* Not found. */
968         return(ENXIO);
969 }
970
971 /*
972  * Support for select() and poll() system calls
973  *
974  * Return true iff the specific operation will not block indefinitely.
975  * Otherwise, return false but make a note that a selwakeup() must be done.
976  */
977 int
978 bpfpoll(struct dev_poll_args *ap)
979 {
980         dev_t dev = ap->a_head.a_dev;
981         struct bpf_d *d;
982         int revents;
983
984         d = dev->si_drv1;
985         if (d->bd_bif == NULL)
986                 return(ENXIO);
987
988         revents = ap->a_events & (POLLOUT | POLLWRNORM);
989         crit_enter();
990         if (ap->a_events & (POLLIN | POLLRDNORM)) {
991                 /*
992                  * An imitation of the FIONREAD ioctl code.
993                  * XXX not quite.  An exact imitation:
994                  *      if (d->b_slen != 0 ||
995                  *          (d->bd_hbuf != NULL && d->bd_hlen != 0)
996                  */
997                 if (d->bd_hlen != 0 ||
998                     ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
999                     d->bd_slen != 0))
1000                         revents |= ap->a_events & (POLLIN | POLLRDNORM);
1001                 else {
1002                         selrecord(curthread, &d->bd_sel);
1003                         /* Start the read timeout if necessary. */
1004                         if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1005                                 callout_reset(&d->bd_callout, d->bd_rtout,
1006                                     bpf_timed_out, d);
1007                                 d->bd_state = BPF_WAITING;
1008                         }
1009                 }
1010         }
1011         crit_exit();
1012         ap->a_events = revents;
1013         return(0);
1014 }
1015
1016 /*
1017  * Process the packet pkt of length pktlen.  The packet is parsed
1018  * by each listener's filter, and if accepted, stashed into the
1019  * corresponding buffer.
1020  */
1021 void
1022 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
1023 {
1024         struct bpf_d *d;
1025         u_int slen;
1026
1027         /*
1028          * Note that the ipl does not have to be raised at this point.
1029          * The only problem that could arise here is that if two different
1030          * interfaces shared any data.  This is not the case.
1031          */
1032         SLIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1033                 ++d->bd_rcount;
1034                 slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
1035                 if (slen != 0)
1036                         catchpacket(d, pkt, pktlen, slen, ovbcopy);
1037         }
1038 }
1039
1040 /*
1041  * Copy data from an mbuf chain into a buffer.  This code is derived
1042  * from m_copydata in sys/uipc_mbuf.c.
1043  */
1044 static void
1045 bpf_mcopy(const void *src_arg, void *dst_arg, size_t len)
1046 {
1047         const struct mbuf *m;
1048         u_int count;
1049         u_char *dst;
1050
1051         m = src_arg;
1052         dst = dst_arg;
1053         while (len > 0) {
1054                 if (m == NULL)
1055                         panic("bpf_mcopy");
1056                 count = min(m->m_len, len);
1057                 bcopy(mtod(m, void *), dst, count);
1058                 m = m->m_next;
1059                 dst += count;
1060                 len -= count;
1061         }
1062 }
1063
1064 /*
1065  * Process the packet in the mbuf chain m.  The packet is parsed by each
1066  * listener's filter, and if accepted, stashed into the corresponding
1067  * buffer.
1068  */
1069 void
1070 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
1071 {
1072         struct bpf_d *d;
1073         u_int pktlen, slen;
1074         struct mbuf *m0;
1075
1076         /* Don't compute pktlen, if no descriptor is attached. */
1077         if (SLIST_EMPTY(&bp->bif_dlist))
1078                 return;
1079
1080         pktlen = 0;
1081         for (m0 = m; m0 != NULL; m0 = m0->m_next)
1082                 pktlen += m0->m_len;
1083
1084         SLIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1085                 if (!d->bd_seesent && (m->m_pkthdr.rcvif == NULL))
1086                         continue;
1087                 ++d->bd_rcount;
1088                 slen = bpf_filter(d->bd_filter, (u_char *)m, pktlen, 0);
1089                 if (slen != 0)
1090                         catchpacket(d, (u_char *)m, pktlen, slen, bpf_mcopy);
1091         }
1092 }
1093
1094 void
1095 bpf_mtap_family(struct bpf_if *bp, struct mbuf *m, sa_family_t family)
1096 {
1097         u_int family4;
1098
1099         KKASSERT(family != AF_UNSPEC);
1100         
1101         family4 = (u_int)family;
1102         bpf_ptap(bp, m, &family4, sizeof(family4));
1103 }
1104
1105 /*
1106  * Process the packet in the mbuf chain m with the header in m prepended.
1107  * The packet is parsed by each listener's filter, and if accepted,
1108  * stashed into the corresponding buffer.
1109  */
1110 void
1111 bpf_ptap(struct bpf_if *bp, struct mbuf *m, const void *data, u_int dlen)
1112 {
1113         struct mbuf mb;
1114
1115         /*
1116          * Craft on-stack mbuf suitable for passing to bpf_mtap.
1117          * Note that we cut corners here; we only setup what's
1118          * absolutely needed--this mbuf should never go anywhere else.
1119          */
1120         mb.m_next = m;
1121         mb.m_data = __DECONST(void *, data); /* LINTED */
1122         mb.m_len = dlen;
1123
1124         bpf_mtap(bp, &mb);
1125 }
1126
1127 /*
1128  * Move the packet data from interface memory (pkt) into the
1129  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
1130  * otherwise 0.  "copy" is the routine called to do the actual data
1131  * transfer.  bcopy is passed in to copy contiguous chunks, while
1132  * bpf_mcopy is passed in to copy mbuf chains.  In the latter case,
1133  * pkt is really an mbuf.
1134  */
1135 static void
1136 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
1137             void (*cpfn)(const void *, void *, size_t))
1138 {
1139         struct bpf_hdr *hp;
1140         int totlen, curlen;
1141         int hdrlen = d->bd_bif->bif_hdrlen;
1142         /*
1143          * Figure out how many bytes to move.  If the packet is
1144          * greater or equal to the snapshot length, transfer that
1145          * much.  Otherwise, transfer the whole packet (unless
1146          * we hit the buffer size limit).
1147          */
1148         totlen = hdrlen + min(snaplen, pktlen);
1149         if (totlen > d->bd_bufsize)
1150                 totlen = d->bd_bufsize;
1151
1152         /*
1153          * Round up the end of the previous packet to the next longword.
1154          */
1155         curlen = BPF_WORDALIGN(d->bd_slen);
1156         if (curlen + totlen > d->bd_bufsize) {
1157                 /*
1158                  * This packet will overflow the storage buffer.
1159                  * Rotate the buffers if we can, then wakeup any
1160                  * pending reads.
1161                  */
1162                 if (d->bd_fbuf == NULL) {
1163                         /*
1164                          * We haven't completed the previous read yet,
1165                          * so drop the packet.
1166                          */
1167                         ++d->bd_dcount;
1168                         return;
1169                 }
1170                 ROTATE_BUFFERS(d);
1171                 bpf_wakeup(d);
1172                 curlen = 0;
1173         }
1174         else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
1175                 /*
1176                  * Immediate mode is set, or the read timeout has
1177                  * already expired during a select call.  A packet
1178                  * arrived, so the reader should be woken up.
1179                  */
1180                 bpf_wakeup(d);
1181
1182         /*
1183          * Append the bpf header.
1184          */
1185         hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
1186         microtime(&hp->bh_tstamp);
1187         hp->bh_datalen = pktlen;
1188         hp->bh_hdrlen = hdrlen;
1189         /*
1190          * Copy the packet data into the store buffer and update its length.
1191          */
1192         (*cpfn)(pkt, (u_char *)hp + hdrlen, (hp->bh_caplen = totlen - hdrlen));
1193         d->bd_slen = curlen + totlen;
1194 }
1195
1196 /*
1197  * Initialize all nonzero fields of a descriptor.
1198  */
1199 static int
1200 bpf_allocbufs(struct bpf_d *d)
1201 {
1202         d->bd_fbuf = malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1203         if (d->bd_fbuf == NULL)
1204                 return(ENOBUFS);
1205
1206         d->bd_sbuf = malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1207         if (d->bd_sbuf == NULL) {
1208                 free(d->bd_fbuf, M_BPF);
1209                 return(ENOBUFS);
1210         }
1211         d->bd_slen = 0;
1212         d->bd_hlen = 0;
1213         return(0);
1214 }
1215
1216 /*
1217  * Free buffers currently in use by a descriptor.
1218  * Called on close.
1219  */
1220 static void
1221 bpf_freed(struct bpf_d *d)
1222 {
1223         /*
1224          * We don't need to lock out interrupts since this descriptor has
1225          * been detached from its interface and it yet hasn't been marked
1226          * free.
1227          */
1228         if (d->bd_sbuf != NULL) {
1229                 free(d->bd_sbuf, M_BPF);
1230                 if (d->bd_hbuf != NULL)
1231                         free(d->bd_hbuf, M_BPF);
1232                 if (d->bd_fbuf != NULL)
1233                         free(d->bd_fbuf, M_BPF);
1234         }
1235         if (d->bd_filter)
1236                 free(d->bd_filter, M_BPF);
1237 }
1238
1239 /*
1240  * Attach an interface to bpf.  ifp is a pointer to the structure
1241  * defining the interface to be attached, dlt is the link layer type,
1242  * and hdrlen is the fixed size of the link header (variable length
1243  * headers are not yet supported).
1244  */
1245 void
1246 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1247 {
1248         bpfattach_dlt(ifp, dlt, hdrlen, &ifp->if_bpf);
1249 }
1250
1251 void
1252 bpfattach_dlt(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
1253 {
1254         struct bpf_if *bp;
1255
1256         bp = malloc(sizeof *bp, M_BPF, M_WAITOK | M_ZERO);
1257
1258         SLIST_INIT(&bp->bif_dlist);
1259         bp->bif_ifp = ifp;
1260         bp->bif_dlt = dlt;
1261         bp->bif_driverp = driverp;
1262         *bp->bif_driverp = NULL;
1263
1264         bp->bif_next = bpf_iflist;
1265         bpf_iflist = bp;
1266
1267         /*
1268          * Compute the length of the bpf header.  This is not necessarily
1269          * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1270          * that the network layer header begins on a longword boundary (for
1271          * performance reasons and to alleviate alignment restrictions).
1272          */
1273         bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1274
1275         if (bootverbose)
1276                 if_printf(ifp, "bpf attached\n");
1277 }
1278
1279 /*
1280  * Detach bpf from an interface.  This involves detaching each descriptor
1281  * associated with the interface, and leaving bd_bif NULL.  Notify each
1282  * descriptor as it's detached so that any sleepers wake up and get
1283  * ENXIO.
1284  */
1285 void
1286 bpfdetach(struct ifnet *ifp)
1287 {
1288         struct bpf_if *bp, *bp_prev;
1289         struct bpf_d *d;
1290
1291         crit_enter();
1292
1293         /* Locate BPF interface information */
1294         bp_prev = NULL;
1295         for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1296                 if (ifp == bp->bif_ifp)
1297                         break;
1298                 bp_prev = bp;
1299         }
1300
1301         /* Interface wasn't attached */
1302         if (bp->bif_ifp == NULL) {
1303                 crit_exit();
1304                 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
1305                 return;
1306         }
1307
1308         while ((d = SLIST_FIRST(&bp->bif_dlist)) != NULL) {
1309                 bpf_detachd(d);
1310                 bpf_wakeup(d);
1311         }
1312
1313         if (bp_prev != NULL)
1314                 bp_prev->bif_next = bp->bif_next;
1315         else
1316                 bpf_iflist = bp->bif_next;
1317
1318         free(bp, M_BPF);
1319
1320         crit_exit();
1321 }
1322
1323 /*
1324  * Get a list of available data link type of the interface.
1325  */
1326 static int
1327 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
1328 {
1329         int n, error;
1330         struct ifnet *ifp;
1331         struct bpf_if *bp;
1332
1333         ifp = d->bd_bif->bif_ifp;
1334         n = 0;
1335         error = 0;
1336         for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
1337                 if (bp->bif_ifp != ifp)
1338                         continue;
1339                 if (bfl->bfl_list != NULL) {
1340                         if (n >= bfl->bfl_len) {
1341                                 return (ENOMEM);
1342                         }
1343                         error = copyout(&bp->bif_dlt,
1344                             bfl->bfl_list + n, sizeof(u_int));
1345                 }
1346                 n++;
1347         }
1348         bfl->bfl_len = n;
1349         return(error);
1350 }
1351
1352 /*
1353  * Set the data link type of a BPF instance.
1354  */
1355 static int
1356 bpf_setdlt(struct bpf_d *d, u_int dlt)
1357 {
1358         int error, opromisc;
1359         struct ifnet *ifp;
1360         struct bpf_if *bp;
1361
1362         if (d->bd_bif->bif_dlt == dlt)
1363                 return (0);
1364         ifp = d->bd_bif->bif_ifp;
1365         for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
1366                 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
1367                         break;
1368         }
1369         if (bp != NULL) {
1370                 opromisc = d->bd_promisc;
1371                 crit_enter();
1372                 bpf_detachd(d);
1373                 bpf_attachd(d, bp);
1374                 reset_d(d);
1375                 if (opromisc) {
1376                         error = ifpromisc(bp->bif_ifp, 1);
1377                         if (error)
1378                                 if_printf(bp->bif_ifp,
1379                                         "bpf_setdlt: ifpromisc failed (%d)\n",
1380                                         error);
1381                         else
1382                                 d->bd_promisc = 1;
1383                 }
1384                 crit_exit();
1385         }
1386         return(bp == NULL ? EINVAL : 0);
1387 }
1388
1389 static void
1390 bpf_drvinit(void *unused)
1391 {
1392         dev_ops_add(&bpf_ops, 0, 0);
1393 }
1394
1395 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,bpf_drvinit,NULL)
1396
1397 #else /* !BPF */
1398 /*
1399  * NOP stubs to allow bpf-using drivers to load and function.
1400  *
1401  * A 'better' implementation would allow the core bpf functionality
1402  * to be loaded at runtime.
1403  */
1404
1405 void
1406 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
1407 {
1408 }
1409
1410 void
1411 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
1412 {
1413 }
1414
1415 void
1416 bpf_ptap(struct bpf_if *bp, struct mbuf *m, const void *data, u_int dlen)
1417 {
1418 }
1419
1420 void
1421 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1422 {
1423 }
1424
1425 void
1426 bpfattach_dlt(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
1427 {
1428 }
1429
1430 void
1431 bpfdetach(struct ifnet *ifp)
1432 {
1433 }
1434
1435 u_int
1436 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
1437 {
1438         return -1;      /* "no filter" behaviour */
1439 }
1440
1441 #endif /* !BPF */