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