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