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
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 #include "opt_compat.h"
42 #include "opt_netgraph.h"
44 #include <sys/types.h>
45 #include <sys/param.h>
47 #include <sys/rwlock.h>
48 #include <sys/systm.h>
50 #include <sys/fcntl.h>
52 #include <sys/malloc.h>
57 #include <sys/signalvar.h>
58 #include <sys/filio.h>
59 #include <sys/sockio.h>
60 #include <sys/ttycom.h>
63 #include <sys/event.h>
68 #include <sys/socket.h>
73 #include <net/bpf_buffer.h>
75 #include <net/bpf_jitter.h>
77 #include <net/bpf_zerocopy.h>
78 #include <net/bpfdesc.h>
81 #include <netinet/in.h>
82 #include <netinet/if_ether.h>
83 #include <sys/kernel.h>
84 #include <sys/sysctl.h>
86 #include <net80211/ieee80211_freebsd.h>
88 #include <security/mac/mac_framework.h>
90 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
92 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
94 #define PRINET 26 /* interruptible */
96 #define SIZEOF_BPF_HDR(type) \
97 (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
99 #ifdef COMPAT_FREEBSD32
100 #include <sys/mount.h>
101 #include <compat/freebsd32/freebsd32.h>
102 #define BPF_ALIGNMENT32 sizeof(int32_t)
103 #define BPF_WORDALIGN32(x) (((x)+(BPF_ALIGNMENT32-1))&~(BPF_ALIGNMENT32-1))
107 * 32-bit version of structure prepended to each packet. We use this header
108 * instead of the standard one for 32-bit streams. We mark the a stream as
109 * 32-bit the first time we see a 32-bit compat ioctl request.
112 struct timeval32 bh_tstamp; /* time stamp */
113 uint32_t bh_caplen; /* length of captured portion */
114 uint32_t bh_datalen; /* original length of packet */
115 uint16_t bh_hdrlen; /* length of bpf header (this struct
116 plus alignment padding) */
120 struct bpf_program32 {
125 struct bpf_dltlist32 {
130 #define BIOCSETF32 _IOW('B', 103, struct bpf_program32)
131 #define BIOCSRTIMEOUT32 _IOW('B', 109, struct timeval32)
132 #define BIOCGRTIMEOUT32 _IOR('B', 110, struct timeval32)
133 #define BIOCGDLTLIST32 _IOWR('B', 121, struct bpf_dltlist32)
134 #define BIOCSETWF32 _IOW('B', 123, struct bpf_program32)
135 #define BIOCSETFNR32 _IOW('B', 130, struct bpf_program32)
139 * bpf_iflist is a list of BPF interface structures, each corresponding to a
140 * specific DLT. The same network interface might have several BPF interface
141 * structures registered by different layers in the stack (i.e., 802.11
142 * frames, ethernet frames, etc).
144 static LIST_HEAD(, bpf_if) bpf_iflist, bpf_freelist;
145 static struct mtx bpf_mtx; /* bpf global lock */
146 static int bpf_bpfd_cnt;
148 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
149 static void bpf_detachd(struct bpf_d *);
150 static void bpf_detachd_locked(struct bpf_d *);
151 static void bpf_freed(struct bpf_d *);
152 static int bpf_movein(struct uio *, int, struct ifnet *, struct mbuf **,
153 struct sockaddr *, int *, struct bpf_insn *);
154 static int bpf_setif(struct bpf_d *, struct ifreq *);
155 static void bpf_timed_out(void *);
157 bpf_wakeup(struct bpf_d *);
158 static void catchpacket(struct bpf_d *, u_char *, u_int, u_int,
159 void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
161 static void reset_d(struct bpf_d *);
162 static int bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
163 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
164 static int bpf_setdlt(struct bpf_d *, u_int);
165 static void filt_bpfdetach(struct knote *);
166 static int filt_bpfread(struct knote *, long);
167 static void bpf_drvinit(void *);
168 static int bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
170 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW, 0, "bpf sysctl");
171 int bpf_maxinsns = BPF_MAXINSNS;
172 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
173 &bpf_maxinsns, 0, "Maximum bpf program instructions");
174 static int bpf_zerocopy_enable = 0;
175 SYSCTL_INT(_net_bpf, OID_AUTO, zerocopy_enable, CTLFLAG_RW,
176 &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
177 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
178 bpf_stats_sysctl, "bpf statistics portal");
180 static VNET_DEFINE(int, bpf_optimize_writers) = 0;
181 #define V_bpf_optimize_writers VNET(bpf_optimize_writers)
182 SYSCTL_VNET_INT(_net_bpf, OID_AUTO, optimize_writers,
183 CTLFLAG_RW, &VNET_NAME(bpf_optimize_writers), 0,
184 "Do not send packets until BPF program is set");
186 static d_open_t bpfopen;
187 static d_read_t bpfread;
188 static d_write_t bpfwrite;
189 static d_ioctl_t bpfioctl;
190 static d_poll_t bpfpoll;
191 static d_kqfilter_t bpfkqfilter;
193 static struct cdevsw bpf_cdevsw = {
194 .d_version = D_VERSION,
201 .d_kqfilter = bpfkqfilter,
204 static struct filterops bpfread_filtops = {
206 .f_detach = filt_bpfdetach,
207 .f_event = filt_bpfread,
210 eventhandler_tag bpf_ifdetach_cookie = NULL;
213 * LOCKING MODEL USED BY BPF:
215 * 1) global lock (BPF_LOCK). Mutex, used to protect interface addition/removal,
216 * some global counters and every bpf_if reference.
217 * 2) Interface lock. Rwlock, used to protect list of BPF descriptors and their filters.
218 * 3) Descriptor lock. Mutex, used to protect BPF buffers and various structure fields
219 * used by bpf_mtap code.
223 * Global lock, interface lock, descriptor lock
225 * We have to acquire interface lock before descriptor main lock due to BPF_MTAP[2]
226 * working model. In many places (like bpf_detachd) we start with BPF descriptor
227 * (and we need to at least rlock it to get reliable interface pointer). This
228 * gives us potential LOR. As a result, we use global lock to protect from bpf_if
229 * change in every such place.
231 * Changing d->bd_bif is protected by 1) global lock, 2) interface lock and
232 * 3) descriptor main wlock.
233 * Reading bd_bif can be protected by any of these locks, typically global lock.
235 * Changing read/write BPF filter is protected by the same three locks,
236 * the same applies for reading.
238 * Sleeping in global lock is not allowed due to bpfdetach() using it.
242 * Wrapper functions for various buffering methods. If the set of buffer
243 * modes expands, we will probably want to introduce a switch data structure
244 * similar to protosw, et.
247 bpf_append_bytes(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
253 switch (d->bd_bufmode) {
254 case BPF_BUFMODE_BUFFER:
255 return (bpf_buffer_append_bytes(d, buf, offset, src, len));
257 case BPF_BUFMODE_ZBUF:
259 return (bpf_zerocopy_append_bytes(d, buf, offset, src, len));
262 panic("bpf_buf_append_bytes");
267 bpf_append_mbuf(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
273 switch (d->bd_bufmode) {
274 case BPF_BUFMODE_BUFFER:
275 return (bpf_buffer_append_mbuf(d, buf, offset, src, len));
277 case BPF_BUFMODE_ZBUF:
279 return (bpf_zerocopy_append_mbuf(d, buf, offset, src, len));
282 panic("bpf_buf_append_mbuf");
287 * This function gets called when the free buffer is re-assigned.
290 bpf_buf_reclaimed(struct bpf_d *d)
295 switch (d->bd_bufmode) {
296 case BPF_BUFMODE_BUFFER:
299 case BPF_BUFMODE_ZBUF:
300 bpf_zerocopy_buf_reclaimed(d);
304 panic("bpf_buf_reclaimed");
309 * If the buffer mechanism has a way to decide that a held buffer can be made
310 * free, then it is exposed via the bpf_canfreebuf() interface. (1) is
311 * returned if the buffer can be discarded, (0) is returned if it cannot.
314 bpf_canfreebuf(struct bpf_d *d)
319 switch (d->bd_bufmode) {
320 case BPF_BUFMODE_ZBUF:
321 return (bpf_zerocopy_canfreebuf(d));
327 * Allow the buffer model to indicate that the current store buffer is
328 * immutable, regardless of the appearance of space. Return (1) if the
329 * buffer is writable, and (0) if not.
332 bpf_canwritebuf(struct bpf_d *d)
336 switch (d->bd_bufmode) {
337 case BPF_BUFMODE_ZBUF:
338 return (bpf_zerocopy_canwritebuf(d));
344 * Notify buffer model that an attempt to write to the store buffer has
345 * resulted in a dropped packet, in which case the buffer may be considered
349 bpf_buffull(struct bpf_d *d)
354 switch (d->bd_bufmode) {
355 case BPF_BUFMODE_ZBUF:
356 bpf_zerocopy_buffull(d);
362 * Notify the buffer model that a buffer has moved into the hold position.
365 bpf_bufheld(struct bpf_d *d)
370 switch (d->bd_bufmode) {
371 case BPF_BUFMODE_ZBUF:
372 bpf_zerocopy_bufheld(d);
378 bpf_free(struct bpf_d *d)
381 switch (d->bd_bufmode) {
382 case BPF_BUFMODE_BUFFER:
383 return (bpf_buffer_free(d));
385 case BPF_BUFMODE_ZBUF:
386 return (bpf_zerocopy_free(d));
389 panic("bpf_buf_free");
394 bpf_uiomove(struct bpf_d *d, caddr_t buf, u_int len, struct uio *uio)
397 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
399 return (bpf_buffer_uiomove(d, buf, len, uio));
403 bpf_ioctl_sblen(struct bpf_d *d, u_int *i)
406 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
408 return (bpf_buffer_ioctl_sblen(d, i));
412 bpf_ioctl_getzmax(struct thread *td, struct bpf_d *d, size_t *i)
415 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
417 return (bpf_zerocopy_ioctl_getzmax(td, d, i));
421 bpf_ioctl_rotzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
424 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
426 return (bpf_zerocopy_ioctl_rotzbuf(td, d, bz));
430 bpf_ioctl_setzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
433 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
435 return (bpf_zerocopy_ioctl_setzbuf(td, d, bz));
439 * General BPF functions.
442 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
443 struct sockaddr *sockp, int *hdrlen, struct bpf_insn *wfilter)
445 const struct ieee80211_bpf_params *p;
446 struct ether_header *eh;
454 * Build a sockaddr based on the data link layer type.
455 * We do this at this level because the ethernet header
456 * is copied directly into the data field of the sockaddr.
457 * In the case of SLIP, there is no header and the packet
458 * is forwarded as is.
459 * Also, we are careful to leave room at the front of the mbuf
460 * for the link level header.
465 sockp->sa_family = AF_INET;
470 sockp->sa_family = AF_UNSPEC;
471 /* XXX Would MAXLINKHDR be better? */
472 hlen = ETHER_HDR_LEN;
476 sockp->sa_family = AF_IMPLINK;
481 sockp->sa_family = AF_UNSPEC;
487 * null interface types require a 4 byte pseudo header which
488 * corresponds to the address family of the packet.
490 sockp->sa_family = AF_UNSPEC;
494 case DLT_ATM_RFC1483:
496 * en atm driver requires 4-byte atm pseudo header.
497 * though it isn't standard, vpi:vci needs to be
500 sockp->sa_family = AF_UNSPEC;
501 hlen = 12; /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
505 sockp->sa_family = AF_UNSPEC;
506 hlen = 4; /* This should match PPP_HDRLEN */
509 case DLT_IEEE802_11: /* IEEE 802.11 wireless */
510 sockp->sa_family = AF_IEEE80211;
514 case DLT_IEEE802_11_RADIO: /* IEEE 802.11 wireless w/ phy params */
515 sockp->sa_family = AF_IEEE80211;
516 sockp->sa_len = 12; /* XXX != 0 */
517 hlen = sizeof(struct ieee80211_bpf_params);
524 len = uio->uio_resid;
525 if (len < hlen || len - hlen > ifp->if_mtu)
528 m = m_get2(len, M_WAITOK, MT_DATA, M_PKTHDR);
531 m->m_pkthdr.len = m->m_len = len;
534 error = uiomove(mtod(m, u_char *), len, uio);
538 slen = bpf_filter(wfilter, mtod(m, u_char *), len, len);
544 /* Check for multicast destination */
547 eh = mtod(m, struct ether_header *);
548 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
549 if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
550 ETHER_ADDR_LEN) == 0)
551 m->m_flags |= M_BCAST;
553 m->m_flags |= M_MCAST;
559 * Make room for link header, and copy it to sockaddr
562 if (sockp->sa_family == AF_IEEE80211) {
564 * Collect true length from the parameter header
565 * NB: sockp is known to be zero'd so if we do a
566 * short copy unspecified parameters will be
568 * NB: packet may not be aligned after stripping
572 p = mtod(m, const struct ieee80211_bpf_params *);
574 if (hlen > sizeof(sockp->sa_data)) {
579 bcopy(m->m_data, sockp->sa_data, hlen);
590 * Attach file to the bpf interface, i.e. make d listen on bp.
593 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
600 * Save sysctl value to protect from sysctl change
603 op_w = V_bpf_optimize_writers || d->bd_writer;
605 if (d->bd_bif != NULL)
606 bpf_detachd_locked(d);
608 * Point d at bp, and add d to the interface's list.
609 * Since there are many applicaiotns using BPF for
610 * sending raw packets only (dhcpd, cdpd are good examples)
611 * we can delay adding d to the list of active listeners until
612 * some filter is configured.
621 /* Add to writers-only list */
622 LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
624 * We decrement bd_writer on every filter set operation.
625 * First BIOCSETF is done by pcap_open_live() to set up
626 * snap length. After that appliation usually sets its own filter
630 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
637 CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
638 __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
641 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
645 * Add d to the list of active bp filters.
646 * Reuqires bpf_attachd() to be called before
649 bpf_upgraded(struct bpf_d *d)
658 * Filter can be set several times without specifying interface.
659 * Mark d as reader and exit.
671 /* Remove from writers-only list */
672 LIST_REMOVE(d, bd_next);
673 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
674 /* Mark d as reader */
680 CTR2(KTR_NET, "%s: upgrade required by pid %d", __func__, d->bd_pid);
682 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
686 * Detach a file from its interface.
689 bpf_detachd(struct bpf_d *d)
692 bpf_detachd_locked(d);
697 bpf_detachd_locked(struct bpf_d *d)
703 CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
707 /* Check if descriptor is attached */
708 if ((bp = d->bd_bif) == NULL)
714 /* Save bd_writer value */
715 error = d->bd_writer;
718 * Remove d from the interface's descriptor list.
720 LIST_REMOVE(d, bd_next);
729 /* Call event handler iff d is attached */
731 EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
734 * Check if this descriptor had requested promiscuous mode.
735 * If so, turn it off.
739 CURVNET_SET(ifp->if_vnet);
740 error = ifpromisc(ifp, 0);
742 if (error != 0 && error != ENXIO) {
744 * ENXIO can happen if a pccard is unplugged
745 * Something is really wrong if we were able to put
746 * the driver into promiscuous mode, but can't
749 if_printf(bp->bif_ifp,
750 "bpf_detach: ifpromisc failed (%d)\n", error);
756 * Close the descriptor by detaching it from its interface,
757 * deallocating its buffers, and marking it free.
762 struct bpf_d *d = data;
765 if (d->bd_state == BPF_WAITING)
766 callout_stop(&d->bd_callout);
767 d->bd_state = BPF_IDLE;
769 funsetown(&d->bd_sigio);
772 mac_bpfdesc_destroy(d);
774 seldrain(&d->bd_sel);
775 knlist_destroy(&d->bd_sel.si_note);
776 callout_drain(&d->bd_callout);
782 * Open ethernet device. Returns ENXIO for illegal minor device number,
783 * EBUSY if file is open by another process.
787 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
792 d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
793 error = devfs_set_cdevpriv(d, bpf_dtor);
800 * For historical reasons, perform a one-time initialization call to
801 * the buffer routines, even though we're not yet committed to a
802 * particular buffer method.
805 if ((flags & FREAD) == 0)
807 d->bd_hbuf_in_use = 0;
808 d->bd_bufmode = BPF_BUFMODE_BUFFER;
810 d->bd_direction = BPF_D_INOUT;
811 BPF_PID_REFRESH(d, td);
814 mac_bpfdesc_create(td->td_ucred, d);
816 mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
817 callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
818 knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
820 /* Allocate default buffers */
821 size = d->bd_bufsize;
822 bpf_buffer_ioctl_sblen(d, &size);
828 * bpfread - read next chunk of packets from buffers
831 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
838 error = devfs_get_cdevpriv((void **)&d);
843 * Restrict application to use a buffer the same size as
846 if (uio->uio_resid != d->bd_bufsize)
849 non_block = ((ioflag & O_NONBLOCK) != 0);
852 BPF_PID_REFRESH_CUR(d);
853 if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
857 if (d->bd_state == BPF_WAITING)
858 callout_stop(&d->bd_callout);
859 timed_out = (d->bd_state == BPF_TIMED_OUT);
860 d->bd_state = BPF_IDLE;
861 while (d->bd_hbuf_in_use) {
862 error = mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
863 PRINET|PCATCH, "bd_hbuf", 0);
870 * If the hold buffer is empty, then do a timed sleep, which
871 * ends when the timeout expires or when enough packets
872 * have arrived to fill the store buffer.
874 while (d->bd_hbuf == NULL) {
875 if (d->bd_slen != 0) {
877 * A packet(s) either arrived since the previous
878 * read or arrived while we were asleep.
880 if (d->bd_immediate || non_block || timed_out) {
882 * Rotate the buffers and return what's here
883 * if we are in immediate mode, non-blocking
884 * flag is set, or this descriptor timed out.
892 * No data is available, check to see if the bpf device
893 * is still pointed at a real interface. If not, return
894 * ENXIO so that the userland process knows to rebind
895 * it before using it again.
897 if (d->bd_bif == NULL) {
904 return (EWOULDBLOCK);
906 error = msleep(d, &d->bd_lock, PRINET|PCATCH,
908 if (error == EINTR || error == ERESTART) {
912 if (error == EWOULDBLOCK) {
914 * On a timeout, return what's in the buffer,
915 * which may be nothing. If there is something
916 * in the store buffer, we can rotate the buffers.
920 * We filled up the buffer in between
921 * getting the timeout and arriving
922 * here, so we don't need to rotate.
926 if (d->bd_slen == 0) {
935 * At this point, we know we have something in the hold slot.
937 d->bd_hbuf_in_use = 1;
941 * Move data from hold buffer into user space.
942 * We know the entire buffer is transferred since
943 * we checked above that the read buffer is bpf_bufsize bytes.
945 * We do not have to worry about simultaneous reads because
946 * we waited for sole access to the hold buffer above.
948 error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
951 KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
952 d->bd_fbuf = d->bd_hbuf;
955 bpf_buf_reclaimed(d);
956 d->bd_hbuf_in_use = 0;
957 wakeup(&d->bd_hbuf_in_use);
964 * If there are processes sleeping on this descriptor, wake them up.
967 bpf_wakeup(struct bpf_d *d)
971 if (d->bd_state == BPF_WAITING) {
972 callout_stop(&d->bd_callout);
973 d->bd_state = BPF_IDLE;
976 if (d->bd_async && d->bd_sig && d->bd_sigio)
977 pgsigio(&d->bd_sigio, d->bd_sig, 0);
979 selwakeuppri(&d->bd_sel, PRINET);
980 KNOTE_LOCKED(&d->bd_sel.si_note, 0);
984 bpf_timed_out(void *arg)
986 struct bpf_d *d = (struct bpf_d *)arg;
990 if (callout_pending(&d->bd_callout) || !callout_active(&d->bd_callout))
992 if (d->bd_state == BPF_WAITING) {
993 d->bd_state = BPF_TIMED_OUT;
1000 bpf_ready(struct bpf_d *d)
1003 BPFD_LOCK_ASSERT(d);
1005 if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
1007 if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1014 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1018 struct mbuf *m, *mc;
1019 struct sockaddr dst;
1022 error = devfs_get_cdevpriv((void **)&d);
1026 BPF_PID_REFRESH_CUR(d);
1028 /* XXX: locking required */
1029 if (d->bd_bif == NULL) {
1034 ifp = d->bd_bif->bif_ifp;
1036 if ((ifp->if_flags & IFF_UP) == 0) {
1041 if (uio->uio_resid == 0) {
1046 bzero(&dst, sizeof(dst));
1049 /* XXX: bpf_movein() can sleep */
1050 error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp,
1051 &m, &dst, &hlen, d->bd_wfilter);
1058 dst.sa_family = pseudo_AF_HDRCMPLT;
1060 if (d->bd_feedback) {
1061 mc = m_dup(m, M_NOWAIT);
1063 mc->m_pkthdr.rcvif = ifp;
1064 /* Set M_PROMISC for outgoing packets to be discarded. */
1065 if (d->bd_direction == BPF_D_INOUT)
1066 m->m_flags |= M_PROMISC;
1070 m->m_pkthdr.len -= hlen;
1072 m->m_data += hlen; /* XXX */
1074 CURVNET_SET(ifp->if_vnet);
1077 mac_bpfdesc_create_mbuf(d, m);
1079 mac_bpfdesc_create_mbuf(d, mc);
1083 error = (*ifp->if_output)(ifp, m, &dst, NULL);
1089 (*ifp->if_input)(ifp, mc);
1099 * Reset a descriptor by flushing its packet buffer and clearing the receive
1100 * and drop counts. This is doable for kernel-only buffers, but with
1101 * zero-copy buffers, we can't write to (or rotate) buffers that are
1102 * currently owned by userspace. It would be nice if we could encapsulate
1103 * this logic in the buffer code rather than here.
1106 reset_d(struct bpf_d *d)
1109 BPFD_LOCK_ASSERT(d);
1111 while (d->bd_hbuf_in_use)
1112 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1114 if ((d->bd_hbuf != NULL) &&
1115 (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1116 /* Free the hold buffer. */
1117 d->bd_fbuf = d->bd_hbuf;
1120 bpf_buf_reclaimed(d);
1122 if (bpf_canwritebuf(d))
1134 * FIONREAD Check for read packet available.
1135 * SIOCGIFADDR Get interface address - convenient hook to driver.
1136 * BIOCGBLEN Get buffer len [for read()].
1137 * BIOCSETF Set read filter.
1138 * BIOCSETFNR Set read filter without resetting descriptor.
1139 * BIOCSETWF Set write filter.
1140 * BIOCFLUSH Flush read packet buffer.
1141 * BIOCPROMISC Put interface into promiscuous mode.
1142 * BIOCGDLT Get link layer type.
1143 * BIOCGETIF Get interface name.
1144 * BIOCSETIF Set interface.
1145 * BIOCSRTIMEOUT Set read timeout.
1146 * BIOCGRTIMEOUT Get read timeout.
1147 * BIOCGSTATS Get packet stats.
1148 * BIOCIMMEDIATE Set immediate mode.
1149 * BIOCVERSION Get filter language version.
1150 * BIOCGHDRCMPLT Get "header already complete" flag
1151 * BIOCSHDRCMPLT Set "header already complete" flag
1152 * BIOCGDIRECTION Get packet direction flag
1153 * BIOCSDIRECTION Set packet direction flag
1154 * BIOCGTSTAMP Get time stamp format and resolution.
1155 * BIOCSTSTAMP Set time stamp format and resolution.
1156 * BIOCLOCK Set "locked" flag
1157 * BIOCFEEDBACK Set packet feedback mode.
1158 * BIOCSETZBUF Set current zero-copy buffer locations.
1159 * BIOCGETZMAX Get maximum zero-copy buffer size.
1160 * BIOCROTZBUF Force rotation of zero-copy buffer
1161 * BIOCSETBUFMODE Set buffer mode.
1162 * BIOCGETBUFMODE Get current buffer mode.
1166 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1172 error = devfs_get_cdevpriv((void **)&d);
1177 * Refresh PID associated with this descriptor.
1180 BPF_PID_REFRESH(d, td);
1181 if (d->bd_state == BPF_WAITING)
1182 callout_stop(&d->bd_callout);
1183 d->bd_state = BPF_IDLE;
1186 if (d->bd_locked == 1) {
1192 #ifdef COMPAT_FREEBSD32
1193 case BIOCGDLTLIST32:
1197 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1198 case BIOCGRTIMEOUT32:
1209 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1210 case BIOCSRTIMEOUT32:
1220 #ifdef COMPAT_FREEBSD32
1222 * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1223 * that it will get 32-bit packet headers.
1229 case BIOCGDLTLIST32:
1230 case BIOCGRTIMEOUT32:
1231 case BIOCSRTIMEOUT32:
1238 CURVNET_SET(TD_TO_VNET(td));
1246 * Check for read packet available.
1254 while (d->bd_hbuf_in_use)
1255 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1256 PRINET, "bd_hbuf", 0);
1269 if (d->bd_bif == NULL)
1272 ifp = d->bd_bif->bif_ifp;
1273 error = (*ifp->if_ioctl)(ifp, cmd, addr);
1279 * Get buffer len [for read()].
1283 *(u_int *)addr = d->bd_bufsize;
1288 * Set buffer length.
1291 error = bpf_ioctl_sblen(d, (u_int *)addr);
1295 * Set link layer read filter.
1300 #ifdef COMPAT_FREEBSD32
1305 error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1309 * Flush read packet buffer.
1318 * Put interface into promiscuous mode.
1321 if (d->bd_bif == NULL) {
1323 * No interface attached yet.
1328 if (d->bd_promisc == 0) {
1329 error = ifpromisc(d->bd_bif->bif_ifp, 1);
1336 * Get current data link type.
1340 if (d->bd_bif == NULL)
1343 *(u_int *)addr = d->bd_bif->bif_dlt;
1348 * Get a list of supported data link types.
1350 #ifdef COMPAT_FREEBSD32
1351 case BIOCGDLTLIST32:
1353 struct bpf_dltlist32 *list32;
1354 struct bpf_dltlist dltlist;
1356 list32 = (struct bpf_dltlist32 *)addr;
1357 dltlist.bfl_len = list32->bfl_len;
1358 dltlist.bfl_list = PTRIN(list32->bfl_list);
1360 if (d->bd_bif == NULL)
1363 error = bpf_getdltlist(d, &dltlist);
1365 list32->bfl_len = dltlist.bfl_len;
1374 if (d->bd_bif == NULL)
1377 error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1382 * Set data link type.
1386 if (d->bd_bif == NULL)
1389 error = bpf_setdlt(d, *(u_int *)addr);
1394 * Get interface name.
1398 if (d->bd_bif == NULL)
1401 struct ifnet *const ifp = d->bd_bif->bif_ifp;
1402 struct ifreq *const ifr = (struct ifreq *)addr;
1404 strlcpy(ifr->ifr_name, ifp->if_xname,
1405 sizeof(ifr->ifr_name));
1415 error = bpf_setif(d, (struct ifreq *)addr);
1423 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1424 case BIOCSRTIMEOUT32:
1427 struct timeval *tv = (struct timeval *)addr;
1428 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1429 struct timeval32 *tv32;
1430 struct timeval tv64;
1432 if (cmd == BIOCSRTIMEOUT32) {
1433 tv32 = (struct timeval32 *)addr;
1435 tv->tv_sec = tv32->tv_sec;
1436 tv->tv_usec = tv32->tv_usec;
1439 tv = (struct timeval *)addr;
1442 * Subtract 1 tick from tvtohz() since this isn't
1445 if ((error = itimerfix(tv)) == 0)
1446 d->bd_rtout = tvtohz(tv) - 1;
1454 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1455 case BIOCGRTIMEOUT32:
1459 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1460 struct timeval32 *tv32;
1461 struct timeval tv64;
1463 if (cmd == BIOCGRTIMEOUT32)
1467 tv = (struct timeval *)addr;
1469 tv->tv_sec = d->bd_rtout / hz;
1470 tv->tv_usec = (d->bd_rtout % hz) * tick;
1471 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1472 if (cmd == BIOCGRTIMEOUT32) {
1473 tv32 = (struct timeval32 *)addr;
1474 tv32->tv_sec = tv->tv_sec;
1475 tv32->tv_usec = tv->tv_usec;
1487 struct bpf_stat *bs = (struct bpf_stat *)addr;
1489 /* XXXCSJP overflow */
1490 bs->bs_recv = d->bd_rcount;
1491 bs->bs_drop = d->bd_dcount;
1496 * Set immediate mode.
1500 d->bd_immediate = *(u_int *)addr;
1506 struct bpf_version *bv = (struct bpf_version *)addr;
1508 bv->bv_major = BPF_MAJOR_VERSION;
1509 bv->bv_minor = BPF_MINOR_VERSION;
1514 * Get "header already complete" flag
1518 *(u_int *)addr = d->bd_hdrcmplt;
1523 * Set "header already complete" flag
1527 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1532 * Get packet direction flag
1534 case BIOCGDIRECTION:
1536 *(u_int *)addr = d->bd_direction;
1541 * Set packet direction flag
1543 case BIOCSDIRECTION:
1547 direction = *(u_int *)addr;
1548 switch (direction) {
1553 d->bd_direction = direction;
1563 * Get packet timestamp format and resolution.
1567 *(u_int *)addr = d->bd_tstamp;
1572 * Set packet timestamp format and resolution.
1578 func = *(u_int *)addr;
1579 if (BPF_T_VALID(func))
1580 d->bd_tstamp = func;
1588 d->bd_feedback = *(u_int *)addr;
1598 case FIONBIO: /* Non-blocking I/O */
1601 case FIOASYNC: /* Send signal on receive packets */
1603 d->bd_async = *(int *)addr;
1609 * XXX: Add some sort of locking here?
1610 * fsetown() can sleep.
1612 error = fsetown(*(int *)addr, &d->bd_sigio);
1617 *(int *)addr = fgetown(&d->bd_sigio);
1621 /* This is deprecated, FIOSETOWN should be used instead. */
1623 error = fsetown(-(*(int *)addr), &d->bd_sigio);
1626 /* This is deprecated, FIOGETOWN should be used instead. */
1628 *(int *)addr = -fgetown(&d->bd_sigio);
1631 case BIOCSRSIG: /* Set receive signal */
1635 sig = *(u_int *)addr;
1648 *(u_int *)addr = d->bd_sig;
1652 case BIOCGETBUFMODE:
1654 *(u_int *)addr = d->bd_bufmode;
1658 case BIOCSETBUFMODE:
1660 * Allow the buffering mode to be changed as long as we
1661 * haven't yet committed to a particular mode. Our
1662 * definition of commitment, for now, is whether or not a
1663 * buffer has been allocated or an interface attached, since
1664 * that's the point where things get tricky.
1666 switch (*(u_int *)addr) {
1667 case BPF_BUFMODE_BUFFER:
1670 case BPF_BUFMODE_ZBUF:
1671 if (bpf_zerocopy_enable)
1681 if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1682 d->bd_fbuf != NULL || d->bd_bif != NULL) {
1687 d->bd_bufmode = *(u_int *)addr;
1692 error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1696 error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1700 error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1708 * Set d's packet filter program to fp. If this file already has a filter,
1709 * free it and replace it. Returns EINVAL for bogus requests.
1711 * Note we need global lock here to serialize bpf_setf() and bpf_setif() calls
1712 * since reading d->bd_bif can't be protected by d or interface lock due to
1715 * Additionally, we have to acquire interface write lock due to bpf_mtap() uses
1716 * interface read lock to read all filers.
1720 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1722 #ifdef COMPAT_FREEBSD32
1723 struct bpf_program fp_swab;
1724 struct bpf_program32 *fp32;
1726 struct bpf_insn *fcode, *old;
1728 bpf_jit_filter *jfunc, *ofunc;
1734 #ifdef COMPAT_FREEBSD32
1739 fp32 = (struct bpf_program32 *)fp;
1740 fp_swab.bf_len = fp32->bf_len;
1741 fp_swab.bf_insns = (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1757 jfunc = ofunc = NULL;
1762 * Check new filter validness before acquiring any locks.
1763 * Allocate memory for new filter, if needed.
1766 if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1768 size = flen * sizeof(*fp->bf_insns);
1770 /* We're setting up new filter. Copy and check actual data. */
1771 fcode = malloc(size, M_BPF, M_WAITOK);
1772 if (copyin(fp->bf_insns, fcode, size) != 0 ||
1773 !bpf_validate(fcode, flen)) {
1778 /* Filter is copied inside fcode and is perfectly valid. */
1779 jfunc = bpf_jitter(fcode, flen);
1786 * Set up new filter.
1787 * Protect filter change by interface lock.
1788 * Additionally, we are protected by global lock here.
1790 if (d->bd_bif != NULL)
1791 BPFIF_WLOCK(d->bd_bif);
1793 if (cmd == BIOCSETWF) {
1794 old = d->bd_wfilter;
1795 d->bd_wfilter = fcode;
1797 old = d->bd_rfilter;
1798 d->bd_rfilter = fcode;
1800 ofunc = d->bd_bfilter;
1801 d->bd_bfilter = jfunc;
1803 if (cmd == BIOCSETF)
1806 if (fcode != NULL) {
1808 * Do not require upgrade by first BIOCSETF
1809 * (used to set snaplen) by pcap_open_live().
1811 if (d->bd_writer != 0 && --d->bd_writer == 0)
1813 CTR4(KTR_NET, "%s: filter function set by pid %d, "
1814 "bd_writer counter %d, need_upgrade %d",
1815 __func__, d->bd_pid, d->bd_writer, need_upgrade);
1819 if (d->bd_bif != NULL)
1820 BPFIF_WUNLOCK(d->bd_bif);
1825 bpf_destroy_jit_filter(ofunc);
1828 /* Move d to active readers list. */
1837 * Detach a file from its current interface (if attached at all) and attach
1838 * to the interface indicated by the name stored in ifr.
1839 * Return an errno or 0.
1842 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1845 struct ifnet *theywant;
1849 theywant = ifunit(ifr->ifr_name);
1850 if (theywant == NULL || theywant->if_bpf == NULL)
1853 bp = theywant->if_bpf;
1855 /* Check if interface is not being detached from BPF */
1857 if (bp->flags & BPFIF_FLAG_DYING) {
1864 * Behavior here depends on the buffering model. If we're using
1865 * kernel memory buffers, then we can allocate them here. If we're
1866 * using zero-copy, then the user process must have registered
1867 * buffers by the time we get here. If not, return an error.
1869 switch (d->bd_bufmode) {
1870 case BPF_BUFMODE_BUFFER:
1871 case BPF_BUFMODE_ZBUF:
1872 if (d->bd_sbuf == NULL)
1877 panic("bpf_setif: bufmode %d", d->bd_bufmode);
1879 if (bp != d->bd_bif)
1888 * Support for select() and poll() system calls
1890 * Return true iff the specific operation will not block indefinitely.
1891 * Otherwise, return false but make a note that a selwakeup() must be done.
1894 bpfpoll(struct cdev *dev, int events, struct thread *td)
1899 if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
1901 (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1904 * Refresh PID associated with this descriptor.
1906 revents = events & (POLLOUT | POLLWRNORM);
1908 BPF_PID_REFRESH(d, td);
1909 if (events & (POLLIN | POLLRDNORM)) {
1911 revents |= events & (POLLIN | POLLRDNORM);
1913 selrecord(td, &d->bd_sel);
1914 /* Start the read timeout if necessary. */
1915 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1916 callout_reset(&d->bd_callout, d->bd_rtout,
1918 d->bd_state = BPF_WAITING;
1927 * Support for kevent() system call. Register EVFILT_READ filters and
1928 * reject all others.
1931 bpfkqfilter(struct cdev *dev, struct knote *kn)
1935 if (devfs_get_cdevpriv((void **)&d) != 0 ||
1936 kn->kn_filter != EVFILT_READ)
1940 * Refresh PID associated with this descriptor.
1943 BPF_PID_REFRESH_CUR(d);
1944 kn->kn_fop = &bpfread_filtops;
1946 knlist_add(&d->bd_sel.si_note, kn, 1);
1953 filt_bpfdetach(struct knote *kn)
1955 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1957 knlist_remove(&d->bd_sel.si_note, kn, 0);
1961 filt_bpfread(struct knote *kn, long hint)
1963 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1966 BPFD_LOCK_ASSERT(d);
1967 ready = bpf_ready(d);
1969 kn->kn_data = d->bd_slen;
1970 while (d->bd_hbuf_in_use)
1971 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1972 PRINET, "bd_hbuf", 0);
1974 kn->kn_data += d->bd_hlen;
1975 } else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1976 callout_reset(&d->bd_callout, d->bd_rtout,
1978 d->bd_state = BPF_WAITING;
1984 #define BPF_TSTAMP_NONE 0
1985 #define BPF_TSTAMP_FAST 1
1986 #define BPF_TSTAMP_NORMAL 2
1987 #define BPF_TSTAMP_EXTERN 3
1990 bpf_ts_quality(int tstype)
1993 if (tstype == BPF_T_NONE)
1994 return (BPF_TSTAMP_NONE);
1995 if ((tstype & BPF_T_FAST) != 0)
1996 return (BPF_TSTAMP_FAST);
1998 return (BPF_TSTAMP_NORMAL);
2002 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
2007 quality = bpf_ts_quality(tstype);
2008 if (quality == BPF_TSTAMP_NONE)
2012 tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2014 *bt = *(struct bintime *)(tag + 1);
2015 return (BPF_TSTAMP_EXTERN);
2018 if (quality == BPF_TSTAMP_NORMAL)
2027 * Incoming linkage from device drivers. Process the packet pkt, of length
2028 * pktlen, which is stored in a contiguous buffer. The packet is parsed
2029 * by each process' filter, and if accepted, stashed into the corresponding
2033 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2043 gottime = BPF_TSTAMP_NONE;
2047 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2049 * We are not using any locks for d here because:
2050 * 1) any filter change is protected by interface
2052 * 2) destroying/detaching d is protected by interface
2056 /* XXX: Do not protect counter for the sake of performance. */
2059 * NB: We dont call BPF_CHECK_DIRECTION() here since there is no
2060 * way for the caller to indiciate to us whether this packet
2061 * is inbound or outbound. In the bpf_mtap() routines, we use
2062 * the interface pointers on the mbuf to figure it out.
2065 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2067 slen = (*(bf->func))(pkt, pktlen, pktlen);
2070 slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2073 * Filter matches. Let's to acquire write lock.
2078 if (gottime < bpf_ts_quality(d->bd_tstamp))
2079 gottime = bpf_gettime(&bt, d->bd_tstamp, NULL);
2081 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2083 catchpacket(d, pkt, pktlen, slen,
2084 bpf_append_bytes, &bt);
2091 #define BPF_CHECK_DIRECTION(d, r, i) \
2092 (((d)->bd_direction == BPF_D_IN && (r) != (i)) || \
2093 ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2096 * Incoming linkage from device drivers, when packet is in an mbuf chain.
2097 * Locking model is explained in bpf_tap().
2100 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2110 /* Skip outgoing duplicate packets. */
2111 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2112 m->m_flags &= ~M_PROMISC;
2116 pktlen = m_length(m, NULL);
2117 gottime = BPF_TSTAMP_NONE;
2121 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2122 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2126 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2127 /* XXX We cannot handle multiple mbufs. */
2128 if (bf != NULL && m->m_next == NULL)
2129 slen = (*(bf->func))(mtod(m, u_char *), pktlen, pktlen);
2132 slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2137 if (gottime < bpf_ts_quality(d->bd_tstamp))
2138 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2140 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2142 catchpacket(d, (u_char *)m, pktlen, slen,
2143 bpf_append_mbuf, &bt);
2151 * Incoming linkage from device drivers, when packet is in
2152 * an mbuf chain and to be prepended by a contiguous header.
2155 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2163 /* Skip outgoing duplicate packets. */
2164 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2165 m->m_flags &= ~M_PROMISC;
2169 pktlen = m_length(m, NULL);
2171 * Craft on-stack mbuf suitable for passing to bpf_filter.
2172 * Note that we cut corners here; we only setup what's
2173 * absolutely needed--this mbuf should never go anywhere else.
2180 gottime = BPF_TSTAMP_NONE;
2184 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2185 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2188 slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2193 if (gottime < bpf_ts_quality(d->bd_tstamp))
2194 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2196 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2198 catchpacket(d, (u_char *)&mb, pktlen, slen,
2199 bpf_append_mbuf, &bt);
2206 #undef BPF_CHECK_DIRECTION
2208 #undef BPF_TSTAMP_NONE
2209 #undef BPF_TSTAMP_FAST
2210 #undef BPF_TSTAMP_NORMAL
2211 #undef BPF_TSTAMP_EXTERN
2214 bpf_hdrlen(struct bpf_d *d)
2218 hdrlen = d->bd_bif->bif_hdrlen;
2219 #ifndef BURN_BRIDGES
2220 if (d->bd_tstamp == BPF_T_NONE ||
2221 BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2222 #ifdef COMPAT_FREEBSD32
2224 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2227 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2230 hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2231 #ifdef COMPAT_FREEBSD32
2233 hdrlen = BPF_WORDALIGN32(hdrlen);
2236 hdrlen = BPF_WORDALIGN(hdrlen);
2238 return (hdrlen - d->bd_bif->bif_hdrlen);
2242 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2246 struct timespec tsn;
2248 if ((tstype & BPF_T_MONOTONIC) == 0) {
2250 bintime_add(&bt2, &boottimebin);
2253 switch (BPF_T_FORMAT(tstype)) {
2254 case BPF_T_MICROTIME:
2255 bintime2timeval(bt, &tsm);
2256 ts->bt_sec = tsm.tv_sec;
2257 ts->bt_frac = tsm.tv_usec;
2259 case BPF_T_NANOTIME:
2260 bintime2timespec(bt, &tsn);
2261 ts->bt_sec = tsn.tv_sec;
2262 ts->bt_frac = tsn.tv_nsec;
2265 ts->bt_sec = bt->sec;
2266 ts->bt_frac = bt->frac;
2272 * Move the packet data from interface memory (pkt) into the
2273 * store buffer. "cpfn" is the routine called to do the actual data
2274 * transfer. bcopy is passed in to copy contiguous chunks, while
2275 * bpf_append_mbuf is passed in to copy mbuf chains. In the latter case,
2276 * pkt is really an mbuf.
2279 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2280 void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2283 struct bpf_xhdr hdr;
2284 #ifndef BURN_BRIDGES
2285 struct bpf_hdr hdr_old;
2286 #ifdef COMPAT_FREEBSD32
2287 struct bpf_hdr32 hdr32_old;
2290 int caplen, curlen, hdrlen, totlen;
2295 BPFD_LOCK_ASSERT(d);
2298 * Detect whether user space has released a buffer back to us, and if
2299 * so, move it from being a hold buffer to a free buffer. This may
2300 * not be the best place to do it (for example, we might only want to
2301 * run this check if we need the space), but for now it's a reliable
2304 if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2305 while (d->bd_hbuf_in_use)
2306 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2307 PRINET, "bd_hbuf", 0);
2308 d->bd_fbuf = d->bd_hbuf;
2311 bpf_buf_reclaimed(d);
2315 * Figure out how many bytes to move. If the packet is
2316 * greater or equal to the snapshot length, transfer that
2317 * much. Otherwise, transfer the whole packet (unless
2318 * we hit the buffer size limit).
2320 hdrlen = bpf_hdrlen(d);
2321 totlen = hdrlen + min(snaplen, pktlen);
2322 if (totlen > d->bd_bufsize)
2323 totlen = d->bd_bufsize;
2326 * Round up the end of the previous packet to the next longword.
2328 * Drop the packet if there's no room and no hope of room
2329 * If the packet would overflow the storage buffer or the storage
2330 * buffer is considered immutable by the buffer model, try to rotate
2331 * the buffer and wakeup pending processes.
2333 #ifdef COMPAT_FREEBSD32
2335 curlen = BPF_WORDALIGN32(d->bd_slen);
2338 curlen = BPF_WORDALIGN(d->bd_slen);
2339 if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2340 if (d->bd_fbuf == NULL) {
2342 * There's no room in the store buffer, and no
2343 * prospect of room, so drop the packet. Notify the
2350 while (d->bd_hbuf_in_use)
2351 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2352 PRINET, "bd_hbuf", 0);
2356 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2358 * Immediate mode is set, or the read timeout has already
2359 * expired during a select call. A packet arrived, so the
2360 * reader should be woken up.
2363 caplen = totlen - hdrlen;
2364 tstype = d->bd_tstamp;
2365 do_timestamp = tstype != BPF_T_NONE;
2366 #ifndef BURN_BRIDGES
2367 if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2370 bpf_bintime2ts(bt, &ts, tstype);
2371 #ifdef COMPAT_FREEBSD32
2372 if (d->bd_compat32) {
2373 bzero(&hdr32_old, sizeof(hdr32_old));
2375 hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2376 hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2378 hdr32_old.bh_datalen = pktlen;
2379 hdr32_old.bh_hdrlen = hdrlen;
2380 hdr32_old.bh_caplen = caplen;
2381 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2386 bzero(&hdr_old, sizeof(hdr_old));
2388 hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2389 hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2391 hdr_old.bh_datalen = pktlen;
2392 hdr_old.bh_hdrlen = hdrlen;
2393 hdr_old.bh_caplen = caplen;
2394 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2401 * Append the bpf header. Note we append the actual header size, but
2402 * move forward the length of the header plus padding.
2404 bzero(&hdr, sizeof(hdr));
2406 bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2407 hdr.bh_datalen = pktlen;
2408 hdr.bh_hdrlen = hdrlen;
2409 hdr.bh_caplen = caplen;
2410 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2413 * Copy the packet data into the store buffer and update its length.
2415 #ifndef BURN_BRIDGES
2418 (*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2419 d->bd_slen = curlen + totlen;
2426 * Free buffers currently in use by a descriptor.
2430 bpf_freed(struct bpf_d *d)
2434 * We don't need to lock out interrupts since this descriptor has
2435 * been detached from its interface and it yet hasn't been marked
2439 if (d->bd_rfilter != NULL) {
2440 free((caddr_t)d->bd_rfilter, M_BPF);
2442 if (d->bd_bfilter != NULL)
2443 bpf_destroy_jit_filter(d->bd_bfilter);
2446 if (d->bd_wfilter != NULL)
2447 free((caddr_t)d->bd_wfilter, M_BPF);
2448 mtx_destroy(&d->bd_lock);
2452 * Attach an interface to bpf. dlt is the link layer type; hdrlen is the
2453 * fixed size of the link header (variable length headers not yet supported).
2456 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2459 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2463 * Attach an interface to bpf. ifp is a pointer to the structure
2464 * defining the interface to be attached, dlt is the link layer type,
2465 * and hdrlen is the fixed size of the link header (variable length
2466 * headers are not yet supporrted).
2469 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2473 bp = malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
2477 LIST_INIT(&bp->bif_dlist);
2478 LIST_INIT(&bp->bif_wlist);
2481 rw_init(&bp->bif_lock, "bpf interface lock");
2482 KASSERT(*driverp == NULL, ("bpfattach2: driverp already initialized"));
2486 LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2489 bp->bif_hdrlen = hdrlen;
2492 if_printf(ifp, "bpf attached\n");
2496 * Detach bpf from an interface. This involves detaching each descriptor
2497 * associated with the interface. Notify each descriptor as it's detached
2498 * so that any sleepers wake up and get ENXIO.
2501 bpfdetach(struct ifnet *ifp)
2503 struct bpf_if *bp, *bp_temp;
2510 /* Find all bpf_if struct's which reference ifp and detach them. */
2511 LIST_FOREACH_SAFE(bp, &bpf_iflist, bif_next, bp_temp) {
2512 if (ifp != bp->bif_ifp)
2515 LIST_REMOVE(bp, bif_next);
2516 /* Add to to-be-freed list */
2517 LIST_INSERT_HEAD(&bpf_freelist, bp, bif_next);
2521 * Delay freeing bp till interface is detached
2522 * and all routes through this interface are removed.
2523 * Mark bp as detached to restrict new consumers.
2526 bp->flags |= BPFIF_FLAG_DYING;
2529 CTR4(KTR_NET, "%s: sheduling free for encap %d (%p) for if %p",
2530 __func__, bp->bif_dlt, bp, ifp);
2532 /* Free common descriptors */
2533 while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
2534 bpf_detachd_locked(d);
2540 /* Free writer-only descriptors */
2541 while ((d = LIST_FIRST(&bp->bif_wlist)) != NULL) {
2542 bpf_detachd_locked(d);
2552 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
2557 * Interface departure handler.
2558 * Note departure event does not guarantee interface is going down.
2559 * Interface renaming is currently done via departure/arrival event set.
2561 * Departure handled is called after all routes pointing to
2562 * given interface are removed and interface is in down state
2563 * restricting any packets to be sent/received. We assume it is now safe
2564 * to free data allocated by BPF.
2567 bpf_ifdetach(void *arg __unused, struct ifnet *ifp)
2569 struct bpf_if *bp, *bp_temp;
2574 * Find matching entries in free list.
2575 * Nothing should be found if bpfdetach() was not called.
2577 LIST_FOREACH_SAFE(bp, &bpf_freelist, bif_next, bp_temp) {
2578 if (ifp != bp->bif_ifp)
2581 CTR3(KTR_NET, "%s: freeing BPF instance %p for interface %p",
2584 LIST_REMOVE(bp, bif_next);
2586 rw_destroy(&bp->bif_lock);
2594 * Note that we cannot zero other pointers to
2595 * custom DLTs possibly used by given interface.
2602 * Get a list of available data link type of the interface.
2605 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2613 ifp = d->bd_bif->bif_ifp;
2616 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2617 if (bp->bif_ifp != ifp)
2619 if (bfl->bfl_list != NULL) {
2620 if (n >= bfl->bfl_len)
2622 error = copyout(&bp->bif_dlt,
2623 bfl->bfl_list + n, sizeof(u_int));
2632 * Set the data link type of a BPF instance.
2635 bpf_setdlt(struct bpf_d *d, u_int dlt)
2637 int error, opromisc;
2643 if (d->bd_bif->bif_dlt == dlt)
2645 ifp = d->bd_bif->bif_ifp;
2647 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2648 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2653 opromisc = d->bd_promisc;
2659 error = ifpromisc(bp->bif_ifp, 1);
2661 if_printf(bp->bif_ifp,
2662 "bpf_setdlt: ifpromisc failed (%d)\n",
2668 return (bp == NULL ? EINVAL : 0);
2672 bpf_drvinit(void *unused)
2676 mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
2677 LIST_INIT(&bpf_iflist);
2678 LIST_INIT(&bpf_freelist);
2680 dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2681 /* For compatibility */
2682 make_dev_alias(dev, "bpf0");
2684 /* Register interface departure handler */
2685 bpf_ifdetach_cookie = EVENTHANDLER_REGISTER(
2686 ifnet_departure_event, bpf_ifdetach, NULL,
2687 EVENTHANDLER_PRI_ANY);
2691 * Zero out the various packet counters associated with all of the bpf
2692 * descriptors. At some point, we will probably want to get a bit more
2693 * granular and allow the user to specify descriptors to be zeroed.
2696 bpf_zero_counters(void)
2702 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2704 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2720 * Fill filter statistics
2723 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2726 bzero(d, sizeof(*d));
2727 BPFD_LOCK_ASSERT(bd);
2728 d->bd_structsize = sizeof(*d);
2729 /* XXX: reading should be protected by global lock */
2730 d->bd_immediate = bd->bd_immediate;
2731 d->bd_promisc = bd->bd_promisc;
2732 d->bd_hdrcmplt = bd->bd_hdrcmplt;
2733 d->bd_direction = bd->bd_direction;
2734 d->bd_feedback = bd->bd_feedback;
2735 d->bd_async = bd->bd_async;
2736 d->bd_rcount = bd->bd_rcount;
2737 d->bd_dcount = bd->bd_dcount;
2738 d->bd_fcount = bd->bd_fcount;
2739 d->bd_sig = bd->bd_sig;
2740 d->bd_slen = bd->bd_slen;
2741 d->bd_hlen = bd->bd_hlen;
2742 d->bd_bufsize = bd->bd_bufsize;
2743 d->bd_pid = bd->bd_pid;
2744 strlcpy(d->bd_ifname,
2745 bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2746 d->bd_locked = bd->bd_locked;
2747 d->bd_wcount = bd->bd_wcount;
2748 d->bd_wdcount = bd->bd_wdcount;
2749 d->bd_wfcount = bd->bd_wfcount;
2750 d->bd_zcopy = bd->bd_zcopy;
2751 d->bd_bufmode = bd->bd_bufmode;
2755 * Handle `netstat -B' stats request
2758 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2760 static const struct xbpf_d zerostats;
2761 struct xbpf_d *xbdbuf, *xbd, tempstats;
2767 * XXX This is not technically correct. It is possible for non
2768 * privileged users to open bpf devices. It would make sense
2769 * if the users who opened the devices were able to retrieve
2770 * the statistics for them, too.
2772 error = priv_check(req->td, PRIV_NET_BPF);
2776 * Check to see if the user is requesting that the counters be
2777 * zeroed out. Explicitly check that the supplied data is zeroed,
2778 * as we aren't allowing the user to set the counters currently.
2780 if (req->newptr != NULL) {
2781 if (req->newlen != sizeof(tempstats))
2783 memset(&tempstats, 0, sizeof(tempstats));
2784 error = SYSCTL_IN(req, &tempstats, sizeof(tempstats));
2787 if (bcmp(&tempstats, &zerostats, sizeof(tempstats)) != 0)
2789 bpf_zero_counters();
2792 if (req->oldptr == NULL)
2793 return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
2794 if (bpf_bpfd_cnt == 0)
2795 return (SYSCTL_OUT(req, 0, 0));
2796 xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
2798 if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
2800 free(xbdbuf, M_BPF);
2804 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2806 /* Send writers-only first */
2807 LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
2808 xbd = &xbdbuf[index++];
2810 bpfstats_fill_xbpf(xbd, bd);
2813 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2814 xbd = &xbdbuf[index++];
2816 bpfstats_fill_xbpf(xbd, bd);
2822 error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
2823 free(xbdbuf, M_BPF);
2827 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
2829 #else /* !DEV_BPF && !NETGRAPH_BPF */
2831 * NOP stubs to allow bpf-using drivers to load and function.
2833 * A 'better' implementation would allow the core bpf functionality
2834 * to be loaded at runtime.
2836 static struct bpf_if bp_null;
2839 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2844 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2849 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
2854 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2857 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2861 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2864 *driverp = &bp_null;
2868 bpfdetach(struct ifnet *ifp)
2873 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
2875 return -1; /* "no filter" behaviour */
2879 bpf_validate(const struct bpf_insn *f, int len)
2881 return 0; /* false */
2884 #endif /* !DEV_BPF && !NETGRAPH_BPF */