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