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