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