2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1990, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * Copyright (c) 2019 Andrey V. Elsukov <ae@FreeBSD.org>
8 * This code is derived from the Stanford/CMU enet packet filter,
9 * (net/enet.c) distributed as part of 4.3BSD, and code contributed
10 * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
11 * Berkeley Laboratory.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @(#)bpf.c 8.4 (Berkeley) 1/9/95
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
45 #include "opt_netgraph.h"
47 #include <sys/param.h>
49 #include <sys/eventhandler.h>
50 #include <sys/fcntl.h>
54 #include <sys/malloc.h>
56 #include <sys/mutex.h>
60 #include <sys/signalvar.h>
61 #include <sys/filio.h>
62 #include <sys/sockio.h>
63 #include <sys/ttycom.h>
65 #include <sys/sysent.h>
66 #include <sys/systm.h>
68 #include <sys/event.h>
73 #include <sys/socket.h>
80 #include <net/if_var.h>
81 #include <net/if_vlan_var.h>
82 #include <net/if_dl.h>
84 #include <net/bpf_buffer.h>
86 #include <net/bpf_jitter.h>
88 #include <net/bpf_zerocopy.h>
89 #include <net/bpfdesc.h>
90 #include <net/route.h>
93 #include <netinet/in.h>
94 #include <netinet/if_ether.h>
95 #include <sys/kernel.h>
96 #include <sys/sysctl.h>
98 #include <net80211/ieee80211_freebsd.h>
100 #include <security/mac/mac_framework.h>
102 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
104 static struct bpf_if_ext dead_bpf_if = {
105 .bif_dlist = CK_LIST_HEAD_INITIALIZER()
109 #define bif_next bif_ext.bif_next
110 #define bif_dlist bif_ext.bif_dlist
111 struct bpf_if_ext bif_ext; /* public members */
112 u_int bif_dlt; /* link layer type */
113 u_int bif_hdrlen; /* length of link header */
114 struct bpfd_list bif_wlist; /* writer-only list */
115 struct ifnet *bif_ifp; /* corresponding interface */
116 struct bpf_if **bif_bpf; /* Pointer to pointer to us */
117 volatile u_int bif_refcnt;
118 struct epoch_context epoch_ctx;
121 CTASSERT(offsetof(struct bpf_if, bif_ext) == 0);
123 struct bpf_program_buffer {
124 struct epoch_context epoch_ctx;
126 bpf_jit_filter *func;
131 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
133 #define PRINET 26 /* interruptible */
134 #define BPF_PRIO_MAX 7
136 #define SIZEOF_BPF_HDR(type) \
137 (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
139 #ifdef COMPAT_FREEBSD32
140 #include <sys/mount.h>
141 #include <compat/freebsd32/freebsd32.h>
142 #define BPF_ALIGNMENT32 sizeof(int32_t)
143 #define BPF_WORDALIGN32(x) roundup2(x, BPF_ALIGNMENT32)
147 * 32-bit version of structure prepended to each packet. We use this header
148 * instead of the standard one for 32-bit streams. We mark the a stream as
149 * 32-bit the first time we see a 32-bit compat ioctl request.
152 struct timeval32 bh_tstamp; /* time stamp */
153 uint32_t bh_caplen; /* length of captured portion */
154 uint32_t bh_datalen; /* original length of packet */
155 uint16_t bh_hdrlen; /* length of bpf header (this struct
156 plus alignment padding) */
160 struct bpf_program32 {
165 struct bpf_dltlist32 {
170 #define BIOCSETF32 _IOW('B', 103, struct bpf_program32)
171 #define BIOCSRTIMEOUT32 _IOW('B', 109, struct timeval32)
172 #define BIOCGRTIMEOUT32 _IOR('B', 110, struct timeval32)
173 #define BIOCGDLTLIST32 _IOWR('B', 121, struct bpf_dltlist32)
174 #define BIOCSETWF32 _IOW('B', 123, struct bpf_program32)
175 #define BIOCSETFNR32 _IOW('B', 130, struct bpf_program32)
178 #define BPF_LOCK() sx_xlock(&bpf_sx)
179 #define BPF_UNLOCK() sx_xunlock(&bpf_sx)
180 #define BPF_LOCK_ASSERT() sx_assert(&bpf_sx, SA_XLOCKED)
182 * bpf_iflist is a list of BPF interface structures, each corresponding to a
183 * specific DLT. The same network interface might have several BPF interface
184 * structures registered by different layers in the stack (i.e., 802.11
185 * frames, ethernet frames, etc).
187 CK_LIST_HEAD(bpf_iflist, bpf_if);
188 static struct bpf_iflist bpf_iflist;
189 static struct sx bpf_sx; /* bpf global lock */
190 static int bpf_bpfd_cnt;
192 static void bpfif_ref(struct bpf_if *);
193 static void bpfif_rele(struct bpf_if *);
195 static void bpfd_ref(struct bpf_d *);
196 static void bpfd_rele(struct bpf_d *);
197 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
198 static void bpf_detachd(struct bpf_d *);
199 static void bpf_detachd_locked(struct bpf_d *, bool);
200 static void bpfd_free(epoch_context_t);
201 static int bpf_movein(struct uio *, int, struct ifnet *, struct mbuf **,
202 struct sockaddr *, int *, struct bpf_d *);
203 static int bpf_setif(struct bpf_d *, struct ifreq *);
204 static void bpf_timed_out(void *);
206 bpf_wakeup(struct bpf_d *);
207 static void catchpacket(struct bpf_d *, u_char *, u_int, u_int,
208 void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
210 static void reset_d(struct bpf_d *);
211 static int bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
212 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
213 static int bpf_setdlt(struct bpf_d *, u_int);
214 static void filt_bpfdetach(struct knote *);
215 static int filt_bpfread(struct knote *, long);
216 static int filt_bpfwrite(struct knote *, long);
217 static void bpf_drvinit(void *);
218 static int bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
220 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
222 int bpf_maxinsns = BPF_MAXINSNS;
223 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
224 &bpf_maxinsns, 0, "Maximum bpf program instructions");
225 static int bpf_zerocopy_enable = 0;
226 SYSCTL_INT(_net_bpf, OID_AUTO, zerocopy_enable, CTLFLAG_RW,
227 &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
228 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
229 bpf_stats_sysctl, "bpf statistics portal");
231 VNET_DEFINE_STATIC(int, bpf_optimize_writers) = 0;
232 #define V_bpf_optimize_writers VNET(bpf_optimize_writers)
233 SYSCTL_INT(_net_bpf, OID_AUTO, optimize_writers, CTLFLAG_VNET | CTLFLAG_RWTUN,
234 &VNET_NAME(bpf_optimize_writers), 0,
235 "Do not send packets until BPF program is set");
237 static d_open_t bpfopen;
238 static d_read_t bpfread;
239 static d_write_t bpfwrite;
240 static d_ioctl_t bpfioctl;
241 static d_poll_t bpfpoll;
242 static d_kqfilter_t bpfkqfilter;
244 static struct cdevsw bpf_cdevsw = {
245 .d_version = D_VERSION,
252 .d_kqfilter = bpfkqfilter,
255 static struct filterops bpfread_filtops = {
257 .f_detach = filt_bpfdetach,
258 .f_event = filt_bpfread,
261 static struct filterops bpfwrite_filtops = {
263 .f_detach = filt_bpfdetach,
264 .f_event = filt_bpfwrite,
268 * LOCKING MODEL USED BY BPF
271 * 1) global lock (BPF_LOCK). Sx, used to protect some global counters,
272 * every bpf_iflist changes, serializes ioctl access to bpf descriptors.
273 * 2) Descriptor lock. Mutex, used to protect BPF buffers and various
274 * structure fields used by bpf_*tap* code.
276 * Lock order: global lock, then descriptor lock.
278 * There are several possible consumers:
280 * 1. The kernel registers interface pointer with bpfattach().
281 * Each call allocates new bpf_if structure, references ifnet pointer
282 * and links bpf_if into bpf_iflist chain. This is protected with global
285 * 2. An userland application uses ioctl() call to bpf_d descriptor.
286 * All such call are serialized with global lock. BPF filters can be
287 * changed, but pointer to old filter will be freed using NET_EPOCH_CALL().
288 * Thus it should be safe for bpf_tap/bpf_mtap* code to do access to
289 * filter pointers, even if change will happen during bpf_tap execution.
290 * Destroying of bpf_d descriptor also is doing using NET_EPOCH_CALL().
292 * 3. An userland application can write packets into bpf_d descriptor.
293 * There we need to be sure, that ifnet won't disappear during bpfwrite().
295 * 4. The kernel invokes bpf_tap/bpf_mtap* functions. The access to
296 * bif_dlist is protected with net_epoch_preempt section. So, it should
297 * be safe to make access to bpf_d descriptor inside the section.
299 * 5. The kernel invokes bpfdetach() on interface destroying. All lists
300 * are modified with global lock held and actual free() is done using
305 bpfif_free(epoch_context_t ctx)
309 bp = __containerof(ctx, struct bpf_if, epoch_ctx);
310 if_rele(bp->bif_ifp);
315 bpfif_ref(struct bpf_if *bp)
318 refcount_acquire(&bp->bif_refcnt);
322 bpfif_rele(struct bpf_if *bp)
325 if (!refcount_release(&bp->bif_refcnt))
327 NET_EPOCH_CALL(bpfif_free, &bp->epoch_ctx);
331 bpfd_ref(struct bpf_d *d)
334 refcount_acquire(&d->bd_refcnt);
338 bpfd_rele(struct bpf_d *d)
341 if (!refcount_release(&d->bd_refcnt))
343 NET_EPOCH_CALL(bpfd_free, &d->epoch_ctx);
346 static struct bpf_program_buffer*
347 bpf_program_buffer_alloc(size_t size, int flags)
350 return (malloc(sizeof(struct bpf_program_buffer) + size,
355 bpf_program_buffer_free(epoch_context_t ctx)
357 struct bpf_program_buffer *ptr;
359 ptr = __containerof(ctx, struct bpf_program_buffer, epoch_ctx);
361 if (ptr->func != NULL)
362 bpf_destroy_jit_filter(ptr->func);
368 * Wrapper functions for various buffering methods. If the set of buffer
369 * modes expands, we will probably want to introduce a switch data structure
370 * similar to protosw, et.
373 bpf_append_bytes(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
379 switch (d->bd_bufmode) {
380 case BPF_BUFMODE_BUFFER:
381 return (bpf_buffer_append_bytes(d, buf, offset, src, len));
383 case BPF_BUFMODE_ZBUF:
384 counter_u64_add(d->bd_zcopy, 1);
385 return (bpf_zerocopy_append_bytes(d, buf, offset, src, len));
388 panic("bpf_buf_append_bytes");
393 bpf_append_mbuf(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
399 switch (d->bd_bufmode) {
400 case BPF_BUFMODE_BUFFER:
401 return (bpf_buffer_append_mbuf(d, buf, offset, src, len));
403 case BPF_BUFMODE_ZBUF:
404 counter_u64_add(d->bd_zcopy, 1);
405 return (bpf_zerocopy_append_mbuf(d, buf, offset, src, len));
408 panic("bpf_buf_append_mbuf");
413 * This function gets called when the free buffer is re-assigned.
416 bpf_buf_reclaimed(struct bpf_d *d)
421 switch (d->bd_bufmode) {
422 case BPF_BUFMODE_BUFFER:
425 case BPF_BUFMODE_ZBUF:
426 bpf_zerocopy_buf_reclaimed(d);
430 panic("bpf_buf_reclaimed");
435 * If the buffer mechanism has a way to decide that a held buffer can be made
436 * free, then it is exposed via the bpf_canfreebuf() interface. (1) is
437 * returned if the buffer can be discarded, (0) is returned if it cannot.
440 bpf_canfreebuf(struct bpf_d *d)
445 switch (d->bd_bufmode) {
446 case BPF_BUFMODE_ZBUF:
447 return (bpf_zerocopy_canfreebuf(d));
453 * Allow the buffer model to indicate that the current store buffer is
454 * immutable, regardless of the appearance of space. Return (1) if the
455 * buffer is writable, and (0) if not.
458 bpf_canwritebuf(struct bpf_d *d)
462 switch (d->bd_bufmode) {
463 case BPF_BUFMODE_ZBUF:
464 return (bpf_zerocopy_canwritebuf(d));
470 * Notify buffer model that an attempt to write to the store buffer has
471 * resulted in a dropped packet, in which case the buffer may be considered
475 bpf_buffull(struct bpf_d *d)
480 switch (d->bd_bufmode) {
481 case BPF_BUFMODE_ZBUF:
482 bpf_zerocopy_buffull(d);
488 * Notify the buffer model that a buffer has moved into the hold position.
491 bpf_bufheld(struct bpf_d *d)
496 switch (d->bd_bufmode) {
497 case BPF_BUFMODE_ZBUF:
498 bpf_zerocopy_bufheld(d);
504 bpf_free(struct bpf_d *d)
507 switch (d->bd_bufmode) {
508 case BPF_BUFMODE_BUFFER:
509 return (bpf_buffer_free(d));
511 case BPF_BUFMODE_ZBUF:
512 return (bpf_zerocopy_free(d));
515 panic("bpf_buf_free");
520 bpf_uiomove(struct bpf_d *d, caddr_t buf, u_int len, struct uio *uio)
523 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
525 return (bpf_buffer_uiomove(d, buf, len, uio));
529 bpf_ioctl_sblen(struct bpf_d *d, u_int *i)
532 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
534 return (bpf_buffer_ioctl_sblen(d, i));
538 bpf_ioctl_getzmax(struct thread *td, struct bpf_d *d, size_t *i)
541 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
543 return (bpf_zerocopy_ioctl_getzmax(td, d, i));
547 bpf_ioctl_rotzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
550 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
552 return (bpf_zerocopy_ioctl_rotzbuf(td, d, bz));
556 bpf_ioctl_setzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
559 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
561 return (bpf_zerocopy_ioctl_setzbuf(td, d, bz));
565 * General BPF functions.
568 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
569 struct sockaddr *sockp, int *hdrlen, struct bpf_d *d)
571 const struct ieee80211_bpf_params *p;
572 struct ether_header *eh;
580 * Build a sockaddr based on the data link layer type.
581 * We do this at this level because the ethernet header
582 * is copied directly into the data field of the sockaddr.
583 * In the case of SLIP, there is no header and the packet
584 * is forwarded as is.
585 * Also, we are careful to leave room at the front of the mbuf
586 * for the link level header.
590 sockp->sa_family = AF_INET;
595 sockp->sa_family = AF_UNSPEC;
596 /* XXX Would MAXLINKHDR be better? */
597 hlen = ETHER_HDR_LEN;
601 sockp->sa_family = AF_IMPLINK;
606 sockp->sa_family = AF_UNSPEC;
612 * null interface types require a 4 byte pseudo header which
613 * corresponds to the address family of the packet.
615 sockp->sa_family = AF_UNSPEC;
619 case DLT_ATM_RFC1483:
621 * en atm driver requires 4-byte atm pseudo header.
622 * though it isn't standard, vpi:vci needs to be
625 sockp->sa_family = AF_UNSPEC;
626 hlen = 12; /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
630 sockp->sa_family = AF_UNSPEC;
631 hlen = 4; /* This should match PPP_HDRLEN */
634 case DLT_IEEE802_11: /* IEEE 802.11 wireless */
635 sockp->sa_family = AF_IEEE80211;
639 case DLT_IEEE802_11_RADIO: /* IEEE 802.11 wireless w/ phy params */
640 sockp->sa_family = AF_IEEE80211;
641 sockp->sa_len = 12; /* XXX != 0 */
642 hlen = sizeof(struct ieee80211_bpf_params);
649 len = uio->uio_resid;
650 if (len < hlen || len - hlen > ifp->if_mtu)
653 /* Allocate a mbuf for our write, since m_get2 fails if len >= to MJUMPAGESIZE, use m_getjcl for bigger buffers */
654 m = m_get3(len, M_WAITOK, MT_DATA, M_PKTHDR);
657 m->m_pkthdr.len = m->m_len = len;
660 error = uiomove(mtod(m, u_char *), len, uio);
664 slen = bpf_filter(d->bd_wfilter, mtod(m, u_char *), len, len);
670 /* Check for multicast destination */
673 eh = mtod(m, struct ether_header *);
674 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
675 if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
676 ETHER_ADDR_LEN) == 0)
677 m->m_flags |= M_BCAST;
679 m->m_flags |= M_MCAST;
681 if (d->bd_hdrcmplt == 0) {
682 memcpy(eh->ether_shost, IF_LLADDR(ifp),
683 sizeof(eh->ether_shost));
689 * Make room for link header, and copy it to sockaddr
692 if (sockp->sa_family == AF_IEEE80211) {
694 * Collect true length from the parameter header
695 * NB: sockp is known to be zero'd so if we do a
696 * short copy unspecified parameters will be
698 * NB: packet may not be aligned after stripping
702 p = mtod(m, const struct ieee80211_bpf_params *);
704 if (hlen > sizeof(sockp->sa_data)) {
709 bcopy(mtod(m, const void *), sockp->sa_data, hlen);
720 * Attach descriptor to the bpf interface, i.e. make d listen on bp,
721 * then reset its buffers and counters with reset_d().
724 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
731 * Save sysctl value to protect from sysctl change
734 op_w = V_bpf_optimize_writers || d->bd_writer;
736 if (d->bd_bif != NULL)
737 bpf_detachd_locked(d, false);
739 * Point d at bp, and add d to the interface's list.
740 * Since there are many applications using BPF for
741 * sending raw packets only (dhcpd, cdpd are good examples)
742 * we can delay adding d to the list of active listeners until
743 * some filter is configured.
748 * Hold reference to bpif while descriptor uses this interface.
753 /* Add to writers-only list */
754 CK_LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
756 * We decrement bd_writer on every filter set operation.
757 * First BIOCSETF is done by pcap_open_live() to set up
758 * snap length. After that appliation usually sets its own
763 CK_LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
769 CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
770 __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
773 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
777 * Check if we need to upgrade our descriptor @d from write-only mode.
780 bpf_check_upgrade(u_long cmd, struct bpf_d *d, struct bpf_insn *fcode,
783 int is_snap, need_upgrade;
786 * Check if we've already upgraded or new filter is empty.
788 if (d->bd_writer == 0 || fcode == NULL)
794 * Check if cmd looks like snaplen setting from
795 * pcap_bpf.c:pcap_open_live().
796 * Note we're not checking .k value here:
797 * while pcap_open_live() definitely sets to non-zero value,
798 * we'd prefer to treat k=0 (deny ALL) case the same way: e.g.
799 * do not consider upgrading immediately
801 if (cmd == BIOCSETF && flen == 1 &&
802 fcode[0].code == (BPF_RET | BPF_K))
809 * We're setting first filter and it doesn't look like
810 * setting snaplen. We're probably using bpf directly.
811 * Upgrade immediately.
816 * Do not require upgrade by first BIOCSETF
817 * (used to set snaplen) by pcap_open_live().
820 if (--d->bd_writer == 0) {
822 * First snaplen filter has already
823 * been set. This is probably catch-all
831 "%s: filter function set by pid %d, "
832 "bd_writer counter %d, snap %d upgrade %d",
833 __func__, d->bd_pid, d->bd_writer,
834 is_snap, need_upgrade);
836 return (need_upgrade);
840 * Detach a file from its interface.
843 bpf_detachd(struct bpf_d *d)
846 bpf_detachd_locked(d, false);
851 bpf_detachd_locked(struct bpf_d *d, bool detached_ifp)
858 CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
860 /* Check if descriptor is attached */
861 if ((bp = d->bd_bif) == NULL)
865 /* Remove d from the interface's descriptor list. */
866 CK_LIST_REMOVE(d, bd_next);
867 /* Save bd_writer value */
868 error = d->bd_writer;
873 * Notify descriptor as it's detached, so that any
874 * sleepers wake up and get ENXIO.
881 /* Call event handler iff d is attached */
883 EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
886 * Check if this descriptor had requested promiscuous mode.
887 * If so and ifnet is not detached, turn it off.
889 if (d->bd_promisc && !detached_ifp) {
891 CURVNET_SET(ifp->if_vnet);
892 error = ifpromisc(ifp, 0);
894 if (error != 0 && error != ENXIO) {
896 * ENXIO can happen if a pccard is unplugged
897 * Something is really wrong if we were able to put
898 * the driver into promiscuous mode, but can't
901 if_printf(bp->bif_ifp,
902 "bpf_detach: ifpromisc failed (%d)\n", error);
909 * Close the descriptor by detaching it from its interface,
910 * deallocating its buffers, and marking it free.
915 struct bpf_d *d = data;
918 if (d->bd_state == BPF_WAITING)
919 callout_stop(&d->bd_callout);
920 d->bd_state = BPF_IDLE;
922 funsetown(&d->bd_sigio);
925 mac_bpfdesc_destroy(d);
927 seldrain(&d->bd_sel);
928 knlist_destroy(&d->bd_sel.si_note);
929 callout_drain(&d->bd_callout);
934 * Open ethernet device. Returns ENXIO for illegal minor device number,
935 * EBUSY if file is open by another process.
939 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
944 d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
945 error = devfs_set_cdevpriv(d, bpf_dtor);
952 d->bd_rcount = counter_u64_alloc(M_WAITOK);
953 d->bd_dcount = counter_u64_alloc(M_WAITOK);
954 d->bd_fcount = counter_u64_alloc(M_WAITOK);
955 d->bd_wcount = counter_u64_alloc(M_WAITOK);
956 d->bd_wfcount = counter_u64_alloc(M_WAITOK);
957 d->bd_wdcount = counter_u64_alloc(M_WAITOK);
958 d->bd_zcopy = counter_u64_alloc(M_WAITOK);
961 * For historical reasons, perform a one-time initialization call to
962 * the buffer routines, even though we're not yet committed to a
963 * particular buffer method.
966 if ((flags & FREAD) == 0)
968 d->bd_hbuf_in_use = 0;
969 d->bd_bufmode = BPF_BUFMODE_BUFFER;
971 d->bd_direction = BPF_D_INOUT;
973 BPF_PID_REFRESH(d, td);
976 mac_bpfdesc_create(td->td_ucred, d);
978 mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
979 callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
980 knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
982 /* Disable VLAN pcp tagging. */
989 * bpfread - read next chunk of packets from buffers
992 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
999 error = devfs_get_cdevpriv((void **)&d);
1004 * Restrict application to use a buffer the same size as
1005 * as kernel buffers.
1007 if (uio->uio_resid != d->bd_bufsize)
1010 non_block = ((ioflag & O_NONBLOCK) != 0);
1013 BPF_PID_REFRESH_CUR(d);
1014 if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
1016 return (EOPNOTSUPP);
1018 if (d->bd_state == BPF_WAITING)
1019 callout_stop(&d->bd_callout);
1020 timed_out = (d->bd_state == BPF_TIMED_OUT);
1021 d->bd_state = BPF_IDLE;
1022 while (d->bd_hbuf_in_use) {
1023 error = mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1024 PRINET|PCATCH, "bd_hbuf", 0);
1031 * If the hold buffer is empty, then do a timed sleep, which
1032 * ends when the timeout expires or when enough packets
1033 * have arrived to fill the store buffer.
1035 while (d->bd_hbuf == NULL) {
1036 if (d->bd_slen != 0) {
1038 * A packet(s) either arrived since the previous
1039 * read or arrived while we were asleep.
1041 if (d->bd_immediate || non_block || timed_out) {
1043 * Rotate the buffers and return what's here
1044 * if we are in immediate mode, non-blocking
1045 * flag is set, or this descriptor timed out.
1053 * No data is available, check to see if the bpf device
1054 * is still pointed at a real interface. If not, return
1055 * ENXIO so that the userland process knows to rebind
1056 * it before using it again.
1058 if (d->bd_bif == NULL) {
1065 return (EWOULDBLOCK);
1067 error = msleep(d, &d->bd_lock, PRINET|PCATCH,
1068 "bpf", d->bd_rtout);
1069 if (error == EINTR || error == ERESTART) {
1073 if (error == EWOULDBLOCK) {
1075 * On a timeout, return what's in the buffer,
1076 * which may be nothing. If there is something
1077 * in the store buffer, we can rotate the buffers.
1081 * We filled up the buffer in between
1082 * getting the timeout and arriving
1083 * here, so we don't need to rotate.
1087 if (d->bd_slen == 0) {
1096 * At this point, we know we have something in the hold slot.
1098 d->bd_hbuf_in_use = 1;
1102 * Move data from hold buffer into user space.
1103 * We know the entire buffer is transferred since
1104 * we checked above that the read buffer is bpf_bufsize bytes.
1106 * We do not have to worry about simultaneous reads because
1107 * we waited for sole access to the hold buffer above.
1109 error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
1112 KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
1113 d->bd_fbuf = d->bd_hbuf;
1116 bpf_buf_reclaimed(d);
1117 d->bd_hbuf_in_use = 0;
1118 wakeup(&d->bd_hbuf_in_use);
1125 * If there are processes sleeping on this descriptor, wake them up.
1127 static __inline void
1128 bpf_wakeup(struct bpf_d *d)
1131 BPFD_LOCK_ASSERT(d);
1132 if (d->bd_state == BPF_WAITING) {
1133 callout_stop(&d->bd_callout);
1134 d->bd_state = BPF_IDLE;
1137 if (d->bd_async && d->bd_sig && d->bd_sigio)
1138 pgsigio(&d->bd_sigio, d->bd_sig, 0);
1140 selwakeuppri(&d->bd_sel, PRINET);
1141 KNOTE_LOCKED(&d->bd_sel.si_note, 0);
1145 bpf_timed_out(void *arg)
1147 struct bpf_d *d = (struct bpf_d *)arg;
1149 BPFD_LOCK_ASSERT(d);
1151 if (callout_pending(&d->bd_callout) ||
1152 !callout_active(&d->bd_callout))
1154 if (d->bd_state == BPF_WAITING) {
1155 d->bd_state = BPF_TIMED_OUT;
1156 if (d->bd_slen != 0)
1162 bpf_ready(struct bpf_d *d)
1165 BPFD_LOCK_ASSERT(d);
1167 if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
1169 if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1176 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1179 struct sockaddr dst;
1180 struct epoch_tracker et;
1184 struct mbuf *m, *mc;
1187 error = devfs_get_cdevpriv((void **)&d);
1191 NET_EPOCH_ENTER(et);
1193 BPF_PID_REFRESH_CUR(d);
1194 counter_u64_add(d->bd_wcount, 1);
1195 if ((bp = d->bd_bif) == NULL) {
1201 if ((ifp->if_flags & IFF_UP) == 0) {
1206 if (uio->uio_resid == 0)
1209 bzero(&dst, sizeof(dst));
1214 * Take extra reference, unlock d and exit from epoch section,
1215 * since bpf_movein() can sleep.
1221 error = bpf_movein(uio, (int)bp->bif_dlt, ifp,
1222 &m, &dst, &hlen, d);
1225 counter_u64_add(d->bd_wdcount, 1);
1232 * Check that descriptor is still attached to the interface.
1233 * This can happen on bpfdetach(). To avoid access to detached
1234 * ifnet, free mbuf and return ENXIO.
1236 if (d->bd_bif == NULL) {
1237 counter_u64_add(d->bd_wdcount, 1);
1243 counter_u64_add(d->bd_wfcount, 1);
1245 dst.sa_family = pseudo_AF_HDRCMPLT;
1247 if (d->bd_feedback) {
1248 mc = m_dup(m, M_NOWAIT);
1250 mc->m_pkthdr.rcvif = ifp;
1251 /* Set M_PROMISC for outgoing packets to be discarded. */
1252 if (d->bd_direction == BPF_D_INOUT)
1253 m->m_flags |= M_PROMISC;
1257 m->m_pkthdr.len -= hlen;
1259 m->m_data += hlen; /* XXX */
1261 CURVNET_SET(ifp->if_vnet);
1263 mac_bpfdesc_create_mbuf(d, m);
1265 mac_bpfdesc_create_mbuf(d, mc);
1268 bzero(&ro, sizeof(ro));
1270 ro.ro_prepend = (u_char *)&dst.sa_data;
1272 ro.ro_flags = RT_HAS_HEADER;
1276 vlan_set_pcp(m, d->bd_pcp);
1278 /* Avoid possible recursion on BPFD_LOCK(). */
1279 NET_EPOCH_ENTER(et);
1281 error = (*ifp->if_output)(ifp, m, &dst, &ro);
1283 counter_u64_add(d->bd_wdcount, 1);
1287 (*ifp->if_input)(ifp, mc);
1297 counter_u64_add(d->bd_wdcount, 1);
1304 * Reset a descriptor by flushing its packet buffer and clearing the receive
1305 * and drop counts. This is doable for kernel-only buffers, but with
1306 * zero-copy buffers, we can't write to (or rotate) buffers that are
1307 * currently owned by userspace. It would be nice if we could encapsulate
1308 * this logic in the buffer code rather than here.
1311 reset_d(struct bpf_d *d)
1314 BPFD_LOCK_ASSERT(d);
1316 while (d->bd_hbuf_in_use)
1317 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1319 if ((d->bd_hbuf != NULL) &&
1320 (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1321 /* Free the hold buffer. */
1322 d->bd_fbuf = d->bd_hbuf;
1325 bpf_buf_reclaimed(d);
1327 if (bpf_canwritebuf(d))
1329 counter_u64_zero(d->bd_rcount);
1330 counter_u64_zero(d->bd_dcount);
1331 counter_u64_zero(d->bd_fcount);
1332 counter_u64_zero(d->bd_wcount);
1333 counter_u64_zero(d->bd_wfcount);
1334 counter_u64_zero(d->bd_wdcount);
1335 counter_u64_zero(d->bd_zcopy);
1339 * FIONREAD Check for read packet available.
1340 * BIOCGBLEN Get buffer len [for read()].
1341 * BIOCSETF Set read filter.
1342 * BIOCSETFNR Set read filter without resetting descriptor.
1343 * BIOCSETWF Set write filter.
1344 * BIOCFLUSH Flush read packet buffer.
1345 * BIOCPROMISC Put interface into promiscuous mode.
1346 * BIOCGDLT Get link layer type.
1347 * BIOCGETIF Get interface name.
1348 * BIOCSETIF Set interface.
1349 * BIOCSRTIMEOUT Set read timeout.
1350 * BIOCGRTIMEOUT Get read timeout.
1351 * BIOCGSTATS Get packet stats.
1352 * BIOCIMMEDIATE Set immediate mode.
1353 * BIOCVERSION Get filter language version.
1354 * BIOCGHDRCMPLT Get "header already complete" flag
1355 * BIOCSHDRCMPLT Set "header already complete" flag
1356 * BIOCGDIRECTION Get packet direction flag
1357 * BIOCSDIRECTION Set packet direction flag
1358 * BIOCGTSTAMP Get time stamp format and resolution.
1359 * BIOCSTSTAMP Set time stamp format and resolution.
1360 * BIOCLOCK Set "locked" flag
1361 * BIOCFEEDBACK Set packet feedback mode.
1362 * BIOCSETZBUF Set current zero-copy buffer locations.
1363 * BIOCGETZMAX Get maximum zero-copy buffer size.
1364 * BIOCROTZBUF Force rotation of zero-copy buffer
1365 * BIOCSETBUFMODE Set buffer mode.
1366 * BIOCGETBUFMODE Get current buffer mode.
1367 * BIOCSETVLANPCP Set VLAN PCP tag.
1371 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1377 error = devfs_get_cdevpriv((void **)&d);
1382 * Refresh PID associated with this descriptor.
1385 BPF_PID_REFRESH(d, td);
1386 if (d->bd_state == BPF_WAITING)
1387 callout_stop(&d->bd_callout);
1388 d->bd_state = BPF_IDLE;
1391 if (d->bd_locked == 1) {
1397 #ifdef COMPAT_FREEBSD32
1398 case BIOCGDLTLIST32:
1402 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1403 case BIOCGRTIMEOUT32:
1414 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1415 case BIOCSRTIMEOUT32:
1425 #ifdef COMPAT_FREEBSD32
1427 * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1428 * that it will get 32-bit packet headers.
1434 case BIOCGDLTLIST32:
1435 case BIOCGRTIMEOUT32:
1436 case BIOCSRTIMEOUT32:
1437 if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
1445 CURVNET_SET(TD_TO_VNET(td));
1452 * Check for read packet available.
1460 while (d->bd_hbuf_in_use)
1461 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1462 PRINET, "bd_hbuf", 0);
1472 * Get buffer len [for read()].
1476 *(u_int *)addr = d->bd_bufsize;
1481 * Set buffer length.
1484 error = bpf_ioctl_sblen(d, (u_int *)addr);
1488 * Set link layer read filter.
1493 #ifdef COMPAT_FREEBSD32
1498 error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1502 * Flush read packet buffer.
1511 * Put interface into promiscuous mode.
1514 if (d->bd_bif == NULL) {
1516 * No interface attached yet.
1521 if (d->bd_promisc == 0) {
1522 error = ifpromisc(d->bd_bif->bif_ifp, 1);
1529 * Get current data link type.
1533 if (d->bd_bif == NULL)
1536 *(u_int *)addr = d->bd_bif->bif_dlt;
1541 * Get a list of supported data link types.
1543 #ifdef COMPAT_FREEBSD32
1544 case BIOCGDLTLIST32:
1546 struct bpf_dltlist32 *list32;
1547 struct bpf_dltlist dltlist;
1549 list32 = (struct bpf_dltlist32 *)addr;
1550 dltlist.bfl_len = list32->bfl_len;
1551 dltlist.bfl_list = PTRIN(list32->bfl_list);
1553 if (d->bd_bif == NULL)
1556 error = bpf_getdltlist(d, &dltlist);
1558 list32->bfl_len = dltlist.bfl_len;
1567 if (d->bd_bif == NULL)
1570 error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1575 * Set data link type.
1579 if (d->bd_bif == NULL)
1582 error = bpf_setdlt(d, *(u_int *)addr);
1587 * Get interface name.
1591 if (d->bd_bif == NULL)
1594 struct ifnet *const ifp = d->bd_bif->bif_ifp;
1595 struct ifreq *const ifr = (struct ifreq *)addr;
1597 strlcpy(ifr->ifr_name, ifp->if_xname,
1598 sizeof(ifr->ifr_name));
1608 int alloc_buf, size;
1611 * Behavior here depends on the buffering model. If
1612 * we're using kernel memory buffers, then we can
1613 * allocate them here. If we're using zero-copy,
1614 * then the user process must have registered buffers
1615 * by the time we get here.
1619 if (d->bd_bufmode == BPF_BUFMODE_BUFFER &&
1624 size = d->bd_bufsize;
1625 error = bpf_buffer_ioctl_sblen(d, &size);
1630 error = bpf_setif(d, (struct ifreq *)addr);
1639 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1640 case BIOCSRTIMEOUT32:
1643 struct timeval *tv = (struct timeval *)addr;
1644 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1645 struct timeval32 *tv32;
1646 struct timeval tv64;
1648 if (cmd == BIOCSRTIMEOUT32) {
1649 tv32 = (struct timeval32 *)addr;
1651 tv->tv_sec = tv32->tv_sec;
1652 tv->tv_usec = tv32->tv_usec;
1655 tv = (struct timeval *)addr;
1658 * Subtract 1 tick from tvtohz() since this isn't
1661 if ((error = itimerfix(tv)) == 0)
1662 d->bd_rtout = tvtohz(tv) - 1;
1670 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1671 case BIOCGRTIMEOUT32:
1675 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1676 struct timeval32 *tv32;
1677 struct timeval tv64;
1679 if (cmd == BIOCGRTIMEOUT32)
1683 tv = (struct timeval *)addr;
1685 tv->tv_sec = d->bd_rtout / hz;
1686 tv->tv_usec = (d->bd_rtout % hz) * tick;
1687 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1688 if (cmd == BIOCGRTIMEOUT32) {
1689 tv32 = (struct timeval32 *)addr;
1690 tv32->tv_sec = tv->tv_sec;
1691 tv32->tv_usec = tv->tv_usec;
1703 struct bpf_stat *bs = (struct bpf_stat *)addr;
1705 /* XXXCSJP overflow */
1706 bs->bs_recv = (u_int)counter_u64_fetch(d->bd_rcount);
1707 bs->bs_drop = (u_int)counter_u64_fetch(d->bd_dcount);
1712 * Set immediate mode.
1716 d->bd_immediate = *(u_int *)addr;
1722 struct bpf_version *bv = (struct bpf_version *)addr;
1724 bv->bv_major = BPF_MAJOR_VERSION;
1725 bv->bv_minor = BPF_MINOR_VERSION;
1730 * Get "header already complete" flag
1734 *(u_int *)addr = d->bd_hdrcmplt;
1739 * Set "header already complete" flag
1743 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1748 * Get packet direction flag
1750 case BIOCGDIRECTION:
1752 *(u_int *)addr = d->bd_direction;
1757 * Set packet direction flag
1759 case BIOCSDIRECTION:
1763 direction = *(u_int *)addr;
1764 switch (direction) {
1769 d->bd_direction = direction;
1779 * Get packet timestamp format and resolution.
1783 *(u_int *)addr = d->bd_tstamp;
1788 * Set packet timestamp format and resolution.
1794 func = *(u_int *)addr;
1795 if (BPF_T_VALID(func))
1796 d->bd_tstamp = func;
1804 d->bd_feedback = *(u_int *)addr;
1814 case FIONBIO: /* Non-blocking I/O */
1817 case FIOASYNC: /* Send signal on receive packets */
1819 d->bd_async = *(int *)addr;
1825 * XXX: Add some sort of locking here?
1826 * fsetown() can sleep.
1828 error = fsetown(*(int *)addr, &d->bd_sigio);
1833 *(int *)addr = fgetown(&d->bd_sigio);
1837 /* This is deprecated, FIOSETOWN should be used instead. */
1839 error = fsetown(-(*(int *)addr), &d->bd_sigio);
1842 /* This is deprecated, FIOGETOWN should be used instead. */
1844 *(int *)addr = -fgetown(&d->bd_sigio);
1847 case BIOCSRSIG: /* Set receive signal */
1851 sig = *(u_int *)addr;
1864 *(u_int *)addr = d->bd_sig;
1868 case BIOCGETBUFMODE:
1870 *(u_int *)addr = d->bd_bufmode;
1874 case BIOCSETBUFMODE:
1876 * Allow the buffering mode to be changed as long as we
1877 * haven't yet committed to a particular mode. Our
1878 * definition of commitment, for now, is whether or not a
1879 * buffer has been allocated or an interface attached, since
1880 * that's the point where things get tricky.
1882 switch (*(u_int *)addr) {
1883 case BPF_BUFMODE_BUFFER:
1886 case BPF_BUFMODE_ZBUF:
1887 if (bpf_zerocopy_enable)
1897 if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1898 d->bd_fbuf != NULL || d->bd_bif != NULL) {
1903 d->bd_bufmode = *(u_int *)addr;
1908 error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1912 error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1916 error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1919 case BIOCSETVLANPCP:
1923 pcp = *(u_int *)addr;
1924 if (pcp > BPF_PRIO_MAX || pcp < 0) {
1937 * Set d's packet filter program to fp. If this file already has a filter,
1938 * free it and replace it. Returns EINVAL for bogus requests.
1940 * Note we use global lock here to serialize bpf_setf() and bpf_setif()
1944 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1946 #ifdef COMPAT_FREEBSD32
1947 struct bpf_program fp_swab;
1948 struct bpf_program32 *fp32;
1950 struct bpf_program_buffer *fcode;
1951 struct bpf_insn *filter;
1953 bpf_jit_filter *jfunc;
1959 #ifdef COMPAT_FREEBSD32
1964 fp32 = (struct bpf_program32 *)fp;
1965 fp_swab.bf_len = fp32->bf_len;
1967 (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1986 * Check new filter validness before acquiring any locks.
1987 * Allocate memory for new filter, if needed.
1990 if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1992 size = flen * sizeof(*fp->bf_insns);
1994 /* We're setting up new filter. Copy and check actual data. */
1995 fcode = bpf_program_buffer_alloc(size, M_WAITOK);
1996 filter = (struct bpf_insn *)fcode->buffer;
1997 if (copyin(fp->bf_insns, filter, size) != 0 ||
1998 !bpf_validate(filter, flen)) {
2003 if (cmd != BIOCSETWF) {
2005 * Filter is copied inside fcode and is
2008 jfunc = bpf_jitter(filter, flen);
2013 track_event = false;
2018 /* Set up new filter. */
2019 if (cmd == BIOCSETWF) {
2020 if (d->bd_wfilter != NULL) {
2021 fcode = __containerof((void *)d->bd_wfilter,
2022 struct bpf_program_buffer, buffer);
2027 d->bd_wfilter = filter;
2029 if (d->bd_rfilter != NULL) {
2030 fcode = __containerof((void *)d->bd_rfilter,
2031 struct bpf_program_buffer, buffer);
2033 fcode->func = d->bd_bfilter;
2036 d->bd_rfilter = filter;
2038 d->bd_bfilter = jfunc;
2040 if (cmd == BIOCSETF)
2043 if (bpf_check_upgrade(cmd, d, filter, flen) != 0) {
2045 * Filter can be set several times without
2046 * specifying interface. In this case just mark d
2050 if (d->bd_bif != NULL) {
2052 * Remove descriptor from writers-only list
2053 * and add it to active readers list.
2055 CK_LIST_REMOVE(d, bd_next);
2056 CK_LIST_INSERT_HEAD(&d->bd_bif->bif_dlist,
2059 "%s: upgrade required by pid %d",
2060 __func__, d->bd_pid);
2068 NET_EPOCH_CALL(bpf_program_buffer_free, &fcode->epoch_ctx);
2071 EVENTHANDLER_INVOKE(bpf_track,
2072 d->bd_bif->bif_ifp, d->bd_bif->bif_dlt, 1);
2079 * Detach a file from its current interface (if attached at all) and attach
2080 * to the interface indicated by the name stored in ifr.
2081 * Return an errno or 0.
2084 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
2087 struct ifnet *theywant;
2091 theywant = ifunit(ifr->ifr_name);
2092 if (theywant == NULL || theywant->if_bpf == NULL)
2095 bp = theywant->if_bpf;
2097 * At this point, we expect the buffer is already allocated. If not,
2100 switch (d->bd_bufmode) {
2101 case BPF_BUFMODE_BUFFER:
2102 case BPF_BUFMODE_ZBUF:
2103 if (d->bd_sbuf == NULL)
2108 panic("bpf_setif: bufmode %d", d->bd_bufmode);
2110 if (bp != d->bd_bif)
2121 * Support for select() and poll() system calls
2123 * Return true iff the specific operation will not block indefinitely.
2124 * Otherwise, return false but make a note that a selwakeup() must be done.
2127 bpfpoll(struct cdev *dev, int events, struct thread *td)
2132 if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
2134 (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
2137 * Refresh PID associated with this descriptor.
2139 revents = events & (POLLOUT | POLLWRNORM);
2141 BPF_PID_REFRESH(d, td);
2142 if (events & (POLLIN | POLLRDNORM)) {
2144 revents |= events & (POLLIN | POLLRDNORM);
2146 selrecord(td, &d->bd_sel);
2147 /* Start the read timeout if necessary. */
2148 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2149 callout_reset(&d->bd_callout, d->bd_rtout,
2151 d->bd_state = BPF_WAITING;
2160 * Support for kevent() system call. Register EVFILT_READ filters and
2161 * reject all others.
2164 bpfkqfilter(struct cdev *dev, struct knote *kn)
2168 if (devfs_get_cdevpriv((void **)&d) != 0)
2171 switch (kn->kn_filter) {
2173 kn->kn_fop = &bpfread_filtops;
2177 kn->kn_fop = &bpfwrite_filtops;
2185 * Refresh PID associated with this descriptor.
2188 BPF_PID_REFRESH_CUR(d);
2190 knlist_add(&d->bd_sel.si_note, kn, 1);
2197 filt_bpfdetach(struct knote *kn)
2199 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2201 knlist_remove(&d->bd_sel.si_note, kn, 0);
2205 filt_bpfread(struct knote *kn, long hint)
2207 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2210 BPFD_LOCK_ASSERT(d);
2211 ready = bpf_ready(d);
2213 kn->kn_data = d->bd_slen;
2215 * Ignore the hold buffer if it is being copied to user space.
2217 if (!d->bd_hbuf_in_use && d->bd_hbuf)
2218 kn->kn_data += d->bd_hlen;
2219 } else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2220 callout_reset(&d->bd_callout, d->bd_rtout,
2222 d->bd_state = BPF_WAITING;
2229 filt_bpfwrite(struct knote *kn, long hint)
2231 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2232 BPFD_LOCK_ASSERT(d);
2234 kn->kn_data = d->bd_bif->bif_ifp->if_mtu;
2239 #define BPF_TSTAMP_NONE 0
2240 #define BPF_TSTAMP_FAST 1
2241 #define BPF_TSTAMP_NORMAL 2
2242 #define BPF_TSTAMP_EXTERN 3
2245 bpf_ts_quality(int tstype)
2248 if (tstype == BPF_T_NONE)
2249 return (BPF_TSTAMP_NONE);
2250 if ((tstype & BPF_T_FAST) != 0)
2251 return (BPF_TSTAMP_FAST);
2253 return (BPF_TSTAMP_NORMAL);
2257 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
2262 quality = bpf_ts_quality(tstype);
2263 if (quality == BPF_TSTAMP_NONE)
2267 tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2269 *bt = *(struct bintime *)(tag + 1);
2270 return (BPF_TSTAMP_EXTERN);
2273 if (quality == BPF_TSTAMP_NORMAL)
2282 * Incoming linkage from device drivers. Process the packet pkt, of length
2283 * pktlen, which is stored in a contiguous buffer. The packet is parsed
2284 * by each process' filter, and if accepted, stashed into the corresponding
2288 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2290 struct epoch_tracker et;
2299 gottime = BPF_TSTAMP_NONE;
2300 NET_EPOCH_ENTER(et);
2301 CK_LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2302 counter_u64_add(d->bd_rcount, 1);
2304 * NB: We dont call BPF_CHECK_DIRECTION() here since there
2305 * is no way for the caller to indiciate to us whether this
2306 * packet is inbound or outbound. In the bpf_mtap() routines,
2307 * we use the interface pointers on the mbuf to figure it out.
2310 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2312 slen = (*(bf->func))(pkt, pktlen, pktlen);
2315 slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2318 * Filter matches. Let's to acquire write lock.
2321 counter_u64_add(d->bd_fcount, 1);
2322 if (gottime < bpf_ts_quality(d->bd_tstamp))
2323 gottime = bpf_gettime(&bt, d->bd_tstamp,
2326 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2328 catchpacket(d, pkt, pktlen, slen,
2329 bpf_append_bytes, &bt);
2336 #define BPF_CHECK_DIRECTION(d, r, i) \
2337 (((d)->bd_direction == BPF_D_IN && (r) != (i)) || \
2338 ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2341 * Incoming linkage from device drivers, when packet is in an mbuf chain.
2342 * Locking model is explained in bpf_tap().
2345 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2347 struct epoch_tracker et;
2356 /* Skip outgoing duplicate packets. */
2357 if ((m->m_flags & M_PROMISC) != 0 && m_rcvif(m) == NULL) {
2358 m->m_flags &= ~M_PROMISC;
2362 pktlen = m_length(m, NULL);
2363 gottime = BPF_TSTAMP_NONE;
2365 NET_EPOCH_ENTER(et);
2366 CK_LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2367 if (BPF_CHECK_DIRECTION(d, m_rcvif(m), bp->bif_ifp))
2369 counter_u64_add(d->bd_rcount, 1);
2371 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2372 /* XXX We cannot handle multiple mbufs. */
2373 if (bf != NULL && m->m_next == NULL)
2374 slen = (*(bf->func))(mtod(m, u_char *), pktlen,
2378 slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2382 counter_u64_add(d->bd_fcount, 1);
2383 if (gottime < bpf_ts_quality(d->bd_tstamp))
2384 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2386 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2388 catchpacket(d, (u_char *)m, pktlen, slen,
2389 bpf_append_mbuf, &bt);
2397 * Incoming linkage from device drivers, when packet is in
2398 * an mbuf chain and to be prepended by a contiguous header.
2401 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2403 struct epoch_tracker et;
2410 /* Skip outgoing duplicate packets. */
2411 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2412 m->m_flags &= ~M_PROMISC;
2416 pktlen = m_length(m, NULL);
2418 * Craft on-stack mbuf suitable for passing to bpf_filter.
2419 * Note that we cut corners here; we only setup what's
2420 * absolutely needed--this mbuf should never go anywhere else.
2428 gottime = BPF_TSTAMP_NONE;
2430 NET_EPOCH_ENTER(et);
2431 CK_LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2432 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2434 counter_u64_add(d->bd_rcount, 1);
2435 slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2439 counter_u64_add(d->bd_fcount, 1);
2440 if (gottime < bpf_ts_quality(d->bd_tstamp))
2441 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2443 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2445 catchpacket(d, (u_char *)&mb, pktlen, slen,
2446 bpf_append_mbuf, &bt);
2453 #undef BPF_CHECK_DIRECTION
2454 #undef BPF_TSTAMP_NONE
2455 #undef BPF_TSTAMP_FAST
2456 #undef BPF_TSTAMP_NORMAL
2457 #undef BPF_TSTAMP_EXTERN
2460 bpf_hdrlen(struct bpf_d *d)
2464 hdrlen = d->bd_bif->bif_hdrlen;
2465 #ifndef BURN_BRIDGES
2466 if (d->bd_tstamp == BPF_T_NONE ||
2467 BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2468 #ifdef COMPAT_FREEBSD32
2470 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2473 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2476 hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2477 #ifdef COMPAT_FREEBSD32
2479 hdrlen = BPF_WORDALIGN32(hdrlen);
2482 hdrlen = BPF_WORDALIGN(hdrlen);
2484 return (hdrlen - d->bd_bif->bif_hdrlen);
2488 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2490 struct bintime bt2, boottimebin;
2492 struct timespec tsn;
2494 if ((tstype & BPF_T_MONOTONIC) == 0) {
2496 getboottimebin(&boottimebin);
2497 bintime_add(&bt2, &boottimebin);
2500 switch (BPF_T_FORMAT(tstype)) {
2501 case BPF_T_MICROTIME:
2502 bintime2timeval(bt, &tsm);
2503 ts->bt_sec = tsm.tv_sec;
2504 ts->bt_frac = tsm.tv_usec;
2506 case BPF_T_NANOTIME:
2507 bintime2timespec(bt, &tsn);
2508 ts->bt_sec = tsn.tv_sec;
2509 ts->bt_frac = tsn.tv_nsec;
2512 ts->bt_sec = bt->sec;
2513 ts->bt_frac = bt->frac;
2519 * Move the packet data from interface memory (pkt) into the
2520 * store buffer. "cpfn" is the routine called to do the actual data
2521 * transfer. bcopy is passed in to copy contiguous chunks, while
2522 * bpf_append_mbuf is passed in to copy mbuf chains. In the latter case,
2523 * pkt is really an mbuf.
2526 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2527 void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2530 struct bpf_xhdr hdr;
2531 #ifndef BURN_BRIDGES
2532 struct bpf_hdr hdr_old;
2533 #ifdef COMPAT_FREEBSD32
2534 struct bpf_hdr32 hdr32_old;
2537 int caplen, curlen, hdrlen, totlen;
2542 BPFD_LOCK_ASSERT(d);
2543 if (d->bd_bif == NULL) {
2544 /* Descriptor was detached in concurrent thread */
2545 counter_u64_add(d->bd_dcount, 1);
2550 * Detect whether user space has released a buffer back to us, and if
2551 * so, move it from being a hold buffer to a free buffer. This may
2552 * not be the best place to do it (for example, we might only want to
2553 * run this check if we need the space), but for now it's a reliable
2556 if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2557 d->bd_fbuf = d->bd_hbuf;
2560 bpf_buf_reclaimed(d);
2564 * Figure out how many bytes to move. If the packet is
2565 * greater or equal to the snapshot length, transfer that
2566 * much. Otherwise, transfer the whole packet (unless
2567 * we hit the buffer size limit).
2569 hdrlen = bpf_hdrlen(d);
2570 totlen = hdrlen + min(snaplen, pktlen);
2571 if (totlen > d->bd_bufsize)
2572 totlen = d->bd_bufsize;
2575 * Round up the end of the previous packet to the next longword.
2577 * Drop the packet if there's no room and no hope of room
2578 * If the packet would overflow the storage buffer or the storage
2579 * buffer is considered immutable by the buffer model, try to rotate
2580 * the buffer and wakeup pending processes.
2582 #ifdef COMPAT_FREEBSD32
2584 curlen = BPF_WORDALIGN32(d->bd_slen);
2587 curlen = BPF_WORDALIGN(d->bd_slen);
2588 if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2589 if (d->bd_fbuf == NULL) {
2591 * There's no room in the store buffer, and no
2592 * prospect of room, so drop the packet. Notify the
2596 counter_u64_add(d->bd_dcount, 1);
2599 KASSERT(!d->bd_hbuf_in_use, ("hold buffer is in use"));
2603 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2605 * Immediate mode is set, or the read timeout has already
2606 * expired during a select call. A packet arrived, so the
2607 * reader should be woken up.
2610 caplen = totlen - hdrlen;
2611 tstype = d->bd_tstamp;
2612 do_timestamp = tstype != BPF_T_NONE;
2613 #ifndef BURN_BRIDGES
2614 if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2617 bpf_bintime2ts(bt, &ts, tstype);
2618 #ifdef COMPAT_FREEBSD32
2619 if (d->bd_compat32) {
2620 bzero(&hdr32_old, sizeof(hdr32_old));
2622 hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2623 hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2625 hdr32_old.bh_datalen = pktlen;
2626 hdr32_old.bh_hdrlen = hdrlen;
2627 hdr32_old.bh_caplen = caplen;
2628 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2633 bzero(&hdr_old, sizeof(hdr_old));
2635 hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2636 hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2638 hdr_old.bh_datalen = pktlen;
2639 hdr_old.bh_hdrlen = hdrlen;
2640 hdr_old.bh_caplen = caplen;
2641 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2648 * Append the bpf header. Note we append the actual header size, but
2649 * move forward the length of the header plus padding.
2651 bzero(&hdr, sizeof(hdr));
2653 bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2654 hdr.bh_datalen = pktlen;
2655 hdr.bh_hdrlen = hdrlen;
2656 hdr.bh_caplen = caplen;
2657 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2660 * Copy the packet data into the store buffer and update its length.
2662 #ifndef BURN_BRIDGES
2665 (*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2666 d->bd_slen = curlen + totlen;
2673 * Free buffers currently in use by a descriptor.
2677 bpfd_free(epoch_context_t ctx)
2680 struct bpf_program_buffer *p;
2683 * We don't need to lock out interrupts since this descriptor has
2684 * been detached from its interface and it yet hasn't been marked
2687 d = __containerof(ctx, struct bpf_d, epoch_ctx);
2689 if (d->bd_rfilter != NULL) {
2690 p = __containerof((void *)d->bd_rfilter,
2691 struct bpf_program_buffer, buffer);
2693 p->func = d->bd_bfilter;
2695 bpf_program_buffer_free(&p->epoch_ctx);
2697 if (d->bd_wfilter != NULL) {
2698 p = __containerof((void *)d->bd_wfilter,
2699 struct bpf_program_buffer, buffer);
2703 bpf_program_buffer_free(&p->epoch_ctx);
2706 mtx_destroy(&d->bd_lock);
2707 counter_u64_free(d->bd_rcount);
2708 counter_u64_free(d->bd_dcount);
2709 counter_u64_free(d->bd_fcount);
2710 counter_u64_free(d->bd_wcount);
2711 counter_u64_free(d->bd_wfcount);
2712 counter_u64_free(d->bd_wdcount);
2713 counter_u64_free(d->bd_zcopy);
2718 * Attach an interface to bpf. dlt is the link layer type; hdrlen is the
2719 * fixed size of the link header (variable length headers not yet supported).
2722 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2725 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2729 * Attach an interface to bpf. ifp is a pointer to the structure
2730 * defining the interface to be attached, dlt is the link layer type,
2731 * and hdrlen is the fixed size of the link header (variable length
2732 * headers are not yet supporrted).
2735 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen,
2736 struct bpf_if **driverp)
2740 KASSERT(*driverp == NULL,
2741 ("bpfattach2: driverp already initialized"));
2743 bp = malloc(sizeof(*bp), M_BPF, M_WAITOK | M_ZERO);
2745 CK_LIST_INIT(&bp->bif_dlist);
2746 CK_LIST_INIT(&bp->bif_wlist);
2749 bp->bif_hdrlen = hdrlen;
2750 bp->bif_bpf = driverp;
2754 * Reference ifnet pointer, so it won't freed until
2759 CK_LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2762 if (bootverbose && IS_DEFAULT_VNET(curvnet))
2763 if_printf(ifp, "bpf attached\n");
2768 * When moving interfaces between vnet instances we need a way to
2769 * query the dlt and hdrlen before detach so we can re-attch the if_bpf
2770 * after the vmove. We unfortunately have no device driver infrastructure
2771 * to query the interface for these values after creation/attach, thus
2772 * add this as a workaround.
2775 bpf_get_bp_params(struct bpf_if *bp, u_int *bif_dlt, u_int *bif_hdrlen)
2780 if (bif_dlt == NULL && bif_hdrlen == NULL)
2783 if (bif_dlt != NULL)
2784 *bif_dlt = bp->bif_dlt;
2785 if (bif_hdrlen != NULL)
2786 *bif_hdrlen = bp->bif_hdrlen;
2793 * Detach bpf from an interface. This involves detaching each descriptor
2794 * associated with the interface. Notify each descriptor as it's detached
2795 * so that any sleepers wake up and get ENXIO.
2798 bpfdetach(struct ifnet *ifp)
2800 struct bpf_if *bp, *bp_temp;
2804 /* Find all bpf_if struct's which reference ifp and detach them. */
2805 CK_LIST_FOREACH_SAFE(bp, &bpf_iflist, bif_next, bp_temp) {
2806 if (ifp != bp->bif_ifp)
2809 CK_LIST_REMOVE(bp, bif_next);
2810 *bp->bif_bpf = (struct bpf_if *)&dead_bpf_if;
2813 "%s: sheduling free for encap %d (%p) for if %p",
2814 __func__, bp->bif_dlt, bp, ifp);
2816 /* Detach common descriptors */
2817 while ((d = CK_LIST_FIRST(&bp->bif_dlist)) != NULL) {
2818 bpf_detachd_locked(d, true);
2821 /* Detach writer-only descriptors */
2822 while ((d = CK_LIST_FIRST(&bp->bif_wlist)) != NULL) {
2823 bpf_detachd_locked(d, true);
2831 * Get a list of available data link type of the interface.
2834 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2843 ifp = d->bd_bif->bif_ifp;
2845 CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2846 if (bp->bif_ifp == ifp)
2849 if (bfl->bfl_list == NULL) {
2853 if (n1 > bfl->bfl_len)
2856 lst = malloc(n1 * sizeof(u_int), M_TEMP, M_WAITOK);
2858 CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2859 if (bp->bif_ifp != ifp)
2861 lst[n++] = bp->bif_dlt;
2863 error = copyout(lst, bfl->bfl_list, sizeof(u_int) * n);
2870 * Set the data link type of a BPF instance.
2873 bpf_setdlt(struct bpf_d *d, u_int dlt)
2875 int error, opromisc;
2880 MPASS(d->bd_bif != NULL);
2883 * It is safe to check bd_bif without BPFD_LOCK, it can not be
2884 * changed while we hold global lock.
2886 if (d->bd_bif->bif_dlt == dlt)
2889 ifp = d->bd_bif->bif_ifp;
2890 CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2891 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2897 opromisc = d->bd_promisc;
2900 error = ifpromisc(bp->bif_ifp, 1);
2902 if_printf(bp->bif_ifp, "%s: ifpromisc failed (%d)\n",
2911 bpf_drvinit(void *unused)
2915 sx_init(&bpf_sx, "bpf global lock");
2916 CK_LIST_INIT(&bpf_iflist);
2918 dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2919 /* For compatibility */
2920 make_dev_alias(dev, "bpf0");
2924 * Zero out the various packet counters associated with all of the bpf
2925 * descriptors. At some point, we will probably want to get a bit more
2926 * granular and allow the user to specify descriptors to be zeroed.
2929 bpf_zero_counters(void)
2936 * We are protected by global lock here, interfaces and
2937 * descriptors can not be deleted while we hold it.
2939 CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2940 CK_LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2941 counter_u64_zero(bd->bd_rcount);
2942 counter_u64_zero(bd->bd_dcount);
2943 counter_u64_zero(bd->bd_fcount);
2944 counter_u64_zero(bd->bd_wcount);
2945 counter_u64_zero(bd->bd_wfcount);
2946 counter_u64_zero(bd->bd_zcopy);
2953 * Fill filter statistics
2956 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2960 bzero(d, sizeof(*d));
2961 d->bd_structsize = sizeof(*d);
2962 d->bd_immediate = bd->bd_immediate;
2963 d->bd_promisc = bd->bd_promisc;
2964 d->bd_hdrcmplt = bd->bd_hdrcmplt;
2965 d->bd_direction = bd->bd_direction;
2966 d->bd_feedback = bd->bd_feedback;
2967 d->bd_async = bd->bd_async;
2968 d->bd_rcount = counter_u64_fetch(bd->bd_rcount);
2969 d->bd_dcount = counter_u64_fetch(bd->bd_dcount);
2970 d->bd_fcount = counter_u64_fetch(bd->bd_fcount);
2971 d->bd_sig = bd->bd_sig;
2972 d->bd_slen = bd->bd_slen;
2973 d->bd_hlen = bd->bd_hlen;
2974 d->bd_bufsize = bd->bd_bufsize;
2975 d->bd_pid = bd->bd_pid;
2976 strlcpy(d->bd_ifname,
2977 bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2978 d->bd_locked = bd->bd_locked;
2979 d->bd_wcount = counter_u64_fetch(bd->bd_wcount);
2980 d->bd_wdcount = counter_u64_fetch(bd->bd_wdcount);
2981 d->bd_wfcount = counter_u64_fetch(bd->bd_wfcount);
2982 d->bd_zcopy = counter_u64_fetch(bd->bd_zcopy);
2983 d->bd_bufmode = bd->bd_bufmode;
2987 * Handle `netstat -B' stats request
2990 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2992 static const struct xbpf_d zerostats;
2993 struct xbpf_d *xbdbuf, *xbd, tempstats;
2999 * XXX This is not technically correct. It is possible for non
3000 * privileged users to open bpf devices. It would make sense
3001 * if the users who opened the devices were able to retrieve
3002 * the statistics for them, too.
3004 error = priv_check(req->td, PRIV_NET_BPF);
3008 * Check to see if the user is requesting that the counters be
3009 * zeroed out. Explicitly check that the supplied data is zeroed,
3010 * as we aren't allowing the user to set the counters currently.
3012 if (req->newptr != NULL) {
3013 if (req->newlen != sizeof(tempstats))
3015 memset(&tempstats, 0, sizeof(tempstats));
3016 error = SYSCTL_IN(req, &tempstats, sizeof(tempstats));
3019 if (bcmp(&tempstats, &zerostats, sizeof(tempstats)) != 0)
3021 bpf_zero_counters();
3024 if (req->oldptr == NULL)
3025 return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
3026 if (bpf_bpfd_cnt == 0)
3027 return (SYSCTL_OUT(req, 0, 0));
3028 xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
3030 if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
3032 free(xbdbuf, M_BPF);
3036 CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
3037 /* Send writers-only first */
3038 CK_LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
3039 xbd = &xbdbuf[index++];
3040 bpfstats_fill_xbpf(xbd, bd);
3042 CK_LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
3043 xbd = &xbdbuf[index++];
3044 bpfstats_fill_xbpf(xbd, bd);
3048 error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
3049 free(xbdbuf, M_BPF);
3053 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
3055 #else /* !DEV_BPF && !NETGRAPH_BPF */
3058 * NOP stubs to allow bpf-using drivers to load and function.
3060 * A 'better' implementation would allow the core bpf functionality
3061 * to be loaded at runtime.
3065 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
3070 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
3075 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
3080 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
3083 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
3087 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
3090 *driverp = (struct bpf_if *)&dead_bpf_if;
3094 bpfdetach(struct ifnet *ifp)
3099 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
3101 return -1; /* "no filter" behaviour */
3105 bpf_validate(const struct bpf_insn *f, int len)
3107 return 0; /* false */
3110 #endif /* !DEV_BPF && !NETGRAPH_BPF */
3114 bpf_show_bpf_if(struct bpf_if *bpf_if)
3119 db_printf("%p:\n", bpf_if);
3120 #define BPF_DB_PRINTF(f, e) db_printf(" %s = " f "\n", #e, bpf_if->e);
3121 /* bif_ext.bif_next */
3122 /* bif_ext.bif_dlist */
3123 BPF_DB_PRINTF("%#x", bif_dlt);
3124 BPF_DB_PRINTF("%u", bif_hdrlen);
3126 BPF_DB_PRINTF("%p", bif_ifp);
3127 BPF_DB_PRINTF("%p", bif_bpf);
3128 BPF_DB_PRINTF("%u", bif_refcnt);
3131 DB_SHOW_COMMAND(bpf_if, db_show_bpf_if)
3135 db_printf("usage: show bpf_if <struct bpf_if *>\n");
3139 bpf_show_bpf_if((struct bpf_if *)addr);