xref: /freebsd/sys/net/bpf.c (revision ca9ac06c99bfd0150b85d4d83c396ce6237c0e05)
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  * $FreeBSD$
37  */
38 
39 #include "opt_bpf.h"
40 #include "opt_mac.h"
41 #include "opt_netgraph.h"
42 
43 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/conf.h>
47 #include <sys/fcntl.h>
48 #include <sys/mac.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/time.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/filio.h>
55 #include <sys/sockio.h>
56 #include <sys/ttycom.h>
57 #include <sys/uio.h>
58 
59 #include <sys/event.h>
60 #include <sys/file.h>
61 #include <sys/poll.h>
62 #include <sys/proc.h>
63 
64 #include <sys/socket.h>
65 
66 #include <net/if.h>
67 #include <net/bpf.h>
68 #include <net/bpfdesc.h>
69 
70 #include <netinet/in.h>
71 #include <netinet/if_ether.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
74 
75 static MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
76 
77 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
78 
79 #define PRINET  26			/* interruptible */
80 
81 /*
82  * The default read buffer size is patchable.
83  */
84 static int bpf_bufsize = 4096;
85 SYSCTL_INT(_debug, OID_AUTO, bpf_bufsize, CTLFLAG_RW,
86 	&bpf_bufsize, 0, "");
87 static int bpf_maxbufsize = BPF_MAXBUFSIZE;
88 SYSCTL_INT(_debug, OID_AUTO, bpf_maxbufsize, CTLFLAG_RW,
89 	&bpf_maxbufsize, 0, "");
90 
91 /*
92  * bpf_iflist is a list of BPF interface structures, each corresponding to a
93  * specific DLT.  The same network interface might have several BPF interface
94  * structures registered by different layers in the stack (i.e., 802.11
95  * frames, ethernet frames, etc).
96  */
97 static LIST_HEAD(, bpf_if)	bpf_iflist;
98 static struct mtx	bpf_mtx;		/* bpf global lock */
99 
100 static int	bpf_allocbufs(struct bpf_d *);
101 static void	bpf_attachd(struct bpf_d *d, struct bpf_if *bp);
102 static void	bpf_detachd(struct bpf_d *d);
103 static void	bpf_freed(struct bpf_d *);
104 static void	bpf_mcopy(const void *, void *, size_t);
105 static int	bpf_movein(struct uio *, int,
106 		    struct mbuf **, struct sockaddr *, int *);
107 static int	bpf_setif(struct bpf_d *, struct ifreq *);
108 static void	bpf_timed_out(void *);
109 static __inline void
110 		bpf_wakeup(struct bpf_d *);
111 static void	catchpacket(struct bpf_d *, u_char *, u_int,
112 		    u_int, void (*)(const void *, void *, size_t));
113 static void	reset_d(struct bpf_d *);
114 static int	 bpf_setf(struct bpf_d *, struct bpf_program *);
115 static int	bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
116 static int	bpf_setdlt(struct bpf_d *, u_int);
117 static void	filt_bpfdetach(struct knote *);
118 static int	filt_bpfread(struct knote *, long);
119 
120 static	d_open_t	bpfopen;
121 static	d_close_t	bpfclose;
122 static	d_read_t	bpfread;
123 static	d_write_t	bpfwrite;
124 static	d_ioctl_t	bpfioctl;
125 static	d_poll_t	bpfpoll;
126 static	d_kqfilter_t	bpfkqfilter;
127 
128 static struct cdevsw bpf_cdevsw = {
129 	.d_version =	D_VERSION,
130 	.d_flags =	D_NEEDGIANT,
131 	.d_open =	bpfopen,
132 	.d_close =	bpfclose,
133 	.d_read =	bpfread,
134 	.d_write =	bpfwrite,
135 	.d_ioctl =	bpfioctl,
136 	.d_poll =	bpfpoll,
137 	.d_name =	"bpf",
138 	.d_kqfilter =	bpfkqfilter,
139 };
140 
141 static struct filterops bpfread_filtops =
142 	{ 1, NULL, filt_bpfdetach, filt_bpfread };
143 
144 static int
145 bpf_movein(uio, linktype, mp, sockp, datlen)
146 	struct uio *uio;
147 	int linktype, *datlen;
148 	struct mbuf **mp;
149 	struct sockaddr *sockp;
150 {
151 	struct mbuf *m;
152 	int error;
153 	int len;
154 	int hlen;
155 
156 	/*
157 	 * Build a sockaddr based on the data link layer type.
158 	 * We do this at this level because the ethernet header
159 	 * is copied directly into the data field of the sockaddr.
160 	 * In the case of SLIP, there is no header and the packet
161 	 * is forwarded as is.
162 	 * Also, we are careful to leave room at the front of the mbuf
163 	 * for the link level header.
164 	 */
165 	switch (linktype) {
166 
167 	case DLT_SLIP:
168 		sockp->sa_family = AF_INET;
169 		hlen = 0;
170 		break;
171 
172 	case DLT_EN10MB:
173 		sockp->sa_family = AF_UNSPEC;
174 		/* XXX Would MAXLINKHDR be better? */
175 		hlen = ETHER_HDR_LEN;
176 		break;
177 
178 	case DLT_FDDI:
179 		sockp->sa_family = AF_IMPLINK;
180 		hlen = 0;
181 		break;
182 
183 	case DLT_RAW:
184 	case DLT_NULL:
185 		sockp->sa_family = AF_UNSPEC;
186 		hlen = 0;
187 		break;
188 
189 	case DLT_ATM_RFC1483:
190 		/*
191 		 * en atm driver requires 4-byte atm pseudo header.
192 		 * though it isn't standard, vpi:vci needs to be
193 		 * specified anyway.
194 		 */
195 		sockp->sa_family = AF_UNSPEC;
196 		hlen = 12;	/* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
197 		break;
198 
199 	case DLT_PPP:
200 		sockp->sa_family = AF_UNSPEC;
201 		hlen = 4;	/* This should match PPP_HDRLEN */
202 		break;
203 
204 	default:
205 		return (EIO);
206 	}
207 
208 	len = uio->uio_resid;
209 	*datlen = len - hlen;
210 	if ((unsigned)len > MCLBYTES)
211 		return (EIO);
212 
213 	if (len > MHLEN) {
214 		m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
215 	} else {
216 		MGETHDR(m, M_TRYWAIT, MT_DATA);
217 	}
218 	if (m == NULL)
219 		return (ENOBUFS);
220 	m->m_pkthdr.len = m->m_len = len;
221 	m->m_pkthdr.rcvif = NULL;
222 	*mp = m;
223 
224 	/*
225 	 * Make room for link header.
226 	 */
227 	if (hlen != 0) {
228 		m->m_pkthdr.len -= hlen;
229 		m->m_len -= hlen;
230 #if BSD >= 199103
231 		m->m_data += hlen; /* XXX */
232 #else
233 		m->m_off += hlen;
234 #endif
235 		error = uiomove(sockp->sa_data, hlen, uio);
236 		if (error)
237 			goto bad;
238 	}
239 	error = uiomove(mtod(m, void *), len - hlen, uio);
240 	if (!error)
241 		return (0);
242 bad:
243 	m_freem(m);
244 	return (error);
245 }
246 
247 /*
248  * Attach file to the bpf interface, i.e. make d listen on bp.
249  */
250 static void
251 bpf_attachd(d, bp)
252 	struct bpf_d *d;
253 	struct bpf_if *bp;
254 {
255 	/*
256 	 * Point d at bp, and add d to the interface's list of listeners.
257 	 * Finally, point the driver's bpf cookie at the interface so
258 	 * it will divert packets to bpf.
259 	 */
260 	BPFIF_LOCK(bp);
261 	d->bd_bif = bp;
262 	LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
263 
264 	*bp->bif_driverp = bp;
265 	BPFIF_UNLOCK(bp);
266 }
267 
268 /*
269  * Detach a file from its interface.
270  */
271 static void
272 bpf_detachd(d)
273 	struct bpf_d *d;
274 {
275 	int error;
276 	struct bpf_if *bp;
277 	struct ifnet *ifp;
278 
279 	bp = d->bd_bif;
280 	BPFIF_LOCK(bp);
281 	BPFD_LOCK(d);
282 	ifp = d->bd_bif->bif_ifp;
283 
284 	/*
285 	 * Remove d from the interface's descriptor list.
286 	 */
287 	LIST_REMOVE(d, bd_next);
288 
289 	/*
290 	 * Let the driver know that there are no more listeners.
291 	 */
292 	if (LIST_EMPTY(&bp->bif_dlist))
293 		*bp->bif_driverp = NULL;
294 
295 	d->bd_bif = NULL;
296 	BPFD_UNLOCK(d);
297 	BPFIF_UNLOCK(bp);
298 
299 	/*
300 	 * Check if this descriptor had requested promiscuous mode.
301 	 * If so, turn it off.
302 	 */
303 	if (d->bd_promisc) {
304 		d->bd_promisc = 0;
305 		error = ifpromisc(ifp, 0);
306 		if (error != 0 && error != ENXIO) {
307 			/*
308 			 * ENXIO can happen if a pccard is unplugged
309 			 * Something is really wrong if we were able to put
310 			 * the driver into promiscuous mode, but can't
311 			 * take it out.
312 			 */
313 			if_printf(bp->bif_ifp,
314 				"bpf_detach: ifpromisc failed (%d)\n", error);
315 		}
316 	}
317 }
318 
319 /*
320  * Open ethernet device.  Returns ENXIO for illegal minor device number,
321  * EBUSY if file is open by another process.
322  */
323 /* ARGSUSED */
324 static	int
325 bpfopen(dev, flags, fmt, td)
326 	struct cdev *dev;
327 	int flags;
328 	int fmt;
329 	struct thread *td;
330 {
331 	struct bpf_d *d;
332 
333 	mtx_lock(&bpf_mtx);
334 	d = dev->si_drv1;
335 	/*
336 	 * Each minor can be opened by only one process.  If the requested
337 	 * minor is in use, return EBUSY.
338 	 */
339 	if (d != NULL) {
340 		mtx_unlock(&bpf_mtx);
341 		return (EBUSY);
342 	}
343 	dev->si_drv1 = (struct bpf_d *)~0;	/* mark device in use */
344 	mtx_unlock(&bpf_mtx);
345 
346 	if ((dev->si_flags & SI_NAMED) == 0)
347 		make_dev(&bpf_cdevsw, minor(dev), UID_ROOT, GID_WHEEL, 0600,
348 		    "bpf%d", dev2unit(dev));
349 	MALLOC(d, struct bpf_d *, sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
350 	dev->si_drv1 = d;
351 	d->bd_bufsize = bpf_bufsize;
352 	d->bd_sig = SIGIO;
353 	d->bd_seesent = 1;
354 #ifdef MAC
355 	mac_init_bpfdesc(d);
356 	mac_create_bpfdesc(td->td_ucred, d);
357 #endif
358 	mtx_init(&d->bd_mtx, devtoname(dev), "bpf cdev lock", MTX_DEF);
359 	callout_init(&d->bd_callout, NET_CALLOUT_MPSAFE);
360 	knlist_init(&d->bd_sel.si_note, &d->bd_mtx);
361 
362 	return (0);
363 }
364 
365 /*
366  * Close the descriptor by detaching it from its interface,
367  * deallocating its buffers, and marking it free.
368  */
369 /* ARGSUSED */
370 static	int
371 bpfclose(dev, flags, fmt, td)
372 	struct cdev *dev;
373 	int flags;
374 	int fmt;
375 	struct thread *td;
376 {
377 	struct bpf_d *d = dev->si_drv1;
378 
379 	BPFD_LOCK(d);
380 	if (d->bd_state == BPF_WAITING)
381 		callout_stop(&d->bd_callout);
382 	d->bd_state = BPF_IDLE;
383 	BPFD_UNLOCK(d);
384 	funsetown(&d->bd_sigio);
385 	mtx_lock(&bpf_mtx);
386 	if (d->bd_bif)
387 		bpf_detachd(d);
388 	mtx_unlock(&bpf_mtx);
389 #ifdef MAC
390 	mac_destroy_bpfdesc(d);
391 #endif /* MAC */
392 	knlist_destroy(&d->bd_sel.si_note);
393 	bpf_freed(d);
394 	dev->si_drv1 = NULL;
395 	free(d, M_BPF);
396 
397 	return (0);
398 }
399 
400 
401 /*
402  * Rotate the packet buffers in descriptor d.  Move the store buffer
403  * into the hold slot, and the free buffer into the store slot.
404  * Zero the length of the new store buffer.
405  */
406 #define ROTATE_BUFFERS(d) \
407 	(d)->bd_hbuf = (d)->bd_sbuf; \
408 	(d)->bd_hlen = (d)->bd_slen; \
409 	(d)->bd_sbuf = (d)->bd_fbuf; \
410 	(d)->bd_slen = 0; \
411 	(d)->bd_fbuf = NULL;
412 /*
413  *  bpfread - read next chunk of packets from buffers
414  */
415 static	int
416 bpfread(dev, uio, ioflag)
417 	struct cdev *dev;
418 	struct uio *uio;
419 	int ioflag;
420 {
421 	struct bpf_d *d = dev->si_drv1;
422 	int timed_out;
423 	int error;
424 
425 	/*
426 	 * Restrict application to use a buffer the same size as
427 	 * as kernel buffers.
428 	 */
429 	if (uio->uio_resid != d->bd_bufsize)
430 		return (EINVAL);
431 
432 	BPFD_LOCK(d);
433 	if (d->bd_state == BPF_WAITING)
434 		callout_stop(&d->bd_callout);
435 	timed_out = (d->bd_state == BPF_TIMED_OUT);
436 	d->bd_state = BPF_IDLE;
437 	/*
438 	 * If the hold buffer is empty, then do a timed sleep, which
439 	 * ends when the timeout expires or when enough packets
440 	 * have arrived to fill the store buffer.
441 	 */
442 	while (d->bd_hbuf == NULL) {
443 		if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
444 			/*
445 			 * A packet(s) either arrived since the previous
446 			 * read or arrived while we were asleep.
447 			 * Rotate the buffers and return what's here.
448 			 */
449 			ROTATE_BUFFERS(d);
450 			break;
451 		}
452 
453 		/*
454 		 * No data is available, check to see if the bpf device
455 		 * is still pointed at a real interface.  If not, return
456 		 * ENXIO so that the userland process knows to rebind
457 		 * it before using it again.
458 		 */
459 		if (d->bd_bif == NULL) {
460 			BPFD_UNLOCK(d);
461 			return (ENXIO);
462 		}
463 
464 		if (ioflag & O_NONBLOCK) {
465 			BPFD_UNLOCK(d);
466 			return (EWOULDBLOCK);
467 		}
468 		error = msleep(d, &d->bd_mtx, PRINET|PCATCH,
469 		     "bpf", d->bd_rtout);
470 		if (error == EINTR || error == ERESTART) {
471 			BPFD_UNLOCK(d);
472 			return (error);
473 		}
474 		if (error == EWOULDBLOCK) {
475 			/*
476 			 * On a timeout, return what's in the buffer,
477 			 * which may be nothing.  If there is something
478 			 * in the store buffer, we can rotate the buffers.
479 			 */
480 			if (d->bd_hbuf)
481 				/*
482 				 * We filled up the buffer in between
483 				 * getting the timeout and arriving
484 				 * here, so we don't need to rotate.
485 				 */
486 				break;
487 
488 			if (d->bd_slen == 0) {
489 				BPFD_UNLOCK(d);
490 				return (0);
491 			}
492 			ROTATE_BUFFERS(d);
493 			break;
494 		}
495 	}
496 	/*
497 	 * At this point, we know we have something in the hold slot.
498 	 */
499 	BPFD_UNLOCK(d);
500 
501 	/*
502 	 * Move data from hold buffer into user space.
503 	 * We know the entire buffer is transferred since
504 	 * we checked above that the read buffer is bpf_bufsize bytes.
505 	 */
506 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
507 
508 	BPFD_LOCK(d);
509 	d->bd_fbuf = d->bd_hbuf;
510 	d->bd_hbuf = NULL;
511 	d->bd_hlen = 0;
512 	BPFD_UNLOCK(d);
513 
514 	return (error);
515 }
516 
517 
518 /*
519  * If there are processes sleeping on this descriptor, wake them up.
520  */
521 static __inline void
522 bpf_wakeup(d)
523 	struct bpf_d *d;
524 {
525 	if (d->bd_state == BPF_WAITING) {
526 		callout_stop(&d->bd_callout);
527 		d->bd_state = BPF_IDLE;
528 	}
529 	wakeup(d);
530 	if (d->bd_async && d->bd_sig && d->bd_sigio)
531 		pgsigio(&d->bd_sigio, d->bd_sig, 0);
532 
533 	selwakeuppri(&d->bd_sel, PRINET);
534 	KNOTE_LOCKED(&d->bd_sel.si_note, 0);
535 }
536 
537 static void
538 bpf_timed_out(arg)
539 	void *arg;
540 {
541 	struct bpf_d *d = (struct bpf_d *)arg;
542 
543 	BPFD_LOCK(d);
544 	if (d->bd_state == BPF_WAITING) {
545 		d->bd_state = BPF_TIMED_OUT;
546 		if (d->bd_slen != 0)
547 			bpf_wakeup(d);
548 	}
549 	BPFD_UNLOCK(d);
550 }
551 
552 static	int
553 bpfwrite(dev, uio, ioflag)
554 	struct cdev *dev;
555 	struct uio *uio;
556 	int ioflag;
557 {
558 	struct bpf_d *d = dev->si_drv1;
559 	struct ifnet *ifp;
560 	struct mbuf *m;
561 	int error;
562 	struct sockaddr dst;
563 	int datlen;
564 
565 	if (d->bd_bif == NULL)
566 		return (ENXIO);
567 
568 	ifp = d->bd_bif->bif_ifp;
569 
570 	if ((ifp->if_flags & IFF_UP) == 0)
571 		return (ENETDOWN);
572 
573 	if (uio->uio_resid == 0)
574 		return (0);
575 
576 	bzero(&dst, sizeof(dst));
577 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, &m, &dst, &datlen);
578 	if (error)
579 		return (error);
580 
581 	if (datlen > ifp->if_mtu) {
582 		m_freem(m);
583 		return (EMSGSIZE);
584 	}
585 
586 	if (d->bd_hdrcmplt)
587 		dst.sa_family = pseudo_AF_HDRCMPLT;
588 
589 #ifdef MAC
590 	BPFD_LOCK(d);
591 	mac_create_mbuf_from_bpfdesc(d, m);
592 	BPFD_UNLOCK(d);
593 #endif
594 	NET_LOCK_GIANT();
595 	error = (*ifp->if_output)(ifp, m, &dst, NULL);
596 	NET_UNLOCK_GIANT();
597 	/*
598 	 * The driver frees the mbuf.
599 	 */
600 	return (error);
601 }
602 
603 /*
604  * Reset a descriptor by flushing its packet buffer and clearing the
605  * receive and drop counts.
606  */
607 static void
608 reset_d(d)
609 	struct bpf_d *d;
610 {
611 
612 	mtx_assert(&d->bd_mtx, MA_OWNED);
613 	if (d->bd_hbuf) {
614 		/* Free the hold buffer. */
615 		d->bd_fbuf = d->bd_hbuf;
616 		d->bd_hbuf = NULL;
617 	}
618 	d->bd_slen = 0;
619 	d->bd_hlen = 0;
620 	d->bd_rcount = 0;
621 	d->bd_dcount = 0;
622 }
623 
624 /*
625  *  FIONREAD		Check for read packet available.
626  *  SIOCGIFADDR		Get interface address - convenient hook to driver.
627  *  BIOCGBLEN		Get buffer len [for read()].
628  *  BIOCSETF		Set ethernet read filter.
629  *  BIOCFLUSH		Flush read packet buffer.
630  *  BIOCPROMISC		Put interface into promiscuous mode.
631  *  BIOCGDLT		Get link layer type.
632  *  BIOCGETIF		Get interface name.
633  *  BIOCSETIF		Set interface.
634  *  BIOCSRTIMEOUT	Set read timeout.
635  *  BIOCGRTIMEOUT	Get read timeout.
636  *  BIOCGSTATS		Get packet stats.
637  *  BIOCIMMEDIATE	Set immediate mode.
638  *  BIOCVERSION		Get filter language version.
639  *  BIOCGHDRCMPLT	Get "header already complete" flag
640  *  BIOCSHDRCMPLT	Set "header already complete" flag
641  *  BIOCGSEESENT	Get "see packets sent" flag
642  *  BIOCSSEESENT	Set "see packets sent" flag
643  */
644 /* ARGSUSED */
645 static	int
646 bpfioctl(dev, cmd, addr, flags, td)
647 	struct cdev *dev;
648 	u_long cmd;
649 	caddr_t addr;
650 	int flags;
651 	struct thread *td;
652 {
653 	struct bpf_d *d = dev->si_drv1;
654 	int error = 0;
655 
656 	BPFD_LOCK(d);
657 	if (d->bd_state == BPF_WAITING)
658 		callout_stop(&d->bd_callout);
659 	d->bd_state = BPF_IDLE;
660 	BPFD_UNLOCK(d);
661 
662 	switch (cmd) {
663 
664 	default:
665 		error = EINVAL;
666 		break;
667 
668 	/*
669 	 * Check for read packet available.
670 	 */
671 	case FIONREAD:
672 		{
673 			int n;
674 
675 			BPFD_LOCK(d);
676 			n = d->bd_slen;
677 			if (d->bd_hbuf)
678 				n += d->bd_hlen;
679 			BPFD_UNLOCK(d);
680 
681 			*(int *)addr = n;
682 			break;
683 		}
684 
685 	case SIOCGIFADDR:
686 		{
687 			struct ifnet *ifp;
688 
689 			if (d->bd_bif == NULL)
690 				error = EINVAL;
691 			else {
692 				ifp = d->bd_bif->bif_ifp;
693 				error = (*ifp->if_ioctl)(ifp, cmd, addr);
694 			}
695 			break;
696 		}
697 
698 	/*
699 	 * Get buffer len [for read()].
700 	 */
701 	case BIOCGBLEN:
702 		*(u_int *)addr = d->bd_bufsize;
703 		break;
704 
705 	/*
706 	 * Set buffer length.
707 	 */
708 	case BIOCSBLEN:
709 		if (d->bd_bif != NULL)
710 			error = EINVAL;
711 		else {
712 			u_int size = *(u_int *)addr;
713 
714 			if (size > bpf_maxbufsize)
715 				*(u_int *)addr = size = bpf_maxbufsize;
716 			else if (size < BPF_MINBUFSIZE)
717 				*(u_int *)addr = size = BPF_MINBUFSIZE;
718 			d->bd_bufsize = size;
719 		}
720 		break;
721 
722 	/*
723 	 * Set link layer read filter.
724 	 */
725 	case BIOCSETF:
726 		error = bpf_setf(d, (struct bpf_program *)addr);
727 		break;
728 
729 	/*
730 	 * Flush read packet buffer.
731 	 */
732 	case BIOCFLUSH:
733 		BPFD_LOCK(d);
734 		reset_d(d);
735 		BPFD_UNLOCK(d);
736 		break;
737 
738 	/*
739 	 * Put interface into promiscuous mode.
740 	 */
741 	case BIOCPROMISC:
742 		if (d->bd_bif == NULL) {
743 			/*
744 			 * No interface attached yet.
745 			 */
746 			error = EINVAL;
747 			break;
748 		}
749 		if (d->bd_promisc == 0) {
750 			mtx_lock(&Giant);
751 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
752 			mtx_unlock(&Giant);
753 			if (error == 0)
754 				d->bd_promisc = 1;
755 		}
756 		break;
757 
758 	/*
759 	 * Get current data link type.
760 	 */
761 	case BIOCGDLT:
762 		if (d->bd_bif == NULL)
763 			error = EINVAL;
764 		else
765 			*(u_int *)addr = d->bd_bif->bif_dlt;
766 		break;
767 
768 	/*
769 	 * Get a list of supported data link types.
770 	 */
771 	case BIOCGDLTLIST:
772 		if (d->bd_bif == NULL)
773 			error = EINVAL;
774 		else
775 			error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
776 		break;
777 
778 	/*
779 	 * Set data link type.
780 	 */
781 	case BIOCSDLT:
782 		if (d->bd_bif == NULL)
783 			error = EINVAL;
784 		else
785 			error = bpf_setdlt(d, *(u_int *)addr);
786 		break;
787 
788 	/*
789 	 * Get interface name.
790 	 */
791 	case BIOCGETIF:
792 		if (d->bd_bif == NULL)
793 			error = EINVAL;
794 		else {
795 			struct ifnet *const ifp = d->bd_bif->bif_ifp;
796 			struct ifreq *const ifr = (struct ifreq *)addr;
797 
798 			strlcpy(ifr->ifr_name, ifp->if_xname,
799 			    sizeof(ifr->ifr_name));
800 		}
801 		break;
802 
803 	/*
804 	 * Set interface.
805 	 */
806 	case BIOCSETIF:
807 		error = bpf_setif(d, (struct ifreq *)addr);
808 		break;
809 
810 	/*
811 	 * Set read timeout.
812 	 */
813 	case BIOCSRTIMEOUT:
814 		{
815 			struct timeval *tv = (struct timeval *)addr;
816 
817 			/*
818 			 * Subtract 1 tick from tvtohz() since this isn't
819 			 * a one-shot timer.
820 			 */
821 			if ((error = itimerfix(tv)) == 0)
822 				d->bd_rtout = tvtohz(tv) - 1;
823 			break;
824 		}
825 
826 	/*
827 	 * Get read timeout.
828 	 */
829 	case BIOCGRTIMEOUT:
830 		{
831 			struct timeval *tv = (struct timeval *)addr;
832 
833 			tv->tv_sec = d->bd_rtout / hz;
834 			tv->tv_usec = (d->bd_rtout % hz) * tick;
835 			break;
836 		}
837 
838 	/*
839 	 * Get packet stats.
840 	 */
841 	case BIOCGSTATS:
842 		{
843 			struct bpf_stat *bs = (struct bpf_stat *)addr;
844 
845 			bs->bs_recv = d->bd_rcount;
846 			bs->bs_drop = d->bd_dcount;
847 			break;
848 		}
849 
850 	/*
851 	 * Set immediate mode.
852 	 */
853 	case BIOCIMMEDIATE:
854 		d->bd_immediate = *(u_int *)addr;
855 		break;
856 
857 	case BIOCVERSION:
858 		{
859 			struct bpf_version *bv = (struct bpf_version *)addr;
860 
861 			bv->bv_major = BPF_MAJOR_VERSION;
862 			bv->bv_minor = BPF_MINOR_VERSION;
863 			break;
864 		}
865 
866 	/*
867 	 * Get "header already complete" flag
868 	 */
869 	case BIOCGHDRCMPLT:
870 		*(u_int *)addr = d->bd_hdrcmplt;
871 		break;
872 
873 	/*
874 	 * Set "header already complete" flag
875 	 */
876 	case BIOCSHDRCMPLT:
877 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
878 		break;
879 
880 	/*
881 	 * Get "see sent packets" flag
882 	 */
883 	case BIOCGSEESENT:
884 		*(u_int *)addr = d->bd_seesent;
885 		break;
886 
887 	/*
888 	 * Set "see sent packets" flag
889 	 */
890 	case BIOCSSEESENT:
891 		d->bd_seesent = *(u_int *)addr;
892 		break;
893 
894 	case FIONBIO:		/* Non-blocking I/O */
895 		break;
896 
897 	case FIOASYNC:		/* Send signal on receive packets */
898 		d->bd_async = *(int *)addr;
899 		break;
900 
901 	case FIOSETOWN:
902 		error = fsetown(*(int *)addr, &d->bd_sigio);
903 		break;
904 
905 	case FIOGETOWN:
906 		*(int *)addr = fgetown(&d->bd_sigio);
907 		break;
908 
909 	/* This is deprecated, FIOSETOWN should be used instead. */
910 	case TIOCSPGRP:
911 		error = fsetown(-(*(int *)addr), &d->bd_sigio);
912 		break;
913 
914 	/* This is deprecated, FIOGETOWN should be used instead. */
915 	case TIOCGPGRP:
916 		*(int *)addr = -fgetown(&d->bd_sigio);
917 		break;
918 
919 	case BIOCSRSIG:		/* Set receive signal */
920 		{
921 			u_int sig;
922 
923 			sig = *(u_int *)addr;
924 
925 			if (sig >= NSIG)
926 				error = EINVAL;
927 			else
928 				d->bd_sig = sig;
929 			break;
930 		}
931 	case BIOCGRSIG:
932 		*(u_int *)addr = d->bd_sig;
933 		break;
934 	}
935 	return (error);
936 }
937 
938 /*
939  * Set d's packet filter program to fp.  If this file already has a filter,
940  * free it and replace it.  Returns EINVAL for bogus requests.
941  */
942 static int
943 bpf_setf(d, fp)
944 	struct bpf_d *d;
945 	struct bpf_program *fp;
946 {
947 	struct bpf_insn *fcode, *old;
948 	u_int flen, size;
949 
950 	if (fp->bf_insns == NULL) {
951 		if (fp->bf_len != 0)
952 			return (EINVAL);
953 		BPFD_LOCK(d);
954 		old = d->bd_filter;
955 		d->bd_filter = NULL;
956 		reset_d(d);
957 		BPFD_UNLOCK(d);
958 		if (old != NULL)
959 			free((caddr_t)old, M_BPF);
960 		return (0);
961 	}
962 	flen = fp->bf_len;
963 	if (flen > BPF_MAXINSNS)
964 		return (EINVAL);
965 
966 	size = flen * sizeof(*fp->bf_insns);
967 	fcode = (struct bpf_insn *)malloc(size, M_BPF, M_WAITOK);
968 	if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) == 0 &&
969 	    bpf_validate(fcode, (int)flen)) {
970 		BPFD_LOCK(d);
971 		old = d->bd_filter;
972 		d->bd_filter = fcode;
973 		reset_d(d);
974 		BPFD_UNLOCK(d);
975 		if (old != NULL)
976 			free((caddr_t)old, M_BPF);
977 
978 		return (0);
979 	}
980 	free((caddr_t)fcode, M_BPF);
981 	return (EINVAL);
982 }
983 
984 /*
985  * Detach a file from its current interface (if attached at all) and attach
986  * to the interface indicated by the name stored in ifr.
987  * Return an errno or 0.
988  */
989 static int
990 bpf_setif(d, ifr)
991 	struct bpf_d *d;
992 	struct ifreq *ifr;
993 {
994 	struct bpf_if *bp;
995 	int error;
996 	struct ifnet *theywant;
997 
998 	theywant = ifunit(ifr->ifr_name);
999 	if (theywant == NULL)
1000 		return ENXIO;
1001 
1002 	/*
1003 	 * Look through attached interfaces for the named one.
1004 	 */
1005 	mtx_lock(&bpf_mtx);
1006 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1007 		struct ifnet *ifp = bp->bif_ifp;
1008 
1009 		if (ifp == NULL || ifp != theywant)
1010 			continue;
1011 		/* skip additional entry */
1012 		if (bp->bif_driverp != (struct bpf_if **)&ifp->if_bpf)
1013 			continue;
1014 
1015 		mtx_unlock(&bpf_mtx);
1016 		/*
1017 		 * We found the requested interface.
1018 		 * Allocate the packet buffers if we need to.
1019 		 * If we're already attached to requested interface,
1020 		 * just flush the buffer.
1021 		 */
1022 		if (d->bd_sbuf == NULL) {
1023 			error = bpf_allocbufs(d);
1024 			if (error != 0)
1025 				return (error);
1026 		}
1027 		if (bp != d->bd_bif) {
1028 			if (d->bd_bif)
1029 				/*
1030 				 * Detach if attached to something else.
1031 				 */
1032 				bpf_detachd(d);
1033 
1034 			bpf_attachd(d, bp);
1035 		}
1036 		BPFD_LOCK(d);
1037 		reset_d(d);
1038 		BPFD_UNLOCK(d);
1039 		return (0);
1040 	}
1041 	mtx_unlock(&bpf_mtx);
1042 	/* Not found. */
1043 	return (ENXIO);
1044 }
1045 
1046 /*
1047  * Support for select() and poll() system calls
1048  *
1049  * Return true iff the specific operation will not block indefinitely.
1050  * Otherwise, return false but make a note that a selwakeup() must be done.
1051  */
1052 static int
1053 bpfpoll(dev, events, td)
1054 	struct cdev *dev;
1055 	int events;
1056 	struct thread *td;
1057 {
1058 	struct bpf_d *d;
1059 	int revents;
1060 
1061 	d = dev->si_drv1;
1062 	if (d->bd_bif == NULL)
1063 		return (ENXIO);
1064 
1065 	revents = events & (POLLOUT | POLLWRNORM);
1066 	BPFD_LOCK(d);
1067 	if (events & (POLLIN | POLLRDNORM)) {
1068 		if (bpf_ready(d))
1069 			revents |= events & (POLLIN | POLLRDNORM);
1070 		else {
1071 			selrecord(td, &d->bd_sel);
1072 			/* Start the read timeout if necessary. */
1073 			if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1074 				callout_reset(&d->bd_callout, d->bd_rtout,
1075 				    bpf_timed_out, d);
1076 				d->bd_state = BPF_WAITING;
1077 			}
1078 		}
1079 	}
1080 	BPFD_UNLOCK(d);
1081 	return (revents);
1082 }
1083 
1084 /*
1085  * Support for kevent() system call.  Register EVFILT_READ filters and
1086  * reject all others.
1087  */
1088 int
1089 bpfkqfilter(dev, kn)
1090 	struct cdev *dev;
1091 	struct knote *kn;
1092 {
1093 	struct bpf_d *d = (struct bpf_d *)dev->si_drv1;
1094 
1095 	if (kn->kn_filter != EVFILT_READ)
1096 		return (1);
1097 
1098 	kn->kn_fop = &bpfread_filtops;
1099 	kn->kn_hook = d;
1100 	knlist_add(&d->bd_sel.si_note, kn, 0);
1101 
1102 	return (0);
1103 }
1104 
1105 static void
1106 filt_bpfdetach(kn)
1107 	struct knote *kn;
1108 {
1109 	struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1110 
1111 	knlist_remove(&d->bd_sel.si_note, kn, 0);
1112 }
1113 
1114 static int
1115 filt_bpfread(kn, hint)
1116 	struct knote *kn;
1117 	long hint;
1118 {
1119 	struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
1120 	int ready;
1121 
1122 	BPFD_LOCK_ASSERT(d);
1123 	ready = bpf_ready(d);
1124 	if (ready) {
1125 		kn->kn_data = d->bd_slen;
1126 		if (d->bd_hbuf)
1127 			kn->kn_data += d->bd_hlen;
1128 	}
1129 	else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1130 		callout_reset(&d->bd_callout, d->bd_rtout,
1131 		    bpf_timed_out, d);
1132 		d->bd_state = BPF_WAITING;
1133 	}
1134 
1135 	return (ready);
1136 }
1137 
1138 /*
1139  * Incoming linkage from device drivers.  Process the packet pkt, of length
1140  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
1141  * by each process' filter, and if accepted, stashed into the corresponding
1142  * buffer.
1143  */
1144 void
1145 bpf_tap(bp, pkt, pktlen)
1146 	struct bpf_if *bp;
1147 	u_char *pkt;
1148 	u_int pktlen;
1149 {
1150 	struct bpf_d *d;
1151 	u_int slen;
1152 
1153 	/*
1154 	 * Lockless read to avoid cost of locking the interface if there are
1155 	 * no descriptors attached.
1156 	 */
1157 	if (LIST_EMPTY(&bp->bif_dlist))
1158 		return;
1159 
1160 	BPFIF_LOCK(bp);
1161 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1162 		BPFD_LOCK(d);
1163 		++d->bd_rcount;
1164 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
1165 		if (slen != 0) {
1166 #ifdef MAC
1167 			if (mac_check_bpfdesc_receive(d, bp->bif_ifp) == 0)
1168 #endif
1169 				catchpacket(d, pkt, pktlen, slen, bcopy);
1170 		}
1171 		BPFD_UNLOCK(d);
1172 	}
1173 	BPFIF_UNLOCK(bp);
1174 }
1175 
1176 /*
1177  * Copy data from an mbuf chain into a buffer.  This code is derived
1178  * from m_copydata in sys/uipc_mbuf.c.
1179  */
1180 static void
1181 bpf_mcopy(src_arg, dst_arg, len)
1182 	const void *src_arg;
1183 	void *dst_arg;
1184 	size_t len;
1185 {
1186 	const struct mbuf *m;
1187 	u_int count;
1188 	u_char *dst;
1189 
1190 	m = src_arg;
1191 	dst = dst_arg;
1192 	while (len > 0) {
1193 		if (m == NULL)
1194 			panic("bpf_mcopy");
1195 		count = min(m->m_len, len);
1196 		bcopy(mtod(m, void *), dst, count);
1197 		m = m->m_next;
1198 		dst += count;
1199 		len -= count;
1200 	}
1201 }
1202 
1203 /*
1204  * Incoming linkage from device drivers, when packet is in an mbuf chain.
1205  */
1206 void
1207 bpf_mtap(bp, m)
1208 	struct bpf_if *bp;
1209 	struct mbuf *m;
1210 {
1211 	struct bpf_d *d;
1212 	u_int pktlen, slen;
1213 
1214 	/*
1215 	 * Lockless read to avoid cost of locking the interface if there are
1216 	 * no descriptors attached.
1217 	 */
1218 	if (LIST_EMPTY(&bp->bif_dlist))
1219 		return;
1220 
1221 	pktlen = m_length(m, NULL);
1222 	if (pktlen == m->m_len) {
1223 		bpf_tap(bp, mtod(m, u_char *), pktlen);
1224 		return;
1225 	}
1226 
1227 	BPFIF_LOCK(bp);
1228 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1229 		if (!d->bd_seesent && (m->m_pkthdr.rcvif == NULL))
1230 			continue;
1231 		BPFD_LOCK(d);
1232 		++d->bd_rcount;
1233 		slen = bpf_filter(d->bd_filter, (u_char *)m, pktlen, 0);
1234 		if (slen != 0)
1235 #ifdef MAC
1236 			if (mac_check_bpfdesc_receive(d, bp->bif_ifp) == 0)
1237 #endif
1238 				catchpacket(d, (u_char *)m, pktlen, slen,
1239 				    bpf_mcopy);
1240 		BPFD_UNLOCK(d);
1241 	}
1242 	BPFIF_UNLOCK(bp);
1243 }
1244 
1245 /*
1246  * Incoming linkage from device drivers, when packet is in
1247  * an mbuf chain and to be prepended by a contiguous header.
1248  */
1249 void
1250 bpf_mtap2(bp, data, dlen, m)
1251 	struct bpf_if *bp;
1252 	void *data;
1253 	u_int dlen;
1254 	struct mbuf *m;
1255 {
1256 	struct mbuf mb;
1257 	struct bpf_d *d;
1258 	u_int pktlen, slen;
1259 
1260 	/*
1261 	 * Lockless read to avoid cost of locking the interface if there are
1262 	 * no descriptors attached.
1263 	 */
1264 	if (LIST_EMPTY(&bp->bif_dlist))
1265 		return;
1266 
1267 	pktlen = m_length(m, NULL);
1268 	/*
1269 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
1270 	 * Note that we cut corners here; we only setup what's
1271 	 * absolutely needed--this mbuf should never go anywhere else.
1272 	 */
1273 	mb.m_next = m;
1274 	mb.m_data = data;
1275 	mb.m_len = dlen;
1276 	pktlen += dlen;
1277 
1278 	BPFIF_LOCK(bp);
1279 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1280 		if (!d->bd_seesent && (m->m_pkthdr.rcvif == NULL))
1281 			continue;
1282 		BPFD_LOCK(d);
1283 		++d->bd_rcount;
1284 		slen = bpf_filter(d->bd_filter, (u_char *)&mb, pktlen, 0);
1285 		if (slen != 0)
1286 #ifdef MAC
1287 			if (mac_check_bpfdesc_receive(d, bp->bif_ifp) == 0)
1288 #endif
1289 				catchpacket(d, (u_char *)&mb, pktlen, slen,
1290 				    bpf_mcopy);
1291 		BPFD_UNLOCK(d);
1292 	}
1293 	BPFIF_UNLOCK(bp);
1294 }
1295 
1296 /*
1297  * Move the packet data from interface memory (pkt) into the
1298  * store buffer.  "cpfn" is the routine called to do the actual data
1299  * transfer.  bcopy is passed in to copy contiguous chunks, while
1300  * bpf_mcopy is passed in to copy mbuf chains.  In the latter case,
1301  * pkt is really an mbuf.
1302  */
1303 static void
1304 catchpacket(d, pkt, pktlen, snaplen, cpfn)
1305 	struct bpf_d *d;
1306 	u_char *pkt;
1307 	u_int pktlen, snaplen;
1308 	void (*cpfn)(const void *, void *, size_t);
1309 {
1310 	struct bpf_hdr *hp;
1311 	int totlen, curlen;
1312 	int hdrlen = d->bd_bif->bif_hdrlen;
1313 	int do_wakeup = 0;
1314 
1315 	/*
1316 	 * Figure out how many bytes to move.  If the packet is
1317 	 * greater or equal to the snapshot length, transfer that
1318 	 * much.  Otherwise, transfer the whole packet (unless
1319 	 * we hit the buffer size limit).
1320 	 */
1321 	totlen = hdrlen + min(snaplen, pktlen);
1322 	if (totlen > d->bd_bufsize)
1323 		totlen = d->bd_bufsize;
1324 
1325 	/*
1326 	 * Round up the end of the previous packet to the next longword.
1327 	 */
1328 	curlen = BPF_WORDALIGN(d->bd_slen);
1329 	if (curlen + totlen > d->bd_bufsize) {
1330 		/*
1331 		 * This packet will overflow the storage buffer.
1332 		 * Rotate the buffers if we can, then wakeup any
1333 		 * pending reads.
1334 		 */
1335 		if (d->bd_fbuf == NULL) {
1336 			/*
1337 			 * We haven't completed the previous read yet,
1338 			 * so drop the packet.
1339 			 */
1340 			++d->bd_dcount;
1341 			return;
1342 		}
1343 		ROTATE_BUFFERS(d);
1344 		do_wakeup = 1;
1345 		curlen = 0;
1346 	}
1347 	else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
1348 		/*
1349 		 * Immediate mode is set, or the read timeout has
1350 		 * already expired during a select call.  A packet
1351 		 * arrived, so the reader should be woken up.
1352 		 */
1353 		do_wakeup = 1;
1354 
1355 	/*
1356 	 * Append the bpf header.
1357 	 */
1358 	hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
1359 	microtime(&hp->bh_tstamp);
1360 	hp->bh_datalen = pktlen;
1361 	hp->bh_hdrlen = hdrlen;
1362 	/*
1363 	 * Copy the packet data into the store buffer and update its length.
1364 	 */
1365 	(*cpfn)(pkt, (u_char *)hp + hdrlen, (hp->bh_caplen = totlen - hdrlen));
1366 	d->bd_slen = curlen + totlen;
1367 
1368 	if (do_wakeup)
1369 		bpf_wakeup(d);
1370 }
1371 
1372 /*
1373  * Initialize all nonzero fields of a descriptor.
1374  */
1375 static int
1376 bpf_allocbufs(d)
1377 	struct bpf_d *d;
1378 {
1379 	d->bd_fbuf = (caddr_t)malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1380 	if (d->bd_fbuf == NULL)
1381 		return (ENOBUFS);
1382 
1383 	d->bd_sbuf = (caddr_t)malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1384 	if (d->bd_sbuf == NULL) {
1385 		free(d->bd_fbuf, M_BPF);
1386 		return (ENOBUFS);
1387 	}
1388 	d->bd_slen = 0;
1389 	d->bd_hlen = 0;
1390 	return (0);
1391 }
1392 
1393 /*
1394  * Free buffers currently in use by a descriptor.
1395  * Called on close.
1396  */
1397 static void
1398 bpf_freed(d)
1399 	struct bpf_d *d;
1400 {
1401 	/*
1402 	 * We don't need to lock out interrupts since this descriptor has
1403 	 * been detached from its interface and it yet hasn't been marked
1404 	 * free.
1405 	 */
1406 	if (d->bd_sbuf != NULL) {
1407 		free(d->bd_sbuf, M_BPF);
1408 		if (d->bd_hbuf != NULL)
1409 			free(d->bd_hbuf, M_BPF);
1410 		if (d->bd_fbuf != NULL)
1411 			free(d->bd_fbuf, M_BPF);
1412 	}
1413 	if (d->bd_filter)
1414 		free((caddr_t)d->bd_filter, M_BPF);
1415 	mtx_destroy(&d->bd_mtx);
1416 }
1417 
1418 /*
1419  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
1420  * fixed size of the link header (variable length headers not yet supported).
1421  */
1422 void
1423 bpfattach(ifp, dlt, hdrlen)
1424 	struct ifnet *ifp;
1425 	u_int dlt, hdrlen;
1426 {
1427 
1428 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
1429 }
1430 
1431 /*
1432  * Attach an interface to bpf.  ifp is a pointer to the structure
1433  * defining the interface to be attached, dlt is the link layer type,
1434  * and hdrlen is the fixed size of the link header (variable length
1435  * headers are not yet supporrted).
1436  */
1437 void
1438 bpfattach2(ifp, dlt, hdrlen, driverp)
1439 	struct ifnet *ifp;
1440 	u_int dlt, hdrlen;
1441 	struct bpf_if **driverp;
1442 {
1443 	struct bpf_if *bp;
1444 	bp = (struct bpf_if *)malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
1445 	if (bp == NULL)
1446 		panic("bpfattach");
1447 
1448 	LIST_INIT(&bp->bif_dlist);
1449 	bp->bif_driverp = driverp;
1450 	bp->bif_ifp = ifp;
1451 	bp->bif_dlt = dlt;
1452 	mtx_init(&bp->bif_mtx, "bpf interface lock", NULL, MTX_DEF);
1453 
1454 	mtx_lock(&bpf_mtx);
1455 	LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
1456 	mtx_unlock(&bpf_mtx);
1457 
1458 	*bp->bif_driverp = NULL;
1459 
1460 	/*
1461 	 * Compute the length of the bpf header.  This is not necessarily
1462 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1463 	 * that the network layer header begins on a longword boundary (for
1464 	 * performance reasons and to alleviate alignment restrictions).
1465 	 */
1466 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1467 
1468 	if (bootverbose)
1469 		if_printf(ifp, "bpf attached\n");
1470 }
1471 
1472 /*
1473  * Detach bpf from an interface.  This involves detaching each descriptor
1474  * associated with the interface, and leaving bd_bif NULL.  Notify each
1475  * descriptor as it's detached so that any sleepers wake up and get
1476  * ENXIO.
1477  */
1478 void
1479 bpfdetach(ifp)
1480 	struct ifnet *ifp;
1481 {
1482 	struct bpf_if	*bp;
1483 	struct bpf_d	*d;
1484 
1485 	/* Locate BPF interface information */
1486 	mtx_lock(&bpf_mtx);
1487 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1488 		if (ifp == bp->bif_ifp)
1489 			break;
1490 	}
1491 
1492 	/* Interface wasn't attached */
1493 	if ((bp == NULL) || (bp->bif_ifp == NULL)) {
1494 		mtx_unlock(&bpf_mtx);
1495 		printf("bpfdetach: %s was not attached\n", ifp->if_xname);
1496 		return;
1497 	}
1498 
1499 	LIST_REMOVE(bp, bif_next);
1500 	mtx_unlock(&bpf_mtx);
1501 
1502 	while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
1503 		bpf_detachd(d);
1504 		BPFD_LOCK(d);
1505 		bpf_wakeup(d);
1506 		BPFD_UNLOCK(d);
1507 	}
1508 
1509 	mtx_destroy(&bp->bif_mtx);
1510 	free(bp, M_BPF);
1511 }
1512 
1513 /*
1514  * Get a list of available data link type of the interface.
1515  */
1516 static int
1517 bpf_getdltlist(d, bfl)
1518 	struct bpf_d *d;
1519 	struct bpf_dltlist *bfl;
1520 {
1521 	int n, error;
1522 	struct ifnet *ifp;
1523 	struct bpf_if *bp;
1524 
1525 	ifp = d->bd_bif->bif_ifp;
1526 	n = 0;
1527 	error = 0;
1528 	mtx_lock(&bpf_mtx);
1529 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1530 		if (bp->bif_ifp != ifp)
1531 			continue;
1532 		if (bfl->bfl_list != NULL) {
1533 			if (n >= bfl->bfl_len) {
1534 				mtx_unlock(&bpf_mtx);
1535 				return (ENOMEM);
1536 			}
1537 			error = copyout(&bp->bif_dlt,
1538 			    bfl->bfl_list + n, sizeof(u_int));
1539 		}
1540 		n++;
1541 	}
1542 	mtx_unlock(&bpf_mtx);
1543 	bfl->bfl_len = n;
1544 	return (error);
1545 }
1546 
1547 /*
1548  * Set the data link type of a BPF instance.
1549  */
1550 static int
1551 bpf_setdlt(d, dlt)
1552 	struct bpf_d *d;
1553 	u_int dlt;
1554 {
1555 	int error, opromisc;
1556 	struct ifnet *ifp;
1557 	struct bpf_if *bp;
1558 
1559 	if (d->bd_bif->bif_dlt == dlt)
1560 		return (0);
1561 	ifp = d->bd_bif->bif_ifp;
1562 	mtx_lock(&bpf_mtx);
1563 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
1564 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
1565 			break;
1566 	}
1567 	mtx_unlock(&bpf_mtx);
1568 	if (bp != NULL) {
1569 		opromisc = d->bd_promisc;
1570 		bpf_detachd(d);
1571 		bpf_attachd(d, bp);
1572 		BPFD_LOCK(d);
1573 		reset_d(d);
1574 		BPFD_UNLOCK(d);
1575 		if (opromisc) {
1576 			error = ifpromisc(bp->bif_ifp, 1);
1577 			if (error)
1578 				if_printf(bp->bif_ifp,
1579 					"bpf_setdlt: ifpromisc failed (%d)\n",
1580 					error);
1581 			else
1582 				d->bd_promisc = 1;
1583 		}
1584 	}
1585 	return (bp == NULL ? EINVAL : 0);
1586 }
1587 
1588 static void bpf_drvinit(void *unused);
1589 
1590 static void bpf_clone(void *arg, char *name, int namelen, struct cdev **dev);
1591 
1592 static void
1593 bpf_clone(arg, name, namelen, dev)
1594 	void *arg;
1595 	char *name;
1596 	int namelen;
1597 	struct cdev **dev;
1598 {
1599 	int u;
1600 
1601 	if (*dev != NULL)
1602 		return;
1603 	if (dev_stdclone(name, NULL, "bpf", &u) != 1)
1604 		return;
1605 	*dev = make_dev(&bpf_cdevsw, unit2minor(u), UID_ROOT, GID_WHEEL, 0600,
1606 	    "bpf%d", u);
1607 	(*dev)->si_flags |= SI_CHEAPCLONE;
1608 	return;
1609 }
1610 
1611 static void
1612 bpf_drvinit(unused)
1613 	void *unused;
1614 {
1615 
1616 	mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
1617 	LIST_INIT(&bpf_iflist);
1618 	EVENTHANDLER_REGISTER(dev_clone, bpf_clone, 0, 1000);
1619 }
1620 
1621 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL)
1622 
1623 #else /* !DEV_BPF && !NETGRAPH_BPF */
1624 /*
1625  * NOP stubs to allow bpf-using drivers to load and function.
1626  *
1627  * A 'better' implementation would allow the core bpf functionality
1628  * to be loaded at runtime.
1629  */
1630 
1631 void
1632 bpf_tap(bp, pkt, pktlen)
1633 	struct bpf_if *bp;
1634 	u_char *pkt;
1635 	u_int pktlen;
1636 {
1637 }
1638 
1639 void
1640 bpf_mtap(bp, m)
1641 	struct bpf_if *bp;
1642 	struct mbuf *m;
1643 {
1644 }
1645 
1646 void
1647 bpf_mtap2(bp, d, l, m)
1648 	struct bpf_if *bp;
1649 	void *d;
1650 	u_int l;
1651 	struct mbuf *m;
1652 {
1653 }
1654 
1655 void
1656 bpfattach(ifp, dlt, hdrlen)
1657 	struct ifnet *ifp;
1658 	u_int dlt, hdrlen;
1659 {
1660 }
1661 
1662 void
1663 bpfattach2(ifp, dlt, hdrlen, driverp)
1664 	struct ifnet *ifp;
1665 	u_int dlt, hdrlen;
1666 	struct bpf_if **driverp;
1667 {
1668 }
1669 
1670 void
1671 bpfdetach(ifp)
1672 	struct ifnet *ifp;
1673 {
1674 }
1675 
1676 u_int
1677 bpf_filter(pc, p, wirelen, buflen)
1678 	const struct bpf_insn *pc;
1679 	u_char *p;
1680 	u_int wirelen;
1681 	u_int buflen;
1682 {
1683 	return -1;	/* "no filter" behaviour */
1684 }
1685 
1686 int
1687 bpf_validate(f, len)
1688 	const struct bpf_insn *f;
1689 	int len;
1690 {
1691 	return 0;		/* false */
1692 }
1693 
1694 #endif /* !DEV_BPF && !NETGRAPH_BPF */
1695