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