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