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