xref: /freebsd/sys/net/bpf.c (revision 3cbdda60ff509264469d6894d4e838b0d2ccea5c)
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 	if (len < hlen || len - hlen > ifp->if_mtu)
526 		return (EMSGSIZE);
527 
528 	m = m_get2(M_WAITOK, MT_DATA, M_PKTHDR, len);
529 	if (m == NULL)
530 		return (EIO);
531 	m->m_pkthdr.len = m->m_len = len;
532 	*mp = m;
533 
534 	error = uiomove(mtod(m, u_char *), len, uio);
535 	if (error)
536 		goto bad;
537 
538 	slen = bpf_filter(wfilter, mtod(m, u_char *), len, len);
539 	if (slen == 0) {
540 		error = EPERM;
541 		goto bad;
542 	}
543 
544 	/* Check for multicast destination */
545 	switch (linktype) {
546 	case DLT_EN10MB:
547 		eh = mtod(m, struct ether_header *);
548 		if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
549 			if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
550 			    ETHER_ADDR_LEN) == 0)
551 				m->m_flags |= M_BCAST;
552 			else
553 				m->m_flags |= M_MCAST;
554 		}
555 		break;
556 	}
557 
558 	/*
559 	 * Make room for link header, and copy it to sockaddr
560 	 */
561 	if (hlen != 0) {
562 		if (sockp->sa_family == AF_IEEE80211) {
563 			/*
564 			 * Collect true length from the parameter header
565 			 * NB: sockp is known to be zero'd so if we do a
566 			 *     short copy unspecified parameters will be
567 			 *     zero.
568 			 * NB: packet may not be aligned after stripping
569 			 *     bpf params
570 			 * XXX check ibp_vers
571 			 */
572 			p = mtod(m, const struct ieee80211_bpf_params *);
573 			hlen = p->ibp_len;
574 			if (hlen > sizeof(sockp->sa_data)) {
575 				error = EINVAL;
576 				goto bad;
577 			}
578 		}
579 		bcopy(m->m_data, sockp->sa_data, hlen);
580 	}
581 	*hdrlen = hlen;
582 
583 	return (0);
584 bad:
585 	m_freem(m);
586 	return (error);
587 }
588 
589 /*
590  * Attach file to the bpf interface, i.e. make d listen on bp.
591  */
592 static void
593 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
594 {
595 	int op_w;
596 
597 	BPF_LOCK_ASSERT();
598 
599 	/*
600 	 * Save sysctl value to protect from sysctl change
601 	 * between reads
602 	 */
603 	op_w = V_bpf_optimize_writers;
604 
605 	if (d->bd_bif != NULL)
606 		bpf_detachd_locked(d);
607 	/*
608 	 * Point d at bp, and add d to the interface's list.
609 	 * Since there are many applicaiotns using BPF for
610 	 * sending raw packets only (dhcpd, cdpd are good examples)
611 	 * we can delay adding d to the list of active listeners until
612 	 * some filter is configured.
613 	 */
614 
615 	BPFIF_WLOCK(bp);
616 	BPFD_LOCK(d);
617 
618 	d->bd_bif = bp;
619 
620 	if (op_w != 0) {
621 		/* Add to writers-only list */
622 		LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
623 		/*
624 		 * We decrement bd_writer on every filter set operation.
625 		 * First BIOCSETF is done by pcap_open_live() to set up
626 		 * snap length. After that appliation usually sets its own filter
627 		 */
628 		d->bd_writer = 2;
629 	} else
630 		LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
631 
632 	BPFD_UNLOCK(d);
633 	BPFIF_WUNLOCK(bp);
634 
635 	bpf_bpfd_cnt++;
636 
637 	CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
638 	    __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
639 
640 	if (op_w == 0)
641 		EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
642 }
643 
644 /*
645  * Add d to the list of active bp filters.
646  * Reuqires bpf_attachd() to be called before
647  */
648 static void
649 bpf_upgraded(struct bpf_d *d)
650 {
651 	struct bpf_if *bp;
652 
653 	BPF_LOCK_ASSERT();
654 
655 	bp = d->bd_bif;
656 
657 	/*
658 	 * Filter can be set several times without specifying interface.
659 	 * Mark d as reader and exit.
660 	 */
661 	if (bp == NULL) {
662 		BPFD_LOCK(d);
663 		d->bd_writer = 0;
664 		BPFD_UNLOCK(d);
665 		return;
666 	}
667 
668 	BPFIF_WLOCK(bp);
669 	BPFD_LOCK(d);
670 
671 	/* Remove from writers-only list */
672 	LIST_REMOVE(d, bd_next);
673 	LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
674 	/* Mark d as reader */
675 	d->bd_writer = 0;
676 
677 	BPFD_UNLOCK(d);
678 	BPFIF_WUNLOCK(bp);
679 
680 	CTR2(KTR_NET, "%s: upgrade required by pid %d", __func__, d->bd_pid);
681 
682 	EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
683 }
684 
685 /*
686  * Detach a file from its interface.
687  */
688 static void
689 bpf_detachd(struct bpf_d *d)
690 {
691 	BPF_LOCK();
692 	bpf_detachd_locked(d);
693 	BPF_UNLOCK();
694 }
695 
696 static void
697 bpf_detachd_locked(struct bpf_d *d)
698 {
699 	int error;
700 	struct bpf_if *bp;
701 	struct ifnet *ifp;
702 
703 	CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
704 
705 	BPF_LOCK_ASSERT();
706 
707 	/* Check if descriptor is attached */
708 	if ((bp = d->bd_bif) == NULL)
709 		return;
710 
711 	BPFIF_WLOCK(bp);
712 	BPFD_LOCK(d);
713 
714 	/* Save bd_writer value */
715 	error = d->bd_writer;
716 
717 	/*
718 	 * Remove d from the interface's descriptor list.
719 	 */
720 	LIST_REMOVE(d, bd_next);
721 
722 	ifp = bp->bif_ifp;
723 	d->bd_bif = NULL;
724 	BPFD_UNLOCK(d);
725 	BPFIF_WUNLOCK(bp);
726 
727 	bpf_bpfd_cnt--;
728 
729 	/* Call event handler iff d is attached */
730 	if (error == 0)
731 		EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
732 
733 	/*
734 	 * Check if this descriptor had requested promiscuous mode.
735 	 * If so, turn it off.
736 	 */
737 	if (d->bd_promisc) {
738 		d->bd_promisc = 0;
739 		CURVNET_SET(ifp->if_vnet);
740 		error = ifpromisc(ifp, 0);
741 		CURVNET_RESTORE();
742 		if (error != 0 && error != ENXIO) {
743 			/*
744 			 * ENXIO can happen if a pccard is unplugged
745 			 * Something is really wrong if we were able to put
746 			 * the driver into promiscuous mode, but can't
747 			 * take it out.
748 			 */
749 			if_printf(bp->bif_ifp,
750 				"bpf_detach: ifpromisc failed (%d)\n", error);
751 		}
752 	}
753 }
754 
755 /*
756  * Close the descriptor by detaching it from its interface,
757  * deallocating its buffers, and marking it free.
758  */
759 static void
760 bpf_dtor(void *data)
761 {
762 	struct bpf_d *d = data;
763 
764 	BPFD_LOCK(d);
765 	if (d->bd_state == BPF_WAITING)
766 		callout_stop(&d->bd_callout);
767 	d->bd_state = BPF_IDLE;
768 	BPFD_UNLOCK(d);
769 	funsetown(&d->bd_sigio);
770 	bpf_detachd(d);
771 #ifdef MAC
772 	mac_bpfdesc_destroy(d);
773 #endif /* MAC */
774 	seldrain(&d->bd_sel);
775 	knlist_destroy(&d->bd_sel.si_note);
776 	callout_drain(&d->bd_callout);
777 	bpf_freed(d);
778 	free(d, M_BPF);
779 }
780 
781 /*
782  * Open ethernet device.  Returns ENXIO for illegal minor device number,
783  * EBUSY if file is open by another process.
784  */
785 /* ARGSUSED */
786 static	int
787 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
788 {
789 	struct bpf_d *d;
790 	int error, size;
791 
792 	d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
793 	error = devfs_set_cdevpriv(d, bpf_dtor);
794 	if (error != 0) {
795 		free(d, M_BPF);
796 		return (error);
797 	}
798 
799 	/*
800 	 * For historical reasons, perform a one-time initialization call to
801 	 * the buffer routines, even though we're not yet committed to a
802 	 * particular buffer method.
803 	 */
804 	bpf_buffer_init(d);
805 	d->bd_hbuf_in_use = 0;
806 	d->bd_bufmode = BPF_BUFMODE_BUFFER;
807 	d->bd_sig = SIGIO;
808 	d->bd_direction = BPF_D_INOUT;
809 	BPF_PID_REFRESH(d, td);
810 #ifdef MAC
811 	mac_bpfdesc_init(d);
812 	mac_bpfdesc_create(td->td_ucred, d);
813 #endif
814 	mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
815 	callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
816 	knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
817 
818 	/* Allocate default buffers */
819 	size = d->bd_bufsize;
820 	bpf_buffer_ioctl_sblen(d, &size);
821 
822 	return (0);
823 }
824 
825 /*
826  *  bpfread - read next chunk of packets from buffers
827  */
828 static	int
829 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
830 {
831 	struct bpf_d *d;
832 	int error;
833 	int non_block;
834 	int timed_out;
835 
836 	error = devfs_get_cdevpriv((void **)&d);
837 	if (error != 0)
838 		return (error);
839 
840 	/*
841 	 * Restrict application to use a buffer the same size as
842 	 * as kernel buffers.
843 	 */
844 	if (uio->uio_resid != d->bd_bufsize)
845 		return (EINVAL);
846 
847 	non_block = ((ioflag & O_NONBLOCK) != 0);
848 
849 	BPFD_LOCK(d);
850 	BPF_PID_REFRESH_CUR(d);
851 	if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
852 		BPFD_UNLOCK(d);
853 		return (EOPNOTSUPP);
854 	}
855 	if (d->bd_state == BPF_WAITING)
856 		callout_stop(&d->bd_callout);
857 	timed_out = (d->bd_state == BPF_TIMED_OUT);
858 	d->bd_state = BPF_IDLE;
859 	while (d->bd_hbuf_in_use)
860 		mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
861 		    PRINET|PCATCH, "bd_hbuf", 0);
862 	/*
863 	 * If the hold buffer is empty, then do a timed sleep, which
864 	 * ends when the timeout expires or when enough packets
865 	 * have arrived to fill the store buffer.
866 	 */
867 	while (d->bd_hbuf == NULL) {
868 		if (d->bd_slen != 0) {
869 			/*
870 			 * A packet(s) either arrived since the previous
871 			 * read or arrived while we were asleep.
872 			 */
873 			if (d->bd_immediate || non_block || timed_out) {
874 				/*
875 				 * Rotate the buffers and return what's here
876 				 * if we are in immediate mode, non-blocking
877 				 * flag is set, or this descriptor timed out.
878 				 */
879 				ROTATE_BUFFERS(d);
880 				break;
881 			}
882 		}
883 
884 		/*
885 		 * No data is available, check to see if the bpf device
886 		 * is still pointed at a real interface.  If not, return
887 		 * ENXIO so that the userland process knows to rebind
888 		 * it before using it again.
889 		 */
890 		if (d->bd_bif == NULL) {
891 			BPFD_UNLOCK(d);
892 			return (ENXIO);
893 		}
894 
895 		if (non_block) {
896 			BPFD_UNLOCK(d);
897 			return (EWOULDBLOCK);
898 		}
899 		error = msleep(d, &d->bd_lock, PRINET|PCATCH,
900 		     "bpf", d->bd_rtout);
901 		if (error == EINTR || error == ERESTART) {
902 			BPFD_UNLOCK(d);
903 			return (error);
904 		}
905 		if (error == EWOULDBLOCK) {
906 			/*
907 			 * On a timeout, return what's in the buffer,
908 			 * which may be nothing.  If there is something
909 			 * in the store buffer, we can rotate the buffers.
910 			 */
911 			if (d->bd_hbuf)
912 				/*
913 				 * We filled up the buffer in between
914 				 * getting the timeout and arriving
915 				 * here, so we don't need to rotate.
916 				 */
917 				break;
918 
919 			if (d->bd_slen == 0) {
920 				BPFD_UNLOCK(d);
921 				return (0);
922 			}
923 			ROTATE_BUFFERS(d);
924 			break;
925 		}
926 	}
927 	/*
928 	 * At this point, we know we have something in the hold slot.
929 	 */
930 	d->bd_hbuf_in_use = 1;
931 	BPFD_UNLOCK(d);
932 
933 	/*
934 	 * Move data from hold buffer into user space.
935 	 * We know the entire buffer is transferred since
936 	 * we checked above that the read buffer is bpf_bufsize bytes.
937   	 *
938 	 * We do not have to worry about simultaneous reads because
939 	 * we waited for sole access to the hold buffer above.
940 	 */
941 	error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
942 
943 	BPFD_LOCK(d);
944 	KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
945 	d->bd_fbuf = d->bd_hbuf;
946 	d->bd_hbuf = NULL;
947 	d->bd_hlen = 0;
948 	bpf_buf_reclaimed(d);
949 	d->bd_hbuf_in_use = 0;
950 	wakeup(&d->bd_hbuf_in_use);
951 	BPFD_UNLOCK(d);
952 
953 	return (error);
954 }
955 
956 /*
957  * If there are processes sleeping on this descriptor, wake them up.
958  */
959 static __inline void
960 bpf_wakeup(struct bpf_d *d)
961 {
962 
963 	BPFD_LOCK_ASSERT(d);
964 	if (d->bd_state == BPF_WAITING) {
965 		callout_stop(&d->bd_callout);
966 		d->bd_state = BPF_IDLE;
967 	}
968 	wakeup(d);
969 	if (d->bd_async && d->bd_sig && d->bd_sigio)
970 		pgsigio(&d->bd_sigio, d->bd_sig, 0);
971 
972 	selwakeuppri(&d->bd_sel, PRINET);
973 	KNOTE_LOCKED(&d->bd_sel.si_note, 0);
974 }
975 
976 static void
977 bpf_timed_out(void *arg)
978 {
979 	struct bpf_d *d = (struct bpf_d *)arg;
980 
981 	BPFD_LOCK_ASSERT(d);
982 
983 	if (callout_pending(&d->bd_callout) || !callout_active(&d->bd_callout))
984 		return;
985 	if (d->bd_state == BPF_WAITING) {
986 		d->bd_state = BPF_TIMED_OUT;
987 		if (d->bd_slen != 0)
988 			bpf_wakeup(d);
989 	}
990 }
991 
992 static int
993 bpf_ready(struct bpf_d *d)
994 {
995 
996 	BPFD_LOCK_ASSERT(d);
997 
998 	if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
999 		return (1);
1000 	if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1001 	    d->bd_slen != 0)
1002 		return (1);
1003 	return (0);
1004 }
1005 
1006 static int
1007 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1008 {
1009 	struct bpf_d *d;
1010 	struct ifnet *ifp;
1011 	struct mbuf *m, *mc;
1012 	struct sockaddr dst;
1013 	int error, hlen;
1014 
1015 	error = devfs_get_cdevpriv((void **)&d);
1016 	if (error != 0)
1017 		return (error);
1018 
1019 	BPF_PID_REFRESH_CUR(d);
1020 	d->bd_wcount++;
1021 	/* XXX: locking required */
1022 	if (d->bd_bif == NULL) {
1023 		d->bd_wdcount++;
1024 		return (ENXIO);
1025 	}
1026 
1027 	ifp = d->bd_bif->bif_ifp;
1028 
1029 	if ((ifp->if_flags & IFF_UP) == 0) {
1030 		d->bd_wdcount++;
1031 		return (ENETDOWN);
1032 	}
1033 
1034 	if (uio->uio_resid == 0) {
1035 		d->bd_wdcount++;
1036 		return (0);
1037 	}
1038 
1039 	bzero(&dst, sizeof(dst));
1040 	m = NULL;
1041 	hlen = 0;
1042 	/* XXX: bpf_movein() can sleep */
1043 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp,
1044 	    &m, &dst, &hlen, d->bd_wfilter);
1045 	if (error) {
1046 		d->bd_wdcount++;
1047 		return (error);
1048 	}
1049 	d->bd_wfcount++;
1050 	if (d->bd_hdrcmplt)
1051 		dst.sa_family = pseudo_AF_HDRCMPLT;
1052 
1053 	if (d->bd_feedback) {
1054 		mc = m_dup(m, M_NOWAIT);
1055 		if (mc != NULL)
1056 			mc->m_pkthdr.rcvif = ifp;
1057 		/* Set M_PROMISC for outgoing packets to be discarded. */
1058 		if (d->bd_direction == BPF_D_INOUT)
1059 			m->m_flags |= M_PROMISC;
1060 	} else
1061 		mc = NULL;
1062 
1063 	m->m_pkthdr.len -= hlen;
1064 	m->m_len -= hlen;
1065 	m->m_data += hlen;	/* XXX */
1066 
1067 	CURVNET_SET(ifp->if_vnet);
1068 #ifdef MAC
1069 	BPFD_LOCK(d);
1070 	mac_bpfdesc_create_mbuf(d, m);
1071 	if (mc != NULL)
1072 		mac_bpfdesc_create_mbuf(d, mc);
1073 	BPFD_UNLOCK(d);
1074 #endif
1075 
1076 	error = (*ifp->if_output)(ifp, m, &dst, NULL);
1077 	if (error)
1078 		d->bd_wdcount++;
1079 
1080 	if (mc != NULL) {
1081 		if (error == 0)
1082 			(*ifp->if_input)(ifp, mc);
1083 		else
1084 			m_freem(mc);
1085 	}
1086 	CURVNET_RESTORE();
1087 
1088 	return (error);
1089 }
1090 
1091 /*
1092  * Reset a descriptor by flushing its packet buffer and clearing the receive
1093  * and drop counts.  This is doable for kernel-only buffers, but with
1094  * zero-copy buffers, we can't write to (or rotate) buffers that are
1095  * currently owned by userspace.  It would be nice if we could encapsulate
1096  * this logic in the buffer code rather than here.
1097  */
1098 static void
1099 reset_d(struct bpf_d *d)
1100 {
1101 
1102 	BPFD_LOCK_ASSERT(d);
1103 
1104 	while (d->bd_hbuf_in_use)
1105 		mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1106 		    "bd_hbuf", 0);
1107 	if ((d->bd_hbuf != NULL) &&
1108 	    (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1109 		/* Free the hold buffer. */
1110 		d->bd_fbuf = d->bd_hbuf;
1111 		d->bd_hbuf = NULL;
1112 		d->bd_hlen = 0;
1113 		bpf_buf_reclaimed(d);
1114 	}
1115 	if (bpf_canwritebuf(d))
1116 		d->bd_slen = 0;
1117 	d->bd_rcount = 0;
1118 	d->bd_dcount = 0;
1119 	d->bd_fcount = 0;
1120 	d->bd_wcount = 0;
1121 	d->bd_wfcount = 0;
1122 	d->bd_wdcount = 0;
1123 	d->bd_zcopy = 0;
1124 }
1125 
1126 /*
1127  *  FIONREAD		Check for read packet available.
1128  *  SIOCGIFADDR		Get interface address - convenient hook to driver.
1129  *  BIOCGBLEN		Get buffer len [for read()].
1130  *  BIOCSETF		Set read filter.
1131  *  BIOCSETFNR		Set read filter without resetting descriptor.
1132  *  BIOCSETWF		Set write filter.
1133  *  BIOCFLUSH		Flush read packet buffer.
1134  *  BIOCPROMISC		Put interface into promiscuous mode.
1135  *  BIOCGDLT		Get link layer type.
1136  *  BIOCGETIF		Get interface name.
1137  *  BIOCSETIF		Set interface.
1138  *  BIOCSRTIMEOUT	Set read timeout.
1139  *  BIOCGRTIMEOUT	Get read timeout.
1140  *  BIOCGSTATS		Get packet stats.
1141  *  BIOCIMMEDIATE	Set immediate mode.
1142  *  BIOCVERSION		Get filter language version.
1143  *  BIOCGHDRCMPLT	Get "header already complete" flag
1144  *  BIOCSHDRCMPLT	Set "header already complete" flag
1145  *  BIOCGDIRECTION	Get packet direction flag
1146  *  BIOCSDIRECTION	Set packet direction flag
1147  *  BIOCGTSTAMP		Get time stamp format and resolution.
1148  *  BIOCSTSTAMP		Set time stamp format and resolution.
1149  *  BIOCLOCK		Set "locked" flag
1150  *  BIOCFEEDBACK	Set packet feedback mode.
1151  *  BIOCSETZBUF		Set current zero-copy buffer locations.
1152  *  BIOCGETZMAX		Get maximum zero-copy buffer size.
1153  *  BIOCROTZBUF		Force rotation of zero-copy buffer
1154  *  BIOCSETBUFMODE	Set buffer mode.
1155  *  BIOCGETBUFMODE	Get current buffer mode.
1156  */
1157 /* ARGSUSED */
1158 static	int
1159 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1160     struct thread *td)
1161 {
1162 	struct bpf_d *d;
1163 	int error;
1164 
1165 	error = devfs_get_cdevpriv((void **)&d);
1166 	if (error != 0)
1167 		return (error);
1168 
1169 	/*
1170 	 * Refresh PID associated with this descriptor.
1171 	 */
1172 	BPFD_LOCK(d);
1173 	BPF_PID_REFRESH(d, td);
1174 	if (d->bd_state == BPF_WAITING)
1175 		callout_stop(&d->bd_callout);
1176 	d->bd_state = BPF_IDLE;
1177 	BPFD_UNLOCK(d);
1178 
1179 	if (d->bd_locked == 1) {
1180 		switch (cmd) {
1181 		case BIOCGBLEN:
1182 		case BIOCFLUSH:
1183 		case BIOCGDLT:
1184 		case BIOCGDLTLIST:
1185 #ifdef COMPAT_FREEBSD32
1186 		case BIOCGDLTLIST32:
1187 #endif
1188 		case BIOCGETIF:
1189 		case BIOCGRTIMEOUT:
1190 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1191 		case BIOCGRTIMEOUT32:
1192 #endif
1193 		case BIOCGSTATS:
1194 		case BIOCVERSION:
1195 		case BIOCGRSIG:
1196 		case BIOCGHDRCMPLT:
1197 		case BIOCSTSTAMP:
1198 		case BIOCFEEDBACK:
1199 		case FIONREAD:
1200 		case BIOCLOCK:
1201 		case BIOCSRTIMEOUT:
1202 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1203 		case BIOCSRTIMEOUT32:
1204 #endif
1205 		case BIOCIMMEDIATE:
1206 		case TIOCGPGRP:
1207 		case BIOCROTZBUF:
1208 			break;
1209 		default:
1210 			return (EPERM);
1211 		}
1212 	}
1213 #ifdef COMPAT_FREEBSD32
1214 	/*
1215 	 * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1216 	 * that it will get 32-bit packet headers.
1217 	 */
1218 	switch (cmd) {
1219 	case BIOCSETF32:
1220 	case BIOCSETFNR32:
1221 	case BIOCSETWF32:
1222 	case BIOCGDLTLIST32:
1223 	case BIOCGRTIMEOUT32:
1224 	case BIOCSRTIMEOUT32:
1225 		BPFD_LOCK(d);
1226 		d->bd_compat32 = 1;
1227 		BPFD_UNLOCK(d);
1228 	}
1229 #endif
1230 
1231 	CURVNET_SET(TD_TO_VNET(td));
1232 	switch (cmd) {
1233 
1234 	default:
1235 		error = EINVAL;
1236 		break;
1237 
1238 	/*
1239 	 * Check for read packet available.
1240 	 */
1241 	case FIONREAD:
1242 		{
1243 			int n;
1244 
1245 			BPFD_LOCK(d);
1246 			n = d->bd_slen;
1247 			while (d->bd_hbuf_in_use)
1248 				mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1249 				    PRINET, "bd_hbuf", 0);
1250 			if (d->bd_hbuf)
1251 				n += d->bd_hlen;
1252 			BPFD_UNLOCK(d);
1253 
1254 			*(int *)addr = n;
1255 			break;
1256 		}
1257 
1258 	case SIOCGIFADDR:
1259 		{
1260 			struct ifnet *ifp;
1261 
1262 			if (d->bd_bif == NULL)
1263 				error = EINVAL;
1264 			else {
1265 				ifp = d->bd_bif->bif_ifp;
1266 				error = (*ifp->if_ioctl)(ifp, cmd, addr);
1267 			}
1268 			break;
1269 		}
1270 
1271 	/*
1272 	 * Get buffer len [for read()].
1273 	 */
1274 	case BIOCGBLEN:
1275 		BPFD_LOCK(d);
1276 		*(u_int *)addr = d->bd_bufsize;
1277 		BPFD_UNLOCK(d);
1278 		break;
1279 
1280 	/*
1281 	 * Set buffer length.
1282 	 */
1283 	case BIOCSBLEN:
1284 		error = bpf_ioctl_sblen(d, (u_int *)addr);
1285 		break;
1286 
1287 	/*
1288 	 * Set link layer read filter.
1289 	 */
1290 	case BIOCSETF:
1291 	case BIOCSETFNR:
1292 	case BIOCSETWF:
1293 #ifdef COMPAT_FREEBSD32
1294 	case BIOCSETF32:
1295 	case BIOCSETFNR32:
1296 	case BIOCSETWF32:
1297 #endif
1298 		error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1299 		break;
1300 
1301 	/*
1302 	 * Flush read packet buffer.
1303 	 */
1304 	case BIOCFLUSH:
1305 		BPFD_LOCK(d);
1306 		reset_d(d);
1307 		BPFD_UNLOCK(d);
1308 		break;
1309 
1310 	/*
1311 	 * Put interface into promiscuous mode.
1312 	 */
1313 	case BIOCPROMISC:
1314 		if (d->bd_bif == NULL) {
1315 			/*
1316 			 * No interface attached yet.
1317 			 */
1318 			error = EINVAL;
1319 			break;
1320 		}
1321 		if (d->bd_promisc == 0) {
1322 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
1323 			if (error == 0)
1324 				d->bd_promisc = 1;
1325 		}
1326 		break;
1327 
1328 	/*
1329 	 * Get current data link type.
1330 	 */
1331 	case BIOCGDLT:
1332 		BPF_LOCK();
1333 		if (d->bd_bif == NULL)
1334 			error = EINVAL;
1335 		else
1336 			*(u_int *)addr = d->bd_bif->bif_dlt;
1337 		BPF_UNLOCK();
1338 		break;
1339 
1340 	/*
1341 	 * Get a list of supported data link types.
1342 	 */
1343 #ifdef COMPAT_FREEBSD32
1344 	case BIOCGDLTLIST32:
1345 		{
1346 			struct bpf_dltlist32 *list32;
1347 			struct bpf_dltlist dltlist;
1348 
1349 			list32 = (struct bpf_dltlist32 *)addr;
1350 			dltlist.bfl_len = list32->bfl_len;
1351 			dltlist.bfl_list = PTRIN(list32->bfl_list);
1352 			BPF_LOCK();
1353 			if (d->bd_bif == NULL)
1354 				error = EINVAL;
1355 			else {
1356 				error = bpf_getdltlist(d, &dltlist);
1357 				if (error == 0)
1358 					list32->bfl_len = dltlist.bfl_len;
1359 			}
1360 			BPF_UNLOCK();
1361 			break;
1362 		}
1363 #endif
1364 
1365 	case BIOCGDLTLIST:
1366 		BPF_LOCK();
1367 		if (d->bd_bif == NULL)
1368 			error = EINVAL;
1369 		else
1370 			error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1371 		BPF_UNLOCK();
1372 		break;
1373 
1374 	/*
1375 	 * Set data link type.
1376 	 */
1377 	case BIOCSDLT:
1378 		BPF_LOCK();
1379 		if (d->bd_bif == NULL)
1380 			error = EINVAL;
1381 		else
1382 			error = bpf_setdlt(d, *(u_int *)addr);
1383 		BPF_UNLOCK();
1384 		break;
1385 
1386 	/*
1387 	 * Get interface name.
1388 	 */
1389 	case BIOCGETIF:
1390 		BPF_LOCK();
1391 		if (d->bd_bif == NULL)
1392 			error = EINVAL;
1393 		else {
1394 			struct ifnet *const ifp = d->bd_bif->bif_ifp;
1395 			struct ifreq *const ifr = (struct ifreq *)addr;
1396 
1397 			strlcpy(ifr->ifr_name, ifp->if_xname,
1398 			    sizeof(ifr->ifr_name));
1399 		}
1400 		BPF_UNLOCK();
1401 		break;
1402 
1403 	/*
1404 	 * Set interface.
1405 	 */
1406 	case BIOCSETIF:
1407 		BPF_LOCK();
1408 		error = bpf_setif(d, (struct ifreq *)addr);
1409 		BPF_UNLOCK();
1410 		break;
1411 
1412 	/*
1413 	 * Set read timeout.
1414 	 */
1415 	case BIOCSRTIMEOUT:
1416 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1417 	case BIOCSRTIMEOUT32:
1418 #endif
1419 		{
1420 			struct timeval *tv = (struct timeval *)addr;
1421 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1422 			struct timeval32 *tv32;
1423 			struct timeval tv64;
1424 
1425 			if (cmd == BIOCSRTIMEOUT32) {
1426 				tv32 = (struct timeval32 *)addr;
1427 				tv = &tv64;
1428 				tv->tv_sec = tv32->tv_sec;
1429 				tv->tv_usec = tv32->tv_usec;
1430 			} else
1431 #endif
1432 				tv = (struct timeval *)addr;
1433 
1434 			/*
1435 			 * Subtract 1 tick from tvtohz() since this isn't
1436 			 * a one-shot timer.
1437 			 */
1438 			if ((error = itimerfix(tv)) == 0)
1439 				d->bd_rtout = tvtohz(tv) - 1;
1440 			break;
1441 		}
1442 
1443 	/*
1444 	 * Get read timeout.
1445 	 */
1446 	case BIOCGRTIMEOUT:
1447 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1448 	case BIOCGRTIMEOUT32:
1449 #endif
1450 		{
1451 			struct timeval *tv;
1452 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1453 			struct timeval32 *tv32;
1454 			struct timeval tv64;
1455 
1456 			if (cmd == BIOCGRTIMEOUT32)
1457 				tv = &tv64;
1458 			else
1459 #endif
1460 				tv = (struct timeval *)addr;
1461 
1462 			tv->tv_sec = d->bd_rtout / hz;
1463 			tv->tv_usec = (d->bd_rtout % hz) * tick;
1464 #if defined(COMPAT_FREEBSD32) && !defined(__mips__)
1465 			if (cmd == BIOCGRTIMEOUT32) {
1466 				tv32 = (struct timeval32 *)addr;
1467 				tv32->tv_sec = tv->tv_sec;
1468 				tv32->tv_usec = tv->tv_usec;
1469 			}
1470 #endif
1471 
1472 			break;
1473 		}
1474 
1475 	/*
1476 	 * Get packet stats.
1477 	 */
1478 	case BIOCGSTATS:
1479 		{
1480 			struct bpf_stat *bs = (struct bpf_stat *)addr;
1481 
1482 			/* XXXCSJP overflow */
1483 			bs->bs_recv = d->bd_rcount;
1484 			bs->bs_drop = d->bd_dcount;
1485 			break;
1486 		}
1487 
1488 	/*
1489 	 * Set immediate mode.
1490 	 */
1491 	case BIOCIMMEDIATE:
1492 		BPFD_LOCK(d);
1493 		d->bd_immediate = *(u_int *)addr;
1494 		BPFD_UNLOCK(d);
1495 		break;
1496 
1497 	case BIOCVERSION:
1498 		{
1499 			struct bpf_version *bv = (struct bpf_version *)addr;
1500 
1501 			bv->bv_major = BPF_MAJOR_VERSION;
1502 			bv->bv_minor = BPF_MINOR_VERSION;
1503 			break;
1504 		}
1505 
1506 	/*
1507 	 * Get "header already complete" flag
1508 	 */
1509 	case BIOCGHDRCMPLT:
1510 		BPFD_LOCK(d);
1511 		*(u_int *)addr = d->bd_hdrcmplt;
1512 		BPFD_UNLOCK(d);
1513 		break;
1514 
1515 	/*
1516 	 * Set "header already complete" flag
1517 	 */
1518 	case BIOCSHDRCMPLT:
1519 		BPFD_LOCK(d);
1520 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1521 		BPFD_UNLOCK(d);
1522 		break;
1523 
1524 	/*
1525 	 * Get packet direction flag
1526 	 */
1527 	case BIOCGDIRECTION:
1528 		BPFD_LOCK(d);
1529 		*(u_int *)addr = d->bd_direction;
1530 		BPFD_UNLOCK(d);
1531 		break;
1532 
1533 	/*
1534 	 * Set packet direction flag
1535 	 */
1536 	case BIOCSDIRECTION:
1537 		{
1538 			u_int	direction;
1539 
1540 			direction = *(u_int *)addr;
1541 			switch (direction) {
1542 			case BPF_D_IN:
1543 			case BPF_D_INOUT:
1544 			case BPF_D_OUT:
1545 				BPFD_LOCK(d);
1546 				d->bd_direction = direction;
1547 				BPFD_UNLOCK(d);
1548 				break;
1549 			default:
1550 				error = EINVAL;
1551 			}
1552 		}
1553 		break;
1554 
1555 	/*
1556 	 * Get packet timestamp format and resolution.
1557 	 */
1558 	case BIOCGTSTAMP:
1559 		BPFD_LOCK(d);
1560 		*(u_int *)addr = d->bd_tstamp;
1561 		BPFD_UNLOCK(d);
1562 		break;
1563 
1564 	/*
1565 	 * Set packet timestamp format and resolution.
1566 	 */
1567 	case BIOCSTSTAMP:
1568 		{
1569 			u_int	func;
1570 
1571 			func = *(u_int *)addr;
1572 			if (BPF_T_VALID(func))
1573 				d->bd_tstamp = func;
1574 			else
1575 				error = EINVAL;
1576 		}
1577 		break;
1578 
1579 	case BIOCFEEDBACK:
1580 		BPFD_LOCK(d);
1581 		d->bd_feedback = *(u_int *)addr;
1582 		BPFD_UNLOCK(d);
1583 		break;
1584 
1585 	case BIOCLOCK:
1586 		BPFD_LOCK(d);
1587 		d->bd_locked = 1;
1588 		BPFD_UNLOCK(d);
1589 		break;
1590 
1591 	case FIONBIO:		/* Non-blocking I/O */
1592 		break;
1593 
1594 	case FIOASYNC:		/* Send signal on receive packets */
1595 		BPFD_LOCK(d);
1596 		d->bd_async = *(int *)addr;
1597 		BPFD_UNLOCK(d);
1598 		break;
1599 
1600 	case FIOSETOWN:
1601 		/*
1602 		 * XXX: Add some sort of locking here?
1603 		 * fsetown() can sleep.
1604 		 */
1605 		error = fsetown(*(int *)addr, &d->bd_sigio);
1606 		break;
1607 
1608 	case FIOGETOWN:
1609 		BPFD_LOCK(d);
1610 		*(int *)addr = fgetown(&d->bd_sigio);
1611 		BPFD_UNLOCK(d);
1612 		break;
1613 
1614 	/* This is deprecated, FIOSETOWN should be used instead. */
1615 	case TIOCSPGRP:
1616 		error = fsetown(-(*(int *)addr), &d->bd_sigio);
1617 		break;
1618 
1619 	/* This is deprecated, FIOGETOWN should be used instead. */
1620 	case TIOCGPGRP:
1621 		*(int *)addr = -fgetown(&d->bd_sigio);
1622 		break;
1623 
1624 	case BIOCSRSIG:		/* Set receive signal */
1625 		{
1626 			u_int sig;
1627 
1628 			sig = *(u_int *)addr;
1629 
1630 			if (sig >= NSIG)
1631 				error = EINVAL;
1632 			else {
1633 				BPFD_LOCK(d);
1634 				d->bd_sig = sig;
1635 				BPFD_UNLOCK(d);
1636 			}
1637 			break;
1638 		}
1639 	case BIOCGRSIG:
1640 		BPFD_LOCK(d);
1641 		*(u_int *)addr = d->bd_sig;
1642 		BPFD_UNLOCK(d);
1643 		break;
1644 
1645 	case BIOCGETBUFMODE:
1646 		BPFD_LOCK(d);
1647 		*(u_int *)addr = d->bd_bufmode;
1648 		BPFD_UNLOCK(d);
1649 		break;
1650 
1651 	case BIOCSETBUFMODE:
1652 		/*
1653 		 * Allow the buffering mode to be changed as long as we
1654 		 * haven't yet committed to a particular mode.  Our
1655 		 * definition of commitment, for now, is whether or not a
1656 		 * buffer has been allocated or an interface attached, since
1657 		 * that's the point where things get tricky.
1658 		 */
1659 		switch (*(u_int *)addr) {
1660 		case BPF_BUFMODE_BUFFER:
1661 			break;
1662 
1663 		case BPF_BUFMODE_ZBUF:
1664 			if (bpf_zerocopy_enable)
1665 				break;
1666 			/* FALLSTHROUGH */
1667 
1668 		default:
1669 			CURVNET_RESTORE();
1670 			return (EINVAL);
1671 		}
1672 
1673 		BPFD_LOCK(d);
1674 		if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1675 		    d->bd_fbuf != NULL || d->bd_bif != NULL) {
1676 			BPFD_UNLOCK(d);
1677 			CURVNET_RESTORE();
1678 			return (EBUSY);
1679 		}
1680 		d->bd_bufmode = *(u_int *)addr;
1681 		BPFD_UNLOCK(d);
1682 		break;
1683 
1684 	case BIOCGETZMAX:
1685 		error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1686 		break;
1687 
1688 	case BIOCSETZBUF:
1689 		error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1690 		break;
1691 
1692 	case BIOCROTZBUF:
1693 		error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1694 		break;
1695 	}
1696 	CURVNET_RESTORE();
1697 	return (error);
1698 }
1699 
1700 /*
1701  * Set d's packet filter program to fp.  If this file already has a filter,
1702  * free it and replace it.  Returns EINVAL for bogus requests.
1703  *
1704  * Note we need global lock here to serialize bpf_setf() and bpf_setif() calls
1705  * since reading d->bd_bif can't be protected by d or interface lock due to
1706  * lock order.
1707  *
1708  * Additionally, we have to acquire interface write lock due to bpf_mtap() uses
1709  * interface read lock to read all filers.
1710  *
1711  */
1712 static int
1713 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1714 {
1715 #ifdef COMPAT_FREEBSD32
1716 	struct bpf_program fp_swab;
1717 	struct bpf_program32 *fp32;
1718 #endif
1719 	struct bpf_insn *fcode, *old;
1720 #ifdef BPF_JITTER
1721 	bpf_jit_filter *jfunc, *ofunc;
1722 #endif
1723 	size_t size;
1724 	u_int flen;
1725 	int need_upgrade;
1726 
1727 #ifdef COMPAT_FREEBSD32
1728 	switch (cmd) {
1729 	case BIOCSETF32:
1730 	case BIOCSETWF32:
1731 	case BIOCSETFNR32:
1732 		fp32 = (struct bpf_program32 *)fp;
1733 		fp_swab.bf_len = fp32->bf_len;
1734 		fp_swab.bf_insns = (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1735 		fp = &fp_swab;
1736 		switch (cmd) {
1737 		case BIOCSETF32:
1738 			cmd = BIOCSETF;
1739 			break;
1740 		case BIOCSETWF32:
1741 			cmd = BIOCSETWF;
1742 			break;
1743 		}
1744 		break;
1745 	}
1746 #endif
1747 
1748 	fcode = NULL;
1749 #ifdef BPF_JITTER
1750 	jfunc = ofunc = NULL;
1751 #endif
1752 	need_upgrade = 0;
1753 
1754 	/*
1755 	 * Check new filter validness before acquiring any locks.
1756 	 * Allocate memory for new filter, if needed.
1757 	 */
1758 	flen = fp->bf_len;
1759 	if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1760 		return (EINVAL);
1761 	size = flen * sizeof(*fp->bf_insns);
1762 	if (size > 0) {
1763 		/* We're setting up new filter.  Copy and check actual data. */
1764 		fcode = malloc(size, M_BPF, M_WAITOK);
1765 		if (copyin(fp->bf_insns, fcode, size) != 0 ||
1766 		    !bpf_validate(fcode, flen)) {
1767 			free(fcode, M_BPF);
1768 			return (EINVAL);
1769 		}
1770 #ifdef BPF_JITTER
1771 		/* Filter is copied inside fcode and is perfectly valid. */
1772 		jfunc = bpf_jitter(fcode, flen);
1773 #endif
1774 	}
1775 
1776 	BPF_LOCK();
1777 
1778 	/*
1779 	 * Set up new filter.
1780 	 * Protect filter change by interface lock.
1781 	 * Additionally, we are protected by global lock here.
1782 	 */
1783 	if (d->bd_bif != NULL)
1784 		BPFIF_WLOCK(d->bd_bif);
1785 	BPFD_LOCK(d);
1786 	if (cmd == BIOCSETWF) {
1787 		old = d->bd_wfilter;
1788 		d->bd_wfilter = fcode;
1789 	} else {
1790 		old = d->bd_rfilter;
1791 		d->bd_rfilter = fcode;
1792 #ifdef BPF_JITTER
1793 		ofunc = d->bd_bfilter;
1794 		d->bd_bfilter = jfunc;
1795 #endif
1796 		if (cmd == BIOCSETF)
1797 			reset_d(d);
1798 
1799 		if (fcode != NULL) {
1800 			/*
1801 			 * Do not require upgrade by first BIOCSETF
1802 			 * (used to set snaplen) by pcap_open_live().
1803 			 */
1804 			if (d->bd_writer != 0 && --d->bd_writer == 0)
1805 				need_upgrade = 1;
1806 			CTR4(KTR_NET, "%s: filter function set by pid %d, "
1807 			    "bd_writer counter %d, need_upgrade %d",
1808 			    __func__, d->bd_pid, d->bd_writer, need_upgrade);
1809 		}
1810 	}
1811 	BPFD_UNLOCK(d);
1812 	if (d->bd_bif != NULL)
1813 		BPFIF_WUNLOCK(d->bd_bif);
1814 	if (old != NULL)
1815 		free(old, M_BPF);
1816 #ifdef BPF_JITTER
1817 	if (ofunc != NULL)
1818 		bpf_destroy_jit_filter(ofunc);
1819 #endif
1820 
1821 	/* Move d to active readers list. */
1822 	if (need_upgrade)
1823 		bpf_upgraded(d);
1824 
1825 	BPF_UNLOCK();
1826 	return (0);
1827 }
1828 
1829 /*
1830  * Detach a file from its current interface (if attached at all) and attach
1831  * to the interface indicated by the name stored in ifr.
1832  * Return an errno or 0.
1833  */
1834 static int
1835 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1836 {
1837 	struct bpf_if *bp;
1838 	struct ifnet *theywant;
1839 
1840 	BPF_LOCK_ASSERT();
1841 
1842 	theywant = ifunit(ifr->ifr_name);
1843 	if (theywant == NULL || theywant->if_bpf == NULL)
1844 		return (ENXIO);
1845 
1846 	bp = theywant->if_bpf;
1847 
1848 	/* Check if interface is not being detached from BPF */
1849 	BPFIF_RLOCK(bp);
1850 	if (bp->flags & BPFIF_FLAG_DYING) {
1851 		BPFIF_RUNLOCK(bp);
1852 		return (ENXIO);
1853 	}
1854 	BPFIF_RUNLOCK(bp);
1855 
1856 	/*
1857 	 * Behavior here depends on the buffering model.  If we're using
1858 	 * kernel memory buffers, then we can allocate them here.  If we're
1859 	 * using zero-copy, then the user process must have registered
1860 	 * buffers by the time we get here.  If not, return an error.
1861 	 */
1862 	switch (d->bd_bufmode) {
1863 	case BPF_BUFMODE_BUFFER:
1864 	case BPF_BUFMODE_ZBUF:
1865 		if (d->bd_sbuf == NULL)
1866 			return (EINVAL);
1867 		break;
1868 
1869 	default:
1870 		panic("bpf_setif: bufmode %d", d->bd_bufmode);
1871 	}
1872 	if (bp != d->bd_bif)
1873 		bpf_attachd(d, bp);
1874 	BPFD_LOCK(d);
1875 	reset_d(d);
1876 	BPFD_UNLOCK(d);
1877 	return (0);
1878 }
1879 
1880 /*
1881  * Support for select() and poll() system calls
1882  *
1883  * Return true iff the specific operation will not block indefinitely.
1884  * Otherwise, return false but make a note that a selwakeup() must be done.
1885  */
1886 static int
1887 bpfpoll(struct cdev *dev, int events, struct thread *td)
1888 {
1889 	struct bpf_d *d;
1890 	int revents;
1891 
1892 	if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
1893 		return (events &
1894 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1895 
1896 	/*
1897 	 * Refresh PID associated with this descriptor.
1898 	 */
1899 	revents = events & (POLLOUT | POLLWRNORM);
1900 	BPFD_LOCK(d);
1901 	BPF_PID_REFRESH(d, td);
1902 	if (events & (POLLIN | POLLRDNORM)) {
1903 		if (bpf_ready(d))
1904 			revents |= events & (POLLIN | POLLRDNORM);
1905 		else {
1906 			selrecord(td, &d->bd_sel);
1907 			/* Start the read timeout if necessary. */
1908 			if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1909 				callout_reset(&d->bd_callout, d->bd_rtout,
1910 				    bpf_timed_out, d);
1911 				d->bd_state = BPF_WAITING;
1912 			}
1913 		}
1914 	}
1915 	BPFD_UNLOCK(d);
1916 	return (revents);
1917 }
1918 
1919 /*
1920  * Support for kevent() system call.  Register EVFILT_READ filters and
1921  * reject all others.
1922  */
1923 int
1924 bpfkqfilter(struct cdev *dev, struct knote *kn)
1925 {
1926 	struct bpf_d *d;
1927 
1928 	if (devfs_get_cdevpriv((void **)&d) != 0 ||
1929 	    kn->kn_filter != EVFILT_READ)
1930 		return (1);
1931 
1932 	/*
1933 	 * Refresh PID associated with this descriptor.
1934 	 */
1935 	BPFD_LOCK(d);
1936 	BPF_PID_REFRESH_CUR(d);
1937 	kn->kn_fop = &bpfread_filtops;
1938 	kn->kn_hook = d;
1939 	knlist_add(&d->bd_sel.si_note, kn, 1);
1940 	BPFD_UNLOCK(d);
1941 
1942 	return (0);
1943 }
1944 
1945 static void
1946 filt_bpfdetach(struct knote *kn)
1947 {
1948 	struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1949 
1950 	knlist_remove(&d->bd_sel.si_note, kn, 0);
1951 }
1952 
1953 static int
1954 filt_bpfread(struct knote *kn, long hint)
1955 {
1956 	struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1957 	int ready;
1958 
1959 	BPFD_LOCK_ASSERT(d);
1960 	ready = bpf_ready(d);
1961 	if (ready) {
1962 		kn->kn_data = d->bd_slen;
1963 		while (d->bd_hbuf_in_use)
1964 			mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1965 			    PRINET, "bd_hbuf", 0);
1966 		if (d->bd_hbuf)
1967 			kn->kn_data += d->bd_hlen;
1968 	} else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1969 		callout_reset(&d->bd_callout, d->bd_rtout,
1970 		    bpf_timed_out, d);
1971 		d->bd_state = BPF_WAITING;
1972 	}
1973 
1974 	return (ready);
1975 }
1976 
1977 #define	BPF_TSTAMP_NONE		0
1978 #define	BPF_TSTAMP_FAST		1
1979 #define	BPF_TSTAMP_NORMAL	2
1980 #define	BPF_TSTAMP_EXTERN	3
1981 
1982 static int
1983 bpf_ts_quality(int tstype)
1984 {
1985 
1986 	if (tstype == BPF_T_NONE)
1987 		return (BPF_TSTAMP_NONE);
1988 	if ((tstype & BPF_T_FAST) != 0)
1989 		return (BPF_TSTAMP_FAST);
1990 
1991 	return (BPF_TSTAMP_NORMAL);
1992 }
1993 
1994 static int
1995 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
1996 {
1997 	struct m_tag *tag;
1998 	int quality;
1999 
2000 	quality = bpf_ts_quality(tstype);
2001 	if (quality == BPF_TSTAMP_NONE)
2002 		return (quality);
2003 
2004 	if (m != NULL) {
2005 		tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2006 		if (tag != NULL) {
2007 			*bt = *(struct bintime *)(tag + 1);
2008 			return (BPF_TSTAMP_EXTERN);
2009 		}
2010 	}
2011 	if (quality == BPF_TSTAMP_NORMAL)
2012 		binuptime(bt);
2013 	else
2014 		getbinuptime(bt);
2015 
2016 	return (quality);
2017 }
2018 
2019 /*
2020  * Incoming linkage from device drivers.  Process the packet pkt, of length
2021  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
2022  * by each process' filter, and if accepted, stashed into the corresponding
2023  * buffer.
2024  */
2025 void
2026 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2027 {
2028 	struct bintime bt;
2029 	struct bpf_d *d;
2030 #ifdef BPF_JITTER
2031 	bpf_jit_filter *bf;
2032 #endif
2033 	u_int slen;
2034 	int gottime;
2035 
2036 	gottime = BPF_TSTAMP_NONE;
2037 
2038 	BPFIF_RLOCK(bp);
2039 
2040 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2041 		/*
2042 		 * We are not using any locks for d here because:
2043 		 * 1) any filter change is protected by interface
2044 		 * write lock
2045 		 * 2) destroying/detaching d is protected by interface
2046 		 * write lock, too
2047 		 */
2048 
2049 		/* XXX: Do not protect counter for the sake of performance. */
2050 		++d->bd_rcount;
2051 		/*
2052 		 * NB: We dont call BPF_CHECK_DIRECTION() here since there is no
2053 		 * way for the caller to indiciate to us whether this packet
2054 		 * is inbound or outbound.  In the bpf_mtap() routines, we use
2055 		 * the interface pointers on the mbuf to figure it out.
2056 		 */
2057 #ifdef BPF_JITTER
2058 		bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2059 		if (bf != NULL)
2060 			slen = (*(bf->func))(pkt, pktlen, pktlen);
2061 		else
2062 #endif
2063 		slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2064 		if (slen != 0) {
2065 			/*
2066 			 * Filter matches. Let's to acquire write lock.
2067 			 */
2068 			BPFD_LOCK(d);
2069 
2070 			d->bd_fcount++;
2071 			if (gottime < bpf_ts_quality(d->bd_tstamp))
2072 				gottime = bpf_gettime(&bt, d->bd_tstamp, NULL);
2073 #ifdef MAC
2074 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2075 #endif
2076 				catchpacket(d, pkt, pktlen, slen,
2077 				    bpf_append_bytes, &bt);
2078 			BPFD_UNLOCK(d);
2079 		}
2080 	}
2081 	BPFIF_RUNLOCK(bp);
2082 }
2083 
2084 #define	BPF_CHECK_DIRECTION(d, r, i)				\
2085 	    (((d)->bd_direction == BPF_D_IN && (r) != (i)) ||	\
2086 	    ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2087 
2088 /*
2089  * Incoming linkage from device drivers, when packet is in an mbuf chain.
2090  * Locking model is explained in bpf_tap().
2091  */
2092 void
2093 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2094 {
2095 	struct bintime bt;
2096 	struct bpf_d *d;
2097 #ifdef BPF_JITTER
2098 	bpf_jit_filter *bf;
2099 #endif
2100 	u_int pktlen, slen;
2101 	int gottime;
2102 
2103 	/* Skip outgoing duplicate packets. */
2104 	if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2105 		m->m_flags &= ~M_PROMISC;
2106 		return;
2107 	}
2108 
2109 	pktlen = m_length(m, NULL);
2110 	gottime = BPF_TSTAMP_NONE;
2111 
2112 	BPFIF_RLOCK(bp);
2113 
2114 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2115 		if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2116 			continue;
2117 		++d->bd_rcount;
2118 #ifdef BPF_JITTER
2119 		bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2120 		/* XXX We cannot handle multiple mbufs. */
2121 		if (bf != NULL && m->m_next == NULL)
2122 			slen = (*(bf->func))(mtod(m, u_char *), pktlen, pktlen);
2123 		else
2124 #endif
2125 		slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2126 		if (slen != 0) {
2127 			BPFD_LOCK(d);
2128 
2129 			d->bd_fcount++;
2130 			if (gottime < bpf_ts_quality(d->bd_tstamp))
2131 				gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2132 #ifdef MAC
2133 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2134 #endif
2135 				catchpacket(d, (u_char *)m, pktlen, slen,
2136 				    bpf_append_mbuf, &bt);
2137 			BPFD_UNLOCK(d);
2138 		}
2139 	}
2140 	BPFIF_RUNLOCK(bp);
2141 }
2142 
2143 /*
2144  * Incoming linkage from device drivers, when packet is in
2145  * an mbuf chain and to be prepended by a contiguous header.
2146  */
2147 void
2148 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2149 {
2150 	struct bintime bt;
2151 	struct mbuf mb;
2152 	struct bpf_d *d;
2153 	u_int pktlen, slen;
2154 	int gottime;
2155 
2156 	/* Skip outgoing duplicate packets. */
2157 	if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2158 		m->m_flags &= ~M_PROMISC;
2159 		return;
2160 	}
2161 
2162 	pktlen = m_length(m, NULL);
2163 	/*
2164 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
2165 	 * Note that we cut corners here; we only setup what's
2166 	 * absolutely needed--this mbuf should never go anywhere else.
2167 	 */
2168 	mb.m_next = m;
2169 	mb.m_data = data;
2170 	mb.m_len = dlen;
2171 	pktlen += dlen;
2172 
2173 	gottime = BPF_TSTAMP_NONE;
2174 
2175 	BPFIF_RLOCK(bp);
2176 
2177 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2178 		if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2179 			continue;
2180 		++d->bd_rcount;
2181 		slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2182 		if (slen != 0) {
2183 			BPFD_LOCK(d);
2184 
2185 			d->bd_fcount++;
2186 			if (gottime < bpf_ts_quality(d->bd_tstamp))
2187 				gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2188 #ifdef MAC
2189 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2190 #endif
2191 				catchpacket(d, (u_char *)&mb, pktlen, slen,
2192 				    bpf_append_mbuf, &bt);
2193 			BPFD_UNLOCK(d);
2194 		}
2195 	}
2196 	BPFIF_RUNLOCK(bp);
2197 }
2198 
2199 #undef	BPF_CHECK_DIRECTION
2200 
2201 #undef	BPF_TSTAMP_NONE
2202 #undef	BPF_TSTAMP_FAST
2203 #undef	BPF_TSTAMP_NORMAL
2204 #undef	BPF_TSTAMP_EXTERN
2205 
2206 static int
2207 bpf_hdrlen(struct bpf_d *d)
2208 {
2209 	int hdrlen;
2210 
2211 	hdrlen = d->bd_bif->bif_hdrlen;
2212 #ifndef BURN_BRIDGES
2213 	if (d->bd_tstamp == BPF_T_NONE ||
2214 	    BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2215 #ifdef COMPAT_FREEBSD32
2216 		if (d->bd_compat32)
2217 			hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2218 		else
2219 #endif
2220 			hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2221 	else
2222 #endif
2223 		hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2224 #ifdef COMPAT_FREEBSD32
2225 	if (d->bd_compat32)
2226 		hdrlen = BPF_WORDALIGN32(hdrlen);
2227 	else
2228 #endif
2229 		hdrlen = BPF_WORDALIGN(hdrlen);
2230 
2231 	return (hdrlen - d->bd_bif->bif_hdrlen);
2232 }
2233 
2234 static void
2235 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2236 {
2237 	struct bintime bt2;
2238 	struct timeval tsm;
2239 	struct timespec tsn;
2240 
2241 	if ((tstype & BPF_T_MONOTONIC) == 0) {
2242 		bt2 = *bt;
2243 		bintime_add(&bt2, &boottimebin);
2244 		bt = &bt2;
2245 	}
2246 	switch (BPF_T_FORMAT(tstype)) {
2247 	case BPF_T_MICROTIME:
2248 		bintime2timeval(bt, &tsm);
2249 		ts->bt_sec = tsm.tv_sec;
2250 		ts->bt_frac = tsm.tv_usec;
2251 		break;
2252 	case BPF_T_NANOTIME:
2253 		bintime2timespec(bt, &tsn);
2254 		ts->bt_sec = tsn.tv_sec;
2255 		ts->bt_frac = tsn.tv_nsec;
2256 		break;
2257 	case BPF_T_BINTIME:
2258 		ts->bt_sec = bt->sec;
2259 		ts->bt_frac = bt->frac;
2260 		break;
2261 	}
2262 }
2263 
2264 /*
2265  * Move the packet data from interface memory (pkt) into the
2266  * store buffer.  "cpfn" is the routine called to do the actual data
2267  * transfer.  bcopy is passed in to copy contiguous chunks, while
2268  * bpf_append_mbuf is passed in to copy mbuf chains.  In the latter case,
2269  * pkt is really an mbuf.
2270  */
2271 static void
2272 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2273     void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2274     struct bintime *bt)
2275 {
2276 	struct bpf_xhdr hdr;
2277 #ifndef BURN_BRIDGES
2278 	struct bpf_hdr hdr_old;
2279 #ifdef COMPAT_FREEBSD32
2280 	struct bpf_hdr32 hdr32_old;
2281 #endif
2282 #endif
2283 	int caplen, curlen, hdrlen, totlen;
2284 	int do_wakeup = 0;
2285 	int do_timestamp;
2286 	int tstype;
2287 
2288 	BPFD_LOCK_ASSERT(d);
2289 
2290 	/*
2291 	 * Detect whether user space has released a buffer back to us, and if
2292 	 * so, move it from being a hold buffer to a free buffer.  This may
2293 	 * not be the best place to do it (for example, we might only want to
2294 	 * run this check if we need the space), but for now it's a reliable
2295 	 * spot to do it.
2296 	 */
2297 	if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2298 		while (d->bd_hbuf_in_use)
2299 			mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2300 			    PRINET, "bd_hbuf", 0);
2301 		d->bd_fbuf = d->bd_hbuf;
2302 		d->bd_hbuf = NULL;
2303 		d->bd_hlen = 0;
2304 		bpf_buf_reclaimed(d);
2305 	}
2306 
2307 	/*
2308 	 * Figure out how many bytes to move.  If the packet is
2309 	 * greater or equal to the snapshot length, transfer that
2310 	 * much.  Otherwise, transfer the whole packet (unless
2311 	 * we hit the buffer size limit).
2312 	 */
2313 	hdrlen = bpf_hdrlen(d);
2314 	totlen = hdrlen + min(snaplen, pktlen);
2315 	if (totlen > d->bd_bufsize)
2316 		totlen = d->bd_bufsize;
2317 
2318 	/*
2319 	 * Round up the end of the previous packet to the next longword.
2320 	 *
2321 	 * Drop the packet if there's no room and no hope of room
2322 	 * If the packet would overflow the storage buffer or the storage
2323 	 * buffer is considered immutable by the buffer model, try to rotate
2324 	 * the buffer and wakeup pending processes.
2325 	 */
2326 #ifdef COMPAT_FREEBSD32
2327 	if (d->bd_compat32)
2328 		curlen = BPF_WORDALIGN32(d->bd_slen);
2329 	else
2330 #endif
2331 		curlen = BPF_WORDALIGN(d->bd_slen);
2332 	if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2333 		if (d->bd_fbuf == NULL) {
2334 			/*
2335 			 * There's no room in the store buffer, and no
2336 			 * prospect of room, so drop the packet.  Notify the
2337 			 * buffer model.
2338 			 */
2339 			bpf_buffull(d);
2340 			++d->bd_dcount;
2341 			return;
2342 		}
2343 		while (d->bd_hbuf_in_use)
2344 			mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2345 			    PRINET, "bd_hbuf", 0);
2346 		ROTATE_BUFFERS(d);
2347 		do_wakeup = 1;
2348 		curlen = 0;
2349 	} else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2350 		/*
2351 		 * Immediate mode is set, or the read timeout has already
2352 		 * expired during a select call.  A packet arrived, so the
2353 		 * reader should be woken up.
2354 		 */
2355 		do_wakeup = 1;
2356 	caplen = totlen - hdrlen;
2357 	tstype = d->bd_tstamp;
2358 	do_timestamp = tstype != BPF_T_NONE;
2359 #ifndef BURN_BRIDGES
2360 	if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2361 		struct bpf_ts ts;
2362 		if (do_timestamp)
2363 			bpf_bintime2ts(bt, &ts, tstype);
2364 #ifdef COMPAT_FREEBSD32
2365 		if (d->bd_compat32) {
2366 			bzero(&hdr32_old, sizeof(hdr32_old));
2367 			if (do_timestamp) {
2368 				hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2369 				hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2370 			}
2371 			hdr32_old.bh_datalen = pktlen;
2372 			hdr32_old.bh_hdrlen = hdrlen;
2373 			hdr32_old.bh_caplen = caplen;
2374 			bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2375 			    sizeof(hdr32_old));
2376 			goto copy;
2377 		}
2378 #endif
2379 		bzero(&hdr_old, sizeof(hdr_old));
2380 		if (do_timestamp) {
2381 			hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2382 			hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2383 		}
2384 		hdr_old.bh_datalen = pktlen;
2385 		hdr_old.bh_hdrlen = hdrlen;
2386 		hdr_old.bh_caplen = caplen;
2387 		bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2388 		    sizeof(hdr_old));
2389 		goto copy;
2390 	}
2391 #endif
2392 
2393 	/*
2394 	 * Append the bpf header.  Note we append the actual header size, but
2395 	 * move forward the length of the header plus padding.
2396 	 */
2397 	bzero(&hdr, sizeof(hdr));
2398 	if (do_timestamp)
2399 		bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2400 	hdr.bh_datalen = pktlen;
2401 	hdr.bh_hdrlen = hdrlen;
2402 	hdr.bh_caplen = caplen;
2403 	bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2404 
2405 	/*
2406 	 * Copy the packet data into the store buffer and update its length.
2407 	 */
2408 #ifndef BURN_BRIDGES
2409 copy:
2410 #endif
2411 	(*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2412 	d->bd_slen = curlen + totlen;
2413 
2414 	if (do_wakeup)
2415 		bpf_wakeup(d);
2416 }
2417 
2418 /*
2419  * Free buffers currently in use by a descriptor.
2420  * Called on close.
2421  */
2422 static void
2423 bpf_freed(struct bpf_d *d)
2424 {
2425 
2426 	/*
2427 	 * We don't need to lock out interrupts since this descriptor has
2428 	 * been detached from its interface and it yet hasn't been marked
2429 	 * free.
2430 	 */
2431 	bpf_free(d);
2432 	if (d->bd_rfilter != NULL) {
2433 		free((caddr_t)d->bd_rfilter, M_BPF);
2434 #ifdef BPF_JITTER
2435 		if (d->bd_bfilter != NULL)
2436 			bpf_destroy_jit_filter(d->bd_bfilter);
2437 #endif
2438 	}
2439 	if (d->bd_wfilter != NULL)
2440 		free((caddr_t)d->bd_wfilter, M_BPF);
2441 	mtx_destroy(&d->bd_lock);
2442 }
2443 
2444 /*
2445  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
2446  * fixed size of the link header (variable length headers not yet supported).
2447  */
2448 void
2449 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2450 {
2451 
2452 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2453 }
2454 
2455 /*
2456  * Attach an interface to bpf.  ifp is a pointer to the structure
2457  * defining the interface to be attached, dlt is the link layer type,
2458  * and hdrlen is the fixed size of the link header (variable length
2459  * headers are not yet supporrted).
2460  */
2461 void
2462 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2463 {
2464 	struct bpf_if *bp;
2465 
2466 	bp = malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
2467 	if (bp == NULL)
2468 		panic("bpfattach");
2469 
2470 	LIST_INIT(&bp->bif_dlist);
2471 	LIST_INIT(&bp->bif_wlist);
2472 	bp->bif_ifp = ifp;
2473 	bp->bif_dlt = dlt;
2474 	rw_init(&bp->bif_lock, "bpf interface lock");
2475 	KASSERT(*driverp == NULL, ("bpfattach2: driverp already initialized"));
2476 	*driverp = bp;
2477 
2478 	BPF_LOCK();
2479 	LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2480 	BPF_UNLOCK();
2481 
2482 	bp->bif_hdrlen = hdrlen;
2483 
2484 	if (bootverbose)
2485 		if_printf(ifp, "bpf attached\n");
2486 }
2487 
2488 /*
2489  * Detach bpf from an interface. This involves detaching each descriptor
2490  * associated with the interface. Notify each descriptor as it's detached
2491  * so that any sleepers wake up and get ENXIO.
2492  */
2493 void
2494 bpfdetach(struct ifnet *ifp)
2495 {
2496 	struct bpf_if	*bp, *bp_temp;
2497 	struct bpf_d	*d;
2498 	int ndetached;
2499 
2500 	ndetached = 0;
2501 
2502 	BPF_LOCK();
2503 	/* Find all bpf_if struct's which reference ifp and detach them. */
2504 	LIST_FOREACH_SAFE(bp, &bpf_iflist, bif_next, bp_temp) {
2505 		if (ifp != bp->bif_ifp)
2506 			continue;
2507 
2508 		LIST_REMOVE(bp, bif_next);
2509 		/* Add to to-be-freed list */
2510 		LIST_INSERT_HEAD(&bpf_freelist, bp, bif_next);
2511 
2512 		ndetached++;
2513 		/*
2514 		 * Delay freeing bp till interface is detached
2515 		 * and all routes through this interface are removed.
2516 		 * Mark bp as detached to restrict new consumers.
2517 		 */
2518 		BPFIF_WLOCK(bp);
2519 		bp->flags |= BPFIF_FLAG_DYING;
2520 		BPFIF_WUNLOCK(bp);
2521 
2522 		CTR4(KTR_NET, "%s: sheduling free for encap %d (%p) for if %p",
2523 		    __func__, bp->bif_dlt, bp, ifp);
2524 
2525 		/* Free common descriptors */
2526 		while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
2527 			bpf_detachd_locked(d);
2528 			BPFD_LOCK(d);
2529 			bpf_wakeup(d);
2530 			BPFD_UNLOCK(d);
2531 		}
2532 
2533 		/* Free writer-only descriptors */
2534 		while ((d = LIST_FIRST(&bp->bif_wlist)) != NULL) {
2535 			bpf_detachd_locked(d);
2536 			BPFD_LOCK(d);
2537 			bpf_wakeup(d);
2538 			BPFD_UNLOCK(d);
2539 		}
2540 	}
2541 	BPF_UNLOCK();
2542 
2543 #ifdef INVARIANTS
2544 	if (ndetached == 0)
2545 		printf("bpfdetach: %s was not attached\n", ifp->if_xname);
2546 #endif
2547 }
2548 
2549 /*
2550  * Interface departure handler.
2551  * Note departure event does not guarantee interface is going down.
2552  * Interface renaming is currently done via departure/arrival event set.
2553  *
2554  * Departure handled is called after all routes pointing to
2555  * given interface are removed and interface is in down state
2556  * restricting any packets to be sent/received. We assume it is now safe
2557  * to free data allocated by BPF.
2558  */
2559 static void
2560 bpf_ifdetach(void *arg __unused, struct ifnet *ifp)
2561 {
2562 	struct bpf_if *bp, *bp_temp;
2563 	int nmatched = 0;
2564 
2565 	BPF_LOCK();
2566 	/*
2567 	 * Find matching entries in free list.
2568 	 * Nothing should be found if bpfdetach() was not called.
2569 	 */
2570 	LIST_FOREACH_SAFE(bp, &bpf_freelist, bif_next, bp_temp) {
2571 		if (ifp != bp->bif_ifp)
2572 			continue;
2573 
2574 		CTR3(KTR_NET, "%s: freeing BPF instance %p for interface %p",
2575 		    __func__, bp, ifp);
2576 
2577 		LIST_REMOVE(bp, bif_next);
2578 
2579 		rw_destroy(&bp->bif_lock);
2580 		free(bp, M_BPF);
2581 
2582 		nmatched++;
2583 	}
2584 	BPF_UNLOCK();
2585 
2586 	/*
2587 	 * Note that we cannot zero other pointers to
2588 	 * custom DLTs possibly used by given interface.
2589 	 */
2590 	if (nmatched != 0)
2591 		ifp->if_bpf = NULL;
2592 }
2593 
2594 /*
2595  * Get a list of available data link type of the interface.
2596  */
2597 static int
2598 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2599 {
2600 	int n, error;
2601 	struct ifnet *ifp;
2602 	struct bpf_if *bp;
2603 
2604 	BPF_LOCK_ASSERT();
2605 
2606 	ifp = d->bd_bif->bif_ifp;
2607 	n = 0;
2608 	error = 0;
2609 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2610 		if (bp->bif_ifp != ifp)
2611 			continue;
2612 		if (bfl->bfl_list != NULL) {
2613 			if (n >= bfl->bfl_len)
2614 				return (ENOMEM);
2615 			error = copyout(&bp->bif_dlt,
2616 			    bfl->bfl_list + n, sizeof(u_int));
2617 		}
2618 		n++;
2619 	}
2620 	bfl->bfl_len = n;
2621 	return (error);
2622 }
2623 
2624 /*
2625  * Set the data link type of a BPF instance.
2626  */
2627 static int
2628 bpf_setdlt(struct bpf_d *d, u_int dlt)
2629 {
2630 	int error, opromisc;
2631 	struct ifnet *ifp;
2632 	struct bpf_if *bp;
2633 
2634 	BPF_LOCK_ASSERT();
2635 
2636 	if (d->bd_bif->bif_dlt == dlt)
2637 		return (0);
2638 	ifp = d->bd_bif->bif_ifp;
2639 
2640 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2641 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2642 			break;
2643 	}
2644 
2645 	if (bp != NULL) {
2646 		opromisc = d->bd_promisc;
2647 		bpf_attachd(d, bp);
2648 		BPFD_LOCK(d);
2649 		reset_d(d);
2650 		BPFD_UNLOCK(d);
2651 		if (opromisc) {
2652 			error = ifpromisc(bp->bif_ifp, 1);
2653 			if (error)
2654 				if_printf(bp->bif_ifp,
2655 					"bpf_setdlt: ifpromisc failed (%d)\n",
2656 					error);
2657 			else
2658 				d->bd_promisc = 1;
2659 		}
2660 	}
2661 	return (bp == NULL ? EINVAL : 0);
2662 }
2663 
2664 static void
2665 bpf_drvinit(void *unused)
2666 {
2667 	struct cdev *dev;
2668 
2669 	mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
2670 	LIST_INIT(&bpf_iflist);
2671 	LIST_INIT(&bpf_freelist);
2672 
2673 	dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2674 	/* For compatibility */
2675 	make_dev_alias(dev, "bpf0");
2676 
2677 	/* Register interface departure handler */
2678 	bpf_ifdetach_cookie = EVENTHANDLER_REGISTER(
2679 		    ifnet_departure_event, bpf_ifdetach, NULL,
2680 		    EVENTHANDLER_PRI_ANY);
2681 }
2682 
2683 /*
2684  * Zero out the various packet counters associated with all of the bpf
2685  * descriptors.  At some point, we will probably want to get a bit more
2686  * granular and allow the user to specify descriptors to be zeroed.
2687  */
2688 static void
2689 bpf_zero_counters(void)
2690 {
2691 	struct bpf_if *bp;
2692 	struct bpf_d *bd;
2693 
2694 	BPF_LOCK();
2695 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2696 		BPFIF_RLOCK(bp);
2697 		LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2698 			BPFD_LOCK(bd);
2699 			bd->bd_rcount = 0;
2700 			bd->bd_dcount = 0;
2701 			bd->bd_fcount = 0;
2702 			bd->bd_wcount = 0;
2703 			bd->bd_wfcount = 0;
2704 			bd->bd_zcopy = 0;
2705 			BPFD_UNLOCK(bd);
2706 		}
2707 		BPFIF_RUNLOCK(bp);
2708 	}
2709 	BPF_UNLOCK();
2710 }
2711 
2712 /*
2713  * Fill filter statistics
2714  */
2715 static void
2716 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2717 {
2718 
2719 	bzero(d, sizeof(*d));
2720 	BPFD_LOCK_ASSERT(bd);
2721 	d->bd_structsize = sizeof(*d);
2722 	/* XXX: reading should be protected by global lock */
2723 	d->bd_immediate = bd->bd_immediate;
2724 	d->bd_promisc = bd->bd_promisc;
2725 	d->bd_hdrcmplt = bd->bd_hdrcmplt;
2726 	d->bd_direction = bd->bd_direction;
2727 	d->bd_feedback = bd->bd_feedback;
2728 	d->bd_async = bd->bd_async;
2729 	d->bd_rcount = bd->bd_rcount;
2730 	d->bd_dcount = bd->bd_dcount;
2731 	d->bd_fcount = bd->bd_fcount;
2732 	d->bd_sig = bd->bd_sig;
2733 	d->bd_slen = bd->bd_slen;
2734 	d->bd_hlen = bd->bd_hlen;
2735 	d->bd_bufsize = bd->bd_bufsize;
2736 	d->bd_pid = bd->bd_pid;
2737 	strlcpy(d->bd_ifname,
2738 	    bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2739 	d->bd_locked = bd->bd_locked;
2740 	d->bd_wcount = bd->bd_wcount;
2741 	d->bd_wdcount = bd->bd_wdcount;
2742 	d->bd_wfcount = bd->bd_wfcount;
2743 	d->bd_zcopy = bd->bd_zcopy;
2744 	d->bd_bufmode = bd->bd_bufmode;
2745 }
2746 
2747 /*
2748  * Handle `netstat -B' stats request
2749  */
2750 static int
2751 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2752 {
2753 	struct xbpf_d *xbdbuf, *xbd, zerostats;
2754 	int index, error;
2755 	struct bpf_if *bp;
2756 	struct bpf_d *bd;
2757 
2758 	/*
2759 	 * XXX This is not technically correct. It is possible for non
2760 	 * privileged users to open bpf devices. It would make sense
2761 	 * if the users who opened the devices were able to retrieve
2762 	 * the statistics for them, too.
2763 	 */
2764 	error = priv_check(req->td, PRIV_NET_BPF);
2765 	if (error)
2766 		return (error);
2767 	/*
2768 	 * Check to see if the user is requesting that the counters be
2769 	 * zeroed out.  Explicitly check that the supplied data is zeroed,
2770 	 * as we aren't allowing the user to set the counters currently.
2771 	 */
2772 	if (req->newptr != NULL) {
2773 		if (req->newlen != sizeof(zerostats))
2774 			return (EINVAL);
2775 		bzero(&zerostats, sizeof(zerostats));
2776 		xbd = req->newptr;
2777 		if (bcmp(xbd, &zerostats, sizeof(*xbd)) != 0)
2778 			return (EINVAL);
2779 		bpf_zero_counters();
2780 		return (0);
2781 	}
2782 	if (req->oldptr == NULL)
2783 		return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
2784 	if (bpf_bpfd_cnt == 0)
2785 		return (SYSCTL_OUT(req, 0, 0));
2786 	xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
2787 	BPF_LOCK();
2788 	if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
2789 		BPF_UNLOCK();
2790 		free(xbdbuf, M_BPF);
2791 		return (ENOMEM);
2792 	}
2793 	index = 0;
2794 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2795 		BPFIF_RLOCK(bp);
2796 		/* Send writers-only first */
2797 		LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
2798 			xbd = &xbdbuf[index++];
2799 			BPFD_LOCK(bd);
2800 			bpfstats_fill_xbpf(xbd, bd);
2801 			BPFD_UNLOCK(bd);
2802 		}
2803 		LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2804 			xbd = &xbdbuf[index++];
2805 			BPFD_LOCK(bd);
2806 			bpfstats_fill_xbpf(xbd, bd);
2807 			BPFD_UNLOCK(bd);
2808 		}
2809 		BPFIF_RUNLOCK(bp);
2810 	}
2811 	BPF_UNLOCK();
2812 	error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
2813 	free(xbdbuf, M_BPF);
2814 	return (error);
2815 }
2816 
2817 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
2818 
2819 #else /* !DEV_BPF && !NETGRAPH_BPF */
2820 /*
2821  * NOP stubs to allow bpf-using drivers to load and function.
2822  *
2823  * A 'better' implementation would allow the core bpf functionality
2824  * to be loaded at runtime.
2825  */
2826 static struct bpf_if bp_null;
2827 
2828 void
2829 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2830 {
2831 }
2832 
2833 void
2834 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2835 {
2836 }
2837 
2838 void
2839 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
2840 {
2841 }
2842 
2843 void
2844 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2845 {
2846 
2847 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2848 }
2849 
2850 void
2851 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2852 {
2853 
2854 	*driverp = &bp_null;
2855 }
2856 
2857 void
2858 bpfdetach(struct ifnet *ifp)
2859 {
2860 }
2861 
2862 u_int
2863 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
2864 {
2865 	return -1;	/* "no filter" behaviour */
2866 }
2867 
2868 int
2869 bpf_validate(const struct bpf_insn *f, int len)
2870 {
2871 	return 0;		/* false */
2872 }
2873 
2874 #endif /* !DEV_BPF && !NETGRAPH_BPF */
2875