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