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>
71 #include <net/if_var.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");
93 #define bif_next bif_ext.bif_next
94 #define bif_dlist bif_ext.bif_dlist
95 struct bpf_if_ext bif_ext; /* public members */
96 u_int bif_dlt; /* link layer type */
97 u_int bif_hdrlen; /* length of link header */
98 struct ifnet *bif_ifp; /* corresponding interface */
99 struct rwlock bif_lock; /* interface lock */
100 LIST_HEAD(, bpf_d) bif_wlist; /* writer-only list */
101 int bif_flags; /* Interface flags */
104 CTASSERT(offsetof(struct bpf_if, bif_ext) == 0);
106 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
108 #define PRINET 26 /* interruptible */
110 #define SIZEOF_BPF_HDR(type) \
111 (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
113 #ifdef COMPAT_FREEBSD32
114 #include <sys/mount.h>
115 #include <compat/freebsd32/freebsd32.h>
116 #define BPF_ALIGNMENT32 sizeof(int32_t)
117 #define BPF_WORDALIGN32(x) (((x)+(BPF_ALIGNMENT32-1))&~(BPF_ALIGNMENT32-1))
121 * 32-bit version of structure prepended to each packet. We use this header
122 * instead of the standard one for 32-bit streams. We mark the a stream as
123 * 32-bit the first time we see a 32-bit compat ioctl request.
126 struct timeval32 bh_tstamp; /* time stamp */
127 uint32_t bh_caplen; /* length of captured portion */
128 uint32_t bh_datalen; /* original length of packet */
129 uint16_t bh_hdrlen; /* length of bpf header (this struct
130 plus alignment padding) */
134 struct bpf_program32 {
139 struct bpf_dltlist32 {
144 #define BIOCSETF32 _IOW('B', 103, struct bpf_program32)
145 #define BIOCSRTIMEOUT32 _IOW('B', 109, struct timeval32)
146 #define BIOCGRTIMEOUT32 _IOR('B', 110, struct timeval32)
147 #define BIOCGDLTLIST32 _IOWR('B', 121, struct bpf_dltlist32)
148 #define BIOCSETWF32 _IOW('B', 123, struct bpf_program32)
149 #define BIOCSETFNR32 _IOW('B', 130, struct bpf_program32)
153 * bpf_iflist is a list of BPF interface structures, each corresponding to a
154 * specific DLT. The same network interface might have several BPF interface
155 * structures registered by different layers in the stack (i.e., 802.11
156 * frames, ethernet frames, etc).
158 static LIST_HEAD(, bpf_if) bpf_iflist, bpf_freelist;
159 static struct mtx bpf_mtx; /* bpf global lock */
160 static int bpf_bpfd_cnt;
162 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
163 static void bpf_detachd(struct bpf_d *);
164 static void bpf_detachd_locked(struct bpf_d *);
165 static void bpf_freed(struct bpf_d *);
166 static int bpf_movein(struct uio *, int, struct ifnet *, struct mbuf **,
167 struct sockaddr *, int *, struct bpf_insn *);
168 static int bpf_setif(struct bpf_d *, struct ifreq *);
169 static void bpf_timed_out(void *);
171 bpf_wakeup(struct bpf_d *);
172 static void catchpacket(struct bpf_d *, u_char *, u_int, u_int,
173 void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
175 static void reset_d(struct bpf_d *);
176 static int bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
177 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
178 static int bpf_setdlt(struct bpf_d *, u_int);
179 static void filt_bpfdetach(struct knote *);
180 static int filt_bpfread(struct knote *, long);
181 static void bpf_drvinit(void *);
182 static int bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
184 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW, 0, "bpf sysctl");
185 int bpf_maxinsns = BPF_MAXINSNS;
186 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
187 &bpf_maxinsns, 0, "Maximum bpf program instructions");
188 static int bpf_zerocopy_enable = 0;
189 SYSCTL_INT(_net_bpf, OID_AUTO, zerocopy_enable, CTLFLAG_RW,
190 &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
191 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
192 bpf_stats_sysctl, "bpf statistics portal");
194 static VNET_DEFINE(int, bpf_optimize_writers) = 0;
195 #define V_bpf_optimize_writers VNET(bpf_optimize_writers)
196 SYSCTL_INT(_net_bpf, OID_AUTO, optimize_writers, CTLFLAG_VNET | CTLFLAG_RW,
197 &VNET_NAME(bpf_optimize_writers), 0,
198 "Do not send packets until BPF program is set");
200 static d_open_t bpfopen;
201 static d_read_t bpfread;
202 static d_write_t bpfwrite;
203 static d_ioctl_t bpfioctl;
204 static d_poll_t bpfpoll;
205 static d_kqfilter_t bpfkqfilter;
207 static struct cdevsw bpf_cdevsw = {
208 .d_version = D_VERSION,
215 .d_kqfilter = bpfkqfilter,
218 static struct filterops bpfread_filtops = {
220 .f_detach = filt_bpfdetach,
221 .f_event = filt_bpfread,
224 eventhandler_tag bpf_ifdetach_cookie = NULL;
227 * LOCKING MODEL USED BY BPF:
229 * 1) global lock (BPF_LOCK). Mutex, used to protect interface addition/removal,
230 * some global counters and every bpf_if reference.
231 * 2) Interface lock. Rwlock, used to protect list of BPF descriptors and their filters.
232 * 3) Descriptor lock. Mutex, used to protect BPF buffers and various structure fields
233 * used by bpf_mtap code.
237 * Global lock, interface lock, descriptor lock
239 * We have to acquire interface lock before descriptor main lock due to BPF_MTAP[2]
240 * working model. In many places (like bpf_detachd) we start with BPF descriptor
241 * (and we need to at least rlock it to get reliable interface pointer). This
242 * gives us potential LOR. As a result, we use global lock to protect from bpf_if
243 * change in every such place.
245 * Changing d->bd_bif is protected by 1) global lock, 2) interface lock and
246 * 3) descriptor main wlock.
247 * Reading bd_bif can be protected by any of these locks, typically global lock.
249 * Changing read/write BPF filter is protected by the same three locks,
250 * the same applies for reading.
252 * Sleeping in global lock is not allowed due to bpfdetach() using it.
256 * Wrapper functions for various buffering methods. If the set of buffer
257 * modes expands, we will probably want to introduce a switch data structure
258 * similar to protosw, et.
261 bpf_append_bytes(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
267 switch (d->bd_bufmode) {
268 case BPF_BUFMODE_BUFFER:
269 return (bpf_buffer_append_bytes(d, buf, offset, src, len));
271 case BPF_BUFMODE_ZBUF:
273 return (bpf_zerocopy_append_bytes(d, buf, offset, src, len));
276 panic("bpf_buf_append_bytes");
281 bpf_append_mbuf(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
287 switch (d->bd_bufmode) {
288 case BPF_BUFMODE_BUFFER:
289 return (bpf_buffer_append_mbuf(d, buf, offset, src, len));
291 case BPF_BUFMODE_ZBUF:
293 return (bpf_zerocopy_append_mbuf(d, buf, offset, src, len));
296 panic("bpf_buf_append_mbuf");
301 * This function gets called when the free buffer is re-assigned.
304 bpf_buf_reclaimed(struct bpf_d *d)
309 switch (d->bd_bufmode) {
310 case BPF_BUFMODE_BUFFER:
313 case BPF_BUFMODE_ZBUF:
314 bpf_zerocopy_buf_reclaimed(d);
318 panic("bpf_buf_reclaimed");
323 * If the buffer mechanism has a way to decide that a held buffer can be made
324 * free, then it is exposed via the bpf_canfreebuf() interface. (1) is
325 * returned if the buffer can be discarded, (0) is returned if it cannot.
328 bpf_canfreebuf(struct bpf_d *d)
333 switch (d->bd_bufmode) {
334 case BPF_BUFMODE_ZBUF:
335 return (bpf_zerocopy_canfreebuf(d));
341 * Allow the buffer model to indicate that the current store buffer is
342 * immutable, regardless of the appearance of space. Return (1) if the
343 * buffer is writable, and (0) if not.
346 bpf_canwritebuf(struct bpf_d *d)
350 switch (d->bd_bufmode) {
351 case BPF_BUFMODE_ZBUF:
352 return (bpf_zerocopy_canwritebuf(d));
358 * Notify buffer model that an attempt to write to the store buffer has
359 * resulted in a dropped packet, in which case the buffer may be considered
363 bpf_buffull(struct bpf_d *d)
368 switch (d->bd_bufmode) {
369 case BPF_BUFMODE_ZBUF:
370 bpf_zerocopy_buffull(d);
376 * Notify the buffer model that a buffer has moved into the hold position.
379 bpf_bufheld(struct bpf_d *d)
384 switch (d->bd_bufmode) {
385 case BPF_BUFMODE_ZBUF:
386 bpf_zerocopy_bufheld(d);
392 bpf_free(struct bpf_d *d)
395 switch (d->bd_bufmode) {
396 case BPF_BUFMODE_BUFFER:
397 return (bpf_buffer_free(d));
399 case BPF_BUFMODE_ZBUF:
400 return (bpf_zerocopy_free(d));
403 panic("bpf_buf_free");
408 bpf_uiomove(struct bpf_d *d, caddr_t buf, u_int len, struct uio *uio)
411 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
413 return (bpf_buffer_uiomove(d, buf, len, uio));
417 bpf_ioctl_sblen(struct bpf_d *d, u_int *i)
420 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
422 return (bpf_buffer_ioctl_sblen(d, i));
426 bpf_ioctl_getzmax(struct thread *td, struct bpf_d *d, size_t *i)
429 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
431 return (bpf_zerocopy_ioctl_getzmax(td, d, i));
435 bpf_ioctl_rotzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
438 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
440 return (bpf_zerocopy_ioctl_rotzbuf(td, d, bz));
444 bpf_ioctl_setzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
447 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
449 return (bpf_zerocopy_ioctl_setzbuf(td, d, bz));
453 * General BPF functions.
456 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
457 struct sockaddr *sockp, int *hdrlen, struct bpf_insn *wfilter)
459 const struct ieee80211_bpf_params *p;
460 struct ether_header *eh;
468 * Build a sockaddr based on the data link layer type.
469 * We do this at this level because the ethernet header
470 * is copied directly into the data field of the sockaddr.
471 * In the case of SLIP, there is no header and the packet
472 * is forwarded as is.
473 * Also, we are careful to leave room at the front of the mbuf
474 * for the link level header.
479 sockp->sa_family = AF_INET;
484 sockp->sa_family = AF_UNSPEC;
485 /* XXX Would MAXLINKHDR be better? */
486 hlen = ETHER_HDR_LEN;
490 sockp->sa_family = AF_IMPLINK;
495 sockp->sa_family = AF_UNSPEC;
501 * null interface types require a 4 byte pseudo header which
502 * corresponds to the address family of the packet.
504 sockp->sa_family = AF_UNSPEC;
508 case DLT_ATM_RFC1483:
510 * en atm driver requires 4-byte atm pseudo header.
511 * though it isn't standard, vpi:vci needs to be
514 sockp->sa_family = AF_UNSPEC;
515 hlen = 12; /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
519 sockp->sa_family = AF_UNSPEC;
520 hlen = 4; /* This should match PPP_HDRLEN */
523 case DLT_IEEE802_11: /* IEEE 802.11 wireless */
524 sockp->sa_family = AF_IEEE80211;
528 case DLT_IEEE802_11_RADIO: /* IEEE 802.11 wireless w/ phy params */
529 sockp->sa_family = AF_IEEE80211;
530 sockp->sa_len = 12; /* XXX != 0 */
531 hlen = sizeof(struct ieee80211_bpf_params);
538 len = uio->uio_resid;
539 if (len < hlen || len - hlen > ifp->if_mtu)
542 m = m_get2(len, M_WAITOK, MT_DATA, M_PKTHDR);
545 m->m_pkthdr.len = m->m_len = len;
548 error = uiomove(mtod(m, u_char *), len, uio);
552 slen = bpf_filter(wfilter, mtod(m, u_char *), len, len);
558 /* Check for multicast destination */
561 eh = mtod(m, struct ether_header *);
562 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
563 if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
564 ETHER_ADDR_LEN) == 0)
565 m->m_flags |= M_BCAST;
567 m->m_flags |= M_MCAST;
573 * Make room for link header, and copy it to sockaddr
576 if (sockp->sa_family == AF_IEEE80211) {
578 * Collect true length from the parameter header
579 * NB: sockp is known to be zero'd so if we do a
580 * short copy unspecified parameters will be
582 * NB: packet may not be aligned after stripping
586 p = mtod(m, const struct ieee80211_bpf_params *);
588 if (hlen > sizeof(sockp->sa_data)) {
593 bcopy(mtod(m, const void *), sockp->sa_data, hlen);
604 * Attach file to the bpf interface, i.e. make d listen on bp.
607 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
614 * Save sysctl value to protect from sysctl change
617 op_w = V_bpf_optimize_writers || d->bd_writer;
619 if (d->bd_bif != NULL)
620 bpf_detachd_locked(d);
622 * Point d at bp, and add d to the interface's list.
623 * Since there are many applications using BPF for
624 * sending raw packets only (dhcpd, cdpd are good examples)
625 * we can delay adding d to the list of active listeners until
626 * some filter is configured.
635 /* Add to writers-only list */
636 LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
638 * We decrement bd_writer on every filter set operation.
639 * First BIOCSETF is done by pcap_open_live() to set up
640 * snap length. After that appliation usually sets its own filter
644 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
651 CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
652 __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
655 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
659 * Check if we need to upgrade our descriptor @d from write-only mode.
662 bpf_check_upgrade(u_long cmd, struct bpf_d *d, struct bpf_insn *fcode, int flen)
664 int is_snap, need_upgrade;
667 * Check if we've already upgraded or new filter is empty.
669 if (d->bd_writer == 0 || fcode == NULL)
675 * Check if cmd looks like snaplen setting from
676 * pcap_bpf.c:pcap_open_live().
677 * Note we're not checking .k value here:
678 * while pcap_open_live() definitely sets to to non-zero value,
679 * we'd prefer to treat k=0 (deny ALL) case the same way: e.g.
680 * do not consider upgrading immediately
682 if (cmd == BIOCSETF && flen == 1 && fcode[0].code == (BPF_RET | BPF_K))
689 * We're setting first filter and it doesn't look like
690 * setting snaplen. We're probably using bpf directly.
691 * Upgrade immediately.
696 * Do not require upgrade by first BIOCSETF
697 * (used to set snaplen) by pcap_open_live().
700 if (--d->bd_writer == 0) {
702 * First snaplen filter has already
703 * been set. This is probably catch-all
711 "%s: filter function set by pid %d, "
712 "bd_writer counter %d, snap %d upgrade %d",
713 __func__, d->bd_pid, d->bd_writer,
714 is_snap, need_upgrade);
716 return (need_upgrade);
720 * Add d to the list of active bp filters.
721 * Requires bpf_attachd() to be called before.
724 bpf_upgraded(struct bpf_d *d)
733 * Filter can be set several times without specifying interface.
734 * Mark d as reader and exit.
746 /* Remove from writers-only list */
747 LIST_REMOVE(d, bd_next);
748 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
749 /* Mark d as reader */
755 CTR2(KTR_NET, "%s: upgrade required by pid %d", __func__, d->bd_pid);
757 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
761 * Detach a file from its interface.
764 bpf_detachd(struct bpf_d *d)
767 bpf_detachd_locked(d);
772 bpf_detachd_locked(struct bpf_d *d)
778 CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
782 /* Check if descriptor is attached */
783 if ((bp = d->bd_bif) == NULL)
789 /* Save bd_writer value */
790 error = d->bd_writer;
793 * Remove d from the interface's descriptor list.
795 LIST_REMOVE(d, bd_next);
804 /* Call event handler iff d is attached */
806 EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
809 * Check if this descriptor had requested promiscuous mode.
810 * If so, turn it off.
814 CURVNET_SET(ifp->if_vnet);
815 error = ifpromisc(ifp, 0);
817 if (error != 0 && error != ENXIO) {
819 * ENXIO can happen if a pccard is unplugged
820 * Something is really wrong if we were able to put
821 * the driver into promiscuous mode, but can't
824 if_printf(bp->bif_ifp,
825 "bpf_detach: ifpromisc failed (%d)\n", error);
831 * Close the descriptor by detaching it from its interface,
832 * deallocating its buffers, and marking it free.
837 struct bpf_d *d = data;
840 if (d->bd_state == BPF_WAITING)
841 callout_stop(&d->bd_callout);
842 d->bd_state = BPF_IDLE;
844 funsetown(&d->bd_sigio);
847 mac_bpfdesc_destroy(d);
849 seldrain(&d->bd_sel);
850 knlist_destroy(&d->bd_sel.si_note);
851 callout_drain(&d->bd_callout);
857 * Open ethernet device. Returns ENXIO for illegal minor device number,
858 * EBUSY if file is open by another process.
862 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
867 d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
868 error = devfs_set_cdevpriv(d, bpf_dtor);
875 * For historical reasons, perform a one-time initialization call to
876 * the buffer routines, even though we're not yet committed to a
877 * particular buffer method.
880 if ((flags & FREAD) == 0)
882 d->bd_hbuf_in_use = 0;
883 d->bd_bufmode = BPF_BUFMODE_BUFFER;
885 d->bd_direction = BPF_D_INOUT;
886 BPF_PID_REFRESH(d, td);
889 mac_bpfdesc_create(td->td_ucred, d);
891 mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
892 callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
893 knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
899 * bpfread - read next chunk of packets from buffers
902 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
909 error = devfs_get_cdevpriv((void **)&d);
914 * Restrict application to use a buffer the same size as
917 if (uio->uio_resid != d->bd_bufsize)
920 non_block = ((ioflag & O_NONBLOCK) != 0);
923 BPF_PID_REFRESH_CUR(d);
924 if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
928 if (d->bd_state == BPF_WAITING)
929 callout_stop(&d->bd_callout);
930 timed_out = (d->bd_state == BPF_TIMED_OUT);
931 d->bd_state = BPF_IDLE;
932 while (d->bd_hbuf_in_use) {
933 error = mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
934 PRINET|PCATCH, "bd_hbuf", 0);
941 * If the hold buffer is empty, then do a timed sleep, which
942 * ends when the timeout expires or when enough packets
943 * have arrived to fill the store buffer.
945 while (d->bd_hbuf == NULL) {
946 if (d->bd_slen != 0) {
948 * A packet(s) either arrived since the previous
949 * read or arrived while we were asleep.
951 if (d->bd_immediate || non_block || timed_out) {
953 * Rotate the buffers and return what's here
954 * if we are in immediate mode, non-blocking
955 * flag is set, or this descriptor timed out.
963 * No data is available, check to see if the bpf device
964 * is still pointed at a real interface. If not, return
965 * ENXIO so that the userland process knows to rebind
966 * it before using it again.
968 if (d->bd_bif == NULL) {
975 return (EWOULDBLOCK);
977 error = msleep(d, &d->bd_lock, PRINET|PCATCH,
979 if (error == EINTR || error == ERESTART) {
983 if (error == EWOULDBLOCK) {
985 * On a timeout, return what's in the buffer,
986 * which may be nothing. If there is something
987 * in the store buffer, we can rotate the buffers.
991 * We filled up the buffer in between
992 * getting the timeout and arriving
993 * here, so we don't need to rotate.
997 if (d->bd_slen == 0) {
1006 * At this point, we know we have something in the hold slot.
1008 d->bd_hbuf_in_use = 1;
1012 * Move data from hold buffer into user space.
1013 * We know the entire buffer is transferred since
1014 * we checked above that the read buffer is bpf_bufsize bytes.
1016 * We do not have to worry about simultaneous reads because
1017 * we waited for sole access to the hold buffer above.
1019 error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
1022 KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
1023 d->bd_fbuf = d->bd_hbuf;
1026 bpf_buf_reclaimed(d);
1027 d->bd_hbuf_in_use = 0;
1028 wakeup(&d->bd_hbuf_in_use);
1035 * If there are processes sleeping on this descriptor, wake them up.
1037 static __inline void
1038 bpf_wakeup(struct bpf_d *d)
1041 BPFD_LOCK_ASSERT(d);
1042 if (d->bd_state == BPF_WAITING) {
1043 callout_stop(&d->bd_callout);
1044 d->bd_state = BPF_IDLE;
1047 if (d->bd_async && d->bd_sig && d->bd_sigio)
1048 pgsigio(&d->bd_sigio, d->bd_sig, 0);
1050 selwakeuppri(&d->bd_sel, PRINET);
1051 KNOTE_LOCKED(&d->bd_sel.si_note, 0);
1055 bpf_timed_out(void *arg)
1057 struct bpf_d *d = (struct bpf_d *)arg;
1059 BPFD_LOCK_ASSERT(d);
1061 if (callout_pending(&d->bd_callout) || !callout_active(&d->bd_callout))
1063 if (d->bd_state == BPF_WAITING) {
1064 d->bd_state = BPF_TIMED_OUT;
1065 if (d->bd_slen != 0)
1071 bpf_ready(struct bpf_d *d)
1074 BPFD_LOCK_ASSERT(d);
1076 if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
1078 if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1085 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1089 struct mbuf *m, *mc;
1090 struct sockaddr dst;
1093 error = devfs_get_cdevpriv((void **)&d);
1097 BPF_PID_REFRESH_CUR(d);
1099 /* XXX: locking required */
1100 if (d->bd_bif == NULL) {
1105 ifp = d->bd_bif->bif_ifp;
1107 if ((ifp->if_flags & IFF_UP) == 0) {
1112 if (uio->uio_resid == 0) {
1117 bzero(&dst, sizeof(dst));
1120 /* XXX: bpf_movein() can sleep */
1121 error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp,
1122 &m, &dst, &hlen, d->bd_wfilter);
1129 dst.sa_family = pseudo_AF_HDRCMPLT;
1131 if (d->bd_feedback) {
1132 mc = m_dup(m, M_NOWAIT);
1134 mc->m_pkthdr.rcvif = ifp;
1135 /* Set M_PROMISC for outgoing packets to be discarded. */
1136 if (d->bd_direction == BPF_D_INOUT)
1137 m->m_flags |= M_PROMISC;
1141 m->m_pkthdr.len -= hlen;
1143 m->m_data += hlen; /* XXX */
1145 CURVNET_SET(ifp->if_vnet);
1148 mac_bpfdesc_create_mbuf(d, m);
1150 mac_bpfdesc_create_mbuf(d, mc);
1154 error = (*ifp->if_output)(ifp, m, &dst, NULL);
1160 (*ifp->if_input)(ifp, mc);
1170 * Reset a descriptor by flushing its packet buffer and clearing the receive
1171 * and drop counts. This is doable for kernel-only buffers, but with
1172 * zero-copy buffers, we can't write to (or rotate) buffers that are
1173 * currently owned by userspace. It would be nice if we could encapsulate
1174 * this logic in the buffer code rather than here.
1177 reset_d(struct bpf_d *d)
1180 BPFD_LOCK_ASSERT(d);
1182 while (d->bd_hbuf_in_use)
1183 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1185 if ((d->bd_hbuf != NULL) &&
1186 (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1187 /* Free the hold buffer. */
1188 d->bd_fbuf = d->bd_hbuf;
1191 bpf_buf_reclaimed(d);
1193 if (bpf_canwritebuf(d))
1205 * FIONREAD Check for read packet available.
1206 * BIOCGBLEN Get buffer len [for read()].
1207 * BIOCSETF Set read filter.
1208 * BIOCSETFNR Set read filter without resetting descriptor.
1209 * BIOCSETWF Set write filter.
1210 * BIOCFLUSH Flush read packet buffer.
1211 * BIOCPROMISC Put interface into promiscuous mode.
1212 * BIOCGDLT Get link layer type.
1213 * BIOCGETIF Get interface name.
1214 * BIOCSETIF Set interface.
1215 * BIOCSRTIMEOUT Set read timeout.
1216 * BIOCGRTIMEOUT Get read timeout.
1217 * BIOCGSTATS Get packet stats.
1218 * BIOCIMMEDIATE Set immediate mode.
1219 * BIOCVERSION Get filter language version.
1220 * BIOCGHDRCMPLT Get "header already complete" flag
1221 * BIOCSHDRCMPLT Set "header already complete" flag
1222 * BIOCGDIRECTION Get packet direction flag
1223 * BIOCSDIRECTION Set packet direction flag
1224 * BIOCGTSTAMP Get time stamp format and resolution.
1225 * BIOCSTSTAMP Set time stamp format and resolution.
1226 * BIOCLOCK Set "locked" flag
1227 * BIOCFEEDBACK Set packet feedback mode.
1228 * BIOCSETZBUF Set current zero-copy buffer locations.
1229 * BIOCGETZMAX Get maximum zero-copy buffer size.
1230 * BIOCROTZBUF Force rotation of zero-copy buffer
1231 * BIOCSETBUFMODE Set buffer mode.
1232 * BIOCGETBUFMODE Get current buffer mode.
1236 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1242 error = devfs_get_cdevpriv((void **)&d);
1247 * Refresh PID associated with this descriptor.
1250 BPF_PID_REFRESH(d, td);
1251 if (d->bd_state == BPF_WAITING)
1252 callout_stop(&d->bd_callout);
1253 d->bd_state = BPF_IDLE;
1256 if (d->bd_locked == 1) {
1262 #ifdef COMPAT_FREEBSD32
1263 case BIOCGDLTLIST32:
1267 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1268 case BIOCGRTIMEOUT32:
1279 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1280 case BIOCSRTIMEOUT32:
1290 #ifdef COMPAT_FREEBSD32
1292 * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1293 * that it will get 32-bit packet headers.
1299 case BIOCGDLTLIST32:
1300 case BIOCGRTIMEOUT32:
1301 case BIOCSRTIMEOUT32:
1308 CURVNET_SET(TD_TO_VNET(td));
1316 * Check for read packet available.
1324 while (d->bd_hbuf_in_use)
1325 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1326 PRINET, "bd_hbuf", 0);
1336 * Get buffer len [for read()].
1340 *(u_int *)addr = d->bd_bufsize;
1345 * Set buffer length.
1348 error = bpf_ioctl_sblen(d, (u_int *)addr);
1352 * Set link layer read filter.
1357 #ifdef COMPAT_FREEBSD32
1362 error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1366 * Flush read packet buffer.
1375 * Put interface into promiscuous mode.
1378 if (d->bd_bif == NULL) {
1380 * No interface attached yet.
1385 if (d->bd_promisc == 0) {
1386 error = ifpromisc(d->bd_bif->bif_ifp, 1);
1393 * Get current data link type.
1397 if (d->bd_bif == NULL)
1400 *(u_int *)addr = d->bd_bif->bif_dlt;
1405 * Get a list of supported data link types.
1407 #ifdef COMPAT_FREEBSD32
1408 case BIOCGDLTLIST32:
1410 struct bpf_dltlist32 *list32;
1411 struct bpf_dltlist dltlist;
1413 list32 = (struct bpf_dltlist32 *)addr;
1414 dltlist.bfl_len = list32->bfl_len;
1415 dltlist.bfl_list = PTRIN(list32->bfl_list);
1417 if (d->bd_bif == NULL)
1420 error = bpf_getdltlist(d, &dltlist);
1422 list32->bfl_len = dltlist.bfl_len;
1431 if (d->bd_bif == NULL)
1434 error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1439 * Set data link type.
1443 if (d->bd_bif == NULL)
1446 error = bpf_setdlt(d, *(u_int *)addr);
1451 * Get interface name.
1455 if (d->bd_bif == NULL)
1458 struct ifnet *const ifp = d->bd_bif->bif_ifp;
1459 struct ifreq *const ifr = (struct ifreq *)addr;
1461 strlcpy(ifr->ifr_name, ifp->if_xname,
1462 sizeof(ifr->ifr_name));
1472 int alloc_buf, size;
1475 * Behavior here depends on the buffering model. If
1476 * we're using kernel memory buffers, then we can
1477 * allocate them here. If we're using zero-copy,
1478 * then the user process must have registered buffers
1479 * by the time we get here.
1483 if (d->bd_bufmode == BPF_BUFMODE_BUFFER &&
1488 size = d->bd_bufsize;
1489 error = bpf_buffer_ioctl_sblen(d, &size);
1494 error = bpf_setif(d, (struct ifreq *)addr);
1503 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1504 case BIOCSRTIMEOUT32:
1507 struct timeval *tv = (struct timeval *)addr;
1508 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1509 struct timeval32 *tv32;
1510 struct timeval tv64;
1512 if (cmd == BIOCSRTIMEOUT32) {
1513 tv32 = (struct timeval32 *)addr;
1515 tv->tv_sec = tv32->tv_sec;
1516 tv->tv_usec = tv32->tv_usec;
1519 tv = (struct timeval *)addr;
1522 * Subtract 1 tick from tvtohz() since this isn't
1525 if ((error = itimerfix(tv)) == 0)
1526 d->bd_rtout = tvtohz(tv) - 1;
1534 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1535 case BIOCGRTIMEOUT32:
1539 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1540 struct timeval32 *tv32;
1541 struct timeval tv64;
1543 if (cmd == BIOCGRTIMEOUT32)
1547 tv = (struct timeval *)addr;
1549 tv->tv_sec = d->bd_rtout / hz;
1550 tv->tv_usec = (d->bd_rtout % hz) * tick;
1551 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1552 if (cmd == BIOCGRTIMEOUT32) {
1553 tv32 = (struct timeval32 *)addr;
1554 tv32->tv_sec = tv->tv_sec;
1555 tv32->tv_usec = tv->tv_usec;
1567 struct bpf_stat *bs = (struct bpf_stat *)addr;
1569 /* XXXCSJP overflow */
1570 bs->bs_recv = d->bd_rcount;
1571 bs->bs_drop = d->bd_dcount;
1576 * Set immediate mode.
1580 d->bd_immediate = *(u_int *)addr;
1586 struct bpf_version *bv = (struct bpf_version *)addr;
1588 bv->bv_major = BPF_MAJOR_VERSION;
1589 bv->bv_minor = BPF_MINOR_VERSION;
1594 * Get "header already complete" flag
1598 *(u_int *)addr = d->bd_hdrcmplt;
1603 * Set "header already complete" flag
1607 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1612 * Get packet direction flag
1614 case BIOCGDIRECTION:
1616 *(u_int *)addr = d->bd_direction;
1621 * Set packet direction flag
1623 case BIOCSDIRECTION:
1627 direction = *(u_int *)addr;
1628 switch (direction) {
1633 d->bd_direction = direction;
1643 * Get packet timestamp format and resolution.
1647 *(u_int *)addr = d->bd_tstamp;
1652 * Set packet timestamp format and resolution.
1658 func = *(u_int *)addr;
1659 if (BPF_T_VALID(func))
1660 d->bd_tstamp = func;
1668 d->bd_feedback = *(u_int *)addr;
1678 case FIONBIO: /* Non-blocking I/O */
1681 case FIOASYNC: /* Send signal on receive packets */
1683 d->bd_async = *(int *)addr;
1689 * XXX: Add some sort of locking here?
1690 * fsetown() can sleep.
1692 error = fsetown(*(int *)addr, &d->bd_sigio);
1697 *(int *)addr = fgetown(&d->bd_sigio);
1701 /* This is deprecated, FIOSETOWN should be used instead. */
1703 error = fsetown(-(*(int *)addr), &d->bd_sigio);
1706 /* This is deprecated, FIOGETOWN should be used instead. */
1708 *(int *)addr = -fgetown(&d->bd_sigio);
1711 case BIOCSRSIG: /* Set receive signal */
1715 sig = *(u_int *)addr;
1728 *(u_int *)addr = d->bd_sig;
1732 case BIOCGETBUFMODE:
1734 *(u_int *)addr = d->bd_bufmode;
1738 case BIOCSETBUFMODE:
1740 * Allow the buffering mode to be changed as long as we
1741 * haven't yet committed to a particular mode. Our
1742 * definition of commitment, for now, is whether or not a
1743 * buffer has been allocated or an interface attached, since
1744 * that's the point where things get tricky.
1746 switch (*(u_int *)addr) {
1747 case BPF_BUFMODE_BUFFER:
1750 case BPF_BUFMODE_ZBUF:
1751 if (bpf_zerocopy_enable)
1761 if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1762 d->bd_fbuf != NULL || d->bd_bif != NULL) {
1767 d->bd_bufmode = *(u_int *)addr;
1772 error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1776 error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1780 error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1788 * Set d's packet filter program to fp. If this file already has a filter,
1789 * free it and replace it. Returns EINVAL for bogus requests.
1791 * Note we need global lock here to serialize bpf_setf() and bpf_setif() calls
1792 * since reading d->bd_bif can't be protected by d or interface lock due to
1795 * Additionally, we have to acquire interface write lock due to bpf_mtap() uses
1796 * interface read lock to read all filers.
1800 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1802 #ifdef COMPAT_FREEBSD32
1803 struct bpf_program fp_swab;
1804 struct bpf_program32 *fp32;
1806 struct bpf_insn *fcode, *old;
1808 bpf_jit_filter *jfunc, *ofunc;
1814 #ifdef COMPAT_FREEBSD32
1819 fp32 = (struct bpf_program32 *)fp;
1820 fp_swab.bf_len = fp32->bf_len;
1821 fp_swab.bf_insns = (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1837 jfunc = ofunc = NULL;
1842 * Check new filter validness before acquiring any locks.
1843 * Allocate memory for new filter, if needed.
1846 if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1848 size = flen * sizeof(*fp->bf_insns);
1850 /* We're setting up new filter. Copy and check actual data. */
1851 fcode = malloc(size, M_BPF, M_WAITOK);
1852 if (copyin(fp->bf_insns, fcode, size) != 0 ||
1853 !bpf_validate(fcode, flen)) {
1858 /* Filter is copied inside fcode and is perfectly valid. */
1859 jfunc = bpf_jitter(fcode, flen);
1866 * Set up new filter.
1867 * Protect filter change by interface lock.
1868 * Additionally, we are protected by global lock here.
1870 if (d->bd_bif != NULL)
1871 BPFIF_WLOCK(d->bd_bif);
1873 if (cmd == BIOCSETWF) {
1874 old = d->bd_wfilter;
1875 d->bd_wfilter = fcode;
1877 old = d->bd_rfilter;
1878 d->bd_rfilter = fcode;
1880 ofunc = d->bd_bfilter;
1881 d->bd_bfilter = jfunc;
1883 if (cmd == BIOCSETF)
1886 need_upgrade = bpf_check_upgrade(cmd, d, fcode, flen);
1889 if (d->bd_bif != NULL)
1890 BPFIF_WUNLOCK(d->bd_bif);
1895 bpf_destroy_jit_filter(ofunc);
1898 /* Move d to active readers list. */
1899 if (need_upgrade != 0)
1907 * Detach a file from its current interface (if attached at all) and attach
1908 * to the interface indicated by the name stored in ifr.
1909 * Return an errno or 0.
1912 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1915 struct ifnet *theywant;
1919 theywant = ifunit(ifr->ifr_name);
1920 if (theywant == NULL || theywant->if_bpf == NULL)
1923 bp = theywant->if_bpf;
1925 /* Check if interface is not being detached from BPF */
1927 if (bp->bif_flags & BPFIF_FLAG_DYING) {
1934 * At this point, we expect the buffer is already allocated. If not,
1937 switch (d->bd_bufmode) {
1938 case BPF_BUFMODE_BUFFER:
1939 case BPF_BUFMODE_ZBUF:
1940 if (d->bd_sbuf == NULL)
1945 panic("bpf_setif: bufmode %d", d->bd_bufmode);
1947 if (bp != d->bd_bif)
1956 * Support for select() and poll() system calls
1958 * Return true iff the specific operation will not block indefinitely.
1959 * Otherwise, return false but make a note that a selwakeup() must be done.
1962 bpfpoll(struct cdev *dev, int events, struct thread *td)
1967 if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
1969 (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1972 * Refresh PID associated with this descriptor.
1974 revents = events & (POLLOUT | POLLWRNORM);
1976 BPF_PID_REFRESH(d, td);
1977 if (events & (POLLIN | POLLRDNORM)) {
1979 revents |= events & (POLLIN | POLLRDNORM);
1981 selrecord(td, &d->bd_sel);
1982 /* Start the read timeout if necessary. */
1983 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1984 callout_reset(&d->bd_callout, d->bd_rtout,
1986 d->bd_state = BPF_WAITING;
1995 * Support for kevent() system call. Register EVFILT_READ filters and
1996 * reject all others.
1999 bpfkqfilter(struct cdev *dev, struct knote *kn)
2003 if (devfs_get_cdevpriv((void **)&d) != 0 ||
2004 kn->kn_filter != EVFILT_READ)
2008 * Refresh PID associated with this descriptor.
2011 BPF_PID_REFRESH_CUR(d);
2012 kn->kn_fop = &bpfread_filtops;
2014 knlist_add(&d->bd_sel.si_note, kn, 1);
2021 filt_bpfdetach(struct knote *kn)
2023 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2025 knlist_remove(&d->bd_sel.si_note, kn, 0);
2029 filt_bpfread(struct knote *kn, long hint)
2031 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2034 BPFD_LOCK_ASSERT(d);
2035 ready = bpf_ready(d);
2037 kn->kn_data = d->bd_slen;
2039 * Ignore the hold buffer if it is being copied to user space.
2041 if (!d->bd_hbuf_in_use && d->bd_hbuf)
2042 kn->kn_data += d->bd_hlen;
2043 } else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2044 callout_reset(&d->bd_callout, d->bd_rtout,
2046 d->bd_state = BPF_WAITING;
2052 #define BPF_TSTAMP_NONE 0
2053 #define BPF_TSTAMP_FAST 1
2054 #define BPF_TSTAMP_NORMAL 2
2055 #define BPF_TSTAMP_EXTERN 3
2058 bpf_ts_quality(int tstype)
2061 if (tstype == BPF_T_NONE)
2062 return (BPF_TSTAMP_NONE);
2063 if ((tstype & BPF_T_FAST) != 0)
2064 return (BPF_TSTAMP_FAST);
2066 return (BPF_TSTAMP_NORMAL);
2070 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
2075 quality = bpf_ts_quality(tstype);
2076 if (quality == BPF_TSTAMP_NONE)
2080 tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2082 *bt = *(struct bintime *)(tag + 1);
2083 return (BPF_TSTAMP_EXTERN);
2086 if (quality == BPF_TSTAMP_NORMAL)
2095 * Incoming linkage from device drivers. Process the packet pkt, of length
2096 * pktlen, which is stored in a contiguous buffer. The packet is parsed
2097 * by each process' filter, and if accepted, stashed into the corresponding
2101 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2111 gottime = BPF_TSTAMP_NONE;
2115 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2117 * We are not using any locks for d here because:
2118 * 1) any filter change is protected by interface
2120 * 2) destroying/detaching d is protected by interface
2124 /* XXX: Do not protect counter for the sake of performance. */
2127 * NB: We dont call BPF_CHECK_DIRECTION() here since there is no
2128 * way for the caller to indiciate to us whether this packet
2129 * is inbound or outbound. In the bpf_mtap() routines, we use
2130 * the interface pointers on the mbuf to figure it out.
2133 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2135 slen = (*(bf->func))(pkt, pktlen, pktlen);
2138 slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2141 * Filter matches. Let's to acquire write lock.
2146 if (gottime < bpf_ts_quality(d->bd_tstamp))
2147 gottime = bpf_gettime(&bt, d->bd_tstamp, NULL);
2149 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2151 catchpacket(d, pkt, pktlen, slen,
2152 bpf_append_bytes, &bt);
2159 #define BPF_CHECK_DIRECTION(d, r, i) \
2160 (((d)->bd_direction == BPF_D_IN && (r) != (i)) || \
2161 ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2164 * Incoming linkage from device drivers, when packet is in an mbuf chain.
2165 * Locking model is explained in bpf_tap().
2168 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2178 /* Skip outgoing duplicate packets. */
2179 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2180 m->m_flags &= ~M_PROMISC;
2184 pktlen = m_length(m, NULL);
2185 gottime = BPF_TSTAMP_NONE;
2189 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2190 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2194 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2195 /* XXX We cannot handle multiple mbufs. */
2196 if (bf != NULL && m->m_next == NULL)
2197 slen = (*(bf->func))(mtod(m, u_char *), pktlen, pktlen);
2200 slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2205 if (gottime < bpf_ts_quality(d->bd_tstamp))
2206 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2208 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2210 catchpacket(d, (u_char *)m, pktlen, slen,
2211 bpf_append_mbuf, &bt);
2219 * Incoming linkage from device drivers, when packet is in
2220 * an mbuf chain and to be prepended by a contiguous header.
2223 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2231 /* Skip outgoing duplicate packets. */
2232 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2233 m->m_flags &= ~M_PROMISC;
2237 pktlen = m_length(m, NULL);
2239 * Craft on-stack mbuf suitable for passing to bpf_filter.
2240 * Note that we cut corners here; we only setup what's
2241 * absolutely needed--this mbuf should never go anywhere else.
2248 gottime = BPF_TSTAMP_NONE;
2252 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2253 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2256 slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2261 if (gottime < bpf_ts_quality(d->bd_tstamp))
2262 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2264 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2266 catchpacket(d, (u_char *)&mb, pktlen, slen,
2267 bpf_append_mbuf, &bt);
2274 #undef BPF_CHECK_DIRECTION
2276 #undef BPF_TSTAMP_NONE
2277 #undef BPF_TSTAMP_FAST
2278 #undef BPF_TSTAMP_NORMAL
2279 #undef BPF_TSTAMP_EXTERN
2282 bpf_hdrlen(struct bpf_d *d)
2286 hdrlen = d->bd_bif->bif_hdrlen;
2287 #ifndef BURN_BRIDGES
2288 if (d->bd_tstamp == BPF_T_NONE ||
2289 BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2290 #ifdef COMPAT_FREEBSD32
2292 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2295 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2298 hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2299 #ifdef COMPAT_FREEBSD32
2301 hdrlen = BPF_WORDALIGN32(hdrlen);
2304 hdrlen = BPF_WORDALIGN(hdrlen);
2306 return (hdrlen - d->bd_bif->bif_hdrlen);
2310 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2314 struct timespec tsn;
2316 if ((tstype & BPF_T_MONOTONIC) == 0) {
2318 bintime_add(&bt2, &boottimebin);
2321 switch (BPF_T_FORMAT(tstype)) {
2322 case BPF_T_MICROTIME:
2323 bintime2timeval(bt, &tsm);
2324 ts->bt_sec = tsm.tv_sec;
2325 ts->bt_frac = tsm.tv_usec;
2327 case BPF_T_NANOTIME:
2328 bintime2timespec(bt, &tsn);
2329 ts->bt_sec = tsn.tv_sec;
2330 ts->bt_frac = tsn.tv_nsec;
2333 ts->bt_sec = bt->sec;
2334 ts->bt_frac = bt->frac;
2340 * Move the packet data from interface memory (pkt) into the
2341 * store buffer. "cpfn" is the routine called to do the actual data
2342 * transfer. bcopy is passed in to copy contiguous chunks, while
2343 * bpf_append_mbuf is passed in to copy mbuf chains. In the latter case,
2344 * pkt is really an mbuf.
2347 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2348 void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2351 struct bpf_xhdr hdr;
2352 #ifndef BURN_BRIDGES
2353 struct bpf_hdr hdr_old;
2354 #ifdef COMPAT_FREEBSD32
2355 struct bpf_hdr32 hdr32_old;
2358 int caplen, curlen, hdrlen, totlen;
2363 BPFD_LOCK_ASSERT(d);
2366 * Detect whether user space has released a buffer back to us, and if
2367 * so, move it from being a hold buffer to a free buffer. This may
2368 * not be the best place to do it (for example, we might only want to
2369 * run this check if we need the space), but for now it's a reliable
2372 if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2373 d->bd_fbuf = d->bd_hbuf;
2376 bpf_buf_reclaimed(d);
2380 * Figure out how many bytes to move. If the packet is
2381 * greater or equal to the snapshot length, transfer that
2382 * much. Otherwise, transfer the whole packet (unless
2383 * we hit the buffer size limit).
2385 hdrlen = bpf_hdrlen(d);
2386 totlen = hdrlen + min(snaplen, pktlen);
2387 if (totlen > d->bd_bufsize)
2388 totlen = d->bd_bufsize;
2391 * Round up the end of the previous packet to the next longword.
2393 * Drop the packet if there's no room and no hope of room
2394 * If the packet would overflow the storage buffer or the storage
2395 * buffer is considered immutable by the buffer model, try to rotate
2396 * the buffer and wakeup pending processes.
2398 #ifdef COMPAT_FREEBSD32
2400 curlen = BPF_WORDALIGN32(d->bd_slen);
2403 curlen = BPF_WORDALIGN(d->bd_slen);
2404 if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2405 if (d->bd_fbuf == NULL) {
2407 * There's no room in the store buffer, and no
2408 * prospect of room, so drop the packet. Notify the
2415 KASSERT(!d->bd_hbuf_in_use, ("hold buffer is in use"));
2419 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2421 * Immediate mode is set, or the read timeout has already
2422 * expired during a select call. A packet arrived, so the
2423 * reader should be woken up.
2426 caplen = totlen - hdrlen;
2427 tstype = d->bd_tstamp;
2428 do_timestamp = tstype != BPF_T_NONE;
2429 #ifndef BURN_BRIDGES
2430 if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2433 bpf_bintime2ts(bt, &ts, tstype);
2434 #ifdef COMPAT_FREEBSD32
2435 if (d->bd_compat32) {
2436 bzero(&hdr32_old, sizeof(hdr32_old));
2438 hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2439 hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2441 hdr32_old.bh_datalen = pktlen;
2442 hdr32_old.bh_hdrlen = hdrlen;
2443 hdr32_old.bh_caplen = caplen;
2444 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2449 bzero(&hdr_old, sizeof(hdr_old));
2451 hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2452 hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2454 hdr_old.bh_datalen = pktlen;
2455 hdr_old.bh_hdrlen = hdrlen;
2456 hdr_old.bh_caplen = caplen;
2457 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2464 * Append the bpf header. Note we append the actual header size, but
2465 * move forward the length of the header plus padding.
2467 bzero(&hdr, sizeof(hdr));
2469 bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2470 hdr.bh_datalen = pktlen;
2471 hdr.bh_hdrlen = hdrlen;
2472 hdr.bh_caplen = caplen;
2473 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2476 * Copy the packet data into the store buffer and update its length.
2478 #ifndef BURN_BRIDGES
2481 (*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2482 d->bd_slen = curlen + totlen;
2489 * Free buffers currently in use by a descriptor.
2493 bpf_freed(struct bpf_d *d)
2497 * We don't need to lock out interrupts since this descriptor has
2498 * been detached from its interface and it yet hasn't been marked
2502 if (d->bd_rfilter != NULL) {
2503 free((caddr_t)d->bd_rfilter, M_BPF);
2505 if (d->bd_bfilter != NULL)
2506 bpf_destroy_jit_filter(d->bd_bfilter);
2509 if (d->bd_wfilter != NULL)
2510 free((caddr_t)d->bd_wfilter, M_BPF);
2511 mtx_destroy(&d->bd_lock);
2515 * Attach an interface to bpf. dlt is the link layer type; hdrlen is the
2516 * fixed size of the link header (variable length headers not yet supported).
2519 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2522 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2526 * Attach an interface to bpf. ifp is a pointer to the structure
2527 * defining the interface to be attached, dlt is the link layer type,
2528 * and hdrlen is the fixed size of the link header (variable length
2529 * headers are not yet supporrted).
2532 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2536 bp = malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
2540 LIST_INIT(&bp->bif_dlist);
2541 LIST_INIT(&bp->bif_wlist);
2544 rw_init(&bp->bif_lock, "bpf interface lock");
2545 KASSERT(*driverp == NULL, ("bpfattach2: driverp already initialized"));
2549 LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2552 bp->bif_hdrlen = hdrlen;
2555 if_printf(ifp, "bpf attached\n");
2559 * Detach bpf from an interface. This involves detaching each descriptor
2560 * associated with the interface. Notify each descriptor as it's detached
2561 * so that any sleepers wake up and get ENXIO.
2564 bpfdetach(struct ifnet *ifp)
2566 struct bpf_if *bp, *bp_temp;
2573 /* Find all bpf_if struct's which reference ifp and detach them. */
2574 LIST_FOREACH_SAFE(bp, &bpf_iflist, bif_next, bp_temp) {
2575 if (ifp != bp->bif_ifp)
2578 LIST_REMOVE(bp, bif_next);
2579 /* Add to to-be-freed list */
2580 LIST_INSERT_HEAD(&bpf_freelist, bp, bif_next);
2584 * Delay freeing bp till interface is detached
2585 * and all routes through this interface are removed.
2586 * Mark bp as detached to restrict new consumers.
2589 bp->bif_flags |= BPFIF_FLAG_DYING;
2592 CTR4(KTR_NET, "%s: sheduling free for encap %d (%p) for if %p",
2593 __func__, bp->bif_dlt, bp, ifp);
2595 /* Free common descriptors */
2596 while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
2597 bpf_detachd_locked(d);
2603 /* Free writer-only descriptors */
2604 while ((d = LIST_FIRST(&bp->bif_wlist)) != NULL) {
2605 bpf_detachd_locked(d);
2615 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
2620 * Interface departure handler.
2621 * Note departure event does not guarantee interface is going down.
2622 * Interface renaming is currently done via departure/arrival event set.
2624 * Departure handled is called after all routes pointing to
2625 * given interface are removed and interface is in down state
2626 * restricting any packets to be sent/received. We assume it is now safe
2627 * to free data allocated by BPF.
2630 bpf_ifdetach(void *arg __unused, struct ifnet *ifp)
2632 struct bpf_if *bp, *bp_temp;
2637 * Find matching entries in free list.
2638 * Nothing should be found if bpfdetach() was not called.
2640 LIST_FOREACH_SAFE(bp, &bpf_freelist, bif_next, bp_temp) {
2641 if (ifp != bp->bif_ifp)
2644 CTR3(KTR_NET, "%s: freeing BPF instance %p for interface %p",
2647 LIST_REMOVE(bp, bif_next);
2649 rw_destroy(&bp->bif_lock);
2657 * Note that we cannot zero other pointers to
2658 * custom DLTs possibly used by given interface.
2665 * Get a list of available data link type of the interface.
2668 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2676 ifp = d->bd_bif->bif_ifp;
2679 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2680 if (bp->bif_ifp != ifp)
2682 if (bfl->bfl_list != NULL) {
2683 if (n >= bfl->bfl_len)
2685 error = copyout(&bp->bif_dlt,
2686 bfl->bfl_list + n, sizeof(u_int));
2695 * Set the data link type of a BPF instance.
2698 bpf_setdlt(struct bpf_d *d, u_int dlt)
2700 int error, opromisc;
2706 if (d->bd_bif->bif_dlt == dlt)
2708 ifp = d->bd_bif->bif_ifp;
2710 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2711 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2716 opromisc = d->bd_promisc;
2722 error = ifpromisc(bp->bif_ifp, 1);
2724 if_printf(bp->bif_ifp,
2725 "bpf_setdlt: ifpromisc failed (%d)\n",
2731 return (bp == NULL ? EINVAL : 0);
2735 bpf_drvinit(void *unused)
2739 mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
2740 LIST_INIT(&bpf_iflist);
2741 LIST_INIT(&bpf_freelist);
2743 dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2744 /* For compatibility */
2745 make_dev_alias(dev, "bpf0");
2747 /* Register interface departure handler */
2748 bpf_ifdetach_cookie = EVENTHANDLER_REGISTER(
2749 ifnet_departure_event, bpf_ifdetach, NULL,
2750 EVENTHANDLER_PRI_ANY);
2754 * Zero out the various packet counters associated with all of the bpf
2755 * descriptors. At some point, we will probably want to get a bit more
2756 * granular and allow the user to specify descriptors to be zeroed.
2759 bpf_zero_counters(void)
2765 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2767 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2783 * Fill filter statistics
2786 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2789 bzero(d, sizeof(*d));
2790 BPFD_LOCK_ASSERT(bd);
2791 d->bd_structsize = sizeof(*d);
2792 /* XXX: reading should be protected by global lock */
2793 d->bd_immediate = bd->bd_immediate;
2794 d->bd_promisc = bd->bd_promisc;
2795 d->bd_hdrcmplt = bd->bd_hdrcmplt;
2796 d->bd_direction = bd->bd_direction;
2797 d->bd_feedback = bd->bd_feedback;
2798 d->bd_async = bd->bd_async;
2799 d->bd_rcount = bd->bd_rcount;
2800 d->bd_dcount = bd->bd_dcount;
2801 d->bd_fcount = bd->bd_fcount;
2802 d->bd_sig = bd->bd_sig;
2803 d->bd_slen = bd->bd_slen;
2804 d->bd_hlen = bd->bd_hlen;
2805 d->bd_bufsize = bd->bd_bufsize;
2806 d->bd_pid = bd->bd_pid;
2807 strlcpy(d->bd_ifname,
2808 bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2809 d->bd_locked = bd->bd_locked;
2810 d->bd_wcount = bd->bd_wcount;
2811 d->bd_wdcount = bd->bd_wdcount;
2812 d->bd_wfcount = bd->bd_wfcount;
2813 d->bd_zcopy = bd->bd_zcopy;
2814 d->bd_bufmode = bd->bd_bufmode;
2818 * Handle `netstat -B' stats request
2821 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2823 static const struct xbpf_d zerostats;
2824 struct xbpf_d *xbdbuf, *xbd, tempstats;
2830 * XXX This is not technically correct. It is possible for non
2831 * privileged users to open bpf devices. It would make sense
2832 * if the users who opened the devices were able to retrieve
2833 * the statistics for them, too.
2835 error = priv_check(req->td, PRIV_NET_BPF);
2839 * Check to see if the user is requesting that the counters be
2840 * zeroed out. Explicitly check that the supplied data is zeroed,
2841 * as we aren't allowing the user to set the counters currently.
2843 if (req->newptr != NULL) {
2844 if (req->newlen != sizeof(tempstats))
2846 memset(&tempstats, 0, sizeof(tempstats));
2847 error = SYSCTL_IN(req, &tempstats, sizeof(tempstats));
2850 if (bcmp(&tempstats, &zerostats, sizeof(tempstats)) != 0)
2852 bpf_zero_counters();
2855 if (req->oldptr == NULL)
2856 return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
2857 if (bpf_bpfd_cnt == 0)
2858 return (SYSCTL_OUT(req, 0, 0));
2859 xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
2861 if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
2863 free(xbdbuf, M_BPF);
2867 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2869 /* Send writers-only first */
2870 LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
2871 xbd = &xbdbuf[index++];
2873 bpfstats_fill_xbpf(xbd, bd);
2876 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2877 xbd = &xbdbuf[index++];
2879 bpfstats_fill_xbpf(xbd, bd);
2885 error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
2886 free(xbdbuf, M_BPF);
2890 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
2892 #else /* !DEV_BPF && !NETGRAPH_BPF */
2894 * NOP stubs to allow bpf-using drivers to load and function.
2896 * A 'better' implementation would allow the core bpf functionality
2897 * to be loaded at runtime.
2899 static struct bpf_if bp_null;
2902 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2907 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2912 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
2917 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2920 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2924 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2927 *driverp = &bp_null;
2931 bpfdetach(struct ifnet *ifp)
2936 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
2938 return -1; /* "no filter" behaviour */
2942 bpf_validate(const struct bpf_insn *f, int len)
2944 return 0; /* false */
2947 #endif /* !DEV_BPF && !NETGRAPH_BPF */