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