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