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>
74 #include <net/bpf_buffer.h>
76 #include <net/bpf_jitter.h>
78 #include <net/bpf_zerocopy.h>
79 #include <net/bpfdesc.h>
82 #include <netinet/in.h>
83 #include <netinet/if_ether.h>
84 #include <sys/kernel.h>
85 #include <sys/sysctl.h>
87 #include <net80211/ieee80211_freebsd.h>
89 #include <security/mac/mac_framework.h>
91 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
93 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
95 #define PRINET 26 /* interruptible */
97 #define SIZEOF_BPF_HDR(type) \
98 (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
100 #ifdef COMPAT_FREEBSD32
101 #include <sys/mount.h>
102 #include <compat/freebsd32/freebsd32.h>
103 #define BPF_ALIGNMENT32 sizeof(int32_t)
104 #define BPF_WORDALIGN32(x) (((x)+(BPF_ALIGNMENT32-1))&~(BPF_ALIGNMENT32-1))
108 * 32-bit version of structure prepended to each packet. We use this header
109 * instead of the standard one for 32-bit streams. We mark the a stream as
110 * 32-bit the first time we see a 32-bit compat ioctl request.
113 struct timeval32 bh_tstamp; /* time stamp */
114 uint32_t bh_caplen; /* length of captured portion */
115 uint32_t bh_datalen; /* original length of packet */
116 uint16_t bh_hdrlen; /* length of bpf header (this struct
117 plus alignment padding) */
121 struct bpf_program32 {
126 struct bpf_dltlist32 {
131 #define BIOCSETF32 _IOW('B', 103, struct bpf_program32)
132 #define BIOCSRTIMEOUT32 _IOW('B', 109, struct timeval32)
133 #define BIOCGRTIMEOUT32 _IOR('B', 110, struct timeval32)
134 #define BIOCGDLTLIST32 _IOWR('B', 121, struct bpf_dltlist32)
135 #define BIOCSETWF32 _IOW('B', 123, struct bpf_program32)
136 #define BIOCSETFNR32 _IOW('B', 130, struct bpf_program32)
140 * bpf_iflist is a list of BPF interface structures, each corresponding to a
141 * specific DLT. The same network interface might have several BPF interface
142 * structures registered by different layers in the stack (i.e., 802.11
143 * frames, ethernet frames, etc).
145 static LIST_HEAD(, bpf_if) bpf_iflist, bpf_freelist;
146 static struct mtx bpf_mtx; /* bpf global lock */
147 static int bpf_bpfd_cnt;
149 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
150 static void bpf_detachd(struct bpf_d *);
151 static void bpf_detachd_locked(struct bpf_d *);
152 static void bpf_freed(struct bpf_d *);
153 static int bpf_movein(struct uio *, int, struct ifnet *, struct mbuf **,
154 struct sockaddr *, int *, struct bpf_insn *);
155 static int bpf_setif(struct bpf_d *, struct ifreq *);
156 static void bpf_timed_out(void *);
158 bpf_wakeup(struct bpf_d *);
159 static void catchpacket(struct bpf_d *, u_char *, u_int, u_int,
160 void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
162 static void reset_d(struct bpf_d *);
163 static int bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
164 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
165 static int bpf_setdlt(struct bpf_d *, u_int);
166 static void filt_bpfdetach(struct knote *);
167 static int filt_bpfread(struct knote *, long);
168 static void bpf_drvinit(void *);
169 static int bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
171 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW, 0, "bpf sysctl");
172 int bpf_maxinsns = BPF_MAXINSNS;
173 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
174 &bpf_maxinsns, 0, "Maximum bpf program instructions");
175 static int bpf_zerocopy_enable = 0;
176 SYSCTL_INT(_net_bpf, OID_AUTO, zerocopy_enable, CTLFLAG_RW,
177 &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
178 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
179 bpf_stats_sysctl, "bpf statistics portal");
181 static VNET_DEFINE(int, bpf_optimize_writers) = 0;
182 #define V_bpf_optimize_writers VNET(bpf_optimize_writers)
183 SYSCTL_VNET_INT(_net_bpf, OID_AUTO, optimize_writers,
184 CTLFLAG_RW, &VNET_NAME(bpf_optimize_writers), 0,
185 "Do not send packets until BPF program is set");
187 static d_open_t bpfopen;
188 static d_read_t bpfread;
189 static d_write_t bpfwrite;
190 static d_ioctl_t bpfioctl;
191 static d_poll_t bpfpoll;
192 static d_kqfilter_t bpfkqfilter;
194 static struct cdevsw bpf_cdevsw = {
195 .d_version = D_VERSION,
202 .d_kqfilter = bpfkqfilter,
205 static struct filterops bpfread_filtops = {
207 .f_detach = filt_bpfdetach,
208 .f_event = filt_bpfread,
211 eventhandler_tag bpf_ifdetach_cookie = NULL;
214 * LOCKING MODEL USED BY BPF:
216 * 1) global lock (BPF_LOCK). Mutex, used to protect interface addition/removal,
217 * some global counters and every bpf_if reference.
218 * 2) Interface lock. Rwlock, used to protect list of BPF descriptors and their filters.
219 * 3) Descriptor lock. Mutex, used to protect BPF buffers and various structure fields
220 * used by bpf_mtap code.
224 * Global lock, interface lock, descriptor lock
226 * We have to acquire interface lock before descriptor main lock due to BPF_MTAP[2]
227 * working model. In many places (like bpf_detachd) we start with BPF descriptor
228 * (and we need to at least rlock it to get reliable interface pointer). This
229 * gives us potential LOR. As a result, we use global lock to protect from bpf_if
230 * change in every such place.
232 * Changing d->bd_bif is protected by 1) global lock, 2) interface lock and
233 * 3) descriptor main wlock.
234 * Reading bd_bif can be protected by any of these locks, typically global lock.
236 * Changing read/write BPF filter is protected by the same three locks,
237 * the same applies for reading.
239 * Sleeping in global lock is not allowed due to bpfdetach() using it.
243 * Wrapper functions for various buffering methods. If the set of buffer
244 * modes expands, we will probably want to introduce a switch data structure
245 * similar to protosw, et.
248 bpf_append_bytes(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
254 switch (d->bd_bufmode) {
255 case BPF_BUFMODE_BUFFER:
256 return (bpf_buffer_append_bytes(d, buf, offset, src, len));
258 case BPF_BUFMODE_ZBUF:
260 return (bpf_zerocopy_append_bytes(d, buf, offset, src, len));
263 panic("bpf_buf_append_bytes");
268 bpf_append_mbuf(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
274 switch (d->bd_bufmode) {
275 case BPF_BUFMODE_BUFFER:
276 return (bpf_buffer_append_mbuf(d, buf, offset, src, len));
278 case BPF_BUFMODE_ZBUF:
280 return (bpf_zerocopy_append_mbuf(d, buf, offset, src, len));
283 panic("bpf_buf_append_mbuf");
288 * This function gets called when the free buffer is re-assigned.
291 bpf_buf_reclaimed(struct bpf_d *d)
296 switch (d->bd_bufmode) {
297 case BPF_BUFMODE_BUFFER:
300 case BPF_BUFMODE_ZBUF:
301 bpf_zerocopy_buf_reclaimed(d);
305 panic("bpf_buf_reclaimed");
310 * If the buffer mechanism has a way to decide that a held buffer can be made
311 * free, then it is exposed via the bpf_canfreebuf() interface. (1) is
312 * returned if the buffer can be discarded, (0) is returned if it cannot.
315 bpf_canfreebuf(struct bpf_d *d)
320 switch (d->bd_bufmode) {
321 case BPF_BUFMODE_ZBUF:
322 return (bpf_zerocopy_canfreebuf(d));
328 * Allow the buffer model to indicate that the current store buffer is
329 * immutable, regardless of the appearance of space. Return (1) if the
330 * buffer is writable, and (0) if not.
333 bpf_canwritebuf(struct bpf_d *d)
337 switch (d->bd_bufmode) {
338 case BPF_BUFMODE_ZBUF:
339 return (bpf_zerocopy_canwritebuf(d));
345 * Notify buffer model that an attempt to write to the store buffer has
346 * resulted in a dropped packet, in which case the buffer may be considered
350 bpf_buffull(struct bpf_d *d)
355 switch (d->bd_bufmode) {
356 case BPF_BUFMODE_ZBUF:
357 bpf_zerocopy_buffull(d);
363 * Notify the buffer model that a buffer has moved into the hold position.
366 bpf_bufheld(struct bpf_d *d)
371 switch (d->bd_bufmode) {
372 case BPF_BUFMODE_ZBUF:
373 bpf_zerocopy_bufheld(d);
379 bpf_free(struct bpf_d *d)
382 switch (d->bd_bufmode) {
383 case BPF_BUFMODE_BUFFER:
384 return (bpf_buffer_free(d));
386 case BPF_BUFMODE_ZBUF:
387 return (bpf_zerocopy_free(d));
390 panic("bpf_buf_free");
395 bpf_uiomove(struct bpf_d *d, caddr_t buf, u_int len, struct uio *uio)
398 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
400 return (bpf_buffer_uiomove(d, buf, len, uio));
404 bpf_ioctl_sblen(struct bpf_d *d, u_int *i)
407 if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
409 return (bpf_buffer_ioctl_sblen(d, i));
413 bpf_ioctl_getzmax(struct thread *td, struct bpf_d *d, size_t *i)
416 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
418 return (bpf_zerocopy_ioctl_getzmax(td, d, i));
422 bpf_ioctl_rotzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
425 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
427 return (bpf_zerocopy_ioctl_rotzbuf(td, d, bz));
431 bpf_ioctl_setzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
434 if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
436 return (bpf_zerocopy_ioctl_setzbuf(td, d, bz));
440 * General BPF functions.
443 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
444 struct sockaddr *sockp, int *hdrlen, struct bpf_insn *wfilter)
446 const struct ieee80211_bpf_params *p;
447 struct ether_header *eh;
455 * Build a sockaddr based on the data link layer type.
456 * We do this at this level because the ethernet header
457 * is copied directly into the data field of the sockaddr.
458 * In the case of SLIP, there is no header and the packet
459 * is forwarded as is.
460 * Also, we are careful to leave room at the front of the mbuf
461 * for the link level header.
466 sockp->sa_family = AF_INET;
471 sockp->sa_family = AF_UNSPEC;
472 /* XXX Would MAXLINKHDR be better? */
473 hlen = ETHER_HDR_LEN;
477 sockp->sa_family = AF_IMPLINK;
482 sockp->sa_family = AF_UNSPEC;
488 * null interface types require a 4 byte pseudo header which
489 * corresponds to the address family of the packet.
491 sockp->sa_family = AF_UNSPEC;
495 case DLT_ATM_RFC1483:
497 * en atm driver requires 4-byte atm pseudo header.
498 * though it isn't standard, vpi:vci needs to be
501 sockp->sa_family = AF_UNSPEC;
502 hlen = 12; /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
506 sockp->sa_family = AF_UNSPEC;
507 hlen = 4; /* This should match PPP_HDRLEN */
510 case DLT_IEEE802_11: /* IEEE 802.11 wireless */
511 sockp->sa_family = AF_IEEE80211;
515 case DLT_IEEE802_11_RADIO: /* IEEE 802.11 wireless w/ phy params */
516 sockp->sa_family = AF_IEEE80211;
517 sockp->sa_len = 12; /* XXX != 0 */
518 hlen = sizeof(struct ieee80211_bpf_params);
525 len = uio->uio_resid;
526 if (len < hlen || len - hlen > ifp->if_mtu)
529 m = m_get2(len, M_WAITOK, MT_DATA, M_PKTHDR);
532 m->m_pkthdr.len = m->m_len = len;
535 error = uiomove(mtod(m, u_char *), len, uio);
539 slen = bpf_filter(wfilter, mtod(m, u_char *), len, len);
545 /* Check for multicast destination */
548 eh = mtod(m, struct ether_header *);
549 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
550 if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
551 ETHER_ADDR_LEN) == 0)
552 m->m_flags |= M_BCAST;
554 m->m_flags |= M_MCAST;
560 * Make room for link header, and copy it to sockaddr
563 if (sockp->sa_family == AF_IEEE80211) {
565 * Collect true length from the parameter header
566 * NB: sockp is known to be zero'd so if we do a
567 * short copy unspecified parameters will be
569 * NB: packet may not be aligned after stripping
573 p = mtod(m, const struct ieee80211_bpf_params *);
575 if (hlen > sizeof(sockp->sa_data)) {
580 bcopy(mtod(m, const void *), sockp->sa_data, hlen);
591 * Attach file to the bpf interface, i.e. make d listen on bp.
594 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
601 * Save sysctl value to protect from sysctl change
604 op_w = V_bpf_optimize_writers;
606 if (d->bd_bif != NULL)
607 bpf_detachd_locked(d);
609 * Point d at bp, and add d to the interface's list.
610 * Since there are many applicaiotns using BPF for
611 * sending raw packets only (dhcpd, cdpd are good examples)
612 * we can delay adding d to the list of active listeners until
613 * some filter is configured.
622 /* Add to writers-only list */
623 LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
625 * We decrement bd_writer on every filter set operation.
626 * First BIOCSETF is done by pcap_open_live() to set up
627 * snap length. After that appliation usually sets its own filter
631 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
638 CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
639 __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
642 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
646 * Check if we need to upgrade our descriptor @d from write-only mode.
649 bpf_check_upgrade(u_long cmd, struct bpf_d *d, struct bpf_insn *fcode, int flen)
651 int is_snap, need_upgrade;
654 * Check if we've already upgraded or new filter is empty.
656 if (d->bd_writer == 0 || fcode == NULL)
662 * Check if cmd looks like snaplen setting from
663 * pcap_bpf.c:pcap_open_live().
664 * Note we're not checking .k value here:
665 * while pcap_open_live() definitely sets to to non-zero value,
666 * we'd prefer to treat k=0 (deny ALL) case the same way: e.g.
667 * do not consider upgrading immediately
669 if (cmd == BIOCSETF && flen == 1 && fcode[0].code == (BPF_RET | BPF_K))
676 * We're setting first filter and it doesn't look like
677 * setting snaplen. We're probably using bpf directly.
678 * Upgrade immediately.
683 * Do not require upgrade by first BIOCSETF
684 * (used to set snaplen) by pcap_open_live().
687 if (--d->bd_writer == 0) {
689 * First snaplen filter has already
690 * been set. This is probably catch-all
698 "%s: filter function set by pid %d, "
699 "bd_writer counter %d, snap %d upgrade %d",
700 __func__, d->bd_pid, d->bd_writer,
701 is_snap, need_upgrade);
703 return (need_upgrade);
707 * Add d to the list of active bp filters.
708 * Reuqires bpf_attachd() to be called before
711 bpf_upgraded(struct bpf_d *d)
720 * Filter can be set several times without specifying interface.
721 * Mark d as reader and exit.
733 /* Remove from writers-only list */
734 LIST_REMOVE(d, bd_next);
735 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
736 /* Mark d as reader */
742 CTR2(KTR_NET, "%s: upgrade required by pid %d", __func__, d->bd_pid);
744 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
748 * Detach a file from its interface.
751 bpf_detachd(struct bpf_d *d)
754 bpf_detachd_locked(d);
759 bpf_detachd_locked(struct bpf_d *d)
765 CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
769 /* Check if descriptor is attached */
770 if ((bp = d->bd_bif) == NULL)
776 /* Save bd_writer value */
777 error = d->bd_writer;
780 * Remove d from the interface's descriptor list.
782 LIST_REMOVE(d, bd_next);
791 /* Call event handler iff d is attached */
793 EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
796 * Check if this descriptor had requested promiscuous mode.
797 * If so, turn it off.
801 CURVNET_SET(ifp->if_vnet);
802 error = ifpromisc(ifp, 0);
804 if (error != 0 && error != ENXIO) {
806 * ENXIO can happen if a pccard is unplugged
807 * Something is really wrong if we were able to put
808 * the driver into promiscuous mode, but can't
811 if_printf(bp->bif_ifp,
812 "bpf_detach: ifpromisc failed (%d)\n", error);
818 * Close the descriptor by detaching it from its interface,
819 * deallocating its buffers, and marking it free.
824 struct bpf_d *d = data;
827 if (d->bd_state == BPF_WAITING)
828 callout_stop(&d->bd_callout);
829 d->bd_state = BPF_IDLE;
831 funsetown(&d->bd_sigio);
834 mac_bpfdesc_destroy(d);
836 seldrain(&d->bd_sel);
837 knlist_destroy(&d->bd_sel.si_note);
838 callout_drain(&d->bd_callout);
844 * Open ethernet device. Returns ENXIO for illegal minor device number,
845 * EBUSY if file is open by another process.
849 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
854 d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
855 error = devfs_set_cdevpriv(d, bpf_dtor);
862 * For historical reasons, perform a one-time initialization call to
863 * the buffer routines, even though we're not yet committed to a
864 * particular buffer method.
867 d->bd_hbuf_in_use = 0;
868 d->bd_bufmode = BPF_BUFMODE_BUFFER;
870 d->bd_direction = BPF_D_INOUT;
871 BPF_PID_REFRESH(d, td);
874 mac_bpfdesc_create(td->td_ucred, d);
876 mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
877 callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
878 knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
880 /* Allocate default buffers */
881 size = d->bd_bufsize;
882 bpf_buffer_ioctl_sblen(d, &size);
888 * bpfread - read next chunk of packets from buffers
891 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
898 error = devfs_get_cdevpriv((void **)&d);
903 * Restrict application to use a buffer the same size as
906 if (uio->uio_resid != d->bd_bufsize)
909 non_block = ((ioflag & O_NONBLOCK) != 0);
912 BPF_PID_REFRESH_CUR(d);
913 if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
917 if (d->bd_state == BPF_WAITING)
918 callout_stop(&d->bd_callout);
919 timed_out = (d->bd_state == BPF_TIMED_OUT);
920 d->bd_state = BPF_IDLE;
921 while (d->bd_hbuf_in_use) {
922 error = mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
923 PRINET|PCATCH, "bd_hbuf", 0);
930 * If the hold buffer is empty, then do a timed sleep, which
931 * ends when the timeout expires or when enough packets
932 * have arrived to fill the store buffer.
934 while (d->bd_hbuf == NULL) {
935 if (d->bd_slen != 0) {
937 * A packet(s) either arrived since the previous
938 * read or arrived while we were asleep.
940 if (d->bd_immediate || non_block || timed_out) {
942 * Rotate the buffers and return what's here
943 * if we are in immediate mode, non-blocking
944 * flag is set, or this descriptor timed out.
952 * No data is available, check to see if the bpf device
953 * is still pointed at a real interface. If not, return
954 * ENXIO so that the userland process knows to rebind
955 * it before using it again.
957 if (d->bd_bif == NULL) {
964 return (EWOULDBLOCK);
966 error = msleep(d, &d->bd_lock, PRINET|PCATCH,
968 if (error == EINTR || error == ERESTART) {
972 if (error == EWOULDBLOCK) {
974 * On a timeout, return what's in the buffer,
975 * which may be nothing. If there is something
976 * in the store buffer, we can rotate the buffers.
980 * We filled up the buffer in between
981 * getting the timeout and arriving
982 * here, so we don't need to rotate.
986 if (d->bd_slen == 0) {
995 * At this point, we know we have something in the hold slot.
997 d->bd_hbuf_in_use = 1;
1001 * Move data from hold buffer into user space.
1002 * We know the entire buffer is transferred since
1003 * we checked above that the read buffer is bpf_bufsize bytes.
1005 * We do not have to worry about simultaneous reads because
1006 * we waited for sole access to the hold buffer above.
1008 error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
1011 KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
1012 d->bd_fbuf = d->bd_hbuf;
1015 bpf_buf_reclaimed(d);
1016 d->bd_hbuf_in_use = 0;
1017 wakeup(&d->bd_hbuf_in_use);
1024 * If there are processes sleeping on this descriptor, wake them up.
1026 static __inline void
1027 bpf_wakeup(struct bpf_d *d)
1030 BPFD_LOCK_ASSERT(d);
1031 if (d->bd_state == BPF_WAITING) {
1032 callout_stop(&d->bd_callout);
1033 d->bd_state = BPF_IDLE;
1036 if (d->bd_async && d->bd_sig && d->bd_sigio)
1037 pgsigio(&d->bd_sigio, d->bd_sig, 0);
1039 selwakeuppri(&d->bd_sel, PRINET);
1040 KNOTE_LOCKED(&d->bd_sel.si_note, 0);
1044 bpf_timed_out(void *arg)
1046 struct bpf_d *d = (struct bpf_d *)arg;
1048 BPFD_LOCK_ASSERT(d);
1050 if (callout_pending(&d->bd_callout) || !callout_active(&d->bd_callout))
1052 if (d->bd_state == BPF_WAITING) {
1053 d->bd_state = BPF_TIMED_OUT;
1054 if (d->bd_slen != 0)
1060 bpf_ready(struct bpf_d *d)
1063 BPFD_LOCK_ASSERT(d);
1065 if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
1067 if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1074 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1078 struct mbuf *m, *mc;
1079 struct sockaddr dst;
1082 error = devfs_get_cdevpriv((void **)&d);
1086 BPF_PID_REFRESH_CUR(d);
1088 /* XXX: locking required */
1089 if (d->bd_bif == NULL) {
1094 ifp = d->bd_bif->bif_ifp;
1096 if ((ifp->if_flags & IFF_UP) == 0) {
1101 if (uio->uio_resid == 0) {
1106 bzero(&dst, sizeof(dst));
1109 /* XXX: bpf_movein() can sleep */
1110 error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp,
1111 &m, &dst, &hlen, d->bd_wfilter);
1118 dst.sa_family = pseudo_AF_HDRCMPLT;
1120 if (d->bd_feedback) {
1121 mc = m_dup(m, M_NOWAIT);
1123 mc->m_pkthdr.rcvif = ifp;
1124 /* Set M_PROMISC for outgoing packets to be discarded. */
1125 if (d->bd_direction == BPF_D_INOUT)
1126 m->m_flags |= M_PROMISC;
1130 m->m_pkthdr.len -= hlen;
1132 m->m_data += hlen; /* XXX */
1134 CURVNET_SET(ifp->if_vnet);
1137 mac_bpfdesc_create_mbuf(d, m);
1139 mac_bpfdesc_create_mbuf(d, mc);
1143 error = (*ifp->if_output)(ifp, m, &dst, NULL);
1149 (*ifp->if_input)(ifp, mc);
1159 * Reset a descriptor by flushing its packet buffer and clearing the receive
1160 * and drop counts. This is doable for kernel-only buffers, but with
1161 * zero-copy buffers, we can't write to (or rotate) buffers that are
1162 * currently owned by userspace. It would be nice if we could encapsulate
1163 * this logic in the buffer code rather than here.
1166 reset_d(struct bpf_d *d)
1169 BPFD_LOCK_ASSERT(d);
1171 while (d->bd_hbuf_in_use)
1172 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1174 if ((d->bd_hbuf != NULL) &&
1175 (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1176 /* Free the hold buffer. */
1177 d->bd_fbuf = d->bd_hbuf;
1180 bpf_buf_reclaimed(d);
1182 if (bpf_canwritebuf(d))
1194 * FIONREAD Check for read packet available.
1195 * SIOCGIFADDR Get interface address - convenient hook to driver.
1196 * BIOCGBLEN Get buffer len [for read()].
1197 * BIOCSETF Set read filter.
1198 * BIOCSETFNR Set read filter without resetting descriptor.
1199 * BIOCSETWF Set write filter.
1200 * BIOCFLUSH Flush read packet buffer.
1201 * BIOCPROMISC Put interface into promiscuous mode.
1202 * BIOCGDLT Get link layer type.
1203 * BIOCGETIF Get interface name.
1204 * BIOCSETIF Set interface.
1205 * BIOCSRTIMEOUT Set read timeout.
1206 * BIOCGRTIMEOUT Get read timeout.
1207 * BIOCGSTATS Get packet stats.
1208 * BIOCIMMEDIATE Set immediate mode.
1209 * BIOCVERSION Get filter language version.
1210 * BIOCGHDRCMPLT Get "header already complete" flag
1211 * BIOCSHDRCMPLT Set "header already complete" flag
1212 * BIOCGDIRECTION Get packet direction flag
1213 * BIOCSDIRECTION Set packet direction flag
1214 * BIOCGTSTAMP Get time stamp format and resolution.
1215 * BIOCSTSTAMP Set time stamp format and resolution.
1216 * BIOCLOCK Set "locked" flag
1217 * BIOCFEEDBACK Set packet feedback mode.
1218 * BIOCSETZBUF Set current zero-copy buffer locations.
1219 * BIOCGETZMAX Get maximum zero-copy buffer size.
1220 * BIOCROTZBUF Force rotation of zero-copy buffer
1221 * BIOCSETBUFMODE Set buffer mode.
1222 * BIOCGETBUFMODE Get current buffer mode.
1226 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1232 error = devfs_get_cdevpriv((void **)&d);
1237 * Refresh PID associated with this descriptor.
1240 BPF_PID_REFRESH(d, td);
1241 if (d->bd_state == BPF_WAITING)
1242 callout_stop(&d->bd_callout);
1243 d->bd_state = BPF_IDLE;
1246 if (d->bd_locked == 1) {
1252 #ifdef COMPAT_FREEBSD32
1253 case BIOCGDLTLIST32:
1257 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1258 case BIOCGRTIMEOUT32:
1269 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1270 case BIOCSRTIMEOUT32:
1280 #ifdef COMPAT_FREEBSD32
1282 * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1283 * that it will get 32-bit packet headers.
1289 case BIOCGDLTLIST32:
1290 case BIOCGRTIMEOUT32:
1291 case BIOCSRTIMEOUT32:
1298 CURVNET_SET(TD_TO_VNET(td));
1306 * Check for read packet available.
1314 while (d->bd_hbuf_in_use)
1315 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1316 PRINET, "bd_hbuf", 0);
1329 if (d->bd_bif == NULL)
1332 ifp = d->bd_bif->bif_ifp;
1333 error = (*ifp->if_ioctl)(ifp, cmd, addr);
1339 * Get buffer len [for read()].
1343 *(u_int *)addr = d->bd_bufsize;
1348 * Set buffer length.
1351 error = bpf_ioctl_sblen(d, (u_int *)addr);
1355 * Set link layer read filter.
1360 #ifdef COMPAT_FREEBSD32
1365 error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1369 * Flush read packet buffer.
1378 * Put interface into promiscuous mode.
1381 if (d->bd_bif == NULL) {
1383 * No interface attached yet.
1388 if (d->bd_promisc == 0) {
1389 error = ifpromisc(d->bd_bif->bif_ifp, 1);
1396 * Get current data link type.
1400 if (d->bd_bif == NULL)
1403 *(u_int *)addr = d->bd_bif->bif_dlt;
1408 * Get a list of supported data link types.
1410 #ifdef COMPAT_FREEBSD32
1411 case BIOCGDLTLIST32:
1413 struct bpf_dltlist32 *list32;
1414 struct bpf_dltlist dltlist;
1416 list32 = (struct bpf_dltlist32 *)addr;
1417 dltlist.bfl_len = list32->bfl_len;
1418 dltlist.bfl_list = PTRIN(list32->bfl_list);
1420 if (d->bd_bif == NULL)
1423 error = bpf_getdltlist(d, &dltlist);
1425 list32->bfl_len = dltlist.bfl_len;
1434 if (d->bd_bif == NULL)
1437 error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1442 * Set data link type.
1446 if (d->bd_bif == NULL)
1449 error = bpf_setdlt(d, *(u_int *)addr);
1454 * Get interface name.
1458 if (d->bd_bif == NULL)
1461 struct ifnet *const ifp = d->bd_bif->bif_ifp;
1462 struct ifreq *const ifr = (struct ifreq *)addr;
1464 strlcpy(ifr->ifr_name, ifp->if_xname,
1465 sizeof(ifr->ifr_name));
1475 error = bpf_setif(d, (struct ifreq *)addr);
1483 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1484 case BIOCSRTIMEOUT32:
1487 struct timeval *tv = (struct timeval *)addr;
1488 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1489 struct timeval32 *tv32;
1490 struct timeval tv64;
1492 if (cmd == BIOCSRTIMEOUT32) {
1493 tv32 = (struct timeval32 *)addr;
1495 tv->tv_sec = tv32->tv_sec;
1496 tv->tv_usec = tv32->tv_usec;
1499 tv = (struct timeval *)addr;
1502 * Subtract 1 tick from tvtohz() since this isn't
1505 if ((error = itimerfix(tv)) == 0)
1506 d->bd_rtout = tvtohz(tv) - 1;
1514 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1515 case BIOCGRTIMEOUT32:
1519 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1520 struct timeval32 *tv32;
1521 struct timeval tv64;
1523 if (cmd == BIOCGRTIMEOUT32)
1527 tv = (struct timeval *)addr;
1529 tv->tv_sec = d->bd_rtout / hz;
1530 tv->tv_usec = (d->bd_rtout % hz) * tick;
1531 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1532 if (cmd == BIOCGRTIMEOUT32) {
1533 tv32 = (struct timeval32 *)addr;
1534 tv32->tv_sec = tv->tv_sec;
1535 tv32->tv_usec = tv->tv_usec;
1547 struct bpf_stat *bs = (struct bpf_stat *)addr;
1549 /* XXXCSJP overflow */
1550 bs->bs_recv = d->bd_rcount;
1551 bs->bs_drop = d->bd_dcount;
1556 * Set immediate mode.
1560 d->bd_immediate = *(u_int *)addr;
1566 struct bpf_version *bv = (struct bpf_version *)addr;
1568 bv->bv_major = BPF_MAJOR_VERSION;
1569 bv->bv_minor = BPF_MINOR_VERSION;
1574 * Get "header already complete" flag
1578 *(u_int *)addr = d->bd_hdrcmplt;
1583 * Set "header already complete" flag
1587 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1592 * Get packet direction flag
1594 case BIOCGDIRECTION:
1596 *(u_int *)addr = d->bd_direction;
1601 * Set packet direction flag
1603 case BIOCSDIRECTION:
1607 direction = *(u_int *)addr;
1608 switch (direction) {
1613 d->bd_direction = direction;
1623 * Get packet timestamp format and resolution.
1627 *(u_int *)addr = d->bd_tstamp;
1632 * Set packet timestamp format and resolution.
1638 func = *(u_int *)addr;
1639 if (BPF_T_VALID(func))
1640 d->bd_tstamp = func;
1648 d->bd_feedback = *(u_int *)addr;
1658 case FIONBIO: /* Non-blocking I/O */
1661 case FIOASYNC: /* Send signal on receive packets */
1663 d->bd_async = *(int *)addr;
1669 * XXX: Add some sort of locking here?
1670 * fsetown() can sleep.
1672 error = fsetown(*(int *)addr, &d->bd_sigio);
1677 *(int *)addr = fgetown(&d->bd_sigio);
1681 /* This is deprecated, FIOSETOWN should be used instead. */
1683 error = fsetown(-(*(int *)addr), &d->bd_sigio);
1686 /* This is deprecated, FIOGETOWN should be used instead. */
1688 *(int *)addr = -fgetown(&d->bd_sigio);
1691 case BIOCSRSIG: /* Set receive signal */
1695 sig = *(u_int *)addr;
1708 *(u_int *)addr = d->bd_sig;
1712 case BIOCGETBUFMODE:
1714 *(u_int *)addr = d->bd_bufmode;
1718 case BIOCSETBUFMODE:
1720 * Allow the buffering mode to be changed as long as we
1721 * haven't yet committed to a particular mode. Our
1722 * definition of commitment, for now, is whether or not a
1723 * buffer has been allocated or an interface attached, since
1724 * that's the point where things get tricky.
1726 switch (*(u_int *)addr) {
1727 case BPF_BUFMODE_BUFFER:
1730 case BPF_BUFMODE_ZBUF:
1731 if (bpf_zerocopy_enable)
1741 if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1742 d->bd_fbuf != NULL || d->bd_bif != NULL) {
1747 d->bd_bufmode = *(u_int *)addr;
1752 error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1756 error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1760 error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1768 * Set d's packet filter program to fp. If this file already has a filter,
1769 * free it and replace it. Returns EINVAL for bogus requests.
1771 * Note we need global lock here to serialize bpf_setf() and bpf_setif() calls
1772 * since reading d->bd_bif can't be protected by d or interface lock due to
1775 * Additionally, we have to acquire interface write lock due to bpf_mtap() uses
1776 * interface read lock to read all filers.
1780 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1782 #ifdef COMPAT_FREEBSD32
1783 struct bpf_program fp_swab;
1784 struct bpf_program32 *fp32;
1786 struct bpf_insn *fcode, *old;
1788 bpf_jit_filter *jfunc, *ofunc;
1794 #ifdef COMPAT_FREEBSD32
1799 fp32 = (struct bpf_program32 *)fp;
1800 fp_swab.bf_len = fp32->bf_len;
1801 fp_swab.bf_insns = (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1817 jfunc = ofunc = NULL;
1822 * Check new filter validness before acquiring any locks.
1823 * Allocate memory for new filter, if needed.
1826 if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1828 size = flen * sizeof(*fp->bf_insns);
1830 /* We're setting up new filter. Copy and check actual data. */
1831 fcode = malloc(size, M_BPF, M_WAITOK);
1832 if (copyin(fp->bf_insns, fcode, size) != 0 ||
1833 !bpf_validate(fcode, flen)) {
1838 /* Filter is copied inside fcode and is perfectly valid. */
1839 jfunc = bpf_jitter(fcode, flen);
1846 * Set up new filter.
1847 * Protect filter change by interface lock.
1848 * Additionally, we are protected by global lock here.
1850 if (d->bd_bif != NULL)
1851 BPFIF_WLOCK(d->bd_bif);
1853 if (cmd == BIOCSETWF) {
1854 old = d->bd_wfilter;
1855 d->bd_wfilter = fcode;
1857 old = d->bd_rfilter;
1858 d->bd_rfilter = fcode;
1860 ofunc = d->bd_bfilter;
1861 d->bd_bfilter = jfunc;
1863 if (cmd == BIOCSETF)
1866 need_upgrade = bpf_check_upgrade(cmd, d, fcode, flen);
1869 if (d->bd_bif != NULL)
1870 BPFIF_WUNLOCK(d->bd_bif);
1875 bpf_destroy_jit_filter(ofunc);
1878 /* Move d to active readers list. */
1879 if (need_upgrade != 0)
1887 * Detach a file from its current interface (if attached at all) and attach
1888 * to the interface indicated by the name stored in ifr.
1889 * Return an errno or 0.
1892 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1895 struct ifnet *theywant;
1899 theywant = ifunit(ifr->ifr_name);
1900 if (theywant == NULL || theywant->if_bpf == NULL)
1903 bp = theywant->if_bpf;
1905 /* Check if interface is not being detached from BPF */
1907 if (bp->flags & BPFIF_FLAG_DYING) {
1914 * Behavior here depends on the buffering model. If we're using
1915 * kernel memory buffers, then we can allocate them here. If we're
1916 * using zero-copy, then the user process must have registered
1917 * buffers by the time we get here. If not, return an error.
1919 switch (d->bd_bufmode) {
1920 case BPF_BUFMODE_BUFFER:
1921 case BPF_BUFMODE_ZBUF:
1922 if (d->bd_sbuf == NULL)
1927 panic("bpf_setif: bufmode %d", d->bd_bufmode);
1929 if (bp != d->bd_bif)
1938 * Support for select() and poll() system calls
1940 * Return true iff the specific operation will not block indefinitely.
1941 * Otherwise, return false but make a note that a selwakeup() must be done.
1944 bpfpoll(struct cdev *dev, int events, struct thread *td)
1949 if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
1951 (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1954 * Refresh PID associated with this descriptor.
1956 revents = events & (POLLOUT | POLLWRNORM);
1958 BPF_PID_REFRESH(d, td);
1959 if (events & (POLLIN | POLLRDNORM)) {
1961 revents |= events & (POLLIN | POLLRDNORM);
1963 selrecord(td, &d->bd_sel);
1964 /* Start the read timeout if necessary. */
1965 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1966 callout_reset(&d->bd_callout, d->bd_rtout,
1968 d->bd_state = BPF_WAITING;
1977 * Support for kevent() system call. Register EVFILT_READ filters and
1978 * reject all others.
1981 bpfkqfilter(struct cdev *dev, struct knote *kn)
1985 if (devfs_get_cdevpriv((void **)&d) != 0 ||
1986 kn->kn_filter != EVFILT_READ)
1990 * Refresh PID associated with this descriptor.
1993 BPF_PID_REFRESH_CUR(d);
1994 kn->kn_fop = &bpfread_filtops;
1996 knlist_add(&d->bd_sel.si_note, kn, 1);
2003 filt_bpfdetach(struct knote *kn)
2005 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2007 knlist_remove(&d->bd_sel.si_note, kn, 0);
2011 filt_bpfread(struct knote *kn, long hint)
2013 struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2016 BPFD_LOCK_ASSERT(d);
2017 ready = bpf_ready(d);
2019 kn->kn_data = d->bd_slen;
2020 while (d->bd_hbuf_in_use)
2021 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2022 PRINET, "bd_hbuf", 0);
2024 kn->kn_data += d->bd_hlen;
2025 } else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2026 callout_reset(&d->bd_callout, d->bd_rtout,
2028 d->bd_state = BPF_WAITING;
2034 #define BPF_TSTAMP_NONE 0
2035 #define BPF_TSTAMP_FAST 1
2036 #define BPF_TSTAMP_NORMAL 2
2037 #define BPF_TSTAMP_EXTERN 3
2040 bpf_ts_quality(int tstype)
2043 if (tstype == BPF_T_NONE)
2044 return (BPF_TSTAMP_NONE);
2045 if ((tstype & BPF_T_FAST) != 0)
2046 return (BPF_TSTAMP_FAST);
2048 return (BPF_TSTAMP_NORMAL);
2052 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
2057 quality = bpf_ts_quality(tstype);
2058 if (quality == BPF_TSTAMP_NONE)
2062 tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2064 *bt = *(struct bintime *)(tag + 1);
2065 return (BPF_TSTAMP_EXTERN);
2068 if (quality == BPF_TSTAMP_NORMAL)
2077 * Incoming linkage from device drivers. Process the packet pkt, of length
2078 * pktlen, which is stored in a contiguous buffer. The packet is parsed
2079 * by each process' filter, and if accepted, stashed into the corresponding
2083 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2093 gottime = BPF_TSTAMP_NONE;
2097 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2099 * We are not using any locks for d here because:
2100 * 1) any filter change is protected by interface
2102 * 2) destroying/detaching d is protected by interface
2106 /* XXX: Do not protect counter for the sake of performance. */
2109 * NB: We dont call BPF_CHECK_DIRECTION() here since there is no
2110 * way for the caller to indiciate to us whether this packet
2111 * is inbound or outbound. In the bpf_mtap() routines, we use
2112 * the interface pointers on the mbuf to figure it out.
2115 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2117 slen = (*(bf->func))(pkt, pktlen, pktlen);
2120 slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2123 * Filter matches. Let's to acquire write lock.
2128 if (gottime < bpf_ts_quality(d->bd_tstamp))
2129 gottime = bpf_gettime(&bt, d->bd_tstamp, NULL);
2131 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2133 catchpacket(d, pkt, pktlen, slen,
2134 bpf_append_bytes, &bt);
2141 #define BPF_CHECK_DIRECTION(d, r, i) \
2142 (((d)->bd_direction == BPF_D_IN && (r) != (i)) || \
2143 ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2146 * Incoming linkage from device drivers, when packet is in an mbuf chain.
2147 * Locking model is explained in bpf_tap().
2150 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2160 /* Skip outgoing duplicate packets. */
2161 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2162 m->m_flags &= ~M_PROMISC;
2166 pktlen = m_length(m, NULL);
2167 gottime = BPF_TSTAMP_NONE;
2171 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2172 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2176 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2177 /* XXX We cannot handle multiple mbufs. */
2178 if (bf != NULL && m->m_next == NULL)
2179 slen = (*(bf->func))(mtod(m, u_char *), pktlen, pktlen);
2182 slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2187 if (gottime < bpf_ts_quality(d->bd_tstamp))
2188 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2190 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2192 catchpacket(d, (u_char *)m, pktlen, slen,
2193 bpf_append_mbuf, &bt);
2201 * Incoming linkage from device drivers, when packet is in
2202 * an mbuf chain and to be prepended by a contiguous header.
2205 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2213 /* Skip outgoing duplicate packets. */
2214 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2215 m->m_flags &= ~M_PROMISC;
2219 pktlen = m_length(m, NULL);
2221 * Craft on-stack mbuf suitable for passing to bpf_filter.
2222 * Note that we cut corners here; we only setup what's
2223 * absolutely needed--this mbuf should never go anywhere else.
2230 gottime = BPF_TSTAMP_NONE;
2234 LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2235 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2238 slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2243 if (gottime < bpf_ts_quality(d->bd_tstamp))
2244 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2246 if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2248 catchpacket(d, (u_char *)&mb, pktlen, slen,
2249 bpf_append_mbuf, &bt);
2256 #undef BPF_CHECK_DIRECTION
2258 #undef BPF_TSTAMP_NONE
2259 #undef BPF_TSTAMP_FAST
2260 #undef BPF_TSTAMP_NORMAL
2261 #undef BPF_TSTAMP_EXTERN
2264 bpf_hdrlen(struct bpf_d *d)
2268 hdrlen = d->bd_bif->bif_hdrlen;
2269 #ifndef BURN_BRIDGES
2270 if (d->bd_tstamp == BPF_T_NONE ||
2271 BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2272 #ifdef COMPAT_FREEBSD32
2274 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2277 hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2280 hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2281 #ifdef COMPAT_FREEBSD32
2283 hdrlen = BPF_WORDALIGN32(hdrlen);
2286 hdrlen = BPF_WORDALIGN(hdrlen);
2288 return (hdrlen - d->bd_bif->bif_hdrlen);
2292 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2296 struct timespec tsn;
2298 if ((tstype & BPF_T_MONOTONIC) == 0) {
2300 bintime_add(&bt2, &boottimebin);
2303 switch (BPF_T_FORMAT(tstype)) {
2304 case BPF_T_MICROTIME:
2305 bintime2timeval(bt, &tsm);
2306 ts->bt_sec = tsm.tv_sec;
2307 ts->bt_frac = tsm.tv_usec;
2309 case BPF_T_NANOTIME:
2310 bintime2timespec(bt, &tsn);
2311 ts->bt_sec = tsn.tv_sec;
2312 ts->bt_frac = tsn.tv_nsec;
2315 ts->bt_sec = bt->sec;
2316 ts->bt_frac = bt->frac;
2322 * Move the packet data from interface memory (pkt) into the
2323 * store buffer. "cpfn" is the routine called to do the actual data
2324 * transfer. bcopy is passed in to copy contiguous chunks, while
2325 * bpf_append_mbuf is passed in to copy mbuf chains. In the latter case,
2326 * pkt is really an mbuf.
2329 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2330 void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2333 struct bpf_xhdr hdr;
2334 #ifndef BURN_BRIDGES
2335 struct bpf_hdr hdr_old;
2336 #ifdef COMPAT_FREEBSD32
2337 struct bpf_hdr32 hdr32_old;
2340 int caplen, curlen, hdrlen, totlen;
2345 BPFD_LOCK_ASSERT(d);
2348 * Detect whether user space has released a buffer back to us, and if
2349 * so, move it from being a hold buffer to a free buffer. This may
2350 * not be the best place to do it (for example, we might only want to
2351 * run this check if we need the space), but for now it's a reliable
2354 if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2355 while (d->bd_hbuf_in_use)
2356 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2357 PRINET, "bd_hbuf", 0);
2358 d->bd_fbuf = d->bd_hbuf;
2361 bpf_buf_reclaimed(d);
2365 * Figure out how many bytes to move. If the packet is
2366 * greater or equal to the snapshot length, transfer that
2367 * much. Otherwise, transfer the whole packet (unless
2368 * we hit the buffer size limit).
2370 hdrlen = bpf_hdrlen(d);
2371 totlen = hdrlen + min(snaplen, pktlen);
2372 if (totlen > d->bd_bufsize)
2373 totlen = d->bd_bufsize;
2376 * Round up the end of the previous packet to the next longword.
2378 * Drop the packet if there's no room and no hope of room
2379 * If the packet would overflow the storage buffer or the storage
2380 * buffer is considered immutable by the buffer model, try to rotate
2381 * the buffer and wakeup pending processes.
2383 #ifdef COMPAT_FREEBSD32
2385 curlen = BPF_WORDALIGN32(d->bd_slen);
2388 curlen = BPF_WORDALIGN(d->bd_slen);
2389 if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2390 if (d->bd_fbuf == NULL) {
2392 * There's no room in the store buffer, and no
2393 * prospect of room, so drop the packet. Notify the
2400 while (d->bd_hbuf_in_use)
2401 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2402 PRINET, "bd_hbuf", 0);
2406 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2408 * Immediate mode is set, or the read timeout has already
2409 * expired during a select call. A packet arrived, so the
2410 * reader should be woken up.
2413 caplen = totlen - hdrlen;
2414 tstype = d->bd_tstamp;
2415 do_timestamp = tstype != BPF_T_NONE;
2416 #ifndef BURN_BRIDGES
2417 if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2420 bpf_bintime2ts(bt, &ts, tstype);
2421 #ifdef COMPAT_FREEBSD32
2422 if (d->bd_compat32) {
2423 bzero(&hdr32_old, sizeof(hdr32_old));
2425 hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2426 hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2428 hdr32_old.bh_datalen = pktlen;
2429 hdr32_old.bh_hdrlen = hdrlen;
2430 hdr32_old.bh_caplen = caplen;
2431 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2436 bzero(&hdr_old, sizeof(hdr_old));
2438 hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2439 hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2441 hdr_old.bh_datalen = pktlen;
2442 hdr_old.bh_hdrlen = hdrlen;
2443 hdr_old.bh_caplen = caplen;
2444 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2451 * Append the bpf header. Note we append the actual header size, but
2452 * move forward the length of the header plus padding.
2454 bzero(&hdr, sizeof(hdr));
2456 bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2457 hdr.bh_datalen = pktlen;
2458 hdr.bh_hdrlen = hdrlen;
2459 hdr.bh_caplen = caplen;
2460 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2463 * Copy the packet data into the store buffer and update its length.
2465 #ifndef BURN_BRIDGES
2468 (*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2469 d->bd_slen = curlen + totlen;
2476 * Free buffers currently in use by a descriptor.
2480 bpf_freed(struct bpf_d *d)
2484 * We don't need to lock out interrupts since this descriptor has
2485 * been detached from its interface and it yet hasn't been marked
2489 if (d->bd_rfilter != NULL) {
2490 free((caddr_t)d->bd_rfilter, M_BPF);
2492 if (d->bd_bfilter != NULL)
2493 bpf_destroy_jit_filter(d->bd_bfilter);
2496 if (d->bd_wfilter != NULL)
2497 free((caddr_t)d->bd_wfilter, M_BPF);
2498 mtx_destroy(&d->bd_lock);
2502 * Attach an interface to bpf. dlt is the link layer type; hdrlen is the
2503 * fixed size of the link header (variable length headers not yet supported).
2506 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2509 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2513 * Attach an interface to bpf. ifp is a pointer to the structure
2514 * defining the interface to be attached, dlt is the link layer type,
2515 * and hdrlen is the fixed size of the link header (variable length
2516 * headers are not yet supporrted).
2519 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2523 bp = malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
2527 LIST_INIT(&bp->bif_dlist);
2528 LIST_INIT(&bp->bif_wlist);
2531 rw_init(&bp->bif_lock, "bpf interface lock");
2532 KASSERT(*driverp == NULL, ("bpfattach2: driverp already initialized"));
2536 LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2539 bp->bif_hdrlen = hdrlen;
2542 if_printf(ifp, "bpf attached\n");
2546 * Detach bpf from an interface. This involves detaching each descriptor
2547 * associated with the interface. Notify each descriptor as it's detached
2548 * so that any sleepers wake up and get ENXIO.
2551 bpfdetach(struct ifnet *ifp)
2553 struct bpf_if *bp, *bp_temp;
2560 /* Find all bpf_if struct's which reference ifp and detach them. */
2561 LIST_FOREACH_SAFE(bp, &bpf_iflist, bif_next, bp_temp) {
2562 if (ifp != bp->bif_ifp)
2565 LIST_REMOVE(bp, bif_next);
2566 /* Add to to-be-freed list */
2567 LIST_INSERT_HEAD(&bpf_freelist, bp, bif_next);
2571 * Delay freeing bp till interface is detached
2572 * and all routes through this interface are removed.
2573 * Mark bp as detached to restrict new consumers.
2576 bp->flags |= BPFIF_FLAG_DYING;
2579 CTR4(KTR_NET, "%s: sheduling free for encap %d (%p) for if %p",
2580 __func__, bp->bif_dlt, bp, ifp);
2582 /* Free common descriptors */
2583 while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
2584 bpf_detachd_locked(d);
2590 /* Free writer-only descriptors */
2591 while ((d = LIST_FIRST(&bp->bif_wlist)) != NULL) {
2592 bpf_detachd_locked(d);
2602 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
2607 * Interface departure handler.
2608 * Note departure event does not guarantee interface is going down.
2609 * Interface renaming is currently done via departure/arrival event set.
2611 * Departure handled is called after all routes pointing to
2612 * given interface are removed and interface is in down state
2613 * restricting any packets to be sent/received. We assume it is now safe
2614 * to free data allocated by BPF.
2617 bpf_ifdetach(void *arg __unused, struct ifnet *ifp)
2619 struct bpf_if *bp, *bp_temp;
2624 * Find matching entries in free list.
2625 * Nothing should be found if bpfdetach() was not called.
2627 LIST_FOREACH_SAFE(bp, &bpf_freelist, bif_next, bp_temp) {
2628 if (ifp != bp->bif_ifp)
2631 CTR3(KTR_NET, "%s: freeing BPF instance %p for interface %p",
2634 LIST_REMOVE(bp, bif_next);
2636 rw_destroy(&bp->bif_lock);
2644 * Note that we cannot zero other pointers to
2645 * custom DLTs possibly used by given interface.
2652 * Get a list of available data link type of the interface.
2655 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2663 ifp = d->bd_bif->bif_ifp;
2666 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2667 if (bp->bif_ifp != ifp)
2669 if (bfl->bfl_list != NULL) {
2670 if (n >= bfl->bfl_len)
2672 error = copyout(&bp->bif_dlt,
2673 bfl->bfl_list + n, sizeof(u_int));
2682 * Set the data link type of a BPF instance.
2685 bpf_setdlt(struct bpf_d *d, u_int dlt)
2687 int error, opromisc;
2693 if (d->bd_bif->bif_dlt == dlt)
2695 ifp = d->bd_bif->bif_ifp;
2697 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2698 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2703 opromisc = d->bd_promisc;
2709 error = ifpromisc(bp->bif_ifp, 1);
2711 if_printf(bp->bif_ifp,
2712 "bpf_setdlt: ifpromisc failed (%d)\n",
2718 return (bp == NULL ? EINVAL : 0);
2722 bpf_drvinit(void *unused)
2726 mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
2727 LIST_INIT(&bpf_iflist);
2728 LIST_INIT(&bpf_freelist);
2730 dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2731 /* For compatibility */
2732 make_dev_alias(dev, "bpf0");
2734 /* Register interface departure handler */
2735 bpf_ifdetach_cookie = EVENTHANDLER_REGISTER(
2736 ifnet_departure_event, bpf_ifdetach, NULL,
2737 EVENTHANDLER_PRI_ANY);
2741 * Zero out the various packet counters associated with all of the bpf
2742 * descriptors. At some point, we will probably want to get a bit more
2743 * granular and allow the user to specify descriptors to be zeroed.
2746 bpf_zero_counters(void)
2752 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2754 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2770 * Fill filter statistics
2773 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2776 bzero(d, sizeof(*d));
2777 BPFD_LOCK_ASSERT(bd);
2778 d->bd_structsize = sizeof(*d);
2779 /* XXX: reading should be protected by global lock */
2780 d->bd_immediate = bd->bd_immediate;
2781 d->bd_promisc = bd->bd_promisc;
2782 d->bd_hdrcmplt = bd->bd_hdrcmplt;
2783 d->bd_direction = bd->bd_direction;
2784 d->bd_feedback = bd->bd_feedback;
2785 d->bd_async = bd->bd_async;
2786 d->bd_rcount = bd->bd_rcount;
2787 d->bd_dcount = bd->bd_dcount;
2788 d->bd_fcount = bd->bd_fcount;
2789 d->bd_sig = bd->bd_sig;
2790 d->bd_slen = bd->bd_slen;
2791 d->bd_hlen = bd->bd_hlen;
2792 d->bd_bufsize = bd->bd_bufsize;
2793 d->bd_pid = bd->bd_pid;
2794 strlcpy(d->bd_ifname,
2795 bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2796 d->bd_locked = bd->bd_locked;
2797 d->bd_wcount = bd->bd_wcount;
2798 d->bd_wdcount = bd->bd_wdcount;
2799 d->bd_wfcount = bd->bd_wfcount;
2800 d->bd_zcopy = bd->bd_zcopy;
2801 d->bd_bufmode = bd->bd_bufmode;
2805 * Handle `netstat -B' stats request
2808 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2810 struct xbpf_d *xbdbuf, *xbd, zerostats;
2816 * XXX This is not technically correct. It is possible for non
2817 * privileged users to open bpf devices. It would make sense
2818 * if the users who opened the devices were able to retrieve
2819 * the statistics for them, too.
2821 error = priv_check(req->td, PRIV_NET_BPF);
2825 * Check to see if the user is requesting that the counters be
2826 * zeroed out. Explicitly check that the supplied data is zeroed,
2827 * as we aren't allowing the user to set the counters currently.
2829 if (req->newptr != NULL) {
2830 if (req->newlen != sizeof(zerostats))
2832 bzero(&zerostats, sizeof(zerostats));
2834 if (bcmp(xbd, &zerostats, sizeof(*xbd)) != 0)
2836 bpf_zero_counters();
2839 if (req->oldptr == NULL)
2840 return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
2841 if (bpf_bpfd_cnt == 0)
2842 return (SYSCTL_OUT(req, 0, 0));
2843 xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
2845 if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
2847 free(xbdbuf, M_BPF);
2851 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2853 /* Send writers-only first */
2854 LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
2855 xbd = &xbdbuf[index++];
2857 bpfstats_fill_xbpf(xbd, bd);
2860 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2861 xbd = &xbdbuf[index++];
2863 bpfstats_fill_xbpf(xbd, bd);
2869 error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
2870 free(xbdbuf, M_BPF);
2874 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
2876 #else /* !DEV_BPF && !NETGRAPH_BPF */
2878 * NOP stubs to allow bpf-using drivers to load and function.
2880 * A 'better' implementation would allow the core bpf functionality
2881 * to be loaded at runtime.
2883 static struct bpf_if bp_null;
2886 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2891 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2896 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
2901 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2904 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2908 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2911 *driverp = &bp_null;
2915 bpfdetach(struct ifnet *ifp)
2920 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
2922 return -1; /* "no filter" behaviour */
2926 bpf_validate(const struct bpf_insn *f, int len)
2928 return 0; /* false */
2931 #endif /* !DEV_BPF && !NETGRAPH_BPF */