2 * Copyright (c) 1990, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
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
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)bpf.c 8.4 (Berkeley) 1/9/95
41 #include "opt_netgraph.h"
43 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/systm.h>
47 #include <sys/fcntl.h>
49 #include <sys/malloc.h>
53 #include <sys/signalvar.h>
54 #include <sys/filio.h>
55 #include <sys/sockio.h>
56 #include <sys/ttycom.h>
59 #include <sys/event.h>
64 #include <sys/socket.h>
68 #include <net/bpfdesc.h>
70 #include <netinet/in.h>
71 #include <netinet/if_ether.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
75 static MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
77 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
79 #define PRINET 26 /* interruptible */
82 * bpf_iflist is a list of BPF interface structures, each corresponding to a
83 * specific DLT. The same network interface might have several BPF interface
84 * structures registered by different layers in the stack (i.e., 802.11
85 * frames, ethernet frames, etc).
87 static LIST_HEAD(, bpf_if) bpf_iflist;
88 static struct mtx bpf_mtx; /* bpf global lock */
89 static int bpf_bpfd_cnt;
91 static int bpf_allocbufs(struct bpf_d *);
92 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
93 static void bpf_detachd(struct bpf_d *);
94 static void bpf_freed(struct bpf_d *);
95 static void bpf_mcopy(const void *, void *, size_t);
96 static int bpf_movein(struct uio *, int, struct ifnet *,
97 struct mbuf **, struct sockaddr *, struct bpf_insn *);
98 static int bpf_setif(struct bpf_d *, struct ifreq *);
99 static void bpf_timed_out(void *);
101 bpf_wakeup(struct bpf_d *);
102 static void catchpacket(struct bpf_d *, u_char *, u_int,
103 u_int, void (*)(const void *, void *, size_t),
105 static void reset_d(struct bpf_d *);
106 static int bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
107 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
108 static int bpf_setdlt(struct bpf_d *, u_int);
109 static void filt_bpfdetach(struct knote *);
110 static int filt_bpfread(struct knote *, long);
111 static void bpf_drvinit(void *);
112 static void bpf_clone(void *, struct ucred *, char *, int, struct cdev **);
113 static int bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
116 * The default read buffer size is patchable.
118 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW, 0, "bpf sysctl");
119 static int bpf_bufsize = 4096;
120 SYSCTL_INT(_net_bpf, OID_AUTO, bufsize, CTLFLAG_RW,
121 &bpf_bufsize, 0, "");
122 static int bpf_maxbufsize = BPF_MAXBUFSIZE;
123 SYSCTL_INT(_net_bpf, OID_AUTO, maxbufsize, CTLFLAG_RW,
124 &bpf_maxbufsize, 0, "");
125 static int bpf_maxinsns = BPF_MAXINSNS;
126 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
127 &bpf_maxinsns, 0, "Maximum bpf program instructions");
128 SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_RW,
129 bpf_stats_sysctl, "bpf statistics portal");
131 static d_open_t bpfopen;
132 static d_close_t bpfclose;
133 static d_read_t bpfread;
134 static d_write_t bpfwrite;
135 static d_ioctl_t bpfioctl;
136 static d_poll_t bpfpoll;
137 static d_kqfilter_t bpfkqfilter;
139 static struct cdevsw bpf_cdevsw = {
140 .d_version = D_VERSION,
141 .d_flags = D_NEEDGIANT | D_TRACKCLOSE,
149 .d_kqfilter = bpfkqfilter,
152 static struct filterops bpfread_filtops =
153 { 1, NULL, filt_bpfdetach, filt_bpfread };
156 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
157 struct sockaddr *sockp, struct bpf_insn *wfilter)
159 struct ether_header *eh;
167 * Build a sockaddr based on the data link layer type.
168 * We do this at this level because the ethernet header
169 * is copied directly into the data field of the sockaddr.
170 * In the case of SLIP, there is no header and the packet
171 * is forwarded as is.
172 * Also, we are careful to leave room at the front of the mbuf
173 * for the link level header.
178 sockp->sa_family = AF_INET;
183 sockp->sa_family = AF_UNSPEC;
184 /* XXX Would MAXLINKHDR be better? */
185 hlen = ETHER_HDR_LEN;
189 sockp->sa_family = AF_IMPLINK;
194 sockp->sa_family = AF_UNSPEC;
200 * null interface types require a 4 byte pseudo header which
201 * corresponds to the address family of the packet.
203 sockp->sa_family = AF_UNSPEC;
207 case DLT_ATM_RFC1483:
209 * en atm driver requires 4-byte atm pseudo header.
210 * though it isn't standard, vpi:vci needs to be
213 sockp->sa_family = AF_UNSPEC;
214 hlen = 12; /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
218 sockp->sa_family = AF_UNSPEC;
219 hlen = 4; /* This should match PPP_HDRLEN */
226 len = uio->uio_resid;
228 if (len - hlen > ifp->if_mtu)
231 if ((unsigned)len > MJUM16BYTES)
235 MGETHDR(m, M_TRYWAIT, MT_DATA);
236 else if (len <= MCLBYTES)
237 m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
239 m = m_getjcl(M_TRYWAIT, MT_DATA, M_PKTHDR,
240 #if (MJUMPAGESIZE > MCLBYTES)
241 len <= MJUMPAGESIZE ? MJUMPAGESIZE :
243 (len <= MJUM9BYTES ? MJUM9BYTES : MJUM16BYTES));
246 m->m_pkthdr.len = m->m_len = len;
247 m->m_pkthdr.rcvif = NULL;
250 if (m->m_len < hlen) {
255 error = uiomove(mtod(m, u_char *), len, uio);
259 slen = bpf_filter(wfilter, mtod(m, u_char *), len, len);
265 /* Check for multicast destination */
268 eh = mtod(m, struct ether_header *);
269 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
270 if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
271 ETHER_ADDR_LEN) == 0)
272 m->m_flags |= M_BCAST;
274 m->m_flags |= M_MCAST;
280 * Make room for link header, and copy it to sockaddr
283 bcopy(m->m_data, sockp->sa_data, hlen);
284 m->m_pkthdr.len -= hlen;
287 m->m_data += hlen; /* XXX */
300 * Attach file to the bpf interface, i.e. make d listen on bp.
303 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
306 * Point d at bp, and add d to the interface's list of listeners.
307 * Finally, point the driver's bpf cookie at the interface so
308 * it will divert packets to bpf.
312 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
319 * Detach a file from its interface.
322 bpf_detachd(struct bpf_d *d)
331 ifp = d->bd_bif->bif_ifp;
334 * Remove d from the interface's descriptor list.
336 LIST_REMOVE(d, bd_next);
344 * Check if this descriptor had requested promiscuous mode.
345 * If so, turn it off.
349 error = ifpromisc(ifp, 0);
350 if (error != 0 && error != ENXIO) {
352 * ENXIO can happen if a pccard is unplugged
353 * Something is really wrong if we were able to put
354 * the driver into promiscuous mode, but can't
357 if_printf(bp->bif_ifp,
358 "bpf_detach: ifpromisc failed (%d)\n", error);
364 * Open ethernet device. Returns ENXIO for illegal minor device number,
365 * EBUSY if file is open by another process.
369 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
376 * Each minor can be opened by only one process. If the requested
377 * minor is in use, return EBUSY.
380 mtx_unlock(&bpf_mtx);
383 dev->si_drv1 = (struct bpf_d *)~0; /* mark device in use */
384 mtx_unlock(&bpf_mtx);
386 if ((dev->si_flags & SI_NAMED) == 0)
387 make_dev(&bpf_cdevsw, minor(dev), UID_ROOT, GID_WHEEL, 0600,
388 "bpf%d", dev2unit(dev));
389 MALLOC(d, struct bpf_d *, sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
391 d->bd_bufsize = bpf_bufsize;
394 d->bd_pid = td->td_proc->p_pid;
395 strlcpy(d->bd_pcomm, td->td_proc->p_comm, MAXCOMLEN);
398 mac_create_bpfdesc(td->td_ucred, d);
400 mtx_init(&d->bd_mtx, devtoname(dev), "bpf cdev lock", MTX_DEF);
401 callout_init(&d->bd_callout, NET_CALLOUT_MPSAFE);
402 knlist_init(&d->bd_sel.si_note, &d->bd_mtx, NULL, NULL, NULL);
408 * Close the descriptor by detaching it from its interface,
409 * deallocating its buffers, and marking it free.
413 bpfclose(struct cdev *dev, int flags, int fmt, struct thread *td)
415 struct bpf_d *d = dev->si_drv1;
418 if (d->bd_state == BPF_WAITING)
419 callout_stop(&d->bd_callout);
420 d->bd_state = BPF_IDLE;
422 funsetown(&d->bd_sigio);
426 mtx_unlock(&bpf_mtx);
427 selwakeuppri(&d->bd_sel, PRINET);
429 mac_destroy_bpfdesc(d);
431 knlist_destroy(&d->bd_sel.si_note);
441 * Rotate the packet buffers in descriptor d. Move the store buffer
442 * into the hold slot, and the free buffer into the store slot.
443 * Zero the length of the new store buffer.
445 #define ROTATE_BUFFERS(d) \
446 (d)->bd_hbuf = (d)->bd_sbuf; \
447 (d)->bd_hlen = (d)->bd_slen; \
448 (d)->bd_sbuf = (d)->bd_fbuf; \
452 * bpfread - read next chunk of packets from buffers
455 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
457 struct bpf_d *d = dev->si_drv1;
462 * Restrict application to use a buffer the same size as
465 if (uio->uio_resid != d->bd_bufsize)
469 d->bd_pid = curthread->td_proc->p_pid;
470 if (d->bd_state == BPF_WAITING)
471 callout_stop(&d->bd_callout);
472 timed_out = (d->bd_state == BPF_TIMED_OUT);
473 d->bd_state = BPF_IDLE;
475 * If the hold buffer is empty, then do a timed sleep, which
476 * ends when the timeout expires or when enough packets
477 * have arrived to fill the store buffer.
479 while (d->bd_hbuf == NULL) {
480 if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
482 * A packet(s) either arrived since the previous
483 * read or arrived while we were asleep.
484 * Rotate the buffers and return what's here.
491 * No data is available, check to see if the bpf device
492 * is still pointed at a real interface. If not, return
493 * ENXIO so that the userland process knows to rebind
494 * it before using it again.
496 if (d->bd_bif == NULL) {
501 if (ioflag & O_NONBLOCK) {
503 return (EWOULDBLOCK);
505 error = msleep(d, &d->bd_mtx, PRINET|PCATCH,
507 if (error == EINTR || error == ERESTART) {
511 if (error == EWOULDBLOCK) {
513 * On a timeout, return what's in the buffer,
514 * which may be nothing. If there is something
515 * in the store buffer, we can rotate the buffers.
519 * We filled up the buffer in between
520 * getting the timeout and arriving
521 * here, so we don't need to rotate.
525 if (d->bd_slen == 0) {
534 * At this point, we know we have something in the hold slot.
539 * Move data from hold buffer into user space.
540 * We know the entire buffer is transferred since
541 * we checked above that the read buffer is bpf_bufsize bytes.
543 error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
546 d->bd_fbuf = d->bd_hbuf;
556 * If there are processes sleeping on this descriptor, wake them up.
559 bpf_wakeup(struct bpf_d *d)
563 if (d->bd_state == BPF_WAITING) {
564 callout_stop(&d->bd_callout);
565 d->bd_state = BPF_IDLE;
568 if (d->bd_async && d->bd_sig && d->bd_sigio)
569 pgsigio(&d->bd_sigio, d->bd_sig, 0);
571 selwakeuppri(&d->bd_sel, PRINET);
572 KNOTE_LOCKED(&d->bd_sel.si_note, 0);
576 bpf_timed_out(void *arg)
578 struct bpf_d *d = (struct bpf_d *)arg;
581 if (d->bd_state == BPF_WAITING) {
582 d->bd_state = BPF_TIMED_OUT;
590 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
592 struct bpf_d *d = dev->si_drv1;
598 d->bd_pid = curthread->td_proc->p_pid;
599 if (d->bd_bif == NULL)
602 ifp = d->bd_bif->bif_ifp;
604 if ((ifp->if_flags & IFF_UP) == 0)
607 if (uio->uio_resid == 0)
610 bzero(&dst, sizeof(dst));
611 error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp,
612 &m, &dst, d->bd_wfilter);
617 dst.sa_family = pseudo_AF_HDRCMPLT;
621 mac_create_mbuf_from_bpfdesc(d, m);
625 error = (*ifp->if_output)(ifp, m, &dst, NULL);
628 * The driver frees the mbuf.
634 * Reset a descriptor by flushing its packet buffer and clearing the
635 * receive and drop counts.
638 reset_d(struct bpf_d *d)
641 mtx_assert(&d->bd_mtx, MA_OWNED);
643 /* Free the hold buffer. */
644 d->bd_fbuf = d->bd_hbuf;
655 * FIONREAD Check for read packet available.
656 * SIOCGIFADDR Get interface address - convenient hook to driver.
657 * BIOCGBLEN Get buffer len [for read()].
658 * BIOCSETF Set ethernet read filter.
659 * BIOCSETWF Set ethernet write filter.
660 * BIOCFLUSH Flush read packet buffer.
661 * BIOCPROMISC Put interface into promiscuous mode.
662 * BIOCGDLT Get link layer type.
663 * BIOCGETIF Get interface name.
664 * BIOCSETIF Set interface.
665 * BIOCSRTIMEOUT Set read timeout.
666 * BIOCGRTIMEOUT Get read timeout.
667 * BIOCGSTATS Get packet stats.
668 * BIOCIMMEDIATE Set immediate mode.
669 * BIOCVERSION Get filter language version.
670 * BIOCGHDRCMPLT Get "header already complete" flag
671 * BIOCSHDRCMPLT Set "header already complete" flag
672 * BIOCGSEESENT Get "see packets sent" flag
673 * BIOCSSEESENT Set "see packets sent" flag
674 * BIOCLOCK Set "locked" flag
678 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
681 struct bpf_d *d = dev->si_drv1;
685 * Refresh PID associated with this descriptor.
687 d->bd_pid = td->td_proc->p_pid;
689 if (d->bd_state == BPF_WAITING)
690 callout_stop(&d->bd_callout);
691 d->bd_state = BPF_IDLE;
694 if (d->bd_locked == 1) {
723 * Check for read packet available.
743 if (d->bd_bif == NULL)
746 ifp = d->bd_bif->bif_ifp;
747 error = (*ifp->if_ioctl)(ifp, cmd, addr);
753 * Get buffer len [for read()].
756 *(u_int *)addr = d->bd_bufsize;
763 if (d->bd_bif != NULL)
766 u_int size = *(u_int *)addr;
768 if (size > bpf_maxbufsize)
769 *(u_int *)addr = size = bpf_maxbufsize;
770 else if (size < BPF_MINBUFSIZE)
771 *(u_int *)addr = size = BPF_MINBUFSIZE;
772 d->bd_bufsize = size;
777 * Set link layer read filter.
781 error = bpf_setf(d, (struct bpf_program *)addr, cmd);
785 * Flush read packet buffer.
794 * Put interface into promiscuous mode.
797 if (d->bd_bif == NULL) {
799 * No interface attached yet.
804 if (d->bd_promisc == 0) {
806 error = ifpromisc(d->bd_bif->bif_ifp, 1);
814 * Get current data link type.
817 if (d->bd_bif == NULL)
820 *(u_int *)addr = d->bd_bif->bif_dlt;
824 * Get a list of supported data link types.
827 if (d->bd_bif == NULL)
830 error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
834 * Set data link type.
837 if (d->bd_bif == NULL)
840 error = bpf_setdlt(d, *(u_int *)addr);
844 * Get interface name.
847 if (d->bd_bif == NULL)
850 struct ifnet *const ifp = d->bd_bif->bif_ifp;
851 struct ifreq *const ifr = (struct ifreq *)addr;
853 strlcpy(ifr->ifr_name, ifp->if_xname,
854 sizeof(ifr->ifr_name));
862 error = bpf_setif(d, (struct ifreq *)addr);
870 struct timeval *tv = (struct timeval *)addr;
873 * Subtract 1 tick from tvtohz() since this isn't
876 if ((error = itimerfix(tv)) == 0)
877 d->bd_rtout = tvtohz(tv) - 1;
886 struct timeval *tv = (struct timeval *)addr;
888 tv->tv_sec = d->bd_rtout / hz;
889 tv->tv_usec = (d->bd_rtout % hz) * tick;
898 struct bpf_stat *bs = (struct bpf_stat *)addr;
900 bs->bs_recv = d->bd_rcount;
901 bs->bs_drop = d->bd_dcount;
906 * Set immediate mode.
909 d->bd_immediate = *(u_int *)addr;
914 struct bpf_version *bv = (struct bpf_version *)addr;
916 bv->bv_major = BPF_MAJOR_VERSION;
917 bv->bv_minor = BPF_MINOR_VERSION;
922 * Get "header already complete" flag
925 *(u_int *)addr = d->bd_hdrcmplt;
932 * Set "header already complete" flag
935 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
939 * Get "see sent packets" flag
942 *(u_int *)addr = d->bd_seesent;
946 * Set "see sent packets" flag
949 d->bd_seesent = *(u_int *)addr;
952 case FIONBIO: /* Non-blocking I/O */
955 case FIOASYNC: /* Send signal on receive packets */
956 d->bd_async = *(int *)addr;
960 error = fsetown(*(int *)addr, &d->bd_sigio);
964 *(int *)addr = fgetown(&d->bd_sigio);
967 /* This is deprecated, FIOSETOWN should be used instead. */
969 error = fsetown(-(*(int *)addr), &d->bd_sigio);
972 /* This is deprecated, FIOGETOWN should be used instead. */
974 *(int *)addr = -fgetown(&d->bd_sigio);
977 case BIOCSRSIG: /* Set receive signal */
981 sig = *(u_int *)addr;
990 *(u_int *)addr = d->bd_sig;
997 * Set d's packet filter program to fp. If this file already has a filter,
998 * free it and replace it. Returns EINVAL for bogus requests.
1001 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1003 struct bpf_insn *fcode, *old;
1004 u_int wfilter, flen, size;
1006 if (cmd == BIOCSETWF) {
1007 old = d->bd_wfilter;
1011 old = d->bd_rfilter;
1013 if (fp->bf_insns == NULL) {
1014 if (fp->bf_len != 0)
1018 d->bd_wfilter = NULL;
1020 d->bd_rfilter = NULL;
1024 free((caddr_t)old, M_BPF);
1028 if (flen > bpf_maxinsns)
1031 size = flen * sizeof(*fp->bf_insns);
1032 fcode = (struct bpf_insn *)malloc(size, M_BPF, M_WAITOK);
1033 if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) == 0 &&
1034 bpf_validate(fcode, (int)flen)) {
1037 d->bd_wfilter = fcode;
1039 d->bd_rfilter = fcode;
1043 free((caddr_t)old, M_BPF);
1047 free((caddr_t)fcode, M_BPF);
1052 * Detach a file from its current interface (if attached at all) and attach
1053 * to the interface indicated by the name stored in ifr.
1054 * Return an errno or 0.
1057 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1061 struct ifnet *theywant;
1063 theywant = ifunit(ifr->ifr_name);
1064 if (theywant == NULL || theywant->if_bpf == NULL)
1067 bp = theywant->if_bpf;
1069 * Allocate the packet buffers if we need to.
1070 * If we're already attached to requested interface,
1071 * just flush the buffer.
1073 if (d->bd_sbuf == NULL) {
1074 error = bpf_allocbufs(d);
1078 if (bp != d->bd_bif) {
1081 * Detach if attached to something else.
1094 * Support for select() and poll() system calls
1096 * Return true iff the specific operation will not block indefinitely.
1097 * Otherwise, return false but make a note that a selwakeup() must be done.
1100 bpfpoll(struct cdev *dev, int events, struct thread *td)
1106 if (d->bd_bif == NULL)
1110 * Refresh PID associated with this descriptor.
1112 d->bd_pid = td->td_proc->p_pid;
1113 revents = events & (POLLOUT | POLLWRNORM);
1115 if (events & (POLLIN | POLLRDNORM)) {
1117 revents |= events & (POLLIN | POLLRDNORM);
1119 selrecord(td, &d->bd_sel);
1120 /* Start the read timeout if necessary. */
1121 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1122 callout_reset(&d->bd_callout, d->bd_rtout,
1124 d->bd_state = BPF_WAITING;
1133 * Support for kevent() system call. Register EVFILT_READ filters and
1134 * reject all others.
1137 bpfkqfilter(struct cdev *dev, struct knote *kn)
1139 struct bpf_d *d = (struct bpf_d *)dev->si_drv1;
1141 if (kn->kn_filter != EVFILT_READ)
1145 * Refresh PID associated with this descriptor.
1147 d->bd_pid = curthread->td_proc->p_pid;
1148 kn->kn_fop = &bpfread_filtops;
1150 knlist_add(&d->bd_sel.si_note, kn, 0);
1156 filt_bpfdetach(struct knote *kn)
1158 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1160 knlist_remove(&d->bd_sel.si_note, kn, 0);
1164 filt_bpfread(struct knote *kn, long hint)
1166 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1169 BPFD_LOCK_ASSERT(d);
1170 ready = bpf_ready(d);
1172 kn->kn_data = d->bd_slen;
1174 kn->kn_data += d->bd_hlen;
1176 else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1177 callout_reset(&d->bd_callout, d->bd_rtout,
1179 d->bd_state = BPF_WAITING;
1186 * Incoming linkage from device drivers. Process the packet pkt, of length
1187 * pktlen, which is stored in a contiguous buffer. The packet is parsed
1188 * by each process' filter, and if accepted, stashed into the corresponding
1192 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
1201 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1204 slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
1212 if (mac_check_bpfdesc_receive(d, bp->bif_ifp) == 0)
1214 catchpacket(d, pkt, pktlen, slen, bcopy, &tv);
1222 * Copy data from an mbuf chain into a buffer. This code is derived
1223 * from m_copydata in sys/uipc_mbuf.c.
1226 bpf_mcopy(const void *src_arg, void *dst_arg, size_t len)
1228 const struct mbuf *m;
1237 count = min(m->m_len, len);
1238 bcopy(mtod(m, void *), dst, count);
1246 * Incoming linkage from device drivers, when packet is in an mbuf chain.
1249 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
1258 pktlen = m_length(m, NULL);
1261 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1262 if (!d->bd_seesent && (m->m_pkthdr.rcvif == NULL))
1266 slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
1274 if (mac_check_bpfdesc_receive(d, bp->bif_ifp) == 0)
1276 catchpacket(d, (u_char *)m, pktlen, slen,
1285 * Incoming linkage from device drivers, when packet is in
1286 * an mbuf chain and to be prepended by a contiguous header.
1289 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
1299 pktlen = m_length(m, NULL);
1301 * Craft on-stack mbuf suitable for passing to bpf_filter.
1302 * Note that we cut corners here; we only setup what's
1303 * absolutely needed--this mbuf should never go anywhere else.
1311 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1312 if (!d->bd_seesent && (m->m_pkthdr.rcvif == NULL))
1316 slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
1324 if (mac_check_bpfdesc_receive(d, bp->bif_ifp) == 0)
1326 catchpacket(d, (u_char *)&mb, pktlen, slen,
1335 * Move the packet data from interface memory (pkt) into the
1336 * store buffer. "cpfn" is the routine called to do the actual data
1337 * transfer. bcopy is passed in to copy contiguous chunks, while
1338 * bpf_mcopy is passed in to copy mbuf chains. In the latter case,
1339 * pkt is really an mbuf.
1342 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
1343 void (*cpfn)(const void *, void *, size_t), struct timeval *tv)
1347 int hdrlen = d->bd_bif->bif_hdrlen;
1350 BPFD_LOCK_ASSERT(d);
1352 * Figure out how many bytes to move. If the packet is
1353 * greater or equal to the snapshot length, transfer that
1354 * much. Otherwise, transfer the whole packet (unless
1355 * we hit the buffer size limit).
1357 totlen = hdrlen + min(snaplen, pktlen);
1358 if (totlen > d->bd_bufsize)
1359 totlen = d->bd_bufsize;
1362 * Round up the end of the previous packet to the next longword.
1364 curlen = BPF_WORDALIGN(d->bd_slen);
1365 if (curlen + totlen > d->bd_bufsize) {
1367 * This packet will overflow the storage buffer.
1368 * Rotate the buffers if we can, then wakeup any
1371 if (d->bd_fbuf == NULL) {
1373 * We haven't completed the previous read yet,
1374 * so drop the packet.
1383 else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
1385 * Immediate mode is set, or the read timeout has
1386 * already expired during a select call. A packet
1387 * arrived, so the reader should be woken up.
1392 * Append the bpf header.
1394 hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
1395 hp->bh_tstamp = *tv;
1396 hp->bh_datalen = pktlen;
1397 hp->bh_hdrlen = hdrlen;
1399 * Copy the packet data into the store buffer and update its length.
1401 (*cpfn)(pkt, (u_char *)hp + hdrlen, (hp->bh_caplen = totlen - hdrlen));
1402 d->bd_slen = curlen + totlen;
1409 * Initialize all nonzero fields of a descriptor.
1412 bpf_allocbufs(struct bpf_d *d)
1414 d->bd_fbuf = (caddr_t)malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1415 if (d->bd_fbuf == NULL)
1418 d->bd_sbuf = (caddr_t)malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1419 if (d->bd_sbuf == NULL) {
1420 free(d->bd_fbuf, M_BPF);
1429 * Free buffers currently in use by a descriptor.
1433 bpf_freed(struct bpf_d *d)
1436 * We don't need to lock out interrupts since this descriptor has
1437 * been detached from its interface and it yet hasn't been marked
1440 if (d->bd_sbuf != NULL) {
1441 free(d->bd_sbuf, M_BPF);
1442 if (d->bd_hbuf != NULL)
1443 free(d->bd_hbuf, M_BPF);
1444 if (d->bd_fbuf != NULL)
1445 free(d->bd_fbuf, M_BPF);
1448 free((caddr_t)d->bd_rfilter, M_BPF);
1450 free((caddr_t)d->bd_wfilter, M_BPF);
1451 mtx_destroy(&d->bd_mtx);
1455 * Attach an interface to bpf. dlt is the link layer type; hdrlen is the
1456 * fixed size of the link header (variable length headers not yet supported).
1459 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1462 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
1466 * Attach an interface to bpf. ifp is a pointer to the structure
1467 * defining the interface to be attached, dlt is the link layer type,
1468 * and hdrlen is the fixed size of the link header (variable length
1469 * headers are not yet supporrted).
1472 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
1476 bp = malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
1480 LIST_INIT(&bp->bif_dlist);
1483 mtx_init(&bp->bif_mtx, "bpf interface lock", NULL, MTX_DEF);
1484 KASSERT(*driverp == NULL, ("bpfattach2: driverp already initialized"));
1488 LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
1489 mtx_unlock(&bpf_mtx);
1492 * Compute the length of the bpf header. This is not necessarily
1493 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1494 * that the network layer header begins on a longword boundary (for
1495 * performance reasons and to alleviate alignment restrictions).
1497 bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1500 if_printf(ifp, "bpf attached\n");
1504 * Detach bpf from an interface. This involves detaching each descriptor
1505 * associated with the interface, and leaving bd_bif NULL. Notify each
1506 * descriptor as it's detached so that any sleepers wake up and get
1510 bpfdetach(struct ifnet *ifp)
1515 /* Locate BPF interface information */
1517 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1518 if (ifp == bp->bif_ifp)
1522 /* Interface wasn't attached */
1523 if ((bp == NULL) || (bp->bif_ifp == NULL)) {
1524 mtx_unlock(&bpf_mtx);
1525 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
1529 LIST_REMOVE(bp, bif_next);
1530 mtx_unlock(&bpf_mtx);
1532 while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
1539 mtx_destroy(&bp->bif_mtx);
1544 * Get a list of available data link type of the interface.
1547 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
1553 ifp = d->bd_bif->bif_ifp;
1557 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1558 if (bp->bif_ifp != ifp)
1560 if (bfl->bfl_list != NULL) {
1561 if (n >= bfl->bfl_len) {
1562 mtx_unlock(&bpf_mtx);
1565 error = copyout(&bp->bif_dlt,
1566 bfl->bfl_list + n, sizeof(u_int));
1570 mtx_unlock(&bpf_mtx);
1576 * Set the data link type of a BPF instance.
1579 bpf_setdlt(struct bpf_d *d, u_int dlt)
1581 int error, opromisc;
1585 if (d->bd_bif->bif_dlt == dlt)
1587 ifp = d->bd_bif->bif_ifp;
1589 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1590 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
1593 mtx_unlock(&bpf_mtx);
1595 opromisc = d->bd_promisc;
1602 error = ifpromisc(bp->bif_ifp, 1);
1604 if_printf(bp->bif_ifp,
1605 "bpf_setdlt: ifpromisc failed (%d)\n",
1611 return (bp == NULL ? EINVAL : 0);
1615 bpf_clone(void *arg, struct ucred *cred, char *name, int namelen,
1622 if (dev_stdclone(name, NULL, "bpf", &u) != 1)
1624 *dev = make_dev(&bpf_cdevsw, unit2minor(u), UID_ROOT, GID_WHEEL, 0600,
1627 (*dev)->si_flags |= SI_CHEAPCLONE;
1632 bpf_drvinit(void *unused)
1635 mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
1636 LIST_INIT(&bpf_iflist);
1637 EVENTHANDLER_REGISTER(dev_clone, bpf_clone, 0, 1000);
1641 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
1644 bzero(d, sizeof(*d));
1645 BPFD_LOCK_ASSERT(bd);
1646 d->bd_immediate = bd->bd_immediate;
1647 d->bd_promisc = bd->bd_promisc;
1648 d->bd_hdrcmplt = bd->bd_hdrcmplt;
1649 d->bd_seesent = bd->bd_seesent;
1650 d->bd_async = bd->bd_async;
1651 d->bd_rcount = bd->bd_rcount;
1652 d->bd_dcount = bd->bd_dcount;
1653 d->bd_fcount = bd->bd_fcount;
1654 d->bd_sig = bd->bd_sig;
1655 d->bd_slen = bd->bd_slen;
1656 d->bd_hlen = bd->bd_hlen;
1657 d->bd_bufsize = bd->bd_bufsize;
1658 d->bd_pid = bd->bd_pid;
1659 strlcpy(d->bd_ifname,
1660 bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
1661 strlcpy(d->bd_pcomm, bd->bd_pcomm, MAXCOMLEN);
1662 d->bd_locked = bd->bd_locked;
1666 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
1668 struct xbpf_d *xbdbuf, *xbd;
1674 * XXX This is not technically correct. It is possible for non
1675 * privileged users to open bpf devices. It would make sense
1676 * if the users who opened the devices were able to retrieve
1677 * the statistics for them, too.
1679 error = suser(req->td);
1682 if (req->oldptr == NULL)
1683 return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
1684 if (bpf_bpfd_cnt == 0)
1685 return (SYSCTL_OUT(req, 0, 0));
1686 xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
1688 if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
1689 mtx_unlock(&bpf_mtx);
1690 free(xbdbuf, M_BPF);
1694 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1696 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
1697 xbd = &xbdbuf[index++];
1699 bpfstats_fill_xbpf(xbd, bd);
1704 mtx_unlock(&bpf_mtx);
1705 error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
1706 free(xbdbuf, M_BPF);
1710 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL)
1712 #else /* !DEV_BPF && !NETGRAPH_BPF */
1714 * NOP stubs to allow bpf-using drivers to load and function.
1716 * A 'better' implementation would allow the core bpf functionality
1717 * to be loaded at runtime.
1719 static struct bpf_if bp_null;
1722 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
1727 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
1732 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
1737 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1740 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
1744 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
1747 *driverp = &bp_null;
1751 bpfdetach(struct ifnet *ifp)
1756 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
1758 return -1; /* "no filter" behaviour */
1762 bpf_validate(const struct bpf_insn *f, int len)
1764 return 0; /* false */
1767 #endif /* !DEV_BPF && !NETGRAPH_BPF */
1770 * ABI compatibility hacks. Older drivers check if_bpf against NULL
1771 * to see if there are active listeners. In the new ABI, if_bpf is
1772 * always non-NULL, so bpf_*tap() are always invoked. We check for
1773 * listeners in these wrappers and call the real functions if needed.
1779 void bpf_tap(struct bpf_if *, u_char *, u_int);
1780 void bpf_mtap(struct bpf_if *, struct mbuf *);
1781 void bpf_mtap2(struct bpf_if *, void *, u_int, struct mbuf *);
1784 bpf_tap(bp, pkt, pktlen)
1790 if (bpf_peers_present(bp))
1791 bpf_tap_new(bp, pkt, pktlen);
1800 if (bpf_peers_present(bp))
1801 bpf_mtap_new(bp, m);
1805 bpf_mtap2(bp, d, l, m)
1812 if (bpf_peers_present(bp))
1813 bpf_mtap2_new(bp, d, l, m);