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