Home | History | Annotate | Line # | Download | only in net
bpf.c revision 1.249.2.3
      1 /*	$NetBSD: bpf.c,v 1.249.2.3 2024/09/13 14:13:05 martin Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1990, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from the Stanford/CMU enet packet filter,
      8  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
      9  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
     10  * Berkeley Laboratory.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)bpf.c	8.4 (Berkeley) 1/9/95
     37  * static char rcsid[] =
     38  * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
     39  */
     40 
     41 #include <sys/cdefs.h>
     42 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.249.2.3 2024/09/13 14:13:05 martin Exp $");
     43 
     44 #if defined(_KERNEL_OPT)
     45 #include "opt_bpf.h"
     46 #include "sl.h"
     47 #include "opt_net_mpsafe.h"
     48 #endif
     49 
     50 #include <sys/param.h>
     51 #include <sys/systm.h>
     52 #include <sys/mbuf.h>
     53 #include <sys/buf.h>
     54 #include <sys/time.h>
     55 #include <sys/proc.h>
     56 #include <sys/ioctl.h>
     57 #include <sys/conf.h>
     58 #include <sys/vnode.h>
     59 #include <sys/queue.h>
     60 #include <sys/stat.h>
     61 #include <sys/module.h>
     62 #include <sys/atomic.h>
     63 #include <sys/cpu.h>
     64 
     65 #include <sys/file.h>
     66 #include <sys/filedesc.h>
     67 #include <sys/tty.h>
     68 #include <sys/uio.h>
     69 
     70 #include <sys/protosw.h>
     71 #include <sys/socket.h>
     72 #include <sys/errno.h>
     73 #include <sys/kernel.h>
     74 #include <sys/poll.h>
     75 #include <sys/sysctl.h>
     76 #include <sys/kauth.h>
     77 #include <sys/syslog.h>
     78 #include <sys/percpu.h>
     79 #include <sys/pserialize.h>
     80 #include <sys/lwp.h>
     81 #include <sys/xcall.h>
     82 
     83 #include <net/if.h>
     84 #include <net/slip.h>
     85 
     86 #include <net/bpf.h>
     87 #include <net/bpfdesc.h>
     88 #include <net/bpfjit.h>
     89 
     90 #include <net/if_arc.h>
     91 #include <net/if_ether.h>
     92 #include <net/if_types.h>
     93 
     94 #include <netinet/in.h>
     95 #include <netinet/if_inarp.h>
     96 
     97 
     98 #include <compat/sys/sockio.h>
     99 
    100 #ifndef BPF_BUFSIZE
    101 /*
    102  * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
    103  * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
    104  */
    105 # define BPF_BUFSIZE 32768
    106 #endif
    107 
    108 #define PRINET  26			/* interruptible */
    109 
    110 /*
    111  * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
    112  * XXX the default values should be computed dynamically based
    113  * on available memory size and available mbuf clusters.
    114  */
    115 static int bpf_bufsize = BPF_BUFSIZE;
    116 static int bpf_maxbufsize = BPF_DFLTBUFSIZE;	/* XXX set dynamically, see above */
    117 static bool bpf_jit = false;
    118 
    119 struct bpfjit_ops bpfjit_module_ops = {
    120 	.bj_generate_code = NULL,
    121 	.bj_free_code = NULL
    122 };
    123 
    124 /*
    125  * Global BPF statistics returned by net.bpf.stats sysctl.
    126  */
    127 static struct percpu	*bpf_gstats_percpu; /* struct bpf_stat */
    128 
    129 #define BPF_STATINC(id)					\
    130 	{						\
    131 		struct bpf_stat *__stats =		\
    132 		    percpu_getref(bpf_gstats_percpu);	\
    133 		__stats->bs_##id++;			\
    134 		percpu_putref(bpf_gstats_percpu);	\
    135 	}
    136 
    137 /*
    138  * Locking notes:
    139  * - bpf_mtx (adaptive mutex) protects:
    140  *   - Gobal lists: bpf_iflist and bpf_dlist
    141  *   - struct bpf_if
    142  *   - bpf_close
    143  *   - bpf_psz (pserialize)
    144  * - struct bpf_d has two mutexes:
    145  *   - bd_buf_mtx (spin mutex) protects the buffers that can be accessed
    146  *     on packet tapping
    147  *   - bd_mtx (adaptive mutex) protects member variables other than the buffers
    148  * - Locking order: bpf_mtx => bpf_d#bd_mtx => bpf_d#bd_buf_mtx
    149  * - struct bpf_d obtained via fp->f_bpf in bpf_read and bpf_write is
    150  *   never freed because struct bpf_d is only freed in bpf_close and
    151  *   bpf_close never be called while executing bpf_read and bpf_write
    152  * - A filter that is assigned to bpf_d can be replaced with another filter
    153  *   while tapping packets, so it needs to be done atomically
    154  * - struct bpf_d is iterated on bpf_dlist with psz
    155  * - struct bpf_if is iterated on bpf_iflist with psz or psref
    156  */
    157 /*
    158  * Use a mutex to avoid a race condition between gathering the stats/peers
    159  * and opening/closing the device.
    160  */
    161 static kmutex_t bpf_mtx;
    162 
    163 static struct psref_class	*bpf_psref_class __read_mostly;
    164 static pserialize_t		bpf_psz;
    165 
    166 static inline void
    167 bpf_if_acquire(struct bpf_if *bp, struct psref *psref)
    168 {
    169 
    170 	psref_acquire(psref, &bp->bif_psref, bpf_psref_class);
    171 }
    172 
    173 static inline void
    174 bpf_if_release(struct bpf_if *bp, struct psref *psref)
    175 {
    176 
    177 	psref_release(psref, &bp->bif_psref, bpf_psref_class);
    178 }
    179 
    180 /*
    181  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
    182  *  bpf_dtab holds the descriptors, indexed by minor device #
    183  */
    184 static struct pslist_head bpf_iflist;
    185 static struct pslist_head bpf_dlist;
    186 
    187 /* Macros for bpf_d on bpf_dlist */
    188 #define BPF_DLIST_WRITER_INSERT_HEAD(__d)				\
    189 	PSLIST_WRITER_INSERT_HEAD(&bpf_dlist, (__d), bd_bpf_dlist_entry)
    190 #define BPF_DLIST_READER_FOREACH(__d)					\
    191 	PSLIST_READER_FOREACH((__d), &bpf_dlist, struct bpf_d,		\
    192 	                      bd_bpf_dlist_entry)
    193 #define BPF_DLIST_WRITER_FOREACH(__d)					\
    194 	PSLIST_WRITER_FOREACH((__d), &bpf_dlist, struct bpf_d,		\
    195 	                      bd_bpf_dlist_entry)
    196 #define BPF_DLIST_ENTRY_INIT(__d)					\
    197 	PSLIST_ENTRY_INIT((__d), bd_bpf_dlist_entry)
    198 #define BPF_DLIST_WRITER_REMOVE(__d)					\
    199 	PSLIST_WRITER_REMOVE((__d), bd_bpf_dlist_entry)
    200 #define BPF_DLIST_ENTRY_DESTROY(__d)					\
    201 	PSLIST_ENTRY_DESTROY((__d), bd_bpf_dlist_entry)
    202 
    203 /* Macros for bpf_if on bpf_iflist */
    204 #define BPF_IFLIST_WRITER_INSERT_HEAD(__bp)				\
    205 	PSLIST_WRITER_INSERT_HEAD(&bpf_iflist, (__bp), bif_iflist_entry)
    206 #define BPF_IFLIST_READER_FOREACH(__bp)					\
    207 	PSLIST_READER_FOREACH((__bp), &bpf_iflist, struct bpf_if,	\
    208 	                      bif_iflist_entry)
    209 #define BPF_IFLIST_WRITER_FOREACH(__bp)					\
    210 	PSLIST_WRITER_FOREACH((__bp), &bpf_iflist, struct bpf_if,	\
    211 	                      bif_iflist_entry)
    212 #define BPF_IFLIST_WRITER_REMOVE(__bp)					\
    213 	PSLIST_WRITER_REMOVE((__bp), bif_iflist_entry)
    214 #define BPF_IFLIST_ENTRY_INIT(__bp)					\
    215 	PSLIST_ENTRY_INIT((__bp), bif_iflist_entry)
    216 #define BPF_IFLIST_ENTRY_DESTROY(__bp)					\
    217 	PSLIST_ENTRY_DESTROY((__bp), bif_iflist_entry)
    218 
    219 /* Macros for bpf_d on bpf_if#bif_dlist_pslist */
    220 #define BPFIF_DLIST_READER_FOREACH(__d, __bp)				\
    221 	PSLIST_READER_FOREACH((__d), &(__bp)->bif_dlist_head, struct bpf_d, \
    222 	                      bd_bif_dlist_entry)
    223 #define BPFIF_DLIST_WRITER_INSERT_HEAD(__bp, __d)			\
    224 	PSLIST_WRITER_INSERT_HEAD(&(__bp)->bif_dlist_head, (__d),	\
    225 	                          bd_bif_dlist_entry)
    226 #define BPFIF_DLIST_WRITER_REMOVE(__d)					\
    227 	PSLIST_WRITER_REMOVE((__d), bd_bif_dlist_entry)
    228 #define BPFIF_DLIST_ENTRY_INIT(__d)					\
    229 	PSLIST_ENTRY_INIT((__d), bd_bif_dlist_entry)
    230 #define	BPFIF_DLIST_READER_EMPTY(__bp)					\
    231 	(PSLIST_READER_FIRST(&(__bp)->bif_dlist_head, struct bpf_d,	\
    232 	                     bd_bif_dlist_entry) == NULL)
    233 #define	BPFIF_DLIST_WRITER_EMPTY(__bp)					\
    234 	(PSLIST_WRITER_FIRST(&(__bp)->bif_dlist_head, struct bpf_d,	\
    235 	                     bd_bif_dlist_entry) == NULL)
    236 #define BPFIF_DLIST_ENTRY_DESTROY(__d)					\
    237 	PSLIST_ENTRY_DESTROY((__d), bd_bif_dlist_entry)
    238 
    239 static int	bpf_allocbufs(struct bpf_d *);
    240 static u_int	bpf_xfilter(struct bpf_filter **, void *, u_int, u_int);
    241 static void	bpf_deliver(struct bpf_if *,
    242 		            void *(*cpfn)(void *, const void *, size_t),
    243 		            void *, u_int, u_int, const u_int);
    244 static void	bpf_freed(struct bpf_d *);
    245 static void	bpf_free_filter(struct bpf_filter *);
    246 static void	bpf_ifname(struct ifnet *, struct ifreq *);
    247 static void	*bpf_mcpy(void *, const void *, size_t);
    248 static int	bpf_movein(struct ifnet *, struct uio *, int, uint64_t,
    249 			        struct mbuf **, struct sockaddr *,
    250 				struct bpf_filter **);
    251 static void	bpf_attachd(struct bpf_d *, struct bpf_if *);
    252 static void	bpf_detachd(struct bpf_d *);
    253 static int	bpf_setif(struct bpf_d *, struct ifreq *);
    254 static int	bpf_setf(struct bpf_d *, struct bpf_program *, u_long);
    255 static void	bpf_timed_out(void *);
    256 static inline void
    257 		bpf_wakeup(struct bpf_d *);
    258 static int	bpf_hdrlen(struct bpf_d *);
    259 static void	catchpacket(struct bpf_d *, u_char *, u_int, u_int,
    260     void *(*)(void *, const void *, size_t), struct timespec *);
    261 static void	reset_d(struct bpf_d *);
    262 static int	bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
    263 static int	bpf_setdlt(struct bpf_d *, u_int);
    264 
    265 static int	bpf_read(struct file *, off_t *, struct uio *, kauth_cred_t,
    266     int);
    267 static int	bpf_write(struct file *, off_t *, struct uio *, kauth_cred_t,
    268     int);
    269 static int	bpf_ioctl(struct file *, u_long, void *);
    270 static int	bpf_poll(struct file *, int);
    271 static int	bpf_stat(struct file *, struct stat *);
    272 static int	bpf_close(struct file *);
    273 static int	bpf_kqfilter(struct file *, struct knote *);
    274 static void	bpf_softintr(void *);
    275 
    276 static const struct fileops bpf_fileops = {
    277 	.fo_name = "bpf",
    278 	.fo_read = bpf_read,
    279 	.fo_write = bpf_write,
    280 	.fo_ioctl = bpf_ioctl,
    281 	.fo_fcntl = fnullop_fcntl,
    282 	.fo_poll = bpf_poll,
    283 	.fo_stat = bpf_stat,
    284 	.fo_close = bpf_close,
    285 	.fo_kqfilter = bpf_kqfilter,
    286 	.fo_restart = fnullop_restart,
    287 };
    288 
    289 dev_type_open(bpfopen);
    290 
    291 const struct cdevsw bpf_cdevsw = {
    292 	.d_open = bpfopen,
    293 	.d_close = noclose,
    294 	.d_read = noread,
    295 	.d_write = nowrite,
    296 	.d_ioctl = noioctl,
    297 	.d_stop = nostop,
    298 	.d_tty = notty,
    299 	.d_poll = nopoll,
    300 	.d_mmap = nommap,
    301 	.d_kqfilter = nokqfilter,
    302 	.d_discard = nodiscard,
    303 	.d_flag = D_OTHER | D_MPSAFE
    304 };
    305 
    306 bpfjit_func_t
    307 bpf_jit_generate(bpf_ctx_t *bc, void *code, size_t size)
    308 {
    309 	struct bpfjit_ops *ops = &bpfjit_module_ops;
    310 	bpfjit_func_t (*generate_code)(const bpf_ctx_t *,
    311 	    const struct bpf_insn *, size_t);
    312 
    313 	generate_code = atomic_load_acquire(&ops->bj_generate_code);
    314 	if (generate_code != NULL) {
    315 		return generate_code(bc, code, size);
    316 	}
    317 	return NULL;
    318 }
    319 
    320 void
    321 bpf_jit_freecode(bpfjit_func_t jcode)
    322 {
    323 	KASSERT(bpfjit_module_ops.bj_free_code != NULL);
    324 	bpfjit_module_ops.bj_free_code(jcode);
    325 }
    326 
    327 static int
    328 bpf_movein(struct ifnet *ifp, struct uio *uio, int linktype, uint64_t mtu, struct mbuf **mp,
    329 	   struct sockaddr *sockp, struct bpf_filter **wfilter)
    330 {
    331 	struct mbuf *m, *m0, *n;
    332 	int error;
    333 	size_t len;
    334 	size_t hlen;
    335 	size_t align;
    336 	u_int slen;
    337 
    338 	/*
    339 	 * Build a sockaddr based on the data link layer type.
    340 	 * We do this at this level because the ethernet header
    341 	 * is copied directly into the data field of the sockaddr.
    342 	 * In the case of SLIP, there is no header and the packet
    343 	 * is forwarded as is.
    344 	 * Also, we are careful to leave room at the front of the mbuf
    345 	 * for the link level header.
    346 	 */
    347 	switch (linktype) {
    348 
    349 	case DLT_SLIP:
    350 		sockp->sa_family = AF_INET;
    351 		hlen = 0;
    352 		align = 0;
    353 		break;
    354 
    355 	case DLT_PPP:
    356 		sockp->sa_family = AF_UNSPEC;
    357 		hlen = 0;
    358 		align = 0;
    359 		break;
    360 
    361 	case DLT_EN10MB:
    362 		sockp->sa_family = AF_UNSPEC;
    363 		/* XXX Would MAXLINKHDR be better? */
    364  		/* 6(dst)+6(src)+2(type) */
    365 		hlen = sizeof(struct ether_header);
    366 		align = 2;
    367 		break;
    368 
    369 	case DLT_ARCNET:
    370 		sockp->sa_family = AF_UNSPEC;
    371 		hlen = ARC_HDRLEN;
    372 		align = 5;
    373 		break;
    374 
    375 	case DLT_FDDI:
    376 		sockp->sa_family = AF_LINK;
    377 		/* XXX 4(FORMAC)+6(dst)+6(src) */
    378 		hlen = 16;
    379 		align = 0;
    380 		break;
    381 
    382 	case DLT_ECONET:
    383 		sockp->sa_family = AF_UNSPEC;
    384 		hlen = 6;
    385 		align = 2;
    386 		break;
    387 
    388 	case DLT_NULL:
    389 		sockp->sa_family = AF_UNSPEC;
    390 		if (ifp->if_type == IFT_LOOP) {
    391 			/* Set here to apply the following validations */
    392 			hlen = sizeof(uint32_t);
    393 		} else
    394 			hlen = 0;
    395 		align = 0;
    396 		break;
    397 
    398 	default:
    399 		return (EIO);
    400 	}
    401 
    402 	len = uio->uio_resid;
    403 	/*
    404 	 * If there aren't enough bytes for a link level header or the
    405 	 * packet length exceeds the interface mtu, return an error.
    406 	 */
    407 	if (len - hlen > mtu)
    408 		return (EMSGSIZE);
    409 
    410 	m0 = m = m_gethdr(M_WAIT, MT_DATA);
    411 	m_reset_rcvif(m);
    412 	m->m_pkthdr.len = (int)(len - hlen);
    413 	if (len + align > MHLEN) {
    414 		m_clget(m, M_WAIT);
    415 		if ((m->m_flags & M_EXT) == 0) {
    416 			error = ENOBUFS;
    417 			goto bad;
    418 		}
    419 	}
    420 
    421 	/* Insure the data is properly aligned */
    422 	if (align > 0)
    423 		m->m_data += align;
    424 
    425 	for (;;) {
    426 		len = M_TRAILINGSPACE(m);
    427 		if (len > uio->uio_resid)
    428 			len = uio->uio_resid;
    429 		error = uiomove(mtod(m, void *), len, uio);
    430 		if (error)
    431 			goto bad;
    432 		m->m_len = len;
    433 
    434 		if (uio->uio_resid == 0)
    435 			break;
    436 
    437 		n = m_get(M_WAIT, MT_DATA);
    438 		m_clget(n, M_WAIT);	/* if fails, there is no problem */
    439 		m->m_next = n;
    440 		m = n;
    441 	}
    442 
    443 	slen = bpf_xfilter(wfilter, mtod(m, u_char *), len, len);
    444 	if (slen == 0) {
    445 		error = EPERM;
    446 		goto bad;
    447 	}
    448 
    449 	if (hlen != 0) {
    450 		if (linktype == DLT_NULL && ifp->if_type == IFT_LOOP) {
    451 			uint32_t af;
    452 			/* the link header indicates the address family */
    453 			memcpy(&af, mtod(m0, void *), sizeof(af));
    454 			sockp->sa_family = af;
    455 		} else {
    456 			/* move link level header in the top of mbuf to sa_data */
    457 			memcpy(sockp->sa_data, mtod(m0, void *), hlen);
    458 		}
    459 		m0->m_data += hlen;
    460 		m0->m_len -= hlen;
    461 	}
    462 
    463 	*mp = m0;
    464 	return (0);
    465 
    466 bad:
    467 	m_freem(m0);
    468 	return (error);
    469 }
    470 
    471 /*
    472  * Attach file to the bpf interface, i.e. make d listen on bp.
    473  */
    474 static void
    475 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
    476 {
    477 	struct bpf_event_tracker *t;
    478 
    479 	KASSERT(mutex_owned(&bpf_mtx));
    480 	KASSERT(mutex_owned(d->bd_mtx));
    481 	/*
    482 	 * Point d at bp, and add d to the interface's list of listeners.
    483 	 * Finally, point the driver's bpf cookie at the interface so
    484 	 * it will divert packets to bpf.
    485 	 */
    486 	d->bd_bif = bp;
    487 	BPFIF_DLIST_WRITER_INSERT_HEAD(bp, d);
    488 
    489 	*bp->bif_driverp = bp;
    490 
    491 	SLIST_FOREACH(t, &bp->bif_trackers, bet_entries) {
    492 		t->bet_notify(bp, bp->bif_ifp, bp->bif_dlt,
    493 		    BPF_TRACK_EVENT_ATTACH);
    494 	}
    495 }
    496 
    497 /*
    498  * Detach a file from its interface.
    499  */
    500 static void
    501 bpf_detachd(struct bpf_d *d)
    502 {
    503 	struct bpf_if *bp;
    504 	struct bpf_event_tracker *t;
    505 
    506 	KASSERT(mutex_owned(&bpf_mtx));
    507 	KASSERT(mutex_owned(d->bd_mtx));
    508 
    509 	bp = d->bd_bif;
    510 	/*
    511 	 * Check if this descriptor had requested promiscuous mode.
    512 	 * If so, turn it off.
    513 	 */
    514 	if (d->bd_promisc) {
    515 		int error __diagused;
    516 
    517 		d->bd_promisc = 0;
    518 		/*
    519 		 * Take device out of promiscuous mode.  Since we were
    520 		 * able to enter promiscuous mode, we should be able
    521 		 * to turn it off.  But we can get an error if
    522 		 * the interface was configured down, so only panic
    523 		 * if we don't get an unexpected error.
    524 		 */
    525 		KERNEL_LOCK_UNLESS_NET_MPSAFE();
    526   		error = ifpromisc(bp->bif_ifp, 0);
    527 		KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
    528 #ifdef DIAGNOSTIC
    529 		if (error)
    530 			printf("%s: ifpromisc failed: %d", __func__, error);
    531 #endif
    532 	}
    533 
    534 	/* Remove d from the interface's descriptor list. */
    535 	BPFIF_DLIST_WRITER_REMOVE(d);
    536 
    537 	pserialize_perform(bpf_psz);
    538 
    539 	if (BPFIF_DLIST_WRITER_EMPTY(bp)) {
    540 		/*
    541 		 * Let the driver know that there are no more listeners.
    542 		 */
    543 		*d->bd_bif->bif_driverp = NULL;
    544 	}
    545 
    546 	d->bd_bif = NULL;
    547 
    548 	SLIST_FOREACH(t, &bp->bif_trackers, bet_entries) {
    549 		t->bet_notify(bp, bp->bif_ifp, bp->bif_dlt,
    550 		    BPF_TRACK_EVENT_DETACH);
    551 	}
    552 }
    553 
    554 static void
    555 bpf_init(void)
    556 {
    557 
    558 	mutex_init(&bpf_mtx, MUTEX_DEFAULT, IPL_NONE);
    559 	bpf_psz = pserialize_create();
    560 	bpf_psref_class = psref_class_create("bpf", IPL_SOFTNET);
    561 
    562 	PSLIST_INIT(&bpf_iflist);
    563 	PSLIST_INIT(&bpf_dlist);
    564 
    565 	bpf_gstats_percpu = percpu_alloc(sizeof(struct bpf_stat));
    566 
    567 	return;
    568 }
    569 
    570 /*
    571  * bpfilterattach() is called at boot time.  We don't need to do anything
    572  * here, since any initialization will happen as part of module init code.
    573  */
    574 /* ARGSUSED */
    575 void
    576 bpfilterattach(int n)
    577 {
    578 
    579 }
    580 
    581 /*
    582  * Open ethernet device. Clones.
    583  */
    584 /* ARGSUSED */
    585 int
    586 bpfopen(dev_t dev, int flag, int mode, struct lwp *l)
    587 {
    588 	struct bpf_d *d;
    589 	struct file *fp;
    590 	int error, fd;
    591 
    592 	/* falloc() will fill in the descriptor for us. */
    593 	if ((error = fd_allocfile(&fp, &fd)) != 0)
    594 		return error;
    595 
    596 	d = kmem_zalloc(sizeof(*d), KM_SLEEP);
    597 	d->bd_bufsize = bpf_bufsize;
    598 	d->bd_direction = BPF_D_INOUT;
    599 	d->bd_feedback = 0;
    600 	d->bd_pid = l->l_proc->p_pid;
    601 #ifdef _LP64
    602 	if (curproc->p_flag & PK_32)
    603 		d->bd_compat32 = 1;
    604 #endif
    605 	getnanotime(&d->bd_btime);
    606 	d->bd_atime = d->bd_mtime = d->bd_btime;
    607 	callout_init(&d->bd_callout, CALLOUT_MPSAFE);
    608 	selinit(&d->bd_sel);
    609 	d->bd_sih = softint_establish(SOFTINT_CLOCK, bpf_softintr, d);
    610 	d->bd_jitcode = NULL;
    611 	d->bd_rfilter = NULL;
    612 	d->bd_wfilter = NULL;
    613 	d->bd_locked = 0;
    614 	BPF_DLIST_ENTRY_INIT(d);
    615 	BPFIF_DLIST_ENTRY_INIT(d);
    616 	d->bd_mtx = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
    617 	d->bd_buf_mtx = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NET);
    618 	cv_init(&d->bd_cv, "bpf");
    619 
    620 	mutex_enter(&bpf_mtx);
    621 	BPF_DLIST_WRITER_INSERT_HEAD(d);
    622 	mutex_exit(&bpf_mtx);
    623 
    624 	return fd_clone(fp, fd, flag, &bpf_fileops, d);
    625 }
    626 
    627 /*
    628  * Close the descriptor by detaching it from its interface,
    629  * deallocating its buffers, and marking it free.
    630  */
    631 /* ARGSUSED */
    632 static int
    633 bpf_close(struct file *fp)
    634 {
    635 	struct bpf_d *d;
    636 
    637 	mutex_enter(&bpf_mtx);
    638 
    639 	if ((d = fp->f_bpf) == NULL) {
    640 		mutex_exit(&bpf_mtx);
    641 		return 0;
    642 	}
    643 
    644 	/*
    645 	 * Refresh the PID associated with this bpf file.
    646 	 */
    647 	d->bd_pid = curproc->p_pid;
    648 
    649 	mutex_enter(d->bd_buf_mtx);
    650 	if (d->bd_state == BPF_WAITING)
    651 		callout_halt(&d->bd_callout, d->bd_buf_mtx);
    652 	d->bd_state = BPF_IDLE;
    653 	mutex_exit(d->bd_buf_mtx);
    654 	mutex_enter(d->bd_mtx);
    655 	if (d->bd_bif)
    656 		bpf_detachd(d);
    657 	mutex_exit(d->bd_mtx);
    658 
    659 	BPF_DLIST_WRITER_REMOVE(d);
    660 
    661 	pserialize_perform(bpf_psz);
    662 	mutex_exit(&bpf_mtx);
    663 
    664 	BPFIF_DLIST_ENTRY_DESTROY(d);
    665 	BPF_DLIST_ENTRY_DESTROY(d);
    666 	fp->f_bpf = NULL;
    667 	bpf_freed(d);
    668 	callout_destroy(&d->bd_callout);
    669 	seldestroy(&d->bd_sel);
    670 	softint_disestablish(d->bd_sih);
    671 	mutex_obj_free(d->bd_mtx);
    672 	mutex_obj_free(d->bd_buf_mtx);
    673 	cv_destroy(&d->bd_cv);
    674 
    675 	kmem_free(d, sizeof(*d));
    676 
    677 	return (0);
    678 }
    679 
    680 /*
    681  * Rotate the packet buffers in descriptor d.  Move the store buffer
    682  * into the hold slot, and the free buffer into the store slot.
    683  * Zero the length of the new store buffer.
    684  */
    685 #define ROTATE_BUFFERS(d) \
    686 	(d)->bd_hbuf = (d)->bd_sbuf; \
    687 	(d)->bd_hlen = (d)->bd_slen; \
    688 	(d)->bd_sbuf = (d)->bd_fbuf; \
    689 	(d)->bd_slen = 0; \
    690 	(d)->bd_fbuf = NULL;
    691 /*
    692  *  bpfread - read next chunk of packets from buffers
    693  */
    694 static int
    695 bpf_read(struct file *fp, off_t *offp, struct uio *uio,
    696     kauth_cred_t cred, int flags)
    697 {
    698 	struct bpf_d *d = fp->f_bpf;
    699 	int timed_out;
    700 	int error;
    701 
    702 	/*
    703 	 * Refresh the PID associated with this bpf file.
    704 	 */
    705 	d->bd_pid = curproc->p_pid;
    706 
    707 	getnanotime(&d->bd_atime);
    708 	/*
    709 	 * Restrict application to use a buffer the same size as
    710 	 * the kernel buffers.
    711 	 */
    712 	if (uio->uio_resid != d->bd_bufsize)
    713 		return (EINVAL);
    714 
    715 	mutex_enter(d->bd_buf_mtx);
    716 	if (d->bd_state == BPF_WAITING)
    717 		callout_halt(&d->bd_callout, d->bd_buf_mtx);
    718 	timed_out = (d->bd_state == BPF_TIMED_OUT);
    719 	d->bd_state = BPF_IDLE;
    720 	mutex_exit(d->bd_buf_mtx);
    721 	/*
    722 	 * If the hold buffer is empty, then do a timed sleep, which
    723 	 * ends when the timeout expires or when enough packets
    724 	 * have arrived to fill the store buffer.
    725 	 */
    726 	mutex_enter(d->bd_buf_mtx);
    727 	while (d->bd_hbuf == NULL) {
    728 		if (fp->f_flag & FNONBLOCK) {
    729 			if (d->bd_slen == 0) {
    730 				error = EWOULDBLOCK;
    731 				goto out;
    732 			}
    733 			ROTATE_BUFFERS(d);
    734 			break;
    735 		}
    736 
    737 		if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
    738 			/*
    739 			 * A packet(s) either arrived since the previous
    740 			 * read or arrived while we were asleep.
    741 			 * Rotate the buffers and return what's here.
    742 			 */
    743 			ROTATE_BUFFERS(d);
    744 			break;
    745 		}
    746 
    747 		error = cv_timedwait_sig(&d->bd_cv, d->bd_buf_mtx, d->bd_rtout);
    748 
    749 		if (error == EINTR || error == ERESTART)
    750 			goto out;
    751 
    752 		if (error == EWOULDBLOCK) {
    753 			/*
    754 			 * On a timeout, return what's in the buffer,
    755 			 * which may be nothing.  If there is something
    756 			 * in the store buffer, we can rotate the buffers.
    757 			 */
    758 			if (d->bd_hbuf)
    759 				/*
    760 				 * We filled up the buffer in between
    761 				 * getting the timeout and arriving
    762 				 * here, so we don't need to rotate.
    763 				 */
    764 				break;
    765 
    766 			if (d->bd_slen == 0) {
    767 				error = 0;
    768 				goto out;
    769 			}
    770 			ROTATE_BUFFERS(d);
    771 			break;
    772 		}
    773 		if (error != 0)
    774 			goto out;
    775 	}
    776 	/*
    777 	 * At this point, we know we have something in the hold slot.
    778 	 */
    779 	mutex_exit(d->bd_buf_mtx);
    780 
    781 	/*
    782 	 * Move data from hold buffer into user space.
    783 	 * We know the entire buffer is transferred since
    784 	 * we checked above that the read buffer is bpf_bufsize bytes.
    785 	 */
    786 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
    787 
    788 	mutex_enter(d->bd_buf_mtx);
    789 	d->bd_fbuf = d->bd_hbuf;
    790 	d->bd_hbuf = NULL;
    791 	d->bd_hlen = 0;
    792 out:
    793 	mutex_exit(d->bd_buf_mtx);
    794 	return (error);
    795 }
    796 
    797 
    798 /*
    799  * If there are processes sleeping on this descriptor, wake them up.
    800  */
    801 static inline void
    802 bpf_wakeup(struct bpf_d *d)
    803 {
    804 
    805 	KASSERT(mutex_owned(d->bd_buf_mtx));
    806 
    807 	cv_broadcast(&d->bd_cv);
    808 
    809 	if (d->bd_async)
    810 		softint_schedule(d->bd_sih);
    811 	selnotify(&d->bd_sel, 0, NOTE_SUBMIT);
    812 }
    813 
    814 static void
    815 bpf_softintr(void *cookie)
    816 {
    817 	struct bpf_d *d;
    818 
    819 	d = cookie;
    820 	if (d->bd_async)
    821 		fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
    822 }
    823 
    824 static void
    825 bpf_timed_out(void *arg)
    826 {
    827 	struct bpf_d *d = arg;
    828 
    829 	mutex_enter(d->bd_buf_mtx);
    830 	if (d->bd_state == BPF_WAITING) {
    831 		d->bd_state = BPF_TIMED_OUT;
    832 		if (d->bd_slen != 0)
    833 			bpf_wakeup(d);
    834 	}
    835 	mutex_exit(d->bd_buf_mtx);
    836 }
    837 
    838 
    839 static int
    840 bpf_write(struct file *fp, off_t *offp, struct uio *uio,
    841     kauth_cred_t cred, int flags)
    842 {
    843 	struct bpf_d *d = fp->f_bpf;
    844 	struct bpf_if *bp;
    845 	struct ifnet *ifp;
    846 	struct mbuf *m, *mc;
    847 	int error;
    848 	static struct sockaddr_storage dst;
    849 	struct psref psref;
    850 	int bound;
    851 
    852 	/*
    853 	 * Refresh the PID associated with this bpf file.
    854 	 */
    855 	d->bd_pid = curproc->p_pid;
    856 
    857 	m = NULL;	/* XXX gcc */
    858 
    859 	bound = curlwp_bind();
    860 	mutex_enter(d->bd_mtx);
    861 	bp = d->bd_bif;
    862 	if (bp == NULL) {
    863 		mutex_exit(d->bd_mtx);
    864 		error = ENXIO;
    865 		goto out_bindx;
    866 	}
    867 	bpf_if_acquire(bp, &psref);
    868 	mutex_exit(d->bd_mtx);
    869 
    870 	getnanotime(&d->bd_mtime);
    871 
    872 	ifp = bp->bif_ifp;
    873 	if (if_is_deactivated(ifp)) {
    874 		error = ENXIO;
    875 		goto out;
    876 	}
    877 
    878 	if (uio->uio_resid == 0) {
    879 		error = 0;
    880 		goto out;
    881 	}
    882 
    883 	error = bpf_movein(ifp, uio, (int)bp->bif_dlt, ifp->if_mtu, &m,
    884 		(struct sockaddr *) &dst, &d->bd_wfilter);
    885 	if (error)
    886 		goto out;
    887 
    888 	if (m->m_pkthdr.len > ifp->if_mtu) {
    889 		m_freem(m);
    890 		error = EMSGSIZE;
    891 		goto out;
    892 	}
    893 
    894 	/*
    895 	 * If writing to a loopback interface, the address family has
    896 	 * already been specially computed in bpf_movein(), so don't
    897 	 * clobber it, or the loopback will reject it in looutput().
    898 	 */
    899 	if (d->bd_hdrcmplt && ifp->if_type != IFT_LOOP)
    900 		dst.ss_family = pseudo_AF_HDRCMPLT;
    901 
    902 	if (d->bd_feedback) {
    903 		mc = m_dup(m, 0, M_COPYALL, M_NOWAIT);
    904 		if (mc != NULL)
    905 			m_set_rcvif(mc, ifp);
    906 		/* Set M_PROMISC for outgoing packets to be discarded. */
    907 		if (1 /*d->bd_direction == BPF_D_INOUT*/)
    908 			m->m_flags |= M_PROMISC;
    909 	} else
    910 		mc = NULL;
    911 
    912 	error = if_output_lock(ifp, ifp, m, (struct sockaddr *) &dst, NULL);
    913 
    914 	if (mc != NULL) {
    915 		if (error == 0) {
    916 			int s = splsoftnet();
    917 			KERNEL_LOCK_UNLESS_IFP_MPSAFE(ifp);
    918 			ifp->_if_input(ifp, mc);
    919 			KERNEL_UNLOCK_UNLESS_IFP_MPSAFE(ifp);
    920 			splx(s);
    921 		} else
    922 			m_freem(mc);
    923 	}
    924 	/*
    925 	 * The driver frees the mbuf.
    926 	 */
    927 out:
    928 	bpf_if_release(bp, &psref);
    929 out_bindx:
    930 	curlwp_bindx(bound);
    931 	return error;
    932 }
    933 
    934 /*
    935  * Reset a descriptor by flushing its packet buffer and clearing the
    936  * receive and drop counts.
    937  */
    938 static void
    939 reset_d(struct bpf_d *d)
    940 {
    941 
    942 	KASSERT(mutex_owned(d->bd_mtx));
    943 
    944 	mutex_enter(d->bd_buf_mtx);
    945 	if (d->bd_hbuf) {
    946 		/* Free the hold buffer. */
    947 		d->bd_fbuf = d->bd_hbuf;
    948 		d->bd_hbuf = NULL;
    949 	}
    950 	d->bd_slen = 0;
    951 	d->bd_hlen = 0;
    952 	d->bd_rcount = 0;
    953 	d->bd_dcount = 0;
    954 	d->bd_ccount = 0;
    955 	mutex_exit(d->bd_buf_mtx);
    956 }
    957 
    958 /*
    959  *  FIONREAD		Check for read packet available.
    960  *  BIOCGBLEN		Get buffer len [for read()].
    961  *  BIOCSETF		Set ethernet read filter.
    962  *  BIOCFLUSH		Flush read packet buffer.
    963  *  BIOCPROMISC		Put interface into promiscuous mode.
    964  *  BIOCGDLT		Get link layer type.
    965  *  BIOCGETIF		Get interface name.
    966  *  BIOCSETIF		Set interface.
    967  *  BIOCSRTIMEOUT	Set read timeout.
    968  *  BIOCGRTIMEOUT	Get read timeout.
    969  *  BIOCGSTATS		Get packet stats.
    970  *  BIOCIMMEDIATE	Set immediate mode.
    971  *  BIOCVERSION		Get filter language version.
    972  *  BIOCGHDRCMPLT	Get "header already complete" flag.
    973  *  BIOCSHDRCMPLT	Set "header already complete" flag.
    974  *  BIOCSFEEDBACK	Set packet feedback mode.
    975  *  BIOCGFEEDBACK	Get packet feedback mode.
    976  *  BIOCGDIRECTION	Get packet direction flag
    977  *  BIOCSDIRECTION	Set packet direction flag
    978  */
    979 /* ARGSUSED */
    980 static int
    981 bpf_ioctl(struct file *fp, u_long cmd, void *addr)
    982 {
    983 	struct bpf_d *d = fp->f_bpf;
    984 	int error = 0;
    985 
    986 	/*
    987 	 * Refresh the PID associated with this bpf file.
    988 	 */
    989 	d->bd_pid = curproc->p_pid;
    990 #ifdef _LP64
    991 	if (curproc->p_flag & PK_32)
    992 		d->bd_compat32 = 1;
    993 	else
    994 		d->bd_compat32 = 0;
    995 #endif
    996 
    997 	mutex_enter(d->bd_buf_mtx);
    998 	if (d->bd_state == BPF_WAITING)
    999 		callout_halt(&d->bd_callout, d->bd_buf_mtx);
   1000 	d->bd_state = BPF_IDLE;
   1001 	mutex_exit(d->bd_buf_mtx);
   1002 
   1003 	if (d->bd_locked) {
   1004 		switch (cmd) {
   1005 		case BIOCGBLEN:		/* FALLTHROUGH */
   1006 		case BIOCFLUSH:		/* FALLTHROUGH */
   1007 		case BIOCGDLT:		/* FALLTHROUGH */
   1008 		case BIOCGDLTLIST:	/* FALLTHROUGH */
   1009 		case BIOCGETIF:		/* FALLTHROUGH */
   1010 		case BIOCGRTIMEOUT:	/* FALLTHROUGH */
   1011 		case BIOCGSTATS:	/* FALLTHROUGH */
   1012 		case BIOCVERSION:	/* FALLTHROUGH */
   1013 		case BIOCGHDRCMPLT:	/* FALLTHROUGH */
   1014 		case FIONREAD:		/* FALLTHROUGH */
   1015 		case BIOCLOCK:		/* FALLTHROUGH */
   1016 		case BIOCSRTIMEOUT:	/* FALLTHROUGH */
   1017 		case BIOCIMMEDIATE:	/* FALLTHROUGH */
   1018 		case TIOCGPGRP:
   1019 			break;
   1020 		default:
   1021 			return EPERM;
   1022 		}
   1023 	}
   1024 
   1025 	switch (cmd) {
   1026 
   1027 	default:
   1028 		error = EINVAL;
   1029 		break;
   1030 
   1031 	/*
   1032 	 * Check for read packet available.
   1033 	 */
   1034 	case FIONREAD:
   1035 		{
   1036 			int n;
   1037 
   1038 			mutex_enter(d->bd_buf_mtx);
   1039 			n = d->bd_slen;
   1040 			if (d->bd_hbuf)
   1041 				n += d->bd_hlen;
   1042 			mutex_exit(d->bd_buf_mtx);
   1043 
   1044 			*(int *)addr = n;
   1045 			break;
   1046 		}
   1047 
   1048 	/*
   1049 	 * Get buffer len [for read()].
   1050 	 */
   1051 	case BIOCGBLEN:
   1052 		*(u_int *)addr = d->bd_bufsize;
   1053 		break;
   1054 
   1055 	/*
   1056 	 * Set buffer length.
   1057 	 */
   1058 	case BIOCSBLEN:
   1059 		/*
   1060 		 * Forbid to change the buffer length if buffers are already
   1061 		 * allocated.
   1062 		 */
   1063 		mutex_enter(d->bd_mtx);
   1064 		mutex_enter(d->bd_buf_mtx);
   1065 		if (d->bd_bif != NULL || d->bd_sbuf != NULL)
   1066 			error = EINVAL;
   1067 		else {
   1068 			u_int size = *(u_int *)addr;
   1069 
   1070 			if (size > bpf_maxbufsize)
   1071 				*(u_int *)addr = size = bpf_maxbufsize;
   1072 			else if (size < BPF_MINBUFSIZE)
   1073 				*(u_int *)addr = size = BPF_MINBUFSIZE;
   1074 			d->bd_bufsize = size;
   1075 		}
   1076 		mutex_exit(d->bd_buf_mtx);
   1077 		mutex_exit(d->bd_mtx);
   1078 		break;
   1079 
   1080 	/*
   1081 	 * Set link layer read filter.
   1082 	 */
   1083 	case BIOCSETF:		/* FALLTHROUGH */
   1084 	case BIOCSETWF:
   1085 		error = bpf_setf(d, addr, cmd);
   1086 		break;
   1087 
   1088 	case BIOCLOCK:
   1089 		d->bd_locked = 1;
   1090 		break;
   1091 
   1092 	/*
   1093 	 * Flush read packet buffer.
   1094 	 */
   1095 	case BIOCFLUSH:
   1096 		mutex_enter(d->bd_mtx);
   1097 		reset_d(d);
   1098 		mutex_exit(d->bd_mtx);
   1099 		break;
   1100 
   1101 	/*
   1102 	 * Put interface into promiscuous mode.
   1103 	 */
   1104 	case BIOCPROMISC:
   1105 		mutex_enter(d->bd_mtx);
   1106 		if (d->bd_bif == NULL) {
   1107 			mutex_exit(d->bd_mtx);
   1108 			/*
   1109 			 * No interface attached yet.
   1110 			 */
   1111 			error = EINVAL;
   1112 			break;
   1113 		}
   1114 		if (d->bd_promisc == 0) {
   1115 			KERNEL_LOCK_UNLESS_NET_MPSAFE();
   1116 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
   1117 			KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   1118 			if (error == 0)
   1119 				d->bd_promisc = 1;
   1120 		}
   1121 		mutex_exit(d->bd_mtx);
   1122 		break;
   1123 
   1124 	/*
   1125 	 * Get device parameters.
   1126 	 */
   1127 	case BIOCGDLT:
   1128 		mutex_enter(d->bd_mtx);
   1129 		if (d->bd_bif == NULL)
   1130 			error = EINVAL;
   1131 		else
   1132 			*(u_int *)addr = d->bd_bif->bif_dlt;
   1133 		mutex_exit(d->bd_mtx);
   1134 		break;
   1135 
   1136 	/*
   1137 	 * Get a list of supported device parameters.
   1138 	 */
   1139 	case BIOCGDLTLIST:
   1140 		mutex_enter(d->bd_mtx);
   1141 		if (d->bd_bif == NULL)
   1142 			error = EINVAL;
   1143 		else
   1144 			error = bpf_getdltlist(d, addr);
   1145 		mutex_exit(d->bd_mtx);
   1146 		break;
   1147 
   1148 	/*
   1149 	 * Set device parameters.
   1150 	 */
   1151 	case BIOCSDLT:
   1152 		mutex_enter(&bpf_mtx);
   1153 		mutex_enter(d->bd_mtx);
   1154 		if (d->bd_bif == NULL)
   1155 			error = EINVAL;
   1156 		else
   1157 			error = bpf_setdlt(d, *(u_int *)addr);
   1158 		mutex_exit(d->bd_mtx);
   1159 		mutex_exit(&bpf_mtx);
   1160 		break;
   1161 
   1162 	/*
   1163 	 * Set interface name.
   1164 	 */
   1165 #ifdef OBIOCGETIF
   1166 	case OBIOCGETIF:
   1167 #endif
   1168 	case BIOCGETIF:
   1169 		mutex_enter(d->bd_mtx);
   1170 		if (d->bd_bif == NULL)
   1171 			error = EINVAL;
   1172 		else
   1173 			bpf_ifname(d->bd_bif->bif_ifp, addr);
   1174 		mutex_exit(d->bd_mtx);
   1175 		break;
   1176 
   1177 	/*
   1178 	 * Set interface.
   1179 	 */
   1180 #ifdef OBIOCSETIF
   1181 	case OBIOCSETIF:
   1182 #endif
   1183 	case BIOCSETIF:
   1184 		mutex_enter(&bpf_mtx);
   1185 		error = bpf_setif(d, addr);
   1186 		mutex_exit(&bpf_mtx);
   1187 		break;
   1188 
   1189 	/*
   1190 	 * Set read timeout.
   1191 	 */
   1192 	case BIOCSRTIMEOUT:
   1193 		{
   1194 			struct timeval *tv = addr;
   1195 
   1196 			/* Compute number of ticks. */
   1197 			if (tv->tv_sec < 0 ||
   1198 			    tv->tv_usec < 0 || tv->tv_usec >= 1000000) {
   1199 				error = EINVAL;
   1200 				break;
   1201 			} else if (tv->tv_sec > INT_MAX/hz - 1) {
   1202 				d->bd_rtout = INT_MAX;
   1203 			} else {
   1204 				d->bd_rtout = tv->tv_sec * hz
   1205 				    + tv->tv_usec / tick;
   1206 			}
   1207 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
   1208 				d->bd_rtout = 1;
   1209 			break;
   1210 		}
   1211 
   1212 #ifdef BIOCGORTIMEOUT
   1213 	/*
   1214 	 * Get read timeout.
   1215 	 */
   1216 	case BIOCGORTIMEOUT:
   1217 		{
   1218 			struct timeval50 *tv = addr;
   1219 
   1220 			tv->tv_sec = d->bd_rtout / hz;
   1221 			tv->tv_usec = (d->bd_rtout % hz) * tick;
   1222 			break;
   1223 		}
   1224 #endif
   1225 
   1226 #ifdef BIOCSORTIMEOUT
   1227 	/*
   1228 	 * Set read timeout.
   1229 	 */
   1230 	case BIOCSORTIMEOUT:
   1231 		{
   1232 			struct timeval50 *tv = addr;
   1233 
   1234 			/* Compute number of ticks. */
   1235 			if (tv->tv_sec < 0 ||
   1236 			    tv->tv_usec < 0 || tv->tv_usec >= 1000000) {
   1237 				error = EINVAL;
   1238 				break;
   1239 			} else if (tv->tv_sec > INT_MAX/hz - 1) {
   1240 				d->bd_rtout = INT_MAX;
   1241 			} else {
   1242 				d->bd_rtout = tv->tv_sec * hz
   1243 				    + tv->tv_usec / tick;
   1244 			}
   1245 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
   1246 				d->bd_rtout = 1;
   1247 			break;
   1248 		}
   1249 #endif
   1250 
   1251 	/*
   1252 	 * Get read timeout.
   1253 	 */
   1254 	case BIOCGRTIMEOUT:
   1255 		{
   1256 			struct timeval *tv = addr;
   1257 
   1258 			tv->tv_sec = d->bd_rtout / hz;
   1259 			tv->tv_usec = (d->bd_rtout % hz) * tick;
   1260 			break;
   1261 		}
   1262 	/*
   1263 	 * Get packet stats.
   1264 	 */
   1265 	case BIOCGSTATS:
   1266 		{
   1267 			struct bpf_stat *bs = addr;
   1268 
   1269 			bs->bs_recv = d->bd_rcount;
   1270 			bs->bs_drop = d->bd_dcount;
   1271 			bs->bs_capt = d->bd_ccount;
   1272 			break;
   1273 		}
   1274 
   1275 	case BIOCGSTATSOLD:
   1276 		{
   1277 			struct bpf_stat_old *bs = addr;
   1278 
   1279 			bs->bs_recv = d->bd_rcount;
   1280 			bs->bs_drop = d->bd_dcount;
   1281 			break;
   1282 		}
   1283 
   1284 	/*
   1285 	 * Set immediate mode.
   1286 	 */
   1287 	case BIOCIMMEDIATE:
   1288 		d->bd_immediate = *(u_int *)addr;
   1289 		break;
   1290 
   1291 	case BIOCVERSION:
   1292 		{
   1293 			struct bpf_version *bv = addr;
   1294 
   1295 			bv->bv_major = BPF_MAJOR_VERSION;
   1296 			bv->bv_minor = BPF_MINOR_VERSION;
   1297 			break;
   1298 		}
   1299 
   1300 	case BIOCGHDRCMPLT:	/* get "header already complete" flag */
   1301 		*(u_int *)addr = d->bd_hdrcmplt;
   1302 		break;
   1303 
   1304 	case BIOCSHDRCMPLT:	/* set "header already complete" flag */
   1305 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
   1306 		break;
   1307 
   1308 	/*
   1309 	 * Get packet direction flag
   1310 	 */
   1311 	case BIOCGDIRECTION:
   1312 		*(u_int *)addr = d->bd_direction;
   1313 		break;
   1314 
   1315 	/*
   1316 	 * Set packet direction flag
   1317 	 */
   1318 	case BIOCSDIRECTION:
   1319 		{
   1320 			u_int	direction;
   1321 
   1322 			direction = *(u_int *)addr;
   1323 			switch (direction) {
   1324 			case BPF_D_IN:
   1325 			case BPF_D_INOUT:
   1326 			case BPF_D_OUT:
   1327 				d->bd_direction = direction;
   1328 				break;
   1329 			default:
   1330 				error = EINVAL;
   1331 			}
   1332 		}
   1333 		break;
   1334 
   1335 	/*
   1336 	 * Set "feed packets from bpf back to input" mode
   1337 	 */
   1338 	case BIOCSFEEDBACK:
   1339 		d->bd_feedback = *(u_int *)addr;
   1340 		break;
   1341 
   1342 	/*
   1343 	 * Get "feed packets from bpf back to input" mode
   1344 	 */
   1345 	case BIOCGFEEDBACK:
   1346 		*(u_int *)addr = d->bd_feedback;
   1347 		break;
   1348 
   1349 	case FIONBIO:		/* Non-blocking I/O */
   1350 		/*
   1351 		 * No need to do anything special as we use IO_NDELAY in
   1352 		 * bpfread() as an indication of whether or not to block
   1353 		 * the read.
   1354 		 */
   1355 		break;
   1356 
   1357 	case FIOASYNC:		/* Send signal on receive packets */
   1358 		mutex_enter(d->bd_mtx);
   1359 		d->bd_async = *(int *)addr;
   1360 		mutex_exit(d->bd_mtx);
   1361 		break;
   1362 
   1363 	case TIOCSPGRP:		/* Process or group to send signals to */
   1364 	case FIOSETOWN:
   1365 		error = fsetown(&d->bd_pgid, cmd, addr);
   1366 		break;
   1367 
   1368 	case TIOCGPGRP:
   1369 	case FIOGETOWN:
   1370 		error = fgetown(d->bd_pgid, cmd, addr);
   1371 		break;
   1372 	}
   1373 	return (error);
   1374 }
   1375 
   1376 /*
   1377  * Set d's packet filter program to fp.  If this file already has a filter,
   1378  * free it and replace it.  Returns EINVAL for bogus requests.
   1379  */
   1380 static int
   1381 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
   1382 {
   1383 	struct bpf_insn *fcode;
   1384 	bpfjit_func_t jcode;
   1385 	size_t flen, size = 0;
   1386 	struct bpf_filter *oldf, *newf, **storef;
   1387 
   1388 	jcode = NULL;
   1389 	flen = fp->bf_len;
   1390 
   1391 	if ((fp->bf_insns == NULL && flen) || flen > BPF_MAXINSNS) {
   1392 		return EINVAL;
   1393 	}
   1394 
   1395 	if (flen) {
   1396 		/*
   1397 		 * Allocate the buffer, copy the byte-code from
   1398 		 * userspace and validate it.
   1399 		 */
   1400 		size = flen * sizeof(*fp->bf_insns);
   1401 		fcode = kmem_alloc(size, KM_SLEEP);
   1402 		if (copyin(fp->bf_insns, fcode, size) != 0 ||
   1403 		    !bpf_validate(fcode, (int)flen)) {
   1404 			kmem_free(fcode, size);
   1405 			return EINVAL;
   1406 		}
   1407 		if (bpf_jit)
   1408 			jcode = bpf_jit_generate(NULL, fcode, flen);
   1409 	} else {
   1410 		fcode = NULL;
   1411 	}
   1412 
   1413 	newf = kmem_alloc(sizeof(*newf), KM_SLEEP);
   1414 	newf->bf_insn = fcode;
   1415 	newf->bf_size = size;
   1416 	newf->bf_jitcode = jcode;
   1417 	if (cmd == BIOCSETF)
   1418 		d->bd_jitcode = jcode; /* XXX just for kvm(3) users */
   1419 
   1420 	/* Need to hold bpf_mtx for pserialize_perform */
   1421 	mutex_enter(&bpf_mtx);
   1422 	mutex_enter(d->bd_mtx);
   1423 	if (cmd == BIOCSETWF) {
   1424 		oldf = d->bd_wfilter;
   1425 		storef = &d->bd_wfilter;
   1426 	} else {
   1427 		oldf = d->bd_rfilter;
   1428 		storef = &d->bd_rfilter;
   1429 	}
   1430 	atomic_store_release(storef, newf);
   1431 	reset_d(d);
   1432 	pserialize_perform(bpf_psz);
   1433 	mutex_exit(d->bd_mtx);
   1434 	mutex_exit(&bpf_mtx);
   1435 
   1436 	if (oldf != NULL)
   1437 		bpf_free_filter(oldf);
   1438 
   1439 	return 0;
   1440 }
   1441 
   1442 /*
   1443  * Detach a file from its current interface (if attached at all) and attach
   1444  * to the interface indicated by the name stored in ifr.
   1445  * Return an errno or 0.
   1446  */
   1447 static int
   1448 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
   1449 {
   1450 	struct bpf_if *bp;
   1451 	char *cp;
   1452 	int unit_seen, i, error;
   1453 
   1454 	KASSERT(mutex_owned(&bpf_mtx));
   1455 	/*
   1456 	 * Make sure the provided name has a unit number, and default
   1457 	 * it to '0' if not specified.
   1458 	 * XXX This is ugly ... do this differently?
   1459 	 */
   1460 	unit_seen = 0;
   1461 	cp = ifr->ifr_name;
   1462 	cp[sizeof(ifr->ifr_name) - 1] = '\0';	/* sanity */
   1463 	while (*cp++)
   1464 		if (*cp >= '0' && *cp <= '9')
   1465 			unit_seen = 1;
   1466 	if (!unit_seen) {
   1467 		/* Make sure to leave room for the '\0'. */
   1468 		for (i = 0; i < (IFNAMSIZ - 1); ++i) {
   1469 			if ((ifr->ifr_name[i] >= 'a' &&
   1470 			     ifr->ifr_name[i] <= 'z') ||
   1471 			    (ifr->ifr_name[i] >= 'A' &&
   1472 			     ifr->ifr_name[i] <= 'Z'))
   1473 				continue;
   1474 			ifr->ifr_name[i] = '0';
   1475 		}
   1476 	}
   1477 
   1478 	/*
   1479 	 * Look through attached interfaces for the named one.
   1480 	 */
   1481 	BPF_IFLIST_WRITER_FOREACH(bp) {
   1482 		struct ifnet *ifp = bp->bif_ifp;
   1483 
   1484 		if (ifp == NULL ||
   1485 		    strcmp(ifp->if_xname, ifr->ifr_name) != 0)
   1486 			continue;
   1487 		/* skip additional entry */
   1488 		if (bp->bif_driverp != &ifp->if_bpf)
   1489 			continue;
   1490 		/*
   1491 		 * We found the requested interface.
   1492 		 * Allocate the packet buffers if we need to.
   1493 		 * If we're already attached to requested interface,
   1494 		 * just flush the buffer.
   1495 		 */
   1496 		/*
   1497 		 * bpf_allocbufs is called only here. bpf_mtx ensures that
   1498 		 * no race condition happen on d->bd_sbuf.
   1499 		 */
   1500 		if (d->bd_sbuf == NULL) {
   1501 			error = bpf_allocbufs(d);
   1502 			if (error != 0)
   1503 				return (error);
   1504 		}
   1505 		mutex_enter(d->bd_mtx);
   1506 		if (bp != d->bd_bif) {
   1507 			if (d->bd_bif) {
   1508 				/*
   1509 				 * Detach if attached to something else.
   1510 				 */
   1511 				bpf_detachd(d);
   1512 				BPFIF_DLIST_ENTRY_INIT(d);
   1513 			}
   1514 
   1515 			bpf_attachd(d, bp);
   1516 		}
   1517 		reset_d(d);
   1518 		mutex_exit(d->bd_mtx);
   1519 		return (0);
   1520 	}
   1521 	/* Not found. */
   1522 	return (ENXIO);
   1523 }
   1524 
   1525 /*
   1526  * Copy the interface name to the ifreq.
   1527  */
   1528 static void
   1529 bpf_ifname(struct ifnet *ifp, struct ifreq *ifr)
   1530 {
   1531 	memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
   1532 }
   1533 
   1534 static int
   1535 bpf_stat(struct file *fp, struct stat *st)
   1536 {
   1537 	struct bpf_d *d = fp->f_bpf;
   1538 
   1539 	(void)memset(st, 0, sizeof(*st));
   1540 	mutex_enter(d->bd_mtx);
   1541 	st->st_dev = makedev(cdevsw_lookup_major(&bpf_cdevsw), d->bd_pid);
   1542 	st->st_atimespec = d->bd_atime;
   1543 	st->st_mtimespec = d->bd_mtime;
   1544 	st->st_ctimespec = st->st_birthtimespec = d->bd_btime;
   1545 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
   1546 	st->st_gid = kauth_cred_getegid(fp->f_cred);
   1547 	st->st_mode = S_IFCHR;
   1548 	mutex_exit(d->bd_mtx);
   1549 	return 0;
   1550 }
   1551 
   1552 /*
   1553  * Support for poll() system call
   1554  *
   1555  * Return true iff the specific operation will not block indefinitely - with
   1556  * the assumption that it is safe to positively acknowledge a request for the
   1557  * ability to write to the BPF device.
   1558  * Otherwise, return false but make a note that a selnotify() must be done.
   1559  */
   1560 static int
   1561 bpf_poll(struct file *fp, int events)
   1562 {
   1563 	struct bpf_d *d = fp->f_bpf;
   1564 	int revents;
   1565 
   1566 	/*
   1567 	 * Refresh the PID associated with this bpf file.
   1568 	 */
   1569 	mutex_enter(&bpf_mtx);
   1570 	d->bd_pid = curproc->p_pid;
   1571 
   1572 	revents = events & (POLLOUT | POLLWRNORM);
   1573 	if (events & (POLLIN | POLLRDNORM)) {
   1574 		/*
   1575 		 * An imitation of the FIONREAD ioctl code.
   1576 		 */
   1577 		mutex_enter(d->bd_mtx);
   1578 		mutex_enter(d->bd_buf_mtx);
   1579 		if (d->bd_hlen != 0 ||
   1580 		    ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
   1581 		     d->bd_slen != 0)) {
   1582 			revents |= events & (POLLIN | POLLRDNORM);
   1583 		} else {
   1584 			selrecord(curlwp, &d->bd_sel);
   1585 			/* Start the read timeout if necessary */
   1586 			if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
   1587 				callout_reset(&d->bd_callout, d->bd_rtout,
   1588 					      bpf_timed_out, d);
   1589 				d->bd_state = BPF_WAITING;
   1590 			}
   1591 		}
   1592 		mutex_exit(d->bd_buf_mtx);
   1593 		mutex_exit(d->bd_mtx);
   1594 	}
   1595 
   1596 	mutex_exit(&bpf_mtx);
   1597 	return (revents);
   1598 }
   1599 
   1600 static void
   1601 filt_bpfrdetach(struct knote *kn)
   1602 {
   1603 	struct bpf_d *d = kn->kn_hook;
   1604 
   1605 	mutex_enter(d->bd_buf_mtx);
   1606 	selremove_knote(&d->bd_sel, kn);
   1607 	mutex_exit(d->bd_buf_mtx);
   1608 }
   1609 
   1610 static int
   1611 filt_bpfread(struct knote *kn, long hint)
   1612 {
   1613 	struct bpf_d *d = kn->kn_hook;
   1614 	int rv;
   1615 
   1616 	/*
   1617 	 * Refresh the PID associated with this bpf file.
   1618 	 */
   1619 	d->bd_pid = curproc->p_pid;
   1620 
   1621 	if (hint & NOTE_SUBMIT)
   1622 		KASSERT(mutex_owned(d->bd_buf_mtx));
   1623 	else
   1624 		mutex_enter(d->bd_buf_mtx);
   1625 	kn->kn_data = d->bd_hlen;
   1626 	if (d->bd_immediate)
   1627 		kn->kn_data += d->bd_slen;
   1628 	rv = (kn->kn_data > 0);
   1629 	if (hint & NOTE_SUBMIT)
   1630 		KASSERT(mutex_owned(d->bd_buf_mtx));
   1631 	else
   1632 		mutex_exit(d->bd_buf_mtx);
   1633 	return rv;
   1634 }
   1635 
   1636 static const struct filterops bpfread_filtops = {
   1637 	.f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
   1638 	.f_attach = NULL,
   1639 	.f_detach = filt_bpfrdetach,
   1640 	.f_event = filt_bpfread,
   1641 };
   1642 
   1643 static int
   1644 bpf_kqfilter(struct file *fp, struct knote *kn)
   1645 {
   1646 	struct bpf_d *d = fp->f_bpf;
   1647 
   1648 	switch (kn->kn_filter) {
   1649 	case EVFILT_READ:
   1650 		kn->kn_fop = &bpfread_filtops;
   1651 		break;
   1652 
   1653 	default:
   1654 		return (EINVAL);
   1655 	}
   1656 
   1657 	kn->kn_hook = d;
   1658 
   1659 	mutex_enter(d->bd_buf_mtx);
   1660 	selrecord_knote(&d->bd_sel, kn);
   1661 	mutex_exit(d->bd_buf_mtx);
   1662 
   1663 	return (0);
   1664 }
   1665 
   1666 /*
   1667  * Copy data from an mbuf chain into a buffer.  This code is derived
   1668  * from m_copydata in sys/uipc_mbuf.c.
   1669  */
   1670 static void *
   1671 bpf_mcpy(void *dst_arg, const void *src_arg, size_t len)
   1672 {
   1673 	const struct mbuf *m;
   1674 	u_int count;
   1675 	u_char *dst;
   1676 
   1677 	m = src_arg;
   1678 	dst = dst_arg;
   1679 	while (len > 0) {
   1680 		if (m == NULL)
   1681 			panic("bpf_mcpy");
   1682 		count = uimin(m->m_len, len);
   1683 		memcpy(dst, mtod(m, const void *), count);
   1684 		m = m->m_next;
   1685 		dst += count;
   1686 		len -= count;
   1687 	}
   1688 	return dst_arg;
   1689 }
   1690 
   1691 static inline u_int
   1692 bpf_xfilter(struct bpf_filter **filter, void *pkt, u_int pktlen, u_int buflen)
   1693 {
   1694 	struct bpf_filter *filt;
   1695 	uint32_t mem[BPF_MEMWORDS];
   1696 	bpf_args_t args = {
   1697 		.pkt = (const uint8_t *)pkt,
   1698 		.wirelen = pktlen,
   1699 		.buflen = buflen,
   1700 		.mem = mem,
   1701 		.arg = NULL
   1702 	};
   1703 	u_int slen;
   1704 
   1705 	filt = atomic_load_consume(filter);
   1706 	if (filt == NULL) /* No filter means accept all. */
   1707 		return (u_int)-1;
   1708 
   1709 	if (filt->bf_jitcode != NULL)
   1710 		slen = filt->bf_jitcode(NULL, &args);
   1711 	else
   1712 		slen = bpf_filter_ext(NULL, filt->bf_insn, &args);
   1713 	return slen;
   1714 }
   1715 
   1716 /*
   1717  * Dispatch a packet to all the listeners on interface bp.
   1718  *
   1719  * pkt       pointer to the packet, either a data buffer or an mbuf chain
   1720  * buflen    buffer length, if pkt is a data buffer
   1721  * cpfn      a function that can copy pkt into the listener's buffer
   1722  * pktlen    length of the packet
   1723  * direction BPF_D_IN or BPF_D_OUT
   1724  */
   1725 static inline void
   1726 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
   1727     void *pkt, u_int pktlen, u_int buflen, const u_int direction)
   1728 {
   1729 	bool gottime = false;
   1730 	struct timespec ts;
   1731 	struct bpf_d *d;
   1732 	int s;
   1733 	u_int slen;
   1734 
   1735 	KASSERT(!cpu_intr_p());
   1736 
   1737 	/*
   1738 	 * Note that the IPL does not have to be raised at this point.
   1739 	 * The only problem that could arise here is that if two different
   1740 	 * interfaces shared any data.  This is not the case.
   1741 	 */
   1742 	s = pserialize_read_enter();
   1743 	BPFIF_DLIST_READER_FOREACH(d, bp) {
   1744 		if (direction == BPF_D_IN) {
   1745 			if (d->bd_direction == BPF_D_OUT)
   1746 				continue;
   1747 		} else { /* BPF_D_OUT */
   1748 			if (d->bd_direction == BPF_D_IN)
   1749 				continue;
   1750 		}
   1751 
   1752 		atomic_inc_ulong(&d->bd_rcount);
   1753 		BPF_STATINC(recv);
   1754 
   1755 		slen = bpf_xfilter(&d->bd_rfilter, pkt, pktlen, buflen);
   1756 		if (slen == 0)
   1757 			continue;
   1758 
   1759 		if (!gottime) {
   1760 			gottime = true;
   1761 			nanotime(&ts);
   1762 		}
   1763 		/* Assume catchpacket doesn't sleep */
   1764 		catchpacket(d, pkt, pktlen, slen, cpfn, &ts);
   1765 	}
   1766 	pserialize_read_exit(s);
   1767 }
   1768 
   1769 /*
   1770  * Incoming linkage from device drivers, when the head of the packet is in
   1771  * a buffer, and the tail is in an mbuf chain.
   1772  */
   1773 static void
   1774 _bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m,
   1775 	u_int direction)
   1776 {
   1777 	u_int pktlen;
   1778 	struct mbuf mb;
   1779 
   1780 	/* Skip outgoing duplicate packets. */
   1781 	if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif_index == 0) {
   1782 		m->m_flags &= ~M_PROMISC;
   1783 		return;
   1784 	}
   1785 
   1786 	pktlen = m_length(m) + dlen;
   1787 
   1788 	/*
   1789 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
   1790 	 * Note that we cut corners here; we only setup what's
   1791 	 * absolutely needed--this mbuf should never go anywhere else.
   1792 	 */
   1793 	(void)memset(&mb, 0, sizeof(mb));
   1794 	mb.m_type = MT_DATA;
   1795 	mb.m_next = m;
   1796 	mb.m_data = data;
   1797 	mb.m_len = dlen;
   1798 
   1799 	bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, direction);
   1800 }
   1801 
   1802 /*
   1803  * Incoming linkage from device drivers, when packet is in an mbuf chain.
   1804  */
   1805 static void
   1806 _bpf_mtap(struct bpf_if *bp, struct mbuf *m, u_int direction)
   1807 {
   1808 	void *(*cpfn)(void *, const void *, size_t);
   1809 	u_int pktlen, buflen;
   1810 	void *marg;
   1811 
   1812 	/* Skip outgoing duplicate packets. */
   1813 	if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif_index == 0) {
   1814 		m->m_flags &= ~M_PROMISC;
   1815 		return;
   1816 	}
   1817 
   1818 	pktlen = m_length(m);
   1819 
   1820 	/* Skip zero-sized packets. */
   1821 	if (__predict_false(pktlen == 0)) {
   1822 		return;
   1823 	}
   1824 
   1825 	if (pktlen == m->m_len) {
   1826 		cpfn = (void *)memcpy;
   1827 		marg = mtod(m, void *);
   1828 		buflen = pktlen;
   1829 		KASSERT(buflen != 0);
   1830 	} else {
   1831 		cpfn = bpf_mcpy;
   1832 		marg = m;
   1833 		buflen = 0;
   1834 	}
   1835 
   1836 	bpf_deliver(bp, cpfn, marg, pktlen, buflen, direction);
   1837 }
   1838 
   1839 /*
   1840  * We need to prepend the address family as
   1841  * a four byte field.  Cons up a dummy header
   1842  * to pacify bpf.  This is safe because bpf
   1843  * will only read from the mbuf (i.e., it won't
   1844  * try to free it or keep a pointer a to it).
   1845  */
   1846 static void
   1847 _bpf_mtap_af(struct bpf_if *bp, uint32_t af, struct mbuf *m, u_int direction)
   1848 {
   1849 	struct mbuf m0;
   1850 
   1851 	m0.m_type = MT_DATA;
   1852 	m0.m_flags = 0;
   1853 	m0.m_next = m;
   1854 	m0.m_nextpkt = NULL;
   1855 	m0.m_owner = NULL;
   1856 	m0.m_len = 4;
   1857 	m0.m_data = (char *)&af;
   1858 
   1859 	_bpf_mtap(bp, &m0, direction);
   1860 }
   1861 
   1862 /*
   1863  * Put the SLIP pseudo-"link header" in place.
   1864  * Note this M_PREPEND() should never fail,
   1865  * swince we know we always have enough space
   1866  * in the input buffer.
   1867  */
   1868 static void
   1869 _bpf_mtap_sl_in(struct bpf_if *bp, u_char *chdr, struct mbuf **m)
   1870 {
   1871 	u_char *hp;
   1872 
   1873 	M_PREPEND(*m, SLIP_HDRLEN, M_DONTWAIT);
   1874 	if (*m == NULL)
   1875 		return;
   1876 
   1877 	hp = mtod(*m, u_char *);
   1878 	hp[SLX_DIR] = SLIPDIR_IN;
   1879 	(void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
   1880 
   1881 	_bpf_mtap(bp, *m, BPF_D_IN);
   1882 
   1883 	m_adj(*m, SLIP_HDRLEN);
   1884 }
   1885 
   1886 /*
   1887  * Put the SLIP pseudo-"link header" in
   1888  * place.  The compressed header is now
   1889  * at the beginning of the mbuf.
   1890  */
   1891 static void
   1892 _bpf_mtap_sl_out(struct bpf_if *bp, u_char *chdr, struct mbuf *m)
   1893 {
   1894 	struct mbuf m0;
   1895 	u_char *hp;
   1896 
   1897 	m0.m_type = MT_DATA;
   1898 	m0.m_flags = 0;
   1899 	m0.m_next = m;
   1900 	m0.m_nextpkt = NULL;
   1901 	m0.m_owner = NULL;
   1902 	m0.m_data = m0.m_dat;
   1903 	m0.m_len = SLIP_HDRLEN;
   1904 
   1905 	hp = mtod(&m0, u_char *);
   1906 
   1907 	hp[SLX_DIR] = SLIPDIR_OUT;
   1908 	(void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
   1909 
   1910 	_bpf_mtap(bp, &m0, BPF_D_OUT);
   1911 	m_freem(m);
   1912 }
   1913 
   1914 static struct mbuf *
   1915 bpf_mbuf_enqueue(struct bpf_if *bp, struct mbuf *m)
   1916 {
   1917 	struct mbuf *dup;
   1918 
   1919 	dup = m_dup(m, 0, M_COPYALL, M_NOWAIT);
   1920 	if (dup == NULL)
   1921 		return NULL;
   1922 
   1923 	if (bp->bif_mbuf_tail != NULL) {
   1924 		bp->bif_mbuf_tail->m_nextpkt = dup;
   1925 	} else {
   1926 		bp->bif_mbuf_head = dup;
   1927 	}
   1928 	bp->bif_mbuf_tail = dup;
   1929 #ifdef BPF_MTAP_SOFTINT_DEBUG
   1930 	log(LOG_DEBUG, "%s: enqueued mbuf=%p to %s\n",
   1931 	    __func__, dup, bp->bif_ifp->if_xname);
   1932 #endif
   1933 
   1934 	return dup;
   1935 }
   1936 
   1937 static struct mbuf *
   1938 bpf_mbuf_dequeue(struct bpf_if *bp)
   1939 {
   1940 	struct mbuf *m;
   1941 	int s;
   1942 
   1943 	/* XXX NOMPSAFE: assumed running on one CPU */
   1944 	s = splnet();
   1945 	m = bp->bif_mbuf_head;
   1946 	if (m != NULL) {
   1947 		bp->bif_mbuf_head = m->m_nextpkt;
   1948 		m->m_nextpkt = NULL;
   1949 
   1950 		if (bp->bif_mbuf_head == NULL)
   1951 			bp->bif_mbuf_tail = NULL;
   1952 #ifdef BPF_MTAP_SOFTINT_DEBUG
   1953 		log(LOG_DEBUG, "%s: dequeued mbuf=%p from %s\n",
   1954 		    __func__, m, bp->bif_ifp->if_xname);
   1955 #endif
   1956 	}
   1957 	splx(s);
   1958 
   1959 	return m;
   1960 }
   1961 
   1962 static void
   1963 bpf_mtap_si(void *arg)
   1964 {
   1965 	struct bpf_if *bp = arg;
   1966 	struct mbuf *m;
   1967 
   1968 	while ((m = bpf_mbuf_dequeue(bp)) != NULL) {
   1969 #ifdef BPF_MTAP_SOFTINT_DEBUG
   1970 		log(LOG_DEBUG, "%s: tapping mbuf=%p on %s\n",
   1971 		    __func__, m, bp->bif_ifp->if_xname);
   1972 #endif
   1973 		bpf_ops->bpf_mtap(bp, m, BPF_D_IN);
   1974 		m_freem(m);
   1975 	}
   1976 }
   1977 
   1978 static void
   1979 _bpf_mtap_softint(struct ifnet *ifp, struct mbuf *m)
   1980 {
   1981 	struct bpf_if *bp = ifp->if_bpf;
   1982 	struct mbuf *dup;
   1983 
   1984 	KASSERT(cpu_intr_p());
   1985 
   1986 	/* To avoid extra invocations of the softint */
   1987 	if (BPFIF_DLIST_READER_EMPTY(bp))
   1988 		return;
   1989 	KASSERT(bp->bif_si != NULL);
   1990 
   1991 	dup = bpf_mbuf_enqueue(bp, m);
   1992 	if (dup != NULL)
   1993 		softint_schedule(bp->bif_si);
   1994 }
   1995 
   1996 static int
   1997 bpf_hdrlen(struct bpf_d *d)
   1998 {
   1999 	int hdrlen = d->bd_bif->bif_hdrlen;
   2000 	/*
   2001 	 * Compute the length of the bpf header.  This is not necessarily
   2002 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   2003 	 * that the network layer header begins on a longword boundary (for
   2004 	 * performance reasons and to alleviate alignment restrictions).
   2005 	 */
   2006 #ifdef _LP64
   2007 	if (d->bd_compat32)
   2008 		return (BPF_WORDALIGN32(hdrlen + SIZEOF_BPF_HDR32) - hdrlen);
   2009 	else
   2010 #endif
   2011 		return (BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen);
   2012 }
   2013 
   2014 /*
   2015  * Move the packet data from interface memory (pkt) into the
   2016  * store buffer. Call the wakeup functions if it's time to wakeup
   2017  * a listener (buffer full), "cpfn" is the routine called to do the
   2018  * actual data transfer. memcpy is passed in to copy contiguous chunks,
   2019  * while bpf_mcpy is passed in to copy mbuf chains.  In the latter case,
   2020  * pkt is really an mbuf.
   2021  */
   2022 static void
   2023 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
   2024     void *(*cpfn)(void *, const void *, size_t), struct timespec *ts)
   2025 {
   2026 	char *h;
   2027 	int totlen, curlen, caplen;
   2028 	int hdrlen = bpf_hdrlen(d);
   2029 	int do_wakeup = 0;
   2030 
   2031 	atomic_inc_ulong(&d->bd_ccount);
   2032 	BPF_STATINC(capt);
   2033 	/*
   2034 	 * Figure out how many bytes to move.  If the packet is
   2035 	 * greater or equal to the snapshot length, transfer that
   2036 	 * much.  Otherwise, transfer the whole packet (unless
   2037 	 * we hit the buffer size limit).
   2038 	 */
   2039 	totlen = hdrlen + uimin(snaplen, pktlen);
   2040 	if (totlen > d->bd_bufsize)
   2041 		totlen = d->bd_bufsize;
   2042 	/*
   2043 	 * If we adjusted totlen to fit the bufsize, it could be that
   2044 	 * totlen is smaller than hdrlen because of the link layer header.
   2045 	 */
   2046 	caplen = totlen - hdrlen;
   2047 	if (caplen < 0)
   2048 		caplen = 0;
   2049 
   2050 	mutex_enter(d->bd_buf_mtx);
   2051 	/*
   2052 	 * Round up the end of the previous packet to the next longword.
   2053 	 */
   2054 #ifdef _LP64
   2055 	if (d->bd_compat32)
   2056 		curlen = BPF_WORDALIGN32(d->bd_slen);
   2057 	else
   2058 #endif
   2059 		curlen = BPF_WORDALIGN(d->bd_slen);
   2060 	if (curlen + totlen > d->bd_bufsize) {
   2061 		/*
   2062 		 * This packet will overflow the storage buffer.
   2063 		 * Rotate the buffers if we can, then wakeup any
   2064 		 * pending reads.
   2065 		 */
   2066 		if (d->bd_fbuf == NULL) {
   2067 			mutex_exit(d->bd_buf_mtx);
   2068 			/*
   2069 			 * We haven't completed the previous read yet,
   2070 			 * so drop the packet.
   2071 			 */
   2072 			atomic_inc_ulong(&d->bd_dcount);
   2073 			BPF_STATINC(drop);
   2074 			return;
   2075 		}
   2076 		ROTATE_BUFFERS(d);
   2077 		do_wakeup = 1;
   2078 		curlen = 0;
   2079 	} else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT) {
   2080 		/*
   2081 		 * Immediate mode is set, or the read timeout has
   2082 		 * already expired during a select call.  A packet
   2083 		 * arrived, so the reader should be woken up.
   2084 		 */
   2085 		do_wakeup = 1;
   2086 	}
   2087 
   2088 	/*
   2089 	 * Append the bpf header.
   2090 	 */
   2091 	h = (char *)d->bd_sbuf + curlen;
   2092 #ifdef _LP64
   2093 	if (d->bd_compat32) {
   2094 		struct bpf_hdr32 *hp32;
   2095 
   2096 		hp32 = (struct bpf_hdr32 *)h;
   2097 		hp32->bh_tstamp.tv_sec = ts->tv_sec;
   2098 		hp32->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
   2099 		hp32->bh_datalen = pktlen;
   2100 		hp32->bh_hdrlen = hdrlen;
   2101 		hp32->bh_caplen = caplen;
   2102 	} else
   2103 #endif
   2104 	{
   2105 		struct bpf_hdr *hp;
   2106 
   2107 		hp = (struct bpf_hdr *)h;
   2108 		hp->bh_tstamp.tv_sec = ts->tv_sec;
   2109 		hp->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
   2110 		hp->bh_datalen = pktlen;
   2111 		hp->bh_hdrlen = hdrlen;
   2112 		hp->bh_caplen = caplen;
   2113 	}
   2114 
   2115 	/*
   2116 	 * Copy the packet data into the store buffer and update its length.
   2117 	 */
   2118 	(*cpfn)(h + hdrlen, pkt, caplen);
   2119 	d->bd_slen = curlen + totlen;
   2120 
   2121 	/*
   2122 	 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
   2123 	 * will cause filt_bpfread() to be called with it adjusted.
   2124 	 */
   2125 	if (do_wakeup)
   2126 		bpf_wakeup(d);
   2127 
   2128 	mutex_exit(d->bd_buf_mtx);
   2129 }
   2130 
   2131 /*
   2132  * Initialize all nonzero fields of a descriptor.
   2133  */
   2134 static int
   2135 bpf_allocbufs(struct bpf_d *d)
   2136 {
   2137 
   2138 	d->bd_fbuf = kmem_zalloc(d->bd_bufsize, KM_NOSLEEP);
   2139 	if (!d->bd_fbuf)
   2140 		return (ENOBUFS);
   2141 	d->bd_sbuf = kmem_zalloc(d->bd_bufsize, KM_NOSLEEP);
   2142 	if (!d->bd_sbuf) {
   2143 		kmem_free(d->bd_fbuf, d->bd_bufsize);
   2144 		return (ENOBUFS);
   2145 	}
   2146 	d->bd_slen = 0;
   2147 	d->bd_hlen = 0;
   2148 	return (0);
   2149 }
   2150 
   2151 static void
   2152 bpf_free_filter(struct bpf_filter *filter)
   2153 {
   2154 
   2155 	KASSERT(filter != NULL);
   2156 
   2157 	if (filter->bf_insn != NULL)
   2158 		kmem_free(filter->bf_insn, filter->bf_size);
   2159 	if (filter->bf_jitcode != NULL)
   2160 		bpf_jit_freecode(filter->bf_jitcode);
   2161 	kmem_free(filter, sizeof(*filter));
   2162 }
   2163 
   2164 /*
   2165  * Free buffers currently in use by a descriptor.
   2166  * Called on close.
   2167  */
   2168 static void
   2169 bpf_freed(struct bpf_d *d)
   2170 {
   2171 	/*
   2172 	 * We don't need to lock out interrupts since this descriptor has
   2173 	 * been detached from its interface and it yet hasn't been marked
   2174 	 * free.
   2175 	 */
   2176 	if (d->bd_sbuf != NULL) {
   2177 		kmem_free(d->bd_sbuf, d->bd_bufsize);
   2178 		if (d->bd_hbuf != NULL)
   2179 			kmem_free(d->bd_hbuf, d->bd_bufsize);
   2180 		if (d->bd_fbuf != NULL)
   2181 			kmem_free(d->bd_fbuf, d->bd_bufsize);
   2182 	}
   2183 	if (d->bd_rfilter != NULL) {
   2184 		bpf_free_filter(d->bd_rfilter);
   2185 		d->bd_rfilter = NULL;
   2186 	}
   2187 	if (d->bd_wfilter != NULL) {
   2188 		bpf_free_filter(d->bd_wfilter);
   2189 		d->bd_wfilter = NULL;
   2190 	}
   2191 	d->bd_jitcode = NULL;
   2192 }
   2193 
   2194 /*
   2195  * Attach an interface to bpf.  dlt is the link layer type;
   2196  * hdrlen is the fixed size of the link header for the specified dlt
   2197  * (variable length headers not yet supported).
   2198  */
   2199 static void
   2200 _bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
   2201 {
   2202 	struct bpf_if *bp;
   2203 
   2204 	bp = kmem_alloc(sizeof(*bp), KM_SLEEP);
   2205 
   2206 	mutex_enter(&bpf_mtx);
   2207 	bp->bif_driverp = driverp;
   2208 	bp->bif_ifp = ifp;
   2209 	bp->bif_dlt = dlt;
   2210 	bp->bif_si = NULL;
   2211 	BPF_IFLIST_ENTRY_INIT(bp);
   2212 	PSLIST_INIT(&bp->bif_dlist_head);
   2213 	psref_target_init(&bp->bif_psref, bpf_psref_class);
   2214 	SLIST_INIT(&bp->bif_trackers);
   2215 
   2216 	BPF_IFLIST_WRITER_INSERT_HEAD(bp);
   2217 
   2218 	*bp->bif_driverp = NULL;
   2219 
   2220 	bp->bif_hdrlen = hdrlen;
   2221 	mutex_exit(&bpf_mtx);
   2222 #if 0
   2223 	printf("bpf: %s attached with dlt %x\n", ifp->if_xname, dlt);
   2224 #endif
   2225 }
   2226 
   2227 static void
   2228 _bpf_mtap_softint_init(struct ifnet *ifp)
   2229 {
   2230 	struct bpf_if *bp;
   2231 
   2232 	mutex_enter(&bpf_mtx);
   2233 	BPF_IFLIST_WRITER_FOREACH(bp) {
   2234 		if (bp->bif_ifp != ifp)
   2235 			continue;
   2236 
   2237 		bp->bif_mbuf_head = NULL;
   2238 		bp->bif_mbuf_tail = NULL;
   2239 		bp->bif_si = softint_establish(SOFTINT_NET, bpf_mtap_si, bp);
   2240 		if (bp->bif_si == NULL)
   2241 			panic("%s: softint_establish() failed", __func__);
   2242 		break;
   2243 	}
   2244 	mutex_exit(&bpf_mtx);
   2245 
   2246 	if (bp == NULL)
   2247 		panic("%s: no bpf_if found for %s", __func__, ifp->if_xname);
   2248 }
   2249 
   2250 /*
   2251  * Remove an interface from bpf.
   2252  */
   2253 static void
   2254 _bpfdetach(struct ifnet *ifp)
   2255 {
   2256 	struct bpf_if *bp;
   2257 	struct bpf_d *d;
   2258 	int s;
   2259 
   2260 	mutex_enter(&bpf_mtx);
   2261 	/* Nuke the vnodes for any open instances */
   2262   again_d:
   2263 	BPF_DLIST_WRITER_FOREACH(d) {
   2264 		mutex_enter(d->bd_mtx);
   2265 		if (d->bd_bif != NULL && d->bd_bif->bif_ifp == ifp) {
   2266 			/*
   2267 			 * Detach the descriptor from an interface now.
   2268 			 * It will be free'ed later by close routine.
   2269 			 */
   2270 			bpf_detachd(d);
   2271 			mutex_exit(d->bd_mtx);
   2272 			goto again_d;
   2273 		}
   2274 		mutex_exit(d->bd_mtx);
   2275 	}
   2276 
   2277   again:
   2278 	BPF_IFLIST_WRITER_FOREACH(bp) {
   2279 		if (bp->bif_ifp == ifp) {
   2280 			BPF_IFLIST_WRITER_REMOVE(bp);
   2281 
   2282 			pserialize_perform(bpf_psz);
   2283 			psref_target_destroy(&bp->bif_psref, bpf_psref_class);
   2284 
   2285 			while (!SLIST_EMPTY(&bp->bif_trackers)) {
   2286 				struct bpf_event_tracker *t =
   2287 				    SLIST_FIRST(&bp->bif_trackers);
   2288 				SLIST_REMOVE_HEAD(&bp->bif_trackers,
   2289 				    bet_entries);
   2290 				kmem_free(t, sizeof(*t));
   2291 			}
   2292 
   2293 			BPF_IFLIST_ENTRY_DESTROY(bp);
   2294 			if (bp->bif_si != NULL) {
   2295 				/* XXX NOMPSAFE: assumed running on one CPU */
   2296 				s = splnet();
   2297 				while (bp->bif_mbuf_head != NULL) {
   2298 					struct mbuf *m = bp->bif_mbuf_head;
   2299 					bp->bif_mbuf_head = m->m_nextpkt;
   2300 					m_freem(m);
   2301 				}
   2302 				splx(s);
   2303 				softint_disestablish(bp->bif_si);
   2304 			}
   2305 			kmem_free(bp, sizeof(*bp));
   2306 			goto again;
   2307 		}
   2308 	}
   2309 	mutex_exit(&bpf_mtx);
   2310 }
   2311 
   2312 /*
   2313  * Change the data link type of a interface.
   2314  */
   2315 static void
   2316 _bpf_change_type(struct ifnet *ifp, u_int dlt, u_int hdrlen)
   2317 {
   2318 	struct bpf_if *bp;
   2319 
   2320 	mutex_enter(&bpf_mtx);
   2321 	BPF_IFLIST_WRITER_FOREACH(bp) {
   2322 		if (bp->bif_driverp == &ifp->if_bpf)
   2323 			break;
   2324 	}
   2325 	if (bp == NULL)
   2326 		panic("bpf_change_type");
   2327 
   2328 	bp->bif_dlt = dlt;
   2329 
   2330 	bp->bif_hdrlen = hdrlen;
   2331 	mutex_exit(&bpf_mtx);
   2332 }
   2333 
   2334 /*
   2335  * Get a list of available data link type of the interface.
   2336  */
   2337 static int
   2338 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
   2339 {
   2340 	int n, error;
   2341 	struct ifnet *ifp;
   2342 	struct bpf_if *bp;
   2343 	int s, bound;
   2344 
   2345 	KASSERT(mutex_owned(d->bd_mtx));
   2346 
   2347 	ifp = d->bd_bif->bif_ifp;
   2348 	n = 0;
   2349 	error = 0;
   2350 
   2351 	bound = curlwp_bind();
   2352 	s = pserialize_read_enter();
   2353 	BPF_IFLIST_READER_FOREACH(bp) {
   2354 		if (bp->bif_ifp != ifp)
   2355 			continue;
   2356 		if (bfl->bfl_list != NULL) {
   2357 			struct psref psref;
   2358 
   2359 			if (n >= bfl->bfl_len) {
   2360 				pserialize_read_exit(s);
   2361 				return ENOMEM;
   2362 			}
   2363 
   2364 			bpf_if_acquire(bp, &psref);
   2365 			pserialize_read_exit(s);
   2366 
   2367 			error = copyout(&bp->bif_dlt,
   2368 			    bfl->bfl_list + n, sizeof(u_int));
   2369 
   2370 			s = pserialize_read_enter();
   2371 			bpf_if_release(bp, &psref);
   2372 		}
   2373 		n++;
   2374 	}
   2375 	pserialize_read_exit(s);
   2376 	curlwp_bindx(bound);
   2377 
   2378 	bfl->bfl_len = n;
   2379 	return error;
   2380 }
   2381 
   2382 /*
   2383  * Set the data link type of a BPF instance.
   2384  */
   2385 static int
   2386 bpf_setdlt(struct bpf_d *d, u_int dlt)
   2387 {
   2388 	int error, opromisc;
   2389 	struct ifnet *ifp;
   2390 	struct bpf_if *bp;
   2391 
   2392 	KASSERT(mutex_owned(&bpf_mtx));
   2393 	KASSERT(mutex_owned(d->bd_mtx));
   2394 
   2395 	if (d->bd_bif->bif_dlt == dlt)
   2396 		return 0;
   2397 	ifp = d->bd_bif->bif_ifp;
   2398 	BPF_IFLIST_WRITER_FOREACH(bp) {
   2399 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
   2400 			break;
   2401 	}
   2402 	if (bp == NULL)
   2403 		return EINVAL;
   2404 	opromisc = d->bd_promisc;
   2405 	bpf_detachd(d);
   2406 	BPFIF_DLIST_ENTRY_INIT(d);
   2407 	bpf_attachd(d, bp);
   2408 	reset_d(d);
   2409 	if (opromisc) {
   2410 		KERNEL_LOCK_UNLESS_NET_MPSAFE();
   2411 		error = ifpromisc(bp->bif_ifp, 1);
   2412 		KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   2413 		if (error)
   2414 			printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
   2415 			    bp->bif_ifp->if_xname, error);
   2416 		else
   2417 			d->bd_promisc = 1;
   2418 	}
   2419 	return 0;
   2420 }
   2421 
   2422 static int
   2423 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
   2424 {
   2425 	int newsize, error;
   2426 	struct sysctlnode node;
   2427 
   2428 	node = *rnode;
   2429 	node.sysctl_data = &newsize;
   2430 	newsize = bpf_maxbufsize;
   2431 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2432 	if (error || newp == NULL)
   2433 		return (error);
   2434 
   2435 	if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
   2436 		return (EINVAL);
   2437 
   2438 	bpf_maxbufsize = newsize;
   2439 
   2440 	return (0);
   2441 }
   2442 
   2443 #if defined(MODULAR) || defined(BPFJIT)
   2444 static int
   2445 sysctl_net_bpf_jit(SYSCTLFN_ARGS)
   2446 {
   2447 	bool newval;
   2448 	int error;
   2449 	struct sysctlnode node;
   2450 
   2451 	node = *rnode;
   2452 	node.sysctl_data = &newval;
   2453 	newval = bpf_jit;
   2454 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2455 	if (error != 0 || newp == NULL)
   2456 		return error;
   2457 
   2458 	bpf_jit = newval;
   2459 	if (newval && bpfjit_module_ops.bj_generate_code == NULL) {
   2460 		printf("JIT compilation is postponed "
   2461 		    "until after bpfjit module is loaded\n");
   2462 	}
   2463 
   2464 	return 0;
   2465 }
   2466 #endif
   2467 
   2468 static int
   2469 sysctl_net_bpf_peers(SYSCTLFN_ARGS)
   2470 {
   2471 	int    error, elem_count;
   2472 	struct bpf_d	 *dp;
   2473 	struct bpf_d_ext  dpe;
   2474 	size_t len, needed, elem_size, out_size;
   2475 	char   *sp;
   2476 
   2477 	if (namelen == 1 && name[0] == CTL_QUERY)
   2478 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   2479 
   2480 	if (namelen != 2)
   2481 		return (EINVAL);
   2482 
   2483 	/* BPF peers is privileged information. */
   2484 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
   2485 	    KAUTH_REQ_NETWORK_INTERFACE_GETPRIV, NULL, NULL, NULL);
   2486 	if (error)
   2487 		return (EPERM);
   2488 
   2489 	len = (oldp != NULL) ? *oldlenp : 0;
   2490 	sp = oldp;
   2491 	elem_size = name[0];
   2492 	elem_count = name[1];
   2493 	out_size = MIN(sizeof(dpe), elem_size);
   2494 	needed = 0;
   2495 
   2496 	if (elem_size < 1 || elem_count < 0)
   2497 		return (EINVAL);
   2498 
   2499 	mutex_enter(&bpf_mtx);
   2500 	BPF_DLIST_WRITER_FOREACH(dp) {
   2501 		if (len >= elem_size && elem_count > 0) {
   2502 #define BPF_EXT(field)	dpe.bde_ ## field = dp->bd_ ## field
   2503 			BPF_EXT(bufsize);
   2504 			BPF_EXT(promisc);
   2505 			BPF_EXT(state);
   2506 			BPF_EXT(immediate);
   2507 			BPF_EXT(hdrcmplt);
   2508 			BPF_EXT(direction);
   2509 			BPF_EXT(pid);
   2510 			BPF_EXT(rcount);
   2511 			BPF_EXT(dcount);
   2512 			BPF_EXT(ccount);
   2513 #undef BPF_EXT
   2514 			mutex_enter(dp->bd_mtx);
   2515 			if (dp->bd_bif)
   2516 				(void)strlcpy(dpe.bde_ifname,
   2517 				    dp->bd_bif->bif_ifp->if_xname,
   2518 				    IFNAMSIZ - 1);
   2519 			else
   2520 				dpe.bde_ifname[0] = '\0';
   2521 			dpe.bde_locked = dp->bd_locked;
   2522 			mutex_exit(dp->bd_mtx);
   2523 
   2524 			error = copyout(&dpe, sp, out_size);
   2525 			if (error)
   2526 				break;
   2527 			sp += elem_size;
   2528 			len -= elem_size;
   2529 		}
   2530 		needed += elem_size;
   2531 		if (elem_count > 0 && elem_count != INT_MAX)
   2532 			elem_count--;
   2533 	}
   2534 	mutex_exit(&bpf_mtx);
   2535 
   2536 	*oldlenp = needed;
   2537 
   2538 	return (error);
   2539 }
   2540 
   2541 static void
   2542 bpf_stats(void *p, void *arg, struct cpu_info *ci __unused)
   2543 {
   2544 	struct bpf_stat *const stats = p;
   2545 	struct bpf_stat *sum = arg;
   2546 
   2547 	int s = splnet();
   2548 
   2549 	sum->bs_recv += stats->bs_recv;
   2550 	sum->bs_drop += stats->bs_drop;
   2551 	sum->bs_capt += stats->bs_capt;
   2552 
   2553 	splx(s);
   2554 }
   2555 
   2556 static int
   2557 bpf_sysctl_gstats_handler(SYSCTLFN_ARGS)
   2558 {
   2559 	struct sysctlnode node;
   2560 	int error;
   2561 	struct bpf_stat sum;
   2562 
   2563 	memset(&sum, 0, sizeof(sum));
   2564 	node = *rnode;
   2565 
   2566 	percpu_foreach_xcall(bpf_gstats_percpu, XC_HIGHPRI_IPL(IPL_SOFTNET),
   2567 	    bpf_stats, &sum);
   2568 
   2569 	node.sysctl_data = &sum;
   2570 	node.sysctl_size = sizeof(sum);
   2571 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2572 	if (error != 0 || newp == NULL)
   2573 		return error;
   2574 
   2575 	return 0;
   2576 }
   2577 
   2578 SYSCTL_SETUP(sysctl_net_bpf_setup, "bpf sysctls")
   2579 {
   2580 	const struct sysctlnode *node;
   2581 
   2582 	node = NULL;
   2583 	sysctl_createv(clog, 0, NULL, &node,
   2584 		       CTLFLAG_PERMANENT,
   2585 		       CTLTYPE_NODE, "bpf",
   2586 		       SYSCTL_DESCR("BPF options"),
   2587 		       NULL, 0, NULL, 0,
   2588 		       CTL_NET, CTL_CREATE, CTL_EOL);
   2589 	if (node != NULL) {
   2590 #if defined(MODULAR) || defined(BPFJIT)
   2591 		sysctl_createv(clog, 0, NULL, NULL,
   2592 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2593 			CTLTYPE_BOOL, "jit",
   2594 			SYSCTL_DESCR("Toggle Just-In-Time compilation"),
   2595 			sysctl_net_bpf_jit, 0, &bpf_jit, 0,
   2596 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   2597 #endif
   2598 		sysctl_createv(clog, 0, NULL, NULL,
   2599 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2600 			CTLTYPE_INT, "maxbufsize",
   2601 			SYSCTL_DESCR("Maximum size for data capture buffer"),
   2602 			sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
   2603 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   2604 		sysctl_createv(clog, 0, NULL, NULL,
   2605 			CTLFLAG_PERMANENT,
   2606 			CTLTYPE_STRUCT, "stats",
   2607 			SYSCTL_DESCR("BPF stats"),
   2608 			bpf_sysctl_gstats_handler, 0, NULL, 0,
   2609 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   2610 		sysctl_createv(clog, 0, NULL, NULL,
   2611 			CTLFLAG_PERMANENT,
   2612 			CTLTYPE_STRUCT, "peers",
   2613 			SYSCTL_DESCR("BPF peers"),
   2614 			sysctl_net_bpf_peers, 0, NULL, 0,
   2615 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   2616 	}
   2617 
   2618 }
   2619 
   2620 static int
   2621 _bpf_register_track_event(struct bpf_if **driverp,
   2622 	    void (*_fun)(struct bpf_if *, struct ifnet *, int, int))
   2623 {
   2624 	struct bpf_if *bp;
   2625 	struct bpf_event_tracker *t;
   2626 	int ret = ENOENT;
   2627 
   2628 	t = kmem_zalloc(sizeof(*t), KM_SLEEP);
   2629 	if (!t)
   2630 		return ENOMEM;
   2631 	t->bet_notify = _fun;
   2632 
   2633 	mutex_enter(&bpf_mtx);
   2634 	BPF_IFLIST_WRITER_FOREACH(bp) {
   2635 		if (bp->bif_driverp != driverp)
   2636 			continue;
   2637 		SLIST_INSERT_HEAD(&bp->bif_trackers, t, bet_entries);
   2638 		ret = 0;
   2639 		break;
   2640 	}
   2641 	mutex_exit(&bpf_mtx);
   2642 
   2643 	return ret;
   2644 }
   2645 
   2646 static int
   2647 _bpf_deregister_track_event(struct bpf_if **driverp,
   2648 	    void (*_fun)(struct bpf_if *, struct ifnet *, int, int))
   2649 {
   2650 	struct bpf_if *bp;
   2651 	struct bpf_event_tracker *t = NULL;
   2652 	int ret = ENOENT;
   2653 
   2654 	mutex_enter(&bpf_mtx);
   2655 	BPF_IFLIST_WRITER_FOREACH(bp) {
   2656 		if (bp->bif_driverp != driverp)
   2657 			continue;
   2658 		SLIST_FOREACH(t, &bp->bif_trackers, bet_entries) {
   2659 			if (t->bet_notify == _fun) {
   2660 				ret = 0;
   2661 				break;
   2662 			}
   2663 		}
   2664 		if (ret == 0)
   2665 			break;
   2666 	}
   2667 	if (ret == 0 && t && t->bet_notify == _fun) {
   2668 		SLIST_REMOVE(&bp->bif_trackers, t, bpf_event_tracker,
   2669 		    bet_entries);
   2670 	}
   2671 	mutex_exit(&bpf_mtx);
   2672 	if (ret == 0)
   2673 		kmem_free(t, sizeof(*t));
   2674 	return ret;
   2675 }
   2676 
   2677 struct bpf_ops bpf_ops_kernel = {
   2678 	.bpf_attach =		_bpfattach,
   2679 	.bpf_detach =		_bpfdetach,
   2680 	.bpf_change_type =	_bpf_change_type,
   2681 	.bpf_register_track_event = _bpf_register_track_event,
   2682 	.bpf_deregister_track_event = _bpf_deregister_track_event,
   2683 
   2684 	.bpf_mtap =		_bpf_mtap,
   2685 	.bpf_mtap2 =		_bpf_mtap2,
   2686 	.bpf_mtap_af =		_bpf_mtap_af,
   2687 	.bpf_mtap_sl_in =	_bpf_mtap_sl_in,
   2688 	.bpf_mtap_sl_out =	_bpf_mtap_sl_out,
   2689 
   2690 	.bpf_mtap_softint =		_bpf_mtap_softint,
   2691 	.bpf_mtap_softint_init =	_bpf_mtap_softint_init,
   2692 };
   2693 
   2694 MODULE(MODULE_CLASS_DRIVER, bpf, "bpf_filter");
   2695 
   2696 static int
   2697 bpf_modcmd(modcmd_t cmd, void *arg)
   2698 {
   2699 #ifdef _MODULE
   2700 	devmajor_t bmajor, cmajor;
   2701 #endif
   2702 	int error = 0;
   2703 
   2704 	switch (cmd) {
   2705 	case MODULE_CMD_INIT:
   2706 		bpf_init();
   2707 #ifdef _MODULE
   2708 		bmajor = cmajor = NODEVMAJOR;
   2709 		error = devsw_attach("bpf", NULL, &bmajor,
   2710 		    &bpf_cdevsw, &cmajor);
   2711 		if (error)
   2712 			break;
   2713 #endif
   2714 
   2715 		bpf_ops_handover_enter(&bpf_ops_kernel);
   2716 		atomic_swap_ptr(&bpf_ops, &bpf_ops_kernel);
   2717 		bpf_ops_handover_exit();
   2718 		break;
   2719 
   2720 	case MODULE_CMD_FINI:
   2721 		/*
   2722 		 * While there is no reference counting for bpf callers,
   2723 		 * unload could at least in theory be done similarly to
   2724 		 * system call disestablishment.  This should even be
   2725 		 * a little simpler:
   2726 		 *
   2727 		 * 1) replace op vector with stubs
   2728 		 * 2) post update to all cpus with xc
   2729 		 * 3) check that nobody is in bpf anymore
   2730 		 *    (it's doubtful we'd want something like l_sysent,
   2731 		 *     but we could do something like *signed* percpu
   2732 		 *     counters.  if the sum is 0, we're good).
   2733 		 * 4) if fail, unroll changes
   2734 		 *
   2735 		 * NOTE: change won't be atomic to the outside.  some
   2736 		 * packets may be not captured even if unload is
   2737 		 * not successful.  I think packet capture not working
   2738 		 * is a perfectly logical consequence of trying to
   2739 		 * disable packet capture.
   2740 		 */
   2741 		error = EOPNOTSUPP;
   2742 		break;
   2743 
   2744 	default:
   2745 		error = ENOTTY;
   2746 		break;
   2747 	}
   2748 
   2749 	return error;
   2750 }
   2751