xref: /freebsd/sys/net/bpf.c (revision 8c2dd68caa963f1900a8228b0732b04f5d530ffa)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 2019 Andrey V. Elsukov <ae@FreeBSD.org>
7  *
8  * This code is derived from the Stanford/CMU enet packet filter,
9  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
10  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
11  * Berkeley Laboratory.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      @(#)bpf.c	8.4 (Berkeley) 1/9/95
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include "opt_bpf.h"
44 #include "opt_ddb.h"
45 #include "opt_netgraph.h"
46 
47 #include <sys/param.h>
48 #include <sys/conf.h>
49 #include <sys/eventhandler.h>
50 #include <sys/fcntl.h>
51 #include <sys/jail.h>
52 #include <sys/ktr.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mbuf.h>
56 #include <sys/mutex.h>
57 #include <sys/time.h>
58 #include <sys/priv.h>
59 #include <sys/proc.h>
60 #include <sys/signalvar.h>
61 #include <sys/filio.h>
62 #include <sys/sockio.h>
63 #include <sys/ttycom.h>
64 #include <sys/uio.h>
65 #include <sys/sysent.h>
66 #include <sys/systm.h>
67 
68 #include <sys/event.h>
69 #include <sys/file.h>
70 #include <sys/poll.h>
71 #include <sys/proc.h>
72 
73 #include <sys/socket.h>
74 
75 #ifdef DDB
76 #include <ddb/ddb.h>
77 #endif
78 
79 #include <net/if.h>
80 #include <net/if_var.h>
81 #include <net/if_dl.h>
82 #include <net/bpf.h>
83 #include <net/bpf_buffer.h>
84 #ifdef BPF_JITTER
85 #include <net/bpf_jitter.h>
86 #endif
87 #include <net/bpf_zerocopy.h>
88 #include <net/bpfdesc.h>
89 #include <net/route.h>
90 #include <net/vnet.h>
91 
92 #include <netinet/in.h>
93 #include <netinet/if_ether.h>
94 #include <sys/kernel.h>
95 #include <sys/sysctl.h>
96 
97 #include <net80211/ieee80211_freebsd.h>
98 
99 #include <security/mac/mac_framework.h>
100 
101 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
102 
103 static struct bpf_if_ext dead_bpf_if = {
104 	.bif_dlist = CK_LIST_HEAD_INITIALIZER()
105 };
106 
107 struct bpf_if {
108 #define	bif_next	bif_ext.bif_next
109 #define	bif_dlist	bif_ext.bif_dlist
110 	struct bpf_if_ext bif_ext;	/* public members */
111 	u_int		bif_dlt;	/* link layer type */
112 	u_int		bif_hdrlen;	/* length of link header */
113 	struct bpfd_list bif_wlist;	/* writer-only list */
114 	struct ifnet	*bif_ifp;	/* corresponding interface */
115 	struct bpf_if	**bif_bpf;	/* Pointer to pointer to us */
116 	volatile u_int	bif_refcnt;
117 	struct epoch_context epoch_ctx;
118 };
119 
120 CTASSERT(offsetof(struct bpf_if, bif_ext) == 0);
121 
122 struct bpf_program_buffer {
123 	struct epoch_context	epoch_ctx;
124 #ifdef BPF_JITTER
125 	bpf_jit_filter		*func;
126 #endif
127 	void			*buffer[0];
128 };
129 
130 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
131 
132 #define PRINET  26			/* interruptible */
133 
134 #define	SIZEOF_BPF_HDR(type)	\
135     (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
136 
137 #ifdef COMPAT_FREEBSD32
138 #include <sys/mount.h>
139 #include <compat/freebsd32/freebsd32.h>
140 #define BPF_ALIGNMENT32 sizeof(int32_t)
141 #define	BPF_WORDALIGN32(x) roundup2(x, BPF_ALIGNMENT32)
142 
143 #ifndef BURN_BRIDGES
144 /*
145  * 32-bit version of structure prepended to each packet.  We use this header
146  * instead of the standard one for 32-bit streams.  We mark the a stream as
147  * 32-bit the first time we see a 32-bit compat ioctl request.
148  */
149 struct bpf_hdr32 {
150 	struct timeval32 bh_tstamp;	/* time stamp */
151 	uint32_t	bh_caplen;	/* length of captured portion */
152 	uint32_t	bh_datalen;	/* original length of packet */
153 	uint16_t	bh_hdrlen;	/* length of bpf header (this struct
154 					   plus alignment padding) */
155 };
156 #endif
157 
158 struct bpf_program32 {
159 	u_int bf_len;
160 	uint32_t bf_insns;
161 };
162 
163 struct bpf_dltlist32 {
164 	u_int	bfl_len;
165 	u_int	bfl_list;
166 };
167 
168 #define	BIOCSETF32	_IOW('B', 103, struct bpf_program32)
169 #define	BIOCSRTIMEOUT32	_IOW('B', 109, struct timeval32)
170 #define	BIOCGRTIMEOUT32	_IOR('B', 110, struct timeval32)
171 #define	BIOCGDLTLIST32	_IOWR('B', 121, struct bpf_dltlist32)
172 #define	BIOCSETWF32	_IOW('B', 123, struct bpf_program32)
173 #define	BIOCSETFNR32	_IOW('B', 130, struct bpf_program32)
174 #endif
175 
176 #define BPF_LOCK()	   sx_xlock(&bpf_sx)
177 #define BPF_UNLOCK()		sx_xunlock(&bpf_sx)
178 #define BPF_LOCK_ASSERT()	sx_assert(&bpf_sx, SA_XLOCKED)
179 /*
180  * bpf_iflist is a list of BPF interface structures, each corresponding to a
181  * specific DLT. The same network interface might have several BPF interface
182  * structures registered by different layers in the stack (i.e., 802.11
183  * frames, ethernet frames, etc).
184  */
185 CK_LIST_HEAD(bpf_iflist, bpf_if);
186 static struct bpf_iflist bpf_iflist;
187 static struct sx	bpf_sx;		/* bpf global lock */
188 static int		bpf_bpfd_cnt;
189 
190 static void	bpfif_ref(struct bpf_if *);
191 static void	bpfif_rele(struct bpf_if *);
192 
193 static void	bpfd_ref(struct bpf_d *);
194 static void	bpfd_rele(struct bpf_d *);
195 static void	bpf_attachd(struct bpf_d *, struct bpf_if *);
196 static void	bpf_detachd(struct bpf_d *);
197 static void	bpf_detachd_locked(struct bpf_d *, bool);
198 static void	bpfd_free(epoch_context_t);
199 static int	bpf_movein(struct uio *, int, struct ifnet *, struct mbuf **,
200 		    struct sockaddr *, int *, struct bpf_d *);
201 static int	bpf_setif(struct bpf_d *, struct ifreq *);
202 static void	bpf_timed_out(void *);
203 static __inline void
204 		bpf_wakeup(struct bpf_d *);
205 static void	catchpacket(struct bpf_d *, u_char *, u_int, u_int,
206 		    void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
207 		    struct bintime *);
208 static void	reset_d(struct bpf_d *);
209 static int	bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
210 static int	bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
211 static int	bpf_setdlt(struct bpf_d *, u_int);
212 static void	filt_bpfdetach(struct knote *);
213 static int	filt_bpfread(struct knote *, long);
214 static void	bpf_drvinit(void *);
215 static int	bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
216 
217 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
218     "bpf sysctl");
219 int bpf_maxinsns = BPF_MAXINSNS;
220 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
221     &bpf_maxinsns, 0, "Maximum bpf program instructions");
222 static int bpf_zerocopy_enable = 0;
223 SYSCTL_INT(_net_bpf, OID_AUTO, zerocopy_enable, CTLFLAG_RW,
224     &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
225 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
226     bpf_stats_sysctl, "bpf statistics portal");
227 
228 VNET_DEFINE_STATIC(int, bpf_optimize_writers) = 0;
229 #define	V_bpf_optimize_writers VNET(bpf_optimize_writers)
230 SYSCTL_INT(_net_bpf, OID_AUTO, optimize_writers, CTLFLAG_VNET | CTLFLAG_RWTUN,
231     &VNET_NAME(bpf_optimize_writers), 0,
232     "Do not send packets until BPF program is set");
233 
234 static	d_open_t	bpfopen;
235 static	d_read_t	bpfread;
236 static	d_write_t	bpfwrite;
237 static	d_ioctl_t	bpfioctl;
238 static	d_poll_t	bpfpoll;
239 static	d_kqfilter_t	bpfkqfilter;
240 
241 static struct cdevsw bpf_cdevsw = {
242 	.d_version =	D_VERSION,
243 	.d_open =	bpfopen,
244 	.d_read =	bpfread,
245 	.d_write =	bpfwrite,
246 	.d_ioctl =	bpfioctl,
247 	.d_poll =	bpfpoll,
248 	.d_name =	"bpf",
249 	.d_kqfilter =	bpfkqfilter,
250 };
251 
252 static struct filterops bpfread_filtops = {
253 	.f_isfd = 1,
254 	.f_detach = filt_bpfdetach,
255 	.f_event = filt_bpfread,
256 };
257 
258 /*
259  * LOCKING MODEL USED BY BPF
260  *
261  * Locks:
262  * 1) global lock (BPF_LOCK). Sx, used to protect some global counters,
263  * every bpf_iflist changes, serializes ioctl access to bpf descriptors.
264  * 2) Descriptor lock. Mutex, used to protect BPF buffers and various
265  * structure fields used by bpf_*tap* code.
266  *
267  * Lock order: global lock, then descriptor lock.
268  *
269  * There are several possible consumers:
270  *
271  * 1. The kernel registers interface pointer with bpfattach().
272  * Each call allocates new bpf_if structure, references ifnet pointer
273  * and links bpf_if into bpf_iflist chain. This is protected with global
274  * lock.
275  *
276  * 2. An userland application uses ioctl() call to bpf_d descriptor.
277  * All such call are serialized with global lock. BPF filters can be
278  * changed, but pointer to old filter will be freed using NET_EPOCH_CALL().
279  * Thus it should be safe for bpf_tap/bpf_mtap* code to do access to
280  * filter pointers, even if change will happen during bpf_tap execution.
281  * Destroying of bpf_d descriptor also is doing using NET_EPOCH_CALL().
282  *
283  * 3. An userland application can write packets into bpf_d descriptor.
284  * There we need to be sure, that ifnet won't disappear during bpfwrite().
285  *
286  * 4. The kernel invokes bpf_tap/bpf_mtap* functions. The access to
287  * bif_dlist is protected with net_epoch_preempt section. So, it should
288  * be safe to make access to bpf_d descriptor inside the section.
289  *
290  * 5. The kernel invokes bpfdetach() on interface destroying. All lists
291  * are modified with global lock held and actual free() is done using
292  * NET_EPOCH_CALL().
293  */
294 
295 static void
296 bpfif_free(epoch_context_t ctx)
297 {
298 	struct bpf_if *bp;
299 
300 	bp = __containerof(ctx, struct bpf_if, epoch_ctx);
301 	if_rele(bp->bif_ifp);
302 	free(bp, M_BPF);
303 }
304 
305 static void
306 bpfif_ref(struct bpf_if *bp)
307 {
308 
309 	refcount_acquire(&bp->bif_refcnt);
310 }
311 
312 static void
313 bpfif_rele(struct bpf_if *bp)
314 {
315 
316 	if (!refcount_release(&bp->bif_refcnt))
317 		return;
318 	NET_EPOCH_CALL(bpfif_free, &bp->epoch_ctx);
319 }
320 
321 static void
322 bpfd_ref(struct bpf_d *d)
323 {
324 
325 	refcount_acquire(&d->bd_refcnt);
326 }
327 
328 static void
329 bpfd_rele(struct bpf_d *d)
330 {
331 
332 	if (!refcount_release(&d->bd_refcnt))
333 		return;
334 	NET_EPOCH_CALL(bpfd_free, &d->epoch_ctx);
335 }
336 
337 static struct bpf_program_buffer*
338 bpf_program_buffer_alloc(size_t size, int flags)
339 {
340 
341 	return (malloc(sizeof(struct bpf_program_buffer) + size,
342 	    M_BPF, flags));
343 }
344 
345 static void
346 bpf_program_buffer_free(epoch_context_t ctx)
347 {
348 	struct bpf_program_buffer *ptr;
349 
350 	ptr = __containerof(ctx, struct bpf_program_buffer, epoch_ctx);
351 #ifdef BPF_JITTER
352 	if (ptr->func != NULL)
353 		bpf_destroy_jit_filter(ptr->func);
354 #endif
355 	free(ptr, M_BPF);
356 }
357 
358 /*
359  * Wrapper functions for various buffering methods.  If the set of buffer
360  * modes expands, we will probably want to introduce a switch data structure
361  * similar to protosw, et.
362  */
363 static void
364 bpf_append_bytes(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
365     u_int len)
366 {
367 
368 	BPFD_LOCK_ASSERT(d);
369 
370 	switch (d->bd_bufmode) {
371 	case BPF_BUFMODE_BUFFER:
372 		return (bpf_buffer_append_bytes(d, buf, offset, src, len));
373 
374 	case BPF_BUFMODE_ZBUF:
375 		counter_u64_add(d->bd_zcopy, 1);
376 		return (bpf_zerocopy_append_bytes(d, buf, offset, src, len));
377 
378 	default:
379 		panic("bpf_buf_append_bytes");
380 	}
381 }
382 
383 static void
384 bpf_append_mbuf(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
385     u_int len)
386 {
387 
388 	BPFD_LOCK_ASSERT(d);
389 
390 	switch (d->bd_bufmode) {
391 	case BPF_BUFMODE_BUFFER:
392 		return (bpf_buffer_append_mbuf(d, buf, offset, src, len));
393 
394 	case BPF_BUFMODE_ZBUF:
395 		counter_u64_add(d->bd_zcopy, 1);
396 		return (bpf_zerocopy_append_mbuf(d, buf, offset, src, len));
397 
398 	default:
399 		panic("bpf_buf_append_mbuf");
400 	}
401 }
402 
403 /*
404  * This function gets called when the free buffer is re-assigned.
405  */
406 static void
407 bpf_buf_reclaimed(struct bpf_d *d)
408 {
409 
410 	BPFD_LOCK_ASSERT(d);
411 
412 	switch (d->bd_bufmode) {
413 	case BPF_BUFMODE_BUFFER:
414 		return;
415 
416 	case BPF_BUFMODE_ZBUF:
417 		bpf_zerocopy_buf_reclaimed(d);
418 		return;
419 
420 	default:
421 		panic("bpf_buf_reclaimed");
422 	}
423 }
424 
425 /*
426  * If the buffer mechanism has a way to decide that a held buffer can be made
427  * free, then it is exposed via the bpf_canfreebuf() interface.  (1) is
428  * returned if the buffer can be discarded, (0) is returned if it cannot.
429  */
430 static int
431 bpf_canfreebuf(struct bpf_d *d)
432 {
433 
434 	BPFD_LOCK_ASSERT(d);
435 
436 	switch (d->bd_bufmode) {
437 	case BPF_BUFMODE_ZBUF:
438 		return (bpf_zerocopy_canfreebuf(d));
439 	}
440 	return (0);
441 }
442 
443 /*
444  * Allow the buffer model to indicate that the current store buffer is
445  * immutable, regardless of the appearance of space.  Return (1) if the
446  * buffer is writable, and (0) if not.
447  */
448 static int
449 bpf_canwritebuf(struct bpf_d *d)
450 {
451 	BPFD_LOCK_ASSERT(d);
452 
453 	switch (d->bd_bufmode) {
454 	case BPF_BUFMODE_ZBUF:
455 		return (bpf_zerocopy_canwritebuf(d));
456 	}
457 	return (1);
458 }
459 
460 /*
461  * Notify buffer model that an attempt to write to the store buffer has
462  * resulted in a dropped packet, in which case the buffer may be considered
463  * full.
464  */
465 static void
466 bpf_buffull(struct bpf_d *d)
467 {
468 
469 	BPFD_LOCK_ASSERT(d);
470 
471 	switch (d->bd_bufmode) {
472 	case BPF_BUFMODE_ZBUF:
473 		bpf_zerocopy_buffull(d);
474 		break;
475 	}
476 }
477 
478 /*
479  * Notify the buffer model that a buffer has moved into the hold position.
480  */
481 void
482 bpf_bufheld(struct bpf_d *d)
483 {
484 
485 	BPFD_LOCK_ASSERT(d);
486 
487 	switch (d->bd_bufmode) {
488 	case BPF_BUFMODE_ZBUF:
489 		bpf_zerocopy_bufheld(d);
490 		break;
491 	}
492 }
493 
494 static void
495 bpf_free(struct bpf_d *d)
496 {
497 
498 	switch (d->bd_bufmode) {
499 	case BPF_BUFMODE_BUFFER:
500 		return (bpf_buffer_free(d));
501 
502 	case BPF_BUFMODE_ZBUF:
503 		return (bpf_zerocopy_free(d));
504 
505 	default:
506 		panic("bpf_buf_free");
507 	}
508 }
509 
510 static int
511 bpf_uiomove(struct bpf_d *d, caddr_t buf, u_int len, struct uio *uio)
512 {
513 
514 	if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
515 		return (EOPNOTSUPP);
516 	return (bpf_buffer_uiomove(d, buf, len, uio));
517 }
518 
519 static int
520 bpf_ioctl_sblen(struct bpf_d *d, u_int *i)
521 {
522 
523 	if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
524 		return (EOPNOTSUPP);
525 	return (bpf_buffer_ioctl_sblen(d, i));
526 }
527 
528 static int
529 bpf_ioctl_getzmax(struct thread *td, struct bpf_d *d, size_t *i)
530 {
531 
532 	if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
533 		return (EOPNOTSUPP);
534 	return (bpf_zerocopy_ioctl_getzmax(td, d, i));
535 }
536 
537 static int
538 bpf_ioctl_rotzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
539 {
540 
541 	if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
542 		return (EOPNOTSUPP);
543 	return (bpf_zerocopy_ioctl_rotzbuf(td, d, bz));
544 }
545 
546 static int
547 bpf_ioctl_setzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
548 {
549 
550 	if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
551 		return (EOPNOTSUPP);
552 	return (bpf_zerocopy_ioctl_setzbuf(td, d, bz));
553 }
554 
555 /*
556  * General BPF functions.
557  */
558 static int
559 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
560     struct sockaddr *sockp, int *hdrlen, struct bpf_d *d)
561 {
562 	const struct ieee80211_bpf_params *p;
563 	struct ether_header *eh;
564 	struct mbuf *m;
565 	int error;
566 	int len;
567 	int hlen;
568 	int slen;
569 
570 	/*
571 	 * Build a sockaddr based on the data link layer type.
572 	 * We do this at this level because the ethernet header
573 	 * is copied directly into the data field of the sockaddr.
574 	 * In the case of SLIP, there is no header and the packet
575 	 * is forwarded as is.
576 	 * Also, we are careful to leave room at the front of the mbuf
577 	 * for the link level header.
578 	 */
579 	switch (linktype) {
580 	case DLT_SLIP:
581 		sockp->sa_family = AF_INET;
582 		hlen = 0;
583 		break;
584 
585 	case DLT_EN10MB:
586 		sockp->sa_family = AF_UNSPEC;
587 		/* XXX Would MAXLINKHDR be better? */
588 		hlen = ETHER_HDR_LEN;
589 		break;
590 
591 	case DLT_FDDI:
592 		sockp->sa_family = AF_IMPLINK;
593 		hlen = 0;
594 		break;
595 
596 	case DLT_RAW:
597 		sockp->sa_family = AF_UNSPEC;
598 		hlen = 0;
599 		break;
600 
601 	case DLT_NULL:
602 		/*
603 		 * null interface types require a 4 byte pseudo header which
604 		 * corresponds to the address family of the packet.
605 		 */
606 		sockp->sa_family = AF_UNSPEC;
607 		hlen = 4;
608 		break;
609 
610 	case DLT_ATM_RFC1483:
611 		/*
612 		 * en atm driver requires 4-byte atm pseudo header.
613 		 * though it isn't standard, vpi:vci needs to be
614 		 * specified anyway.
615 		 */
616 		sockp->sa_family = AF_UNSPEC;
617 		hlen = 12;	/* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
618 		break;
619 
620 	case DLT_PPP:
621 		sockp->sa_family = AF_UNSPEC;
622 		hlen = 4;	/* This should match PPP_HDRLEN */
623 		break;
624 
625 	case DLT_IEEE802_11:		/* IEEE 802.11 wireless */
626 		sockp->sa_family = AF_IEEE80211;
627 		hlen = 0;
628 		break;
629 
630 	case DLT_IEEE802_11_RADIO:	/* IEEE 802.11 wireless w/ phy params */
631 		sockp->sa_family = AF_IEEE80211;
632 		sockp->sa_len = 12;	/* XXX != 0 */
633 		hlen = sizeof(struct ieee80211_bpf_params);
634 		break;
635 
636 	default:
637 		return (EIO);
638 	}
639 
640 	len = uio->uio_resid;
641 	if (len < hlen || len - hlen > ifp->if_mtu)
642 		return (EMSGSIZE);
643 
644 	/* Allocate a mbuf for our write, since m_get2 fails if len >= to MJUMPAGESIZE, use m_getjcl for bigger buffers */
645 	if (len < MJUMPAGESIZE)
646 		m = m_get2(len, M_WAITOK, MT_DATA, M_PKTHDR);
647 	else if (len <= MJUM9BYTES)
648 		m = m_getjcl(M_WAITOK, MT_DATA, M_PKTHDR, MJUM9BYTES);
649 	else if (len <= MJUM16BYTES)
650 		m = m_getjcl(M_WAITOK, MT_DATA, M_PKTHDR, MJUM16BYTES);
651 	else
652 		m = NULL;
653 	if (m == NULL)
654 		return (EIO);
655 	m->m_pkthdr.len = m->m_len = len;
656 	*mp = m;
657 
658 	error = uiomove(mtod(m, u_char *), len, uio);
659 	if (error)
660 		goto bad;
661 
662 	slen = bpf_filter(d->bd_wfilter, mtod(m, u_char *), len, len);
663 	if (slen == 0) {
664 		error = EPERM;
665 		goto bad;
666 	}
667 
668 	/* Check for multicast destination */
669 	switch (linktype) {
670 	case DLT_EN10MB:
671 		eh = mtod(m, struct ether_header *);
672 		if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
673 			if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
674 			    ETHER_ADDR_LEN) == 0)
675 				m->m_flags |= M_BCAST;
676 			else
677 				m->m_flags |= M_MCAST;
678 		}
679 		if (d->bd_hdrcmplt == 0) {
680 			memcpy(eh->ether_shost, IF_LLADDR(ifp),
681 			    sizeof(eh->ether_shost));
682 		}
683 		break;
684 	}
685 
686 	/*
687 	 * Make room for link header, and copy it to sockaddr
688 	 */
689 	if (hlen != 0) {
690 		if (sockp->sa_family == AF_IEEE80211) {
691 			/*
692 			 * Collect true length from the parameter header
693 			 * NB: sockp is known to be zero'd so if we do a
694 			 *     short copy unspecified parameters will be
695 			 *     zero.
696 			 * NB: packet may not be aligned after stripping
697 			 *     bpf params
698 			 * XXX check ibp_vers
699 			 */
700 			p = mtod(m, const struct ieee80211_bpf_params *);
701 			hlen = p->ibp_len;
702 			if (hlen > sizeof(sockp->sa_data)) {
703 				error = EINVAL;
704 				goto bad;
705 			}
706 		}
707 		bcopy(mtod(m, const void *), sockp->sa_data, hlen);
708 	}
709 	*hdrlen = hlen;
710 
711 	return (0);
712 bad:
713 	m_freem(m);
714 	return (error);
715 }
716 
717 /*
718  * Attach descriptor to the bpf interface, i.e. make d listen on bp,
719  * then reset its buffers and counters with reset_d().
720  */
721 static void
722 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
723 {
724 	int op_w;
725 
726 	BPF_LOCK_ASSERT();
727 
728 	/*
729 	 * Save sysctl value to protect from sysctl change
730 	 * between reads
731 	 */
732 	op_w = V_bpf_optimize_writers || d->bd_writer;
733 
734 	if (d->bd_bif != NULL)
735 		bpf_detachd_locked(d, false);
736 	/*
737 	 * Point d at bp, and add d to the interface's list.
738 	 * Since there are many applications using BPF for
739 	 * sending raw packets only (dhcpd, cdpd are good examples)
740 	 * we can delay adding d to the list of active listeners until
741 	 * some filter is configured.
742 	 */
743 
744 	BPFD_LOCK(d);
745 	/*
746 	 * Hold reference to bpif while descriptor uses this interface.
747 	 */
748 	bpfif_ref(bp);
749 	d->bd_bif = bp;
750 	if (op_w != 0) {
751 		/* Add to writers-only list */
752 		CK_LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
753 		/*
754 		 * We decrement bd_writer on every filter set operation.
755 		 * First BIOCSETF is done by pcap_open_live() to set up
756 		 * snap length. After that appliation usually sets its own
757 		 * filter.
758 		 */
759 		d->bd_writer = 2;
760 	} else
761 		CK_LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
762 
763 	reset_d(d);
764 	BPFD_UNLOCK(d);
765 	bpf_bpfd_cnt++;
766 
767 	CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
768 	    __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
769 
770 	if (op_w == 0)
771 		EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
772 }
773 
774 /*
775  * Check if we need to upgrade our descriptor @d from write-only mode.
776  */
777 static int
778 bpf_check_upgrade(u_long cmd, struct bpf_d *d, struct bpf_insn *fcode,
779     int flen)
780 {
781 	int is_snap, need_upgrade;
782 
783 	/*
784 	 * Check if we've already upgraded or new filter is empty.
785 	 */
786 	if (d->bd_writer == 0 || fcode == NULL)
787 		return (0);
788 
789 	need_upgrade = 0;
790 
791 	/*
792 	 * Check if cmd looks like snaplen setting from
793 	 * pcap_bpf.c:pcap_open_live().
794 	 * Note we're not checking .k value here:
795 	 * while pcap_open_live() definitely sets to non-zero value,
796 	 * we'd prefer to treat k=0 (deny ALL) case the same way: e.g.
797 	 * do not consider upgrading immediately
798 	 */
799 	if (cmd == BIOCSETF && flen == 1 &&
800 	    fcode[0].code == (BPF_RET | BPF_K))
801 		is_snap = 1;
802 	else
803 		is_snap = 0;
804 
805 	if (is_snap == 0) {
806 		/*
807 		 * We're setting first filter and it doesn't look like
808 		 * setting snaplen.  We're probably using bpf directly.
809 		 * Upgrade immediately.
810 		 */
811 		need_upgrade = 1;
812 	} else {
813 		/*
814 		 * Do not require upgrade by first BIOCSETF
815 		 * (used to set snaplen) by pcap_open_live().
816 		 */
817 
818 		if (--d->bd_writer == 0) {
819 			/*
820 			 * First snaplen filter has already
821 			 * been set. This is probably catch-all
822 			 * filter
823 			 */
824 			need_upgrade = 1;
825 		}
826 	}
827 
828 	CTR5(KTR_NET,
829 	    "%s: filter function set by pid %d, "
830 	    "bd_writer counter %d, snap %d upgrade %d",
831 	    __func__, d->bd_pid, d->bd_writer,
832 	    is_snap, need_upgrade);
833 
834 	return (need_upgrade);
835 }
836 
837 /*
838  * Detach a file from its interface.
839  */
840 static void
841 bpf_detachd(struct bpf_d *d)
842 {
843 	BPF_LOCK();
844 	bpf_detachd_locked(d, false);
845 	BPF_UNLOCK();
846 }
847 
848 static void
849 bpf_detachd_locked(struct bpf_d *d, bool detached_ifp)
850 {
851 	struct bpf_if *bp;
852 	struct ifnet *ifp;
853 	int error;
854 
855 	BPF_LOCK_ASSERT();
856 	CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
857 
858 	/* Check if descriptor is attached */
859 	if ((bp = d->bd_bif) == NULL)
860 		return;
861 
862 	BPFD_LOCK(d);
863 	/* Remove d from the interface's descriptor list. */
864 	CK_LIST_REMOVE(d, bd_next);
865 	/* Save bd_writer value */
866 	error = d->bd_writer;
867 	ifp = bp->bif_ifp;
868 	d->bd_bif = NULL;
869 	if (detached_ifp) {
870 		/*
871 		 * Notify descriptor as it's detached, so that any
872 		 * sleepers wake up and get ENXIO.
873 		 */
874 		bpf_wakeup(d);
875 	}
876 	BPFD_UNLOCK(d);
877 	bpf_bpfd_cnt--;
878 
879 	/* Call event handler iff d is attached */
880 	if (error == 0)
881 		EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
882 
883 	/*
884 	 * Check if this descriptor had requested promiscuous mode.
885 	 * If so and ifnet is not detached, turn it off.
886 	 */
887 	if (d->bd_promisc && !detached_ifp) {
888 		d->bd_promisc = 0;
889 		CURVNET_SET(ifp->if_vnet);
890 		error = ifpromisc(ifp, 0);
891 		CURVNET_RESTORE();
892 		if (error != 0 && error != ENXIO) {
893 			/*
894 			 * ENXIO can happen if a pccard is unplugged
895 			 * Something is really wrong if we were able to put
896 			 * the driver into promiscuous mode, but can't
897 			 * take it out.
898 			 */
899 			if_printf(bp->bif_ifp,
900 				"bpf_detach: ifpromisc failed (%d)\n", error);
901 		}
902 	}
903 	bpfif_rele(bp);
904 }
905 
906 /*
907  * Close the descriptor by detaching it from its interface,
908  * deallocating its buffers, and marking it free.
909  */
910 static void
911 bpf_dtor(void *data)
912 {
913 	struct bpf_d *d = data;
914 
915 	BPFD_LOCK(d);
916 	if (d->bd_state == BPF_WAITING)
917 		callout_stop(&d->bd_callout);
918 	d->bd_state = BPF_IDLE;
919 	BPFD_UNLOCK(d);
920 	funsetown(&d->bd_sigio);
921 	bpf_detachd(d);
922 #ifdef MAC
923 	mac_bpfdesc_destroy(d);
924 #endif /* MAC */
925 	seldrain(&d->bd_sel);
926 	knlist_destroy(&d->bd_sel.si_note);
927 	callout_drain(&d->bd_callout);
928 	bpfd_rele(d);
929 }
930 
931 /*
932  * Open ethernet device.  Returns ENXIO for illegal minor device number,
933  * EBUSY if file is open by another process.
934  */
935 /* ARGSUSED */
936 static	int
937 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
938 {
939 	struct bpf_d *d;
940 	int error;
941 
942 	d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
943 	error = devfs_set_cdevpriv(d, bpf_dtor);
944 	if (error != 0) {
945 		free(d, M_BPF);
946 		return (error);
947 	}
948 
949 	/* Setup counters */
950 	d->bd_rcount = counter_u64_alloc(M_WAITOK);
951 	d->bd_dcount = counter_u64_alloc(M_WAITOK);
952 	d->bd_fcount = counter_u64_alloc(M_WAITOK);
953 	d->bd_wcount = counter_u64_alloc(M_WAITOK);
954 	d->bd_wfcount = counter_u64_alloc(M_WAITOK);
955 	d->bd_wdcount = counter_u64_alloc(M_WAITOK);
956 	d->bd_zcopy = counter_u64_alloc(M_WAITOK);
957 
958 	/*
959 	 * For historical reasons, perform a one-time initialization call to
960 	 * the buffer routines, even though we're not yet committed to a
961 	 * particular buffer method.
962 	 */
963 	bpf_buffer_init(d);
964 	if ((flags & FREAD) == 0)
965 		d->bd_writer = 2;
966 	d->bd_hbuf_in_use = 0;
967 	d->bd_bufmode = BPF_BUFMODE_BUFFER;
968 	d->bd_sig = SIGIO;
969 	d->bd_direction = BPF_D_INOUT;
970 	d->bd_refcnt = 1;
971 	BPF_PID_REFRESH(d, td);
972 #ifdef MAC
973 	mac_bpfdesc_init(d);
974 	mac_bpfdesc_create(td->td_ucred, d);
975 #endif
976 	mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
977 	callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
978 	knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
979 
980 	return (0);
981 }
982 
983 /*
984  *  bpfread - read next chunk of packets from buffers
985  */
986 static	int
987 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
988 {
989 	struct bpf_d *d;
990 	int error;
991 	int non_block;
992 	int timed_out;
993 
994 	error = devfs_get_cdevpriv((void **)&d);
995 	if (error != 0)
996 		return (error);
997 
998 	/*
999 	 * Restrict application to use a buffer the same size as
1000 	 * as kernel buffers.
1001 	 */
1002 	if (uio->uio_resid != d->bd_bufsize)
1003 		return (EINVAL);
1004 
1005 	non_block = ((ioflag & O_NONBLOCK) != 0);
1006 
1007 	BPFD_LOCK(d);
1008 	BPF_PID_REFRESH_CUR(d);
1009 	if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
1010 		BPFD_UNLOCK(d);
1011 		return (EOPNOTSUPP);
1012 	}
1013 	if (d->bd_state == BPF_WAITING)
1014 		callout_stop(&d->bd_callout);
1015 	timed_out = (d->bd_state == BPF_TIMED_OUT);
1016 	d->bd_state = BPF_IDLE;
1017 	while (d->bd_hbuf_in_use) {
1018 		error = mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1019 		    PRINET|PCATCH, "bd_hbuf", 0);
1020 		if (error != 0) {
1021 			BPFD_UNLOCK(d);
1022 			return (error);
1023 		}
1024 	}
1025 	/*
1026 	 * If the hold buffer is empty, then do a timed sleep, which
1027 	 * ends when the timeout expires or when enough packets
1028 	 * have arrived to fill the store buffer.
1029 	 */
1030 	while (d->bd_hbuf == NULL) {
1031 		if (d->bd_slen != 0) {
1032 			/*
1033 			 * A packet(s) either arrived since the previous
1034 			 * read or arrived while we were asleep.
1035 			 */
1036 			if (d->bd_immediate || non_block || timed_out) {
1037 				/*
1038 				 * Rotate the buffers and return what's here
1039 				 * if we are in immediate mode, non-blocking
1040 				 * flag is set, or this descriptor timed out.
1041 				 */
1042 				ROTATE_BUFFERS(d);
1043 				break;
1044 			}
1045 		}
1046 
1047 		/*
1048 		 * No data is available, check to see if the bpf device
1049 		 * is still pointed at a real interface.  If not, return
1050 		 * ENXIO so that the userland process knows to rebind
1051 		 * it before using it again.
1052 		 */
1053 		if (d->bd_bif == NULL) {
1054 			BPFD_UNLOCK(d);
1055 			return (ENXIO);
1056 		}
1057 
1058 		if (non_block) {
1059 			BPFD_UNLOCK(d);
1060 			return (EWOULDBLOCK);
1061 		}
1062 		error = msleep(d, &d->bd_lock, PRINET|PCATCH,
1063 		     "bpf", d->bd_rtout);
1064 		if (error == EINTR || error == ERESTART) {
1065 			BPFD_UNLOCK(d);
1066 			return (error);
1067 		}
1068 		if (error == EWOULDBLOCK) {
1069 			/*
1070 			 * On a timeout, return what's in the buffer,
1071 			 * which may be nothing.  If there is something
1072 			 * in the store buffer, we can rotate the buffers.
1073 			 */
1074 			if (d->bd_hbuf)
1075 				/*
1076 				 * We filled up the buffer in between
1077 				 * getting the timeout and arriving
1078 				 * here, so we don't need to rotate.
1079 				 */
1080 				break;
1081 
1082 			if (d->bd_slen == 0) {
1083 				BPFD_UNLOCK(d);
1084 				return (0);
1085 			}
1086 			ROTATE_BUFFERS(d);
1087 			break;
1088 		}
1089 	}
1090 	/*
1091 	 * At this point, we know we have something in the hold slot.
1092 	 */
1093 	d->bd_hbuf_in_use = 1;
1094 	BPFD_UNLOCK(d);
1095 
1096 	/*
1097 	 * Move data from hold buffer into user space.
1098 	 * We know the entire buffer is transferred since
1099 	 * we checked above that the read buffer is bpf_bufsize bytes.
1100   	 *
1101 	 * We do not have to worry about simultaneous reads because
1102 	 * we waited for sole access to the hold buffer above.
1103 	 */
1104 	error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
1105 
1106 	BPFD_LOCK(d);
1107 	KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
1108 	d->bd_fbuf = d->bd_hbuf;
1109 	d->bd_hbuf = NULL;
1110 	d->bd_hlen = 0;
1111 	bpf_buf_reclaimed(d);
1112 	d->bd_hbuf_in_use = 0;
1113 	wakeup(&d->bd_hbuf_in_use);
1114 	BPFD_UNLOCK(d);
1115 
1116 	return (error);
1117 }
1118 
1119 /*
1120  * If there are processes sleeping on this descriptor, wake them up.
1121  */
1122 static __inline void
1123 bpf_wakeup(struct bpf_d *d)
1124 {
1125 
1126 	BPFD_LOCK_ASSERT(d);
1127 	if (d->bd_state == BPF_WAITING) {
1128 		callout_stop(&d->bd_callout);
1129 		d->bd_state = BPF_IDLE;
1130 	}
1131 	wakeup(d);
1132 	if (d->bd_async && d->bd_sig && d->bd_sigio)
1133 		pgsigio(&d->bd_sigio, d->bd_sig, 0);
1134 
1135 	selwakeuppri(&d->bd_sel, PRINET);
1136 	KNOTE_LOCKED(&d->bd_sel.si_note, 0);
1137 }
1138 
1139 static void
1140 bpf_timed_out(void *arg)
1141 {
1142 	struct bpf_d *d = (struct bpf_d *)arg;
1143 
1144 	BPFD_LOCK_ASSERT(d);
1145 
1146 	if (callout_pending(&d->bd_callout) ||
1147 	    !callout_active(&d->bd_callout))
1148 		return;
1149 	if (d->bd_state == BPF_WAITING) {
1150 		d->bd_state = BPF_TIMED_OUT;
1151 		if (d->bd_slen != 0)
1152 			bpf_wakeup(d);
1153 	}
1154 }
1155 
1156 static int
1157 bpf_ready(struct bpf_d *d)
1158 {
1159 
1160 	BPFD_LOCK_ASSERT(d);
1161 
1162 	if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
1163 		return (1);
1164 	if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1165 	    d->bd_slen != 0)
1166 		return (1);
1167 	return (0);
1168 }
1169 
1170 static int
1171 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1172 {
1173 	struct route ro;
1174 	struct sockaddr dst;
1175 	struct epoch_tracker et;
1176 	struct bpf_if *bp;
1177 	struct bpf_d *d;
1178 	struct ifnet *ifp;
1179 	struct mbuf *m, *mc;
1180 	int error, hlen;
1181 
1182 	error = devfs_get_cdevpriv((void **)&d);
1183 	if (error != 0)
1184 		return (error);
1185 
1186 	NET_EPOCH_ENTER(et);
1187 	BPFD_LOCK(d);
1188 	BPF_PID_REFRESH_CUR(d);
1189 	counter_u64_add(d->bd_wcount, 1);
1190 	if ((bp = d->bd_bif) == NULL) {
1191 		error = ENXIO;
1192 		goto out_locked;
1193 	}
1194 
1195 	ifp = bp->bif_ifp;
1196 	if ((ifp->if_flags & IFF_UP) == 0) {
1197 		error = ENETDOWN;
1198 		goto out_locked;
1199 	}
1200 
1201 	if (uio->uio_resid == 0)
1202 		goto out_locked;
1203 
1204 	bzero(&dst, sizeof(dst));
1205 	m = NULL;
1206 	hlen = 0;
1207 
1208 	/*
1209 	 * Take extra reference, unlock d and exit from epoch section,
1210 	 * since bpf_movein() can sleep.
1211 	 */
1212 	bpfd_ref(d);
1213 	NET_EPOCH_EXIT(et);
1214 	BPFD_UNLOCK(d);
1215 
1216 	error = bpf_movein(uio, (int)bp->bif_dlt, ifp,
1217 	    &m, &dst, &hlen, d);
1218 
1219 	if (error != 0) {
1220 		counter_u64_add(d->bd_wdcount, 1);
1221 		bpfd_rele(d);
1222 		return (error);
1223 	}
1224 
1225 	BPFD_LOCK(d);
1226 	/*
1227 	 * Check that descriptor is still attached to the interface.
1228 	 * This can happen on bpfdetach(). To avoid access to detached
1229 	 * ifnet, free mbuf and return ENXIO.
1230 	 */
1231 	if (d->bd_bif == NULL) {
1232 		counter_u64_add(d->bd_wdcount, 1);
1233 		BPFD_UNLOCK(d);
1234 		bpfd_rele(d);
1235 		m_freem(m);
1236 		return (ENXIO);
1237 	}
1238 	counter_u64_add(d->bd_wfcount, 1);
1239 	if (d->bd_hdrcmplt)
1240 		dst.sa_family = pseudo_AF_HDRCMPLT;
1241 
1242 	if (d->bd_feedback) {
1243 		mc = m_dup(m, M_NOWAIT);
1244 		if (mc != NULL)
1245 			mc->m_pkthdr.rcvif = ifp;
1246 		/* Set M_PROMISC for outgoing packets to be discarded. */
1247 		if (d->bd_direction == BPF_D_INOUT)
1248 			m->m_flags |= M_PROMISC;
1249 	} else
1250 		mc = NULL;
1251 
1252 	m->m_pkthdr.len -= hlen;
1253 	m->m_len -= hlen;
1254 	m->m_data += hlen;	/* XXX */
1255 
1256 	CURVNET_SET(ifp->if_vnet);
1257 #ifdef MAC
1258 	mac_bpfdesc_create_mbuf(d, m);
1259 	if (mc != NULL)
1260 		mac_bpfdesc_create_mbuf(d, mc);
1261 #endif
1262 
1263 	bzero(&ro, sizeof(ro));
1264 	if (hlen != 0) {
1265 		ro.ro_prepend = (u_char *)&dst.sa_data;
1266 		ro.ro_plen = hlen;
1267 		ro.ro_flags = RT_HAS_HEADER;
1268 	}
1269 
1270 	/* Avoid possible recursion on BPFD_LOCK(). */
1271 	NET_EPOCH_ENTER(et);
1272 	BPFD_UNLOCK(d);
1273 	error = (*ifp->if_output)(ifp, m, &dst, &ro);
1274 	if (error)
1275 		counter_u64_add(d->bd_wdcount, 1);
1276 
1277 	if (mc != NULL) {
1278 		if (error == 0)
1279 			(*ifp->if_input)(ifp, mc);
1280 		else
1281 			m_freem(mc);
1282 	}
1283 	NET_EPOCH_EXIT(et);
1284 	CURVNET_RESTORE();
1285 	bpfd_rele(d);
1286 	return (error);
1287 
1288 out_locked:
1289 	counter_u64_add(d->bd_wdcount, 1);
1290 	NET_EPOCH_EXIT(et);
1291 	BPFD_UNLOCK(d);
1292 	return (error);
1293 }
1294 
1295 /*
1296  * Reset a descriptor by flushing its packet buffer and clearing the receive
1297  * and drop counts.  This is doable for kernel-only buffers, but with
1298  * zero-copy buffers, we can't write to (or rotate) buffers that are
1299  * currently owned by userspace.  It would be nice if we could encapsulate
1300  * this logic in the buffer code rather than here.
1301  */
1302 static void
1303 reset_d(struct bpf_d *d)
1304 {
1305 
1306 	BPFD_LOCK_ASSERT(d);
1307 
1308 	while (d->bd_hbuf_in_use)
1309 		mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1310 		    "bd_hbuf", 0);
1311 	if ((d->bd_hbuf != NULL) &&
1312 	    (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1313 		/* Free the hold buffer. */
1314 		d->bd_fbuf = d->bd_hbuf;
1315 		d->bd_hbuf = NULL;
1316 		d->bd_hlen = 0;
1317 		bpf_buf_reclaimed(d);
1318 	}
1319 	if (bpf_canwritebuf(d))
1320 		d->bd_slen = 0;
1321 	counter_u64_zero(d->bd_rcount);
1322 	counter_u64_zero(d->bd_dcount);
1323 	counter_u64_zero(d->bd_fcount);
1324 	counter_u64_zero(d->bd_wcount);
1325 	counter_u64_zero(d->bd_wfcount);
1326 	counter_u64_zero(d->bd_wdcount);
1327 	counter_u64_zero(d->bd_zcopy);
1328 }
1329 
1330 /*
1331  *  FIONREAD		Check for read packet available.
1332  *  BIOCGBLEN		Get buffer len [for read()].
1333  *  BIOCSETF		Set read filter.
1334  *  BIOCSETFNR		Set read filter without resetting descriptor.
1335  *  BIOCSETWF		Set write filter.
1336  *  BIOCFLUSH		Flush read packet buffer.
1337  *  BIOCPROMISC		Put interface into promiscuous mode.
1338  *  BIOCGDLT		Get link layer type.
1339  *  BIOCGETIF		Get interface name.
1340  *  BIOCSETIF		Set interface.
1341  *  BIOCSRTIMEOUT	Set read timeout.
1342  *  BIOCGRTIMEOUT	Get read timeout.
1343  *  BIOCGSTATS		Get packet stats.
1344  *  BIOCIMMEDIATE	Set immediate mode.
1345  *  BIOCVERSION		Get filter language version.
1346  *  BIOCGHDRCMPLT	Get "header already complete" flag
1347  *  BIOCSHDRCMPLT	Set "header already complete" flag
1348  *  BIOCGDIRECTION	Get packet direction flag
1349  *  BIOCSDIRECTION	Set packet direction flag
1350  *  BIOCGTSTAMP		Get time stamp format and resolution.
1351  *  BIOCSTSTAMP		Set time stamp format and resolution.
1352  *  BIOCLOCK		Set "locked" flag
1353  *  BIOCFEEDBACK	Set packet feedback mode.
1354  *  BIOCSETZBUF		Set current zero-copy buffer locations.
1355  *  BIOCGETZMAX		Get maximum zero-copy buffer size.
1356  *  BIOCROTZBUF		Force rotation of zero-copy buffer
1357  *  BIOCSETBUFMODE	Set buffer mode.
1358  *  BIOCGETBUFMODE	Get current buffer mode.
1359  */
1360 /* ARGSUSED */
1361 static	int
1362 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1363     struct thread *td)
1364 {
1365 	struct bpf_d *d;
1366 	int error;
1367 
1368 	error = devfs_get_cdevpriv((void **)&d);
1369 	if (error != 0)
1370 		return (error);
1371 
1372 	/*
1373 	 * Refresh PID associated with this descriptor.
1374 	 */
1375 	BPFD_LOCK(d);
1376 	BPF_PID_REFRESH(d, td);
1377 	if (d->bd_state == BPF_WAITING)
1378 		callout_stop(&d->bd_callout);
1379 	d->bd_state = BPF_IDLE;
1380 	BPFD_UNLOCK(d);
1381 
1382 	if (d->bd_locked == 1) {
1383 		switch (cmd) {
1384 		case BIOCGBLEN:
1385 		case BIOCFLUSH:
1386 		case BIOCGDLT:
1387 		case BIOCGDLTLIST:
1388 #ifdef COMPAT_FREEBSD32
1389 		case BIOCGDLTLIST32:
1390 #endif
1391 		case BIOCGETIF:
1392 		case BIOCGRTIMEOUT:
1393 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1394 		case BIOCGRTIMEOUT32:
1395 #endif
1396 		case BIOCGSTATS:
1397 		case BIOCVERSION:
1398 		case BIOCGRSIG:
1399 		case BIOCGHDRCMPLT:
1400 		case BIOCSTSTAMP:
1401 		case BIOCFEEDBACK:
1402 		case FIONREAD:
1403 		case BIOCLOCK:
1404 		case BIOCSRTIMEOUT:
1405 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1406 		case BIOCSRTIMEOUT32:
1407 #endif
1408 		case BIOCIMMEDIATE:
1409 		case TIOCGPGRP:
1410 		case BIOCROTZBUF:
1411 			break;
1412 		default:
1413 			return (EPERM);
1414 		}
1415 	}
1416 #ifdef COMPAT_FREEBSD32
1417 	/*
1418 	 * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1419 	 * that it will get 32-bit packet headers.
1420 	 */
1421 	switch (cmd) {
1422 	case BIOCSETF32:
1423 	case BIOCSETFNR32:
1424 	case BIOCSETWF32:
1425 	case BIOCGDLTLIST32:
1426 	case BIOCGRTIMEOUT32:
1427 	case BIOCSRTIMEOUT32:
1428 		if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
1429 			BPFD_LOCK(d);
1430 			d->bd_compat32 = 1;
1431 			BPFD_UNLOCK(d);
1432 		}
1433 	}
1434 #endif
1435 
1436 	CURVNET_SET(TD_TO_VNET(td));
1437 	switch (cmd) {
1438 	default:
1439 		error = EINVAL;
1440 		break;
1441 
1442 	/*
1443 	 * Check for read packet available.
1444 	 */
1445 	case FIONREAD:
1446 		{
1447 			int n;
1448 
1449 			BPFD_LOCK(d);
1450 			n = d->bd_slen;
1451 			while (d->bd_hbuf_in_use)
1452 				mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1453 				    PRINET, "bd_hbuf", 0);
1454 			if (d->bd_hbuf)
1455 				n += d->bd_hlen;
1456 			BPFD_UNLOCK(d);
1457 
1458 			*(int *)addr = n;
1459 			break;
1460 		}
1461 
1462 	/*
1463 	 * Get buffer len [for read()].
1464 	 */
1465 	case BIOCGBLEN:
1466 		BPFD_LOCK(d);
1467 		*(u_int *)addr = d->bd_bufsize;
1468 		BPFD_UNLOCK(d);
1469 		break;
1470 
1471 	/*
1472 	 * Set buffer length.
1473 	 */
1474 	case BIOCSBLEN:
1475 		error = bpf_ioctl_sblen(d, (u_int *)addr);
1476 		break;
1477 
1478 	/*
1479 	 * Set link layer read filter.
1480 	 */
1481 	case BIOCSETF:
1482 	case BIOCSETFNR:
1483 	case BIOCSETWF:
1484 #ifdef COMPAT_FREEBSD32
1485 	case BIOCSETF32:
1486 	case BIOCSETFNR32:
1487 	case BIOCSETWF32:
1488 #endif
1489 		error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1490 		break;
1491 
1492 	/*
1493 	 * Flush read packet buffer.
1494 	 */
1495 	case BIOCFLUSH:
1496 		BPFD_LOCK(d);
1497 		reset_d(d);
1498 		BPFD_UNLOCK(d);
1499 		break;
1500 
1501 	/*
1502 	 * Put interface into promiscuous mode.
1503 	 */
1504 	case BIOCPROMISC:
1505 		if (d->bd_bif == NULL) {
1506 			/*
1507 			 * No interface attached yet.
1508 			 */
1509 			error = EINVAL;
1510 			break;
1511 		}
1512 		if (d->bd_promisc == 0) {
1513 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
1514 			if (error == 0)
1515 				d->bd_promisc = 1;
1516 		}
1517 		break;
1518 
1519 	/*
1520 	 * Get current data link type.
1521 	 */
1522 	case BIOCGDLT:
1523 		BPF_LOCK();
1524 		if (d->bd_bif == NULL)
1525 			error = EINVAL;
1526 		else
1527 			*(u_int *)addr = d->bd_bif->bif_dlt;
1528 		BPF_UNLOCK();
1529 		break;
1530 
1531 	/*
1532 	 * Get a list of supported data link types.
1533 	 */
1534 #ifdef COMPAT_FREEBSD32
1535 	case BIOCGDLTLIST32:
1536 		{
1537 			struct bpf_dltlist32 *list32;
1538 			struct bpf_dltlist dltlist;
1539 
1540 			list32 = (struct bpf_dltlist32 *)addr;
1541 			dltlist.bfl_len = list32->bfl_len;
1542 			dltlist.bfl_list = PTRIN(list32->bfl_list);
1543 			BPF_LOCK();
1544 			if (d->bd_bif == NULL)
1545 				error = EINVAL;
1546 			else {
1547 				error = bpf_getdltlist(d, &dltlist);
1548 				if (error == 0)
1549 					list32->bfl_len = dltlist.bfl_len;
1550 			}
1551 			BPF_UNLOCK();
1552 			break;
1553 		}
1554 #endif
1555 
1556 	case BIOCGDLTLIST:
1557 		BPF_LOCK();
1558 		if (d->bd_bif == NULL)
1559 			error = EINVAL;
1560 		else
1561 			error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1562 		BPF_UNLOCK();
1563 		break;
1564 
1565 	/*
1566 	 * Set data link type.
1567 	 */
1568 	case BIOCSDLT:
1569 		BPF_LOCK();
1570 		if (d->bd_bif == NULL)
1571 			error = EINVAL;
1572 		else
1573 			error = bpf_setdlt(d, *(u_int *)addr);
1574 		BPF_UNLOCK();
1575 		break;
1576 
1577 	/*
1578 	 * Get interface name.
1579 	 */
1580 	case BIOCGETIF:
1581 		BPF_LOCK();
1582 		if (d->bd_bif == NULL)
1583 			error = EINVAL;
1584 		else {
1585 			struct ifnet *const ifp = d->bd_bif->bif_ifp;
1586 			struct ifreq *const ifr = (struct ifreq *)addr;
1587 
1588 			strlcpy(ifr->ifr_name, ifp->if_xname,
1589 			    sizeof(ifr->ifr_name));
1590 		}
1591 		BPF_UNLOCK();
1592 		break;
1593 
1594 	/*
1595 	 * Set interface.
1596 	 */
1597 	case BIOCSETIF:
1598 		{
1599 			int alloc_buf, size;
1600 
1601 			/*
1602 			 * Behavior here depends on the buffering model.  If
1603 			 * we're using kernel memory buffers, then we can
1604 			 * allocate them here.  If we're using zero-copy,
1605 			 * then the user process must have registered buffers
1606 			 * by the time we get here.
1607 			 */
1608 			alloc_buf = 0;
1609 			BPFD_LOCK(d);
1610 			if (d->bd_bufmode == BPF_BUFMODE_BUFFER &&
1611 			    d->bd_sbuf == NULL)
1612 				alloc_buf = 1;
1613 			BPFD_UNLOCK(d);
1614 			if (alloc_buf) {
1615 				size = d->bd_bufsize;
1616 				error = bpf_buffer_ioctl_sblen(d, &size);
1617 				if (error != 0)
1618 					break;
1619 			}
1620 			BPF_LOCK();
1621 			error = bpf_setif(d, (struct ifreq *)addr);
1622 			BPF_UNLOCK();
1623 			break;
1624 		}
1625 
1626 	/*
1627 	 * Set read timeout.
1628 	 */
1629 	case BIOCSRTIMEOUT:
1630 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1631 	case BIOCSRTIMEOUT32:
1632 #endif
1633 		{
1634 			struct timeval *tv = (struct timeval *)addr;
1635 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1636 			struct timeval32 *tv32;
1637 			struct timeval tv64;
1638 
1639 			if (cmd == BIOCSRTIMEOUT32) {
1640 				tv32 = (struct timeval32 *)addr;
1641 				tv = &tv64;
1642 				tv->tv_sec = tv32->tv_sec;
1643 				tv->tv_usec = tv32->tv_usec;
1644 			} else
1645 #endif
1646 				tv = (struct timeval *)addr;
1647 
1648 			/*
1649 			 * Subtract 1 tick from tvtohz() since this isn't
1650 			 * a one-shot timer.
1651 			 */
1652 			if ((error = itimerfix(tv)) == 0)
1653 				d->bd_rtout = tvtohz(tv) - 1;
1654 			break;
1655 		}
1656 
1657 	/*
1658 	 * Get read timeout.
1659 	 */
1660 	case BIOCGRTIMEOUT:
1661 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1662 	case BIOCGRTIMEOUT32:
1663 #endif
1664 		{
1665 			struct timeval *tv;
1666 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1667 			struct timeval32 *tv32;
1668 			struct timeval tv64;
1669 
1670 			if (cmd == BIOCGRTIMEOUT32)
1671 				tv = &tv64;
1672 			else
1673 #endif
1674 				tv = (struct timeval *)addr;
1675 
1676 			tv->tv_sec = d->bd_rtout / hz;
1677 			tv->tv_usec = (d->bd_rtout % hz) * tick;
1678 #if defined(COMPAT_FREEBSD32) && defined(__amd64__)
1679 			if (cmd == BIOCGRTIMEOUT32) {
1680 				tv32 = (struct timeval32 *)addr;
1681 				tv32->tv_sec = tv->tv_sec;
1682 				tv32->tv_usec = tv->tv_usec;
1683 			}
1684 #endif
1685 
1686 			break;
1687 		}
1688 
1689 	/*
1690 	 * Get packet stats.
1691 	 */
1692 	case BIOCGSTATS:
1693 		{
1694 			struct bpf_stat *bs = (struct bpf_stat *)addr;
1695 
1696 			/* XXXCSJP overflow */
1697 			bs->bs_recv = (u_int)counter_u64_fetch(d->bd_rcount);
1698 			bs->bs_drop = (u_int)counter_u64_fetch(d->bd_dcount);
1699 			break;
1700 		}
1701 
1702 	/*
1703 	 * Set immediate mode.
1704 	 */
1705 	case BIOCIMMEDIATE:
1706 		BPFD_LOCK(d);
1707 		d->bd_immediate = *(u_int *)addr;
1708 		BPFD_UNLOCK(d);
1709 		break;
1710 
1711 	case BIOCVERSION:
1712 		{
1713 			struct bpf_version *bv = (struct bpf_version *)addr;
1714 
1715 			bv->bv_major = BPF_MAJOR_VERSION;
1716 			bv->bv_minor = BPF_MINOR_VERSION;
1717 			break;
1718 		}
1719 
1720 	/*
1721 	 * Get "header already complete" flag
1722 	 */
1723 	case BIOCGHDRCMPLT:
1724 		BPFD_LOCK(d);
1725 		*(u_int *)addr = d->bd_hdrcmplt;
1726 		BPFD_UNLOCK(d);
1727 		break;
1728 
1729 	/*
1730 	 * Set "header already complete" flag
1731 	 */
1732 	case BIOCSHDRCMPLT:
1733 		BPFD_LOCK(d);
1734 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1735 		BPFD_UNLOCK(d);
1736 		break;
1737 
1738 	/*
1739 	 * Get packet direction flag
1740 	 */
1741 	case BIOCGDIRECTION:
1742 		BPFD_LOCK(d);
1743 		*(u_int *)addr = d->bd_direction;
1744 		BPFD_UNLOCK(d);
1745 		break;
1746 
1747 	/*
1748 	 * Set packet direction flag
1749 	 */
1750 	case BIOCSDIRECTION:
1751 		{
1752 			u_int	direction;
1753 
1754 			direction = *(u_int *)addr;
1755 			switch (direction) {
1756 			case BPF_D_IN:
1757 			case BPF_D_INOUT:
1758 			case BPF_D_OUT:
1759 				BPFD_LOCK(d);
1760 				d->bd_direction = direction;
1761 				BPFD_UNLOCK(d);
1762 				break;
1763 			default:
1764 				error = EINVAL;
1765 			}
1766 		}
1767 		break;
1768 
1769 	/*
1770 	 * Get packet timestamp format and resolution.
1771 	 */
1772 	case BIOCGTSTAMP:
1773 		BPFD_LOCK(d);
1774 		*(u_int *)addr = d->bd_tstamp;
1775 		BPFD_UNLOCK(d);
1776 		break;
1777 
1778 	/*
1779 	 * Set packet timestamp format and resolution.
1780 	 */
1781 	case BIOCSTSTAMP:
1782 		{
1783 			u_int	func;
1784 
1785 			func = *(u_int *)addr;
1786 			if (BPF_T_VALID(func))
1787 				d->bd_tstamp = func;
1788 			else
1789 				error = EINVAL;
1790 		}
1791 		break;
1792 
1793 	case BIOCFEEDBACK:
1794 		BPFD_LOCK(d);
1795 		d->bd_feedback = *(u_int *)addr;
1796 		BPFD_UNLOCK(d);
1797 		break;
1798 
1799 	case BIOCLOCK:
1800 		BPFD_LOCK(d);
1801 		d->bd_locked = 1;
1802 		BPFD_UNLOCK(d);
1803 		break;
1804 
1805 	case FIONBIO:		/* Non-blocking I/O */
1806 		break;
1807 
1808 	case FIOASYNC:		/* Send signal on receive packets */
1809 		BPFD_LOCK(d);
1810 		d->bd_async = *(int *)addr;
1811 		BPFD_UNLOCK(d);
1812 		break;
1813 
1814 	case FIOSETOWN:
1815 		/*
1816 		 * XXX: Add some sort of locking here?
1817 		 * fsetown() can sleep.
1818 		 */
1819 		error = fsetown(*(int *)addr, &d->bd_sigio);
1820 		break;
1821 
1822 	case FIOGETOWN:
1823 		BPFD_LOCK(d);
1824 		*(int *)addr = fgetown(&d->bd_sigio);
1825 		BPFD_UNLOCK(d);
1826 		break;
1827 
1828 	/* This is deprecated, FIOSETOWN should be used instead. */
1829 	case TIOCSPGRP:
1830 		error = fsetown(-(*(int *)addr), &d->bd_sigio);
1831 		break;
1832 
1833 	/* This is deprecated, FIOGETOWN should be used instead. */
1834 	case TIOCGPGRP:
1835 		*(int *)addr = -fgetown(&d->bd_sigio);
1836 		break;
1837 
1838 	case BIOCSRSIG:		/* Set receive signal */
1839 		{
1840 			u_int sig;
1841 
1842 			sig = *(u_int *)addr;
1843 
1844 			if (sig >= NSIG)
1845 				error = EINVAL;
1846 			else {
1847 				BPFD_LOCK(d);
1848 				d->bd_sig = sig;
1849 				BPFD_UNLOCK(d);
1850 			}
1851 			break;
1852 		}
1853 	case BIOCGRSIG:
1854 		BPFD_LOCK(d);
1855 		*(u_int *)addr = d->bd_sig;
1856 		BPFD_UNLOCK(d);
1857 		break;
1858 
1859 	case BIOCGETBUFMODE:
1860 		BPFD_LOCK(d);
1861 		*(u_int *)addr = d->bd_bufmode;
1862 		BPFD_UNLOCK(d);
1863 		break;
1864 
1865 	case BIOCSETBUFMODE:
1866 		/*
1867 		 * Allow the buffering mode to be changed as long as we
1868 		 * haven't yet committed to a particular mode.  Our
1869 		 * definition of commitment, for now, is whether or not a
1870 		 * buffer has been allocated or an interface attached, since
1871 		 * that's the point where things get tricky.
1872 		 */
1873 		switch (*(u_int *)addr) {
1874 		case BPF_BUFMODE_BUFFER:
1875 			break;
1876 
1877 		case BPF_BUFMODE_ZBUF:
1878 			if (bpf_zerocopy_enable)
1879 				break;
1880 			/* FALLSTHROUGH */
1881 
1882 		default:
1883 			CURVNET_RESTORE();
1884 			return (EINVAL);
1885 		}
1886 
1887 		BPFD_LOCK(d);
1888 		if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1889 		    d->bd_fbuf != NULL || d->bd_bif != NULL) {
1890 			BPFD_UNLOCK(d);
1891 			CURVNET_RESTORE();
1892 			return (EBUSY);
1893 		}
1894 		d->bd_bufmode = *(u_int *)addr;
1895 		BPFD_UNLOCK(d);
1896 		break;
1897 
1898 	case BIOCGETZMAX:
1899 		error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1900 		break;
1901 
1902 	case BIOCSETZBUF:
1903 		error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1904 		break;
1905 
1906 	case BIOCROTZBUF:
1907 		error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1908 		break;
1909 	}
1910 	CURVNET_RESTORE();
1911 	return (error);
1912 }
1913 
1914 /*
1915  * Set d's packet filter program to fp. If this file already has a filter,
1916  * free it and replace it. Returns EINVAL for bogus requests.
1917  *
1918  * Note we use global lock here to serialize bpf_setf() and bpf_setif()
1919  * calls.
1920  */
1921 static int
1922 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1923 {
1924 #ifdef COMPAT_FREEBSD32
1925 	struct bpf_program fp_swab;
1926 	struct bpf_program32 *fp32;
1927 #endif
1928 	struct bpf_program_buffer *fcode;
1929 	struct bpf_insn *filter;
1930 #ifdef BPF_JITTER
1931 	bpf_jit_filter *jfunc;
1932 #endif
1933 	size_t size;
1934 	u_int flen;
1935 	bool track_event;
1936 
1937 #ifdef COMPAT_FREEBSD32
1938 	switch (cmd) {
1939 	case BIOCSETF32:
1940 	case BIOCSETWF32:
1941 	case BIOCSETFNR32:
1942 		fp32 = (struct bpf_program32 *)fp;
1943 		fp_swab.bf_len = fp32->bf_len;
1944 		fp_swab.bf_insns =
1945 		    (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1946 		fp = &fp_swab;
1947 		switch (cmd) {
1948 		case BIOCSETF32:
1949 			cmd = BIOCSETF;
1950 			break;
1951 		case BIOCSETWF32:
1952 			cmd = BIOCSETWF;
1953 			break;
1954 		}
1955 		break;
1956 	}
1957 #endif
1958 
1959 	filter = NULL;
1960 #ifdef BPF_JITTER
1961 	jfunc = NULL;
1962 #endif
1963 	/*
1964 	 * Check new filter validness before acquiring any locks.
1965 	 * Allocate memory for new filter, if needed.
1966 	 */
1967 	flen = fp->bf_len;
1968 	if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1969 		return (EINVAL);
1970 	size = flen * sizeof(*fp->bf_insns);
1971 	if (size > 0) {
1972 		/* We're setting up new filter. Copy and check actual data. */
1973 		fcode = bpf_program_buffer_alloc(size, M_WAITOK);
1974 		filter = (struct bpf_insn *)fcode->buffer;
1975 		if (copyin(fp->bf_insns, filter, size) != 0 ||
1976 		    !bpf_validate(filter, flen)) {
1977 			free(fcode, M_BPF);
1978 			return (EINVAL);
1979 		}
1980 #ifdef BPF_JITTER
1981 		if (cmd != BIOCSETWF) {
1982 			/*
1983 			 * Filter is copied inside fcode and is
1984 			 * perfectly valid.
1985 			 */
1986 			jfunc = bpf_jitter(filter, flen);
1987 		}
1988 #endif
1989 	}
1990 
1991 	track_event = false;
1992 	fcode = NULL;
1993 
1994 	BPF_LOCK();
1995 	BPFD_LOCK(d);
1996 	/* Set up new filter. */
1997 	if (cmd == BIOCSETWF) {
1998 		if (d->bd_wfilter != NULL) {
1999 			fcode = __containerof((void *)d->bd_wfilter,
2000 			    struct bpf_program_buffer, buffer);
2001 #ifdef BPF_JITTER
2002 			fcode->func = NULL;
2003 #endif
2004 		}
2005 		d->bd_wfilter = filter;
2006 	} else {
2007 		if (d->bd_rfilter != NULL) {
2008 			fcode = __containerof((void *)d->bd_rfilter,
2009 			    struct bpf_program_buffer, buffer);
2010 #ifdef BPF_JITTER
2011 			fcode->func = d->bd_bfilter;
2012 #endif
2013 		}
2014 		d->bd_rfilter = filter;
2015 #ifdef BPF_JITTER
2016 		d->bd_bfilter = jfunc;
2017 #endif
2018 		if (cmd == BIOCSETF)
2019 			reset_d(d);
2020 
2021 		if (bpf_check_upgrade(cmd, d, filter, flen) != 0) {
2022 			/*
2023 			 * Filter can be set several times without
2024 			 * specifying interface. In this case just mark d
2025 			 * as reader.
2026 			 */
2027 			d->bd_writer = 0;
2028 			if (d->bd_bif != NULL) {
2029 				/*
2030 				 * Remove descriptor from writers-only list
2031 				 * and add it to active readers list.
2032 				 */
2033 				CK_LIST_REMOVE(d, bd_next);
2034 				CK_LIST_INSERT_HEAD(&d->bd_bif->bif_dlist,
2035 				    d, bd_next);
2036 				CTR2(KTR_NET,
2037 				    "%s: upgrade required by pid %d",
2038 				    __func__, d->bd_pid);
2039 				track_event = true;
2040 			}
2041 		}
2042 	}
2043 	BPFD_UNLOCK(d);
2044 
2045 	if (fcode != NULL)
2046 		NET_EPOCH_CALL(bpf_program_buffer_free, &fcode->epoch_ctx);
2047 
2048 	if (track_event)
2049 		EVENTHANDLER_INVOKE(bpf_track,
2050 		    d->bd_bif->bif_ifp, d->bd_bif->bif_dlt, 1);
2051 
2052 	BPF_UNLOCK();
2053 	return (0);
2054 }
2055 
2056 /*
2057  * Detach a file from its current interface (if attached at all) and attach
2058  * to the interface indicated by the name stored in ifr.
2059  * Return an errno or 0.
2060  */
2061 static int
2062 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
2063 {
2064 	struct bpf_if *bp;
2065 	struct ifnet *theywant;
2066 
2067 	BPF_LOCK_ASSERT();
2068 
2069 	theywant = ifunit(ifr->ifr_name);
2070 	if (theywant == NULL || theywant->if_bpf == NULL)
2071 		return (ENXIO);
2072 
2073 	bp = theywant->if_bpf;
2074 	/*
2075 	 * At this point, we expect the buffer is already allocated.  If not,
2076 	 * return an error.
2077 	 */
2078 	switch (d->bd_bufmode) {
2079 	case BPF_BUFMODE_BUFFER:
2080 	case BPF_BUFMODE_ZBUF:
2081 		if (d->bd_sbuf == NULL)
2082 			return (EINVAL);
2083 		break;
2084 
2085 	default:
2086 		panic("bpf_setif: bufmode %d", d->bd_bufmode);
2087 	}
2088 	if (bp != d->bd_bif)
2089 		bpf_attachd(d, bp);
2090 	else {
2091 		BPFD_LOCK(d);
2092 		reset_d(d);
2093 		BPFD_UNLOCK(d);
2094 	}
2095 	return (0);
2096 }
2097 
2098 /*
2099  * Support for select() and poll() system calls
2100  *
2101  * Return true iff the specific operation will not block indefinitely.
2102  * Otherwise, return false but make a note that a selwakeup() must be done.
2103  */
2104 static int
2105 bpfpoll(struct cdev *dev, int events, struct thread *td)
2106 {
2107 	struct bpf_d *d;
2108 	int revents;
2109 
2110 	if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
2111 		return (events &
2112 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
2113 
2114 	/*
2115 	 * Refresh PID associated with this descriptor.
2116 	 */
2117 	revents = events & (POLLOUT | POLLWRNORM);
2118 	BPFD_LOCK(d);
2119 	BPF_PID_REFRESH(d, td);
2120 	if (events & (POLLIN | POLLRDNORM)) {
2121 		if (bpf_ready(d))
2122 			revents |= events & (POLLIN | POLLRDNORM);
2123 		else {
2124 			selrecord(td, &d->bd_sel);
2125 			/* Start the read timeout if necessary. */
2126 			if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2127 				callout_reset(&d->bd_callout, d->bd_rtout,
2128 				    bpf_timed_out, d);
2129 				d->bd_state = BPF_WAITING;
2130 			}
2131 		}
2132 	}
2133 	BPFD_UNLOCK(d);
2134 	return (revents);
2135 }
2136 
2137 /*
2138  * Support for kevent() system call.  Register EVFILT_READ filters and
2139  * reject all others.
2140  */
2141 int
2142 bpfkqfilter(struct cdev *dev, struct knote *kn)
2143 {
2144 	struct bpf_d *d;
2145 
2146 	if (devfs_get_cdevpriv((void **)&d) != 0 ||
2147 	    kn->kn_filter != EVFILT_READ)
2148 		return (1);
2149 
2150 	/*
2151 	 * Refresh PID associated with this descriptor.
2152 	 */
2153 	BPFD_LOCK(d);
2154 	BPF_PID_REFRESH_CUR(d);
2155 	kn->kn_fop = &bpfread_filtops;
2156 	kn->kn_hook = d;
2157 	knlist_add(&d->bd_sel.si_note, kn, 1);
2158 	BPFD_UNLOCK(d);
2159 
2160 	return (0);
2161 }
2162 
2163 static void
2164 filt_bpfdetach(struct knote *kn)
2165 {
2166 	struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2167 
2168 	knlist_remove(&d->bd_sel.si_note, kn, 0);
2169 }
2170 
2171 static int
2172 filt_bpfread(struct knote *kn, long hint)
2173 {
2174 	struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2175 	int ready;
2176 
2177 	BPFD_LOCK_ASSERT(d);
2178 	ready = bpf_ready(d);
2179 	if (ready) {
2180 		kn->kn_data = d->bd_slen;
2181 		/*
2182 		 * Ignore the hold buffer if it is being copied to user space.
2183 		 */
2184 		if (!d->bd_hbuf_in_use && d->bd_hbuf)
2185 			kn->kn_data += d->bd_hlen;
2186 	} else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2187 		callout_reset(&d->bd_callout, d->bd_rtout,
2188 		    bpf_timed_out, d);
2189 		d->bd_state = BPF_WAITING;
2190 	}
2191 
2192 	return (ready);
2193 }
2194 
2195 #define	BPF_TSTAMP_NONE		0
2196 #define	BPF_TSTAMP_FAST		1
2197 #define	BPF_TSTAMP_NORMAL	2
2198 #define	BPF_TSTAMP_EXTERN	3
2199 
2200 static int
2201 bpf_ts_quality(int tstype)
2202 {
2203 
2204 	if (tstype == BPF_T_NONE)
2205 		return (BPF_TSTAMP_NONE);
2206 	if ((tstype & BPF_T_FAST) != 0)
2207 		return (BPF_TSTAMP_FAST);
2208 
2209 	return (BPF_TSTAMP_NORMAL);
2210 }
2211 
2212 static int
2213 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
2214 {
2215 	struct m_tag *tag;
2216 	int quality;
2217 
2218 	quality = bpf_ts_quality(tstype);
2219 	if (quality == BPF_TSTAMP_NONE)
2220 		return (quality);
2221 
2222 	if (m != NULL) {
2223 		tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2224 		if (tag != NULL) {
2225 			*bt = *(struct bintime *)(tag + 1);
2226 			return (BPF_TSTAMP_EXTERN);
2227 		}
2228 	}
2229 	if (quality == BPF_TSTAMP_NORMAL)
2230 		binuptime(bt);
2231 	else
2232 		getbinuptime(bt);
2233 
2234 	return (quality);
2235 }
2236 
2237 /*
2238  * Incoming linkage from device drivers.  Process the packet pkt, of length
2239  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
2240  * by each process' filter, and if accepted, stashed into the corresponding
2241  * buffer.
2242  */
2243 void
2244 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2245 {
2246 	struct epoch_tracker et;
2247 	struct bintime bt;
2248 	struct bpf_d *d;
2249 #ifdef BPF_JITTER
2250 	bpf_jit_filter *bf;
2251 #endif
2252 	u_int slen;
2253 	int gottime;
2254 
2255 	gottime = BPF_TSTAMP_NONE;
2256 	NET_EPOCH_ENTER(et);
2257 	CK_LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2258 		counter_u64_add(d->bd_rcount, 1);
2259 		/*
2260 		 * NB: We dont call BPF_CHECK_DIRECTION() here since there
2261 		 * is no way for the caller to indiciate to us whether this
2262 		 * packet is inbound or outbound. In the bpf_mtap() routines,
2263 		 * we use the interface pointers on the mbuf to figure it out.
2264 		 */
2265 #ifdef BPF_JITTER
2266 		bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2267 		if (bf != NULL)
2268 			slen = (*(bf->func))(pkt, pktlen, pktlen);
2269 		else
2270 #endif
2271 		slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2272 		if (slen != 0) {
2273 			/*
2274 			 * Filter matches. Let's to acquire write lock.
2275 			 */
2276 			BPFD_LOCK(d);
2277 			counter_u64_add(d->bd_fcount, 1);
2278 			if (gottime < bpf_ts_quality(d->bd_tstamp))
2279 				gottime = bpf_gettime(&bt, d->bd_tstamp,
2280 				    NULL);
2281 #ifdef MAC
2282 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2283 #endif
2284 				catchpacket(d, pkt, pktlen, slen,
2285 				    bpf_append_bytes, &bt);
2286 			BPFD_UNLOCK(d);
2287 		}
2288 	}
2289 	NET_EPOCH_EXIT(et);
2290 }
2291 
2292 #define	BPF_CHECK_DIRECTION(d, r, i)				\
2293 	    (((d)->bd_direction == BPF_D_IN && (r) != (i)) ||	\
2294 	    ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2295 
2296 /*
2297  * Incoming linkage from device drivers, when packet is in an mbuf chain.
2298  * Locking model is explained in bpf_tap().
2299  */
2300 void
2301 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2302 {
2303 	struct epoch_tracker et;
2304 	struct bintime bt;
2305 	struct bpf_d *d;
2306 #ifdef BPF_JITTER
2307 	bpf_jit_filter *bf;
2308 #endif
2309 	u_int pktlen, slen;
2310 	int gottime;
2311 
2312 	/* Skip outgoing duplicate packets. */
2313 	if ((m->m_flags & M_PROMISC) != 0 && m_rcvif(m) == NULL) {
2314 		m->m_flags &= ~M_PROMISC;
2315 		return;
2316 	}
2317 
2318 	pktlen = m_length(m, NULL);
2319 	gottime = BPF_TSTAMP_NONE;
2320 
2321 	NET_EPOCH_ENTER(et);
2322 	CK_LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2323 		if (BPF_CHECK_DIRECTION(d, m_rcvif(m), bp->bif_ifp))
2324 			continue;
2325 		counter_u64_add(d->bd_rcount, 1);
2326 #ifdef BPF_JITTER
2327 		bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2328 		/* XXX We cannot handle multiple mbufs. */
2329 		if (bf != NULL && m->m_next == NULL)
2330 			slen = (*(bf->func))(mtod(m, u_char *), pktlen,
2331 			    pktlen);
2332 		else
2333 #endif
2334 		slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2335 		if (slen != 0) {
2336 			BPFD_LOCK(d);
2337 
2338 			counter_u64_add(d->bd_fcount, 1);
2339 			if (gottime < bpf_ts_quality(d->bd_tstamp))
2340 				gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2341 #ifdef MAC
2342 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2343 #endif
2344 				catchpacket(d, (u_char *)m, pktlen, slen,
2345 				    bpf_append_mbuf, &bt);
2346 			BPFD_UNLOCK(d);
2347 		}
2348 	}
2349 	NET_EPOCH_EXIT(et);
2350 }
2351 
2352 /*
2353  * Incoming linkage from device drivers, when packet is in
2354  * an mbuf chain and to be prepended by a contiguous header.
2355  */
2356 void
2357 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2358 {
2359 	struct epoch_tracker et;
2360 	struct bintime bt;
2361 	struct mbuf mb;
2362 	struct bpf_d *d;
2363 	u_int pktlen, slen;
2364 	int gottime;
2365 
2366 	/* Skip outgoing duplicate packets. */
2367 	if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2368 		m->m_flags &= ~M_PROMISC;
2369 		return;
2370 	}
2371 
2372 	pktlen = m_length(m, NULL);
2373 	/*
2374 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
2375 	 * Note that we cut corners here; we only setup what's
2376 	 * absolutely needed--this mbuf should never go anywhere else.
2377 	 */
2378 	mb.m_flags = 0;
2379 	mb.m_next = m;
2380 	mb.m_data = data;
2381 	mb.m_len = dlen;
2382 	pktlen += dlen;
2383 
2384 	gottime = BPF_TSTAMP_NONE;
2385 
2386 	NET_EPOCH_ENTER(et);
2387 	CK_LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2388 		if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2389 			continue;
2390 		counter_u64_add(d->bd_rcount, 1);
2391 		slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2392 		if (slen != 0) {
2393 			BPFD_LOCK(d);
2394 
2395 			counter_u64_add(d->bd_fcount, 1);
2396 			if (gottime < bpf_ts_quality(d->bd_tstamp))
2397 				gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2398 #ifdef MAC
2399 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2400 #endif
2401 				catchpacket(d, (u_char *)&mb, pktlen, slen,
2402 				    bpf_append_mbuf, &bt);
2403 			BPFD_UNLOCK(d);
2404 		}
2405 	}
2406 	NET_EPOCH_EXIT(et);
2407 }
2408 
2409 #undef	BPF_CHECK_DIRECTION
2410 #undef	BPF_TSTAMP_NONE
2411 #undef	BPF_TSTAMP_FAST
2412 #undef	BPF_TSTAMP_NORMAL
2413 #undef	BPF_TSTAMP_EXTERN
2414 
2415 static int
2416 bpf_hdrlen(struct bpf_d *d)
2417 {
2418 	int hdrlen;
2419 
2420 	hdrlen = d->bd_bif->bif_hdrlen;
2421 #ifndef BURN_BRIDGES
2422 	if (d->bd_tstamp == BPF_T_NONE ||
2423 	    BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2424 #ifdef COMPAT_FREEBSD32
2425 		if (d->bd_compat32)
2426 			hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2427 		else
2428 #endif
2429 			hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2430 	else
2431 #endif
2432 		hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2433 #ifdef COMPAT_FREEBSD32
2434 	if (d->bd_compat32)
2435 		hdrlen = BPF_WORDALIGN32(hdrlen);
2436 	else
2437 #endif
2438 		hdrlen = BPF_WORDALIGN(hdrlen);
2439 
2440 	return (hdrlen - d->bd_bif->bif_hdrlen);
2441 }
2442 
2443 static void
2444 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2445 {
2446 	struct bintime bt2, boottimebin;
2447 	struct timeval tsm;
2448 	struct timespec tsn;
2449 
2450 	if ((tstype & BPF_T_MONOTONIC) == 0) {
2451 		bt2 = *bt;
2452 		getboottimebin(&boottimebin);
2453 		bintime_add(&bt2, &boottimebin);
2454 		bt = &bt2;
2455 	}
2456 	switch (BPF_T_FORMAT(tstype)) {
2457 	case BPF_T_MICROTIME:
2458 		bintime2timeval(bt, &tsm);
2459 		ts->bt_sec = tsm.tv_sec;
2460 		ts->bt_frac = tsm.tv_usec;
2461 		break;
2462 	case BPF_T_NANOTIME:
2463 		bintime2timespec(bt, &tsn);
2464 		ts->bt_sec = tsn.tv_sec;
2465 		ts->bt_frac = tsn.tv_nsec;
2466 		break;
2467 	case BPF_T_BINTIME:
2468 		ts->bt_sec = bt->sec;
2469 		ts->bt_frac = bt->frac;
2470 		break;
2471 	}
2472 }
2473 
2474 /*
2475  * Move the packet data from interface memory (pkt) into the
2476  * store buffer.  "cpfn" is the routine called to do the actual data
2477  * transfer.  bcopy is passed in to copy contiguous chunks, while
2478  * bpf_append_mbuf is passed in to copy mbuf chains.  In the latter case,
2479  * pkt is really an mbuf.
2480  */
2481 static void
2482 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2483     void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2484     struct bintime *bt)
2485 {
2486 	struct bpf_xhdr hdr;
2487 #ifndef BURN_BRIDGES
2488 	struct bpf_hdr hdr_old;
2489 #ifdef COMPAT_FREEBSD32
2490 	struct bpf_hdr32 hdr32_old;
2491 #endif
2492 #endif
2493 	int caplen, curlen, hdrlen, totlen;
2494 	int do_wakeup = 0;
2495 	int do_timestamp;
2496 	int tstype;
2497 
2498 	BPFD_LOCK_ASSERT(d);
2499 	if (d->bd_bif == NULL) {
2500 		/* Descriptor was detached in concurrent thread */
2501 		counter_u64_add(d->bd_dcount, 1);
2502 		return;
2503 	}
2504 
2505 	/*
2506 	 * Detect whether user space has released a buffer back to us, and if
2507 	 * so, move it from being a hold buffer to a free buffer.  This may
2508 	 * not be the best place to do it (for example, we might only want to
2509 	 * run this check if we need the space), but for now it's a reliable
2510 	 * spot to do it.
2511 	 */
2512 	if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2513 		d->bd_fbuf = d->bd_hbuf;
2514 		d->bd_hbuf = NULL;
2515 		d->bd_hlen = 0;
2516 		bpf_buf_reclaimed(d);
2517 	}
2518 
2519 	/*
2520 	 * Figure out how many bytes to move.  If the packet is
2521 	 * greater or equal to the snapshot length, transfer that
2522 	 * much.  Otherwise, transfer the whole packet (unless
2523 	 * we hit the buffer size limit).
2524 	 */
2525 	hdrlen = bpf_hdrlen(d);
2526 	totlen = hdrlen + min(snaplen, pktlen);
2527 	if (totlen > d->bd_bufsize)
2528 		totlen = d->bd_bufsize;
2529 
2530 	/*
2531 	 * Round up the end of the previous packet to the next longword.
2532 	 *
2533 	 * Drop the packet if there's no room and no hope of room
2534 	 * If the packet would overflow the storage buffer or the storage
2535 	 * buffer is considered immutable by the buffer model, try to rotate
2536 	 * the buffer and wakeup pending processes.
2537 	 */
2538 #ifdef COMPAT_FREEBSD32
2539 	if (d->bd_compat32)
2540 		curlen = BPF_WORDALIGN32(d->bd_slen);
2541 	else
2542 #endif
2543 		curlen = BPF_WORDALIGN(d->bd_slen);
2544 	if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2545 		if (d->bd_fbuf == NULL) {
2546 			/*
2547 			 * There's no room in the store buffer, and no
2548 			 * prospect of room, so drop the packet.  Notify the
2549 			 * buffer model.
2550 			 */
2551 			bpf_buffull(d);
2552 			counter_u64_add(d->bd_dcount, 1);
2553 			return;
2554 		}
2555 		KASSERT(!d->bd_hbuf_in_use, ("hold buffer is in use"));
2556 		ROTATE_BUFFERS(d);
2557 		do_wakeup = 1;
2558 		curlen = 0;
2559 	} else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2560 		/*
2561 		 * Immediate mode is set, or the read timeout has already
2562 		 * expired during a select call.  A packet arrived, so the
2563 		 * reader should be woken up.
2564 		 */
2565 		do_wakeup = 1;
2566 	caplen = totlen - hdrlen;
2567 	tstype = d->bd_tstamp;
2568 	do_timestamp = tstype != BPF_T_NONE;
2569 #ifndef BURN_BRIDGES
2570 	if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2571 		struct bpf_ts ts;
2572 		if (do_timestamp)
2573 			bpf_bintime2ts(bt, &ts, tstype);
2574 #ifdef COMPAT_FREEBSD32
2575 		if (d->bd_compat32) {
2576 			bzero(&hdr32_old, sizeof(hdr32_old));
2577 			if (do_timestamp) {
2578 				hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2579 				hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2580 			}
2581 			hdr32_old.bh_datalen = pktlen;
2582 			hdr32_old.bh_hdrlen = hdrlen;
2583 			hdr32_old.bh_caplen = caplen;
2584 			bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2585 			    sizeof(hdr32_old));
2586 			goto copy;
2587 		}
2588 #endif
2589 		bzero(&hdr_old, sizeof(hdr_old));
2590 		if (do_timestamp) {
2591 			hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2592 			hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2593 		}
2594 		hdr_old.bh_datalen = pktlen;
2595 		hdr_old.bh_hdrlen = hdrlen;
2596 		hdr_old.bh_caplen = caplen;
2597 		bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2598 		    sizeof(hdr_old));
2599 		goto copy;
2600 	}
2601 #endif
2602 
2603 	/*
2604 	 * Append the bpf header.  Note we append the actual header size, but
2605 	 * move forward the length of the header plus padding.
2606 	 */
2607 	bzero(&hdr, sizeof(hdr));
2608 	if (do_timestamp)
2609 		bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2610 	hdr.bh_datalen = pktlen;
2611 	hdr.bh_hdrlen = hdrlen;
2612 	hdr.bh_caplen = caplen;
2613 	bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2614 
2615 	/*
2616 	 * Copy the packet data into the store buffer and update its length.
2617 	 */
2618 #ifndef BURN_BRIDGES
2619 copy:
2620 #endif
2621 	(*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2622 	d->bd_slen = curlen + totlen;
2623 
2624 	if (do_wakeup)
2625 		bpf_wakeup(d);
2626 }
2627 
2628 /*
2629  * Free buffers currently in use by a descriptor.
2630  * Called on close.
2631  */
2632 static void
2633 bpfd_free(epoch_context_t ctx)
2634 {
2635 	struct bpf_d *d;
2636 	struct bpf_program_buffer *p;
2637 
2638 	/*
2639 	 * We don't need to lock out interrupts since this descriptor has
2640 	 * been detached from its interface and it yet hasn't been marked
2641 	 * free.
2642 	 */
2643 	d = __containerof(ctx, struct bpf_d, epoch_ctx);
2644 	bpf_free(d);
2645 	if (d->bd_rfilter != NULL) {
2646 		p = __containerof((void *)d->bd_rfilter,
2647 		    struct bpf_program_buffer, buffer);
2648 #ifdef BPF_JITTER
2649 		p->func = d->bd_bfilter;
2650 #endif
2651 		bpf_program_buffer_free(&p->epoch_ctx);
2652 	}
2653 	if (d->bd_wfilter != NULL) {
2654 		p = __containerof((void *)d->bd_wfilter,
2655 		    struct bpf_program_buffer, buffer);
2656 #ifdef BPF_JITTER
2657 		p->func = NULL;
2658 #endif
2659 		bpf_program_buffer_free(&p->epoch_ctx);
2660 	}
2661 
2662 	mtx_destroy(&d->bd_lock);
2663 	counter_u64_free(d->bd_rcount);
2664 	counter_u64_free(d->bd_dcount);
2665 	counter_u64_free(d->bd_fcount);
2666 	counter_u64_free(d->bd_wcount);
2667 	counter_u64_free(d->bd_wfcount);
2668 	counter_u64_free(d->bd_wdcount);
2669 	counter_u64_free(d->bd_zcopy);
2670 	free(d, M_BPF);
2671 }
2672 
2673 /*
2674  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
2675  * fixed size of the link header (variable length headers not yet supported).
2676  */
2677 void
2678 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2679 {
2680 
2681 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2682 }
2683 
2684 /*
2685  * Attach an interface to bpf.  ifp is a pointer to the structure
2686  * defining the interface to be attached, dlt is the link layer type,
2687  * and hdrlen is the fixed size of the link header (variable length
2688  * headers are not yet supporrted).
2689  */
2690 void
2691 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen,
2692     struct bpf_if **driverp)
2693 {
2694 	struct bpf_if *bp;
2695 
2696 	KASSERT(*driverp == NULL,
2697 	    ("bpfattach2: driverp already initialized"));
2698 
2699 	bp = malloc(sizeof(*bp), M_BPF, M_WAITOK | M_ZERO);
2700 
2701 	CK_LIST_INIT(&bp->bif_dlist);
2702 	CK_LIST_INIT(&bp->bif_wlist);
2703 	bp->bif_ifp = ifp;
2704 	bp->bif_dlt = dlt;
2705 	bp->bif_hdrlen = hdrlen;
2706 	bp->bif_bpf = driverp;
2707 	bp->bif_refcnt = 1;
2708 	*driverp = bp;
2709 	/*
2710 	 * Reference ifnet pointer, so it won't freed until
2711 	 * we release it.
2712 	 */
2713 	if_ref(ifp);
2714 	BPF_LOCK();
2715 	CK_LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2716 	BPF_UNLOCK();
2717 
2718 	if (bootverbose && IS_DEFAULT_VNET(curvnet))
2719 		if_printf(ifp, "bpf attached\n");
2720 }
2721 
2722 #ifdef VIMAGE
2723 /*
2724  * When moving interfaces between vnet instances we need a way to
2725  * query the dlt and hdrlen before detach so we can re-attch the if_bpf
2726  * after the vmove.  We unfortunately have no device driver infrastructure
2727  * to query the interface for these values after creation/attach, thus
2728  * add this as a workaround.
2729  */
2730 int
2731 bpf_get_bp_params(struct bpf_if *bp, u_int *bif_dlt, u_int *bif_hdrlen)
2732 {
2733 
2734 	if (bp == NULL)
2735 		return (ENXIO);
2736 	if (bif_dlt == NULL && bif_hdrlen == NULL)
2737 		return (0);
2738 
2739 	if (bif_dlt != NULL)
2740 		*bif_dlt = bp->bif_dlt;
2741 	if (bif_hdrlen != NULL)
2742 		*bif_hdrlen = bp->bif_hdrlen;
2743 
2744 	return (0);
2745 }
2746 #endif
2747 
2748 /*
2749  * Detach bpf from an interface. This involves detaching each descriptor
2750  * associated with the interface. Notify each descriptor as it's detached
2751  * so that any sleepers wake up and get ENXIO.
2752  */
2753 void
2754 bpfdetach(struct ifnet *ifp)
2755 {
2756 	struct bpf_if *bp, *bp_temp;
2757 	struct bpf_d *d;
2758 
2759 	BPF_LOCK();
2760 	/* Find all bpf_if struct's which reference ifp and detach them. */
2761 	CK_LIST_FOREACH_SAFE(bp, &bpf_iflist, bif_next, bp_temp) {
2762 		if (ifp != bp->bif_ifp)
2763 			continue;
2764 
2765 		CK_LIST_REMOVE(bp, bif_next);
2766 		*bp->bif_bpf = (struct bpf_if *)&dead_bpf_if;
2767 
2768 		CTR4(KTR_NET,
2769 		    "%s: sheduling free for encap %d (%p) for if %p",
2770 		    __func__, bp->bif_dlt, bp, ifp);
2771 
2772 		/* Detach common descriptors */
2773 		while ((d = CK_LIST_FIRST(&bp->bif_dlist)) != NULL) {
2774 			bpf_detachd_locked(d, true);
2775 		}
2776 
2777 		/* Detach writer-only descriptors */
2778 		while ((d = CK_LIST_FIRST(&bp->bif_wlist)) != NULL) {
2779 			bpf_detachd_locked(d, true);
2780 		}
2781 		bpfif_rele(bp);
2782 	}
2783 	BPF_UNLOCK();
2784 }
2785 
2786 /*
2787  * Get a list of available data link type of the interface.
2788  */
2789 static int
2790 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2791 {
2792 	struct ifnet *ifp;
2793 	struct bpf_if *bp;
2794 	u_int *lst;
2795 	int error, n, n1;
2796 
2797 	BPF_LOCK_ASSERT();
2798 
2799 	ifp = d->bd_bif->bif_ifp;
2800 	n1 = 0;
2801 	CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2802 		if (bp->bif_ifp == ifp)
2803 			n1++;
2804 	}
2805 	if (bfl->bfl_list == NULL) {
2806 		bfl->bfl_len = n1;
2807 		return (0);
2808 	}
2809 	if (n1 > bfl->bfl_len)
2810 		return (ENOMEM);
2811 
2812 	lst = malloc(n1 * sizeof(u_int), M_TEMP, M_WAITOK);
2813 	n = 0;
2814 	CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2815 		if (bp->bif_ifp != ifp)
2816 			continue;
2817 		lst[n++] = bp->bif_dlt;
2818 	}
2819 	error = copyout(lst, bfl->bfl_list, sizeof(u_int) * n);
2820 	free(lst, M_TEMP);
2821 	bfl->bfl_len = n;
2822 	return (error);
2823 }
2824 
2825 /*
2826  * Set the data link type of a BPF instance.
2827  */
2828 static int
2829 bpf_setdlt(struct bpf_d *d, u_int dlt)
2830 {
2831 	int error, opromisc;
2832 	struct ifnet *ifp;
2833 	struct bpf_if *bp;
2834 
2835 	BPF_LOCK_ASSERT();
2836 	MPASS(d->bd_bif != NULL);
2837 
2838 	/*
2839 	 * It is safe to check bd_bif without BPFD_LOCK, it can not be
2840 	 * changed while we hold global lock.
2841 	 */
2842 	if (d->bd_bif->bif_dlt == dlt)
2843 		return (0);
2844 
2845 	ifp = d->bd_bif->bif_ifp;
2846 	CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2847 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2848 			break;
2849 	}
2850 	if (bp == NULL)
2851 		return (EINVAL);
2852 
2853 	opromisc = d->bd_promisc;
2854 	bpf_attachd(d, bp);
2855 	if (opromisc) {
2856 		error = ifpromisc(bp->bif_ifp, 1);
2857 		if (error)
2858 			if_printf(bp->bif_ifp, "%s: ifpromisc failed (%d)\n",
2859 			    __func__, error);
2860 		else
2861 			d->bd_promisc = 1;
2862 	}
2863 	return (0);
2864 }
2865 
2866 static void
2867 bpf_drvinit(void *unused)
2868 {
2869 	struct cdev *dev;
2870 
2871 	sx_init(&bpf_sx, "bpf global lock");
2872 	CK_LIST_INIT(&bpf_iflist);
2873 
2874 	dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2875 	/* For compatibility */
2876 	make_dev_alias(dev, "bpf0");
2877 }
2878 
2879 /*
2880  * Zero out the various packet counters associated with all of the bpf
2881  * descriptors.  At some point, we will probably want to get a bit more
2882  * granular and allow the user to specify descriptors to be zeroed.
2883  */
2884 static void
2885 bpf_zero_counters(void)
2886 {
2887 	struct bpf_if *bp;
2888 	struct bpf_d *bd;
2889 
2890 	BPF_LOCK();
2891 	/*
2892 	 * We are protected by global lock here, interfaces and
2893 	 * descriptors can not be deleted while we hold it.
2894 	 */
2895 	CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2896 		CK_LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2897 			counter_u64_zero(bd->bd_rcount);
2898 			counter_u64_zero(bd->bd_dcount);
2899 			counter_u64_zero(bd->bd_fcount);
2900 			counter_u64_zero(bd->bd_wcount);
2901 			counter_u64_zero(bd->bd_wfcount);
2902 			counter_u64_zero(bd->bd_zcopy);
2903 		}
2904 	}
2905 	BPF_UNLOCK();
2906 }
2907 
2908 /*
2909  * Fill filter statistics
2910  */
2911 static void
2912 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2913 {
2914 
2915 	BPF_LOCK_ASSERT();
2916 	bzero(d, sizeof(*d));
2917 	d->bd_structsize = sizeof(*d);
2918 	d->bd_immediate = bd->bd_immediate;
2919 	d->bd_promisc = bd->bd_promisc;
2920 	d->bd_hdrcmplt = bd->bd_hdrcmplt;
2921 	d->bd_direction = bd->bd_direction;
2922 	d->bd_feedback = bd->bd_feedback;
2923 	d->bd_async = bd->bd_async;
2924 	d->bd_rcount = counter_u64_fetch(bd->bd_rcount);
2925 	d->bd_dcount = counter_u64_fetch(bd->bd_dcount);
2926 	d->bd_fcount = counter_u64_fetch(bd->bd_fcount);
2927 	d->bd_sig = bd->bd_sig;
2928 	d->bd_slen = bd->bd_slen;
2929 	d->bd_hlen = bd->bd_hlen;
2930 	d->bd_bufsize = bd->bd_bufsize;
2931 	d->bd_pid = bd->bd_pid;
2932 	strlcpy(d->bd_ifname,
2933 	    bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2934 	d->bd_locked = bd->bd_locked;
2935 	d->bd_wcount = counter_u64_fetch(bd->bd_wcount);
2936 	d->bd_wdcount = counter_u64_fetch(bd->bd_wdcount);
2937 	d->bd_wfcount = counter_u64_fetch(bd->bd_wfcount);
2938 	d->bd_zcopy = counter_u64_fetch(bd->bd_zcopy);
2939 	d->bd_bufmode = bd->bd_bufmode;
2940 }
2941 
2942 /*
2943  * Handle `netstat -B' stats request
2944  */
2945 static int
2946 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2947 {
2948 	static const struct xbpf_d zerostats;
2949 	struct xbpf_d *xbdbuf, *xbd, tempstats;
2950 	int index, error;
2951 	struct bpf_if *bp;
2952 	struct bpf_d *bd;
2953 
2954 	/*
2955 	 * XXX This is not technically correct. It is possible for non
2956 	 * privileged users to open bpf devices. It would make sense
2957 	 * if the users who opened the devices were able to retrieve
2958 	 * the statistics for them, too.
2959 	 */
2960 	error = priv_check(req->td, PRIV_NET_BPF);
2961 	if (error)
2962 		return (error);
2963 	/*
2964 	 * Check to see if the user is requesting that the counters be
2965 	 * zeroed out.  Explicitly check that the supplied data is zeroed,
2966 	 * as we aren't allowing the user to set the counters currently.
2967 	 */
2968 	if (req->newptr != NULL) {
2969 		if (req->newlen != sizeof(tempstats))
2970 			return (EINVAL);
2971 		memset(&tempstats, 0, sizeof(tempstats));
2972 		error = SYSCTL_IN(req, &tempstats, sizeof(tempstats));
2973 		if (error)
2974 			return (error);
2975 		if (bcmp(&tempstats, &zerostats, sizeof(tempstats)) != 0)
2976 			return (EINVAL);
2977 		bpf_zero_counters();
2978 		return (0);
2979 	}
2980 	if (req->oldptr == NULL)
2981 		return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
2982 	if (bpf_bpfd_cnt == 0)
2983 		return (SYSCTL_OUT(req, 0, 0));
2984 	xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
2985 	BPF_LOCK();
2986 	if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
2987 		BPF_UNLOCK();
2988 		free(xbdbuf, M_BPF);
2989 		return (ENOMEM);
2990 	}
2991 	index = 0;
2992 	CK_LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2993 		/* Send writers-only first */
2994 		CK_LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
2995 			xbd = &xbdbuf[index++];
2996 			bpfstats_fill_xbpf(xbd, bd);
2997 		}
2998 		CK_LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2999 			xbd = &xbdbuf[index++];
3000 			bpfstats_fill_xbpf(xbd, bd);
3001 		}
3002 	}
3003 	BPF_UNLOCK();
3004 	error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
3005 	free(xbdbuf, M_BPF);
3006 	return (error);
3007 }
3008 
3009 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
3010 
3011 #else /* !DEV_BPF && !NETGRAPH_BPF */
3012 
3013 /*
3014  * NOP stubs to allow bpf-using drivers to load and function.
3015  *
3016  * A 'better' implementation would allow the core bpf functionality
3017  * to be loaded at runtime.
3018  */
3019 
3020 void
3021 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
3022 {
3023 }
3024 
3025 void
3026 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
3027 {
3028 }
3029 
3030 void
3031 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
3032 {
3033 }
3034 
3035 void
3036 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
3037 {
3038 
3039 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
3040 }
3041 
3042 void
3043 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
3044 {
3045 
3046 	*driverp = (struct bpf_if *)&dead_bpf_if;
3047 }
3048 
3049 void
3050 bpfdetach(struct ifnet *ifp)
3051 {
3052 }
3053 
3054 u_int
3055 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
3056 {
3057 	return -1;	/* "no filter" behaviour */
3058 }
3059 
3060 int
3061 bpf_validate(const struct bpf_insn *f, int len)
3062 {
3063 	return 0;		/* false */
3064 }
3065 
3066 #endif /* !DEV_BPF && !NETGRAPH_BPF */
3067 
3068 #ifdef DDB
3069 static void
3070 bpf_show_bpf_if(struct bpf_if *bpf_if)
3071 {
3072 
3073 	if (bpf_if == NULL)
3074 		return;
3075 	db_printf("%p:\n", bpf_if);
3076 #define	BPF_DB_PRINTF(f, e)	db_printf("   %s = " f "\n", #e, bpf_if->e);
3077 	/* bif_ext.bif_next */
3078 	/* bif_ext.bif_dlist */
3079 	BPF_DB_PRINTF("%#x", bif_dlt);
3080 	BPF_DB_PRINTF("%u", bif_hdrlen);
3081 	/* bif_wlist */
3082 	BPF_DB_PRINTF("%p", bif_ifp);
3083 	BPF_DB_PRINTF("%p", bif_bpf);
3084 	BPF_DB_PRINTF("%u", bif_refcnt);
3085 }
3086 
3087 DB_SHOW_COMMAND(bpf_if, db_show_bpf_if)
3088 {
3089 
3090 	if (!have_addr) {
3091 		db_printf("usage: show bpf_if <struct bpf_if *>\n");
3092 		return;
3093 	}
3094 
3095 	bpf_show_bpf_if((struct bpf_if *)addr);
3096 }
3097 #endif
3098