xref: /netbsd-src/sys/net/bpf.c (revision 21e37cc72a480a47828990a439cde7ac9ffaf0c6)
1 /*	$NetBSD: bpf.c,v 1.101 2004/06/06 04:35:53 dyoung Exp $	*/
2 
3 /*
4  * Copyright (c) 1990, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from the Stanford/CMU enet packet filter,
8  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
9  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
10  * Berkeley Laboratory.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)bpf.c	8.4 (Berkeley) 1/9/95
37  * static char rcsid[] =
38  * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
39  */
40 
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.101 2004/06/06 04:35:53 dyoung Exp $");
43 
44 #include "bpfilter.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/mbuf.h>
49 #include <sys/buf.h>
50 #include <sys/time.h>
51 #include <sys/proc.h>
52 #include <sys/user.h>
53 #include <sys/ioctl.h>
54 #include <sys/conf.h>
55 #include <sys/vnode.h>
56 
57 #include <sys/file.h>
58 #include <sys/tty.h>
59 #include <sys/uio.h>
60 
61 #include <sys/protosw.h>
62 #include <sys/socket.h>
63 #include <sys/errno.h>
64 #include <sys/kernel.h>
65 #include <sys/poll.h>
66 #include <sys/sysctl.h>
67 
68 #include <net/if.h>
69 
70 #include <net/bpf.h>
71 #include <net/bpfdesc.h>
72 
73 #include <net/if_arc.h>
74 #include <net/if_ether.h>
75 
76 #include <netinet/in.h>
77 #include <netinet/if_inarp.h>
78 
79 #if defined(_KERNEL_OPT)
80 #include "opt_bpf.h"
81 #endif
82 
83 #ifndef BPF_BUFSIZE
84 /*
85  * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
86  * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
87  */
88 # define BPF_BUFSIZE 32768
89 #endif
90 
91 #define PRINET  26			/* interruptible */
92 
93 /*
94  * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
95  * XXX the default values should be computed dynamically based
96  * on available memory size and available mbuf clusters.
97  */
98 int bpf_bufsize = BPF_BUFSIZE;
99 int bpf_maxbufsize = BPF_DFLTBUFSIZE;	/* XXX set dynamically, see above */
100 
101 /*
102  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
103  *  bpf_dtab holds the descriptors, indexed by minor device #
104  */
105 struct bpf_if	*bpf_iflist;
106 struct bpf_d	bpf_dtab[NBPFILTER];
107 
108 static int	bpf_allocbufs __P((struct bpf_d *));
109 static void	bpf_deliver(struct bpf_if *,
110 		            void *(*cpfn)(void *, const void *, size_t),
111 			    void *, u_int, u_int, struct ifnet *);
112 static void	bpf_freed __P((struct bpf_d *));
113 static void	bpf_ifname __P((struct ifnet *, struct ifreq *));
114 static void	*bpf_mcpy __P((void *, const void *, size_t));
115 static int	bpf_movein __P((struct uio *, int, int,
116 			        struct mbuf **, struct sockaddr *));
117 static void	bpf_attachd __P((struct bpf_d *, struct bpf_if *));
118 static void	bpf_detachd __P((struct bpf_d *));
119 static int	bpf_setif __P((struct bpf_d *, struct ifreq *));
120 static void	bpf_timed_out __P((void *));
121 static __inline void
122 		bpf_wakeup __P((struct bpf_d *));
123 static void	catchpacket __P((struct bpf_d *, u_char *, u_int, u_int,
124 				 void *(*)(void *, const void *, size_t)));
125 static void	reset_d __P((struct bpf_d *));
126 static int	bpf_getdltlist __P((struct bpf_d *, struct bpf_dltlist *));
127 static int	bpf_setdlt __P((struct bpf_d *, u_int));
128 
129 dev_type_open(bpfopen);
130 dev_type_close(bpfclose);
131 dev_type_read(bpfread);
132 dev_type_write(bpfwrite);
133 dev_type_ioctl(bpfioctl);
134 dev_type_poll(bpfpoll);
135 dev_type_kqfilter(bpfkqfilter);
136 
137 const struct cdevsw bpf_cdevsw = {
138 	bpfopen, bpfclose, bpfread, bpfwrite, bpfioctl,
139 	nostop, notty, bpfpoll, nommap, bpfkqfilter,
140 };
141 
142 static int
143 bpf_movein(uio, linktype, mtu, mp, sockp)
144 	struct uio *uio;
145 	int linktype;
146 	int mtu;
147 	struct mbuf **mp;
148 	struct sockaddr *sockp;
149 {
150 	struct mbuf *m;
151 	int error;
152 	int len;
153 	int hlen;
154 	int align;
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 		align = 0;
171 		break;
172 
173 	case DLT_PPP:
174 		sockp->sa_family = AF_UNSPEC;
175 		hlen = 0;
176 		align = 0;
177 		break;
178 
179 	case DLT_EN10MB:
180 		sockp->sa_family = AF_UNSPEC;
181 		/* XXX Would MAXLINKHDR be better? */
182  		/* 6(dst)+6(src)+2(type) */
183 		hlen = sizeof(struct ether_header);
184 		align = 2;
185 		break;
186 
187 	case DLT_ARCNET:
188 		sockp->sa_family = AF_UNSPEC;
189 		hlen = ARC_HDRLEN;
190 		align = 5;
191 		break;
192 
193 	case DLT_FDDI:
194 		sockp->sa_family = AF_LINK;
195 		/* XXX 4(FORMAC)+6(dst)+6(src) */
196 		hlen = 16;
197 		align = 0;
198 		break;
199 
200 	case DLT_ECONET:
201 		sockp->sa_family = AF_UNSPEC;
202 		hlen = 6;
203 		align = 2;
204 		break;
205 
206 	case DLT_NULL:
207 		sockp->sa_family = AF_UNSPEC;
208 		hlen = 0;
209 		align = 0;
210 		break;
211 
212 	default:
213 		return (EIO);
214 	}
215 
216 	len = uio->uio_resid;
217 	/*
218 	 * If there aren't enough bytes for a link level header or the
219 	 * packet length exceeds the interface mtu, return an error.
220 	 */
221 	if (len < hlen || len - hlen > mtu)
222 		return (EMSGSIZE);
223 
224 	/*
225 	 * XXX Avoid complicated buffer chaining ---
226 	 * bail if it won't fit in a single mbuf.
227 	 * (Take into account possible alignment bytes)
228 	 */
229 	if ((unsigned)len > MCLBYTES - align)
230 		return (EIO);
231 
232 	m = m_gethdr(M_WAIT, MT_DATA);
233 	m->m_pkthdr.rcvif = 0;
234 	m->m_pkthdr.len = len - hlen;
235 	if (len > MHLEN - align) {
236 		m_clget(m, M_WAIT);
237 		if ((m->m_flags & M_EXT) == 0) {
238 			error = ENOBUFS;
239 			goto bad;
240 		}
241 	}
242 
243 	/* Insure the data is properly aligned */
244 	if (align > 0) {
245 		m->m_data += align;
246 		m->m_len -= align;
247 	}
248 
249 	error = uiomove(mtod(m, caddr_t), len, uio);
250 	if (error)
251 		goto bad;
252 	if (hlen != 0) {
253 		memcpy(sockp->sa_data, mtod(m, caddr_t), hlen);
254 		m->m_data += hlen; /* XXX */
255 		len -= hlen;
256 	}
257 	m->m_len = len;
258 	*mp = m;
259 	return (0);
260 
261 bad:
262 	m_freem(m);
263 	return (error);
264 }
265 
266 /*
267  * Attach file to the bpf interface, i.e. make d listen on bp.
268  * Must be called at splnet.
269  */
270 static void
271 bpf_attachd(d, bp)
272 	struct bpf_d *d;
273 	struct bpf_if *bp;
274 {
275 	/*
276 	 * Point d at bp, and add d to the interface's list of listeners.
277 	 * Finally, point the driver's bpf cookie at the interface so
278 	 * it will divert packets to bpf.
279 	 */
280 	d->bd_bif = bp;
281 	d->bd_next = bp->bif_dlist;
282 	bp->bif_dlist = d;
283 
284 	*bp->bif_driverp = bp;
285 }
286 
287 /*
288  * Detach a file from its interface.
289  */
290 static void
291 bpf_detachd(d)
292 	struct bpf_d *d;
293 {
294 	struct bpf_d **p;
295 	struct bpf_if *bp;
296 
297 	bp = d->bd_bif;
298 	/*
299 	 * Check if this descriptor had requested promiscuous mode.
300 	 * If so, turn it off.
301 	 */
302 	if (d->bd_promisc) {
303 		int error;
304 
305 		d->bd_promisc = 0;
306 		/*
307 		 * Take device out of promiscuous mode.  Since we were
308 		 * able to enter promiscuous mode, we should be able
309 		 * to turn it off.  But we can get an error if
310 		 * the interface was configured down, so only panic
311 		 * if we don't get an unexpected error.
312 		 */
313   		error = ifpromisc(bp->bif_ifp, 0);
314 		if (error && error != EINVAL)
315 			panic("bpf: ifpromisc failed");
316 	}
317 	/* Remove d from the interface's descriptor list. */
318 	p = &bp->bif_dlist;
319 	while (*p != d) {
320 		p = &(*p)->bd_next;
321 		if (*p == 0)
322 			panic("bpf_detachd: descriptor not in list");
323 	}
324 	*p = (*p)->bd_next;
325 	if (bp->bif_dlist == 0)
326 		/*
327 		 * Let the driver know that there are no more listeners.
328 		 */
329 		*d->bd_bif->bif_driverp = 0;
330 	d->bd_bif = 0;
331 }
332 
333 
334 /*
335  * Mark a descriptor free by making it point to itself.
336  * This is probably cheaper than marking with a constant since
337  * the address should be in a register anyway.
338  */
339 #define D_ISFREE(d) ((d) == (d)->bd_next)
340 #define D_MARKFREE(d) ((d)->bd_next = (d))
341 #define D_MARKUSED(d) ((d)->bd_next = 0)
342 
343 /*
344  * bpfilterattach() is called at boot time.
345  */
346 /* ARGSUSED */
347 void
348 bpfilterattach(n)
349 	int n;
350 {
351 	int i;
352 	/*
353 	 * Mark all the descriptors free.
354 	 */
355 	for (i = 0; i < NBPFILTER; ++i)
356 		D_MARKFREE(&bpf_dtab[i]);
357 
358 }
359 
360 /*
361  * Open ethernet device.  Returns ENXIO for illegal minor device number,
362  * EBUSY if file is open by another process.
363  */
364 /* ARGSUSED */
365 int
366 bpfopen(dev, flag, mode, p)
367 	dev_t dev;
368 	int flag;
369 	int mode;
370 	struct proc *p;
371 {
372 	struct bpf_d *d;
373 
374 	if (minor(dev) >= NBPFILTER)
375 		return (ENXIO);
376 	/*
377 	 * Each minor can be opened by only one process.  If the requested
378 	 * minor is in use, return EBUSY.
379 	 */
380 	d = &bpf_dtab[minor(dev)];
381 	if (!D_ISFREE(d))
382 		return (EBUSY);
383 
384 	/* Mark "free" and do most initialization. */
385 	memset((char *)d, 0, sizeof(*d));
386 	d->bd_bufsize = bpf_bufsize;
387 	d->bd_seesent = 1;
388 	callout_init(&d->bd_callout);
389 
390 	return (0);
391 }
392 
393 /*
394  * Close the descriptor by detaching it from its interface,
395  * deallocating its buffers, and marking it free.
396  */
397 /* ARGSUSED */
398 int
399 bpfclose(dev, flag, mode, p)
400 	dev_t dev;
401 	int flag;
402 	int mode;
403 	struct proc *p;
404 {
405 	struct bpf_d *d = &bpf_dtab[minor(dev)];
406 	int s;
407 
408 	s = splnet();
409 	if (d->bd_state == BPF_WAITING)
410 		callout_stop(&d->bd_callout);
411 	d->bd_state = BPF_IDLE;
412 	if (d->bd_bif)
413 		bpf_detachd(d);
414 	splx(s);
415 	bpf_freed(d);
416 
417 	return (0);
418 }
419 
420 /*
421  * Rotate the packet buffers in descriptor d.  Move the store buffer
422  * into the hold slot, and the free buffer into the store slot.
423  * Zero the length of the new store buffer.
424  */
425 #define ROTATE_BUFFERS(d) \
426 	(d)->bd_hbuf = (d)->bd_sbuf; \
427 	(d)->bd_hlen = (d)->bd_slen; \
428 	(d)->bd_sbuf = (d)->bd_fbuf; \
429 	(d)->bd_slen = 0; \
430 	(d)->bd_fbuf = 0;
431 /*
432  *  bpfread - read next chunk of packets from buffers
433  */
434 int
435 bpfread(dev, uio, ioflag)
436 	dev_t dev;
437 	struct uio *uio;
438 	int ioflag;
439 {
440 	struct bpf_d *d = &bpf_dtab[minor(dev)];
441 	int timed_out;
442 	int error;
443 	int s;
444 
445 	/*
446 	 * Restrict application to use a buffer the same size as
447 	 * as kernel buffers.
448 	 */
449 	if (uio->uio_resid != d->bd_bufsize)
450 		return (EINVAL);
451 
452 	s = splnet();
453 	if (d->bd_state == BPF_WAITING)
454 		callout_stop(&d->bd_callout);
455 	timed_out = (d->bd_state == BPF_TIMED_OUT);
456 	d->bd_state = BPF_IDLE;
457 	/*
458 	 * If the hold buffer is empty, then do a timed sleep, which
459 	 * ends when the timeout expires or when enough packets
460 	 * have arrived to fill the store buffer.
461 	 */
462 	while (d->bd_hbuf == 0) {
463 		if (ioflag & IO_NDELAY) {
464 			if (d->bd_slen == 0) {
465 				splx(s);
466 				return (EWOULDBLOCK);
467 			}
468 			ROTATE_BUFFERS(d);
469 			break;
470 		}
471 
472 		if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
473 			/*
474 			 * A packet(s) either arrived since the previous
475 			 * read or arrived while we were asleep.
476 			 * Rotate the buffers and return what's here.
477 			 */
478 			ROTATE_BUFFERS(d);
479 			break;
480 		}
481 		error = tsleep((caddr_t)d, PRINET|PCATCH, "bpf",
482 				d->bd_rtout);
483 		if (error == EINTR || error == ERESTART) {
484 			splx(s);
485 			return (error);
486 		}
487 		if (error == EWOULDBLOCK) {
488 			/*
489 			 * On a timeout, return what's in the buffer,
490 			 * which may be nothing.  If there is something
491 			 * in the store buffer, we can rotate the buffers.
492 			 */
493 			if (d->bd_hbuf)
494 				/*
495 				 * We filled up the buffer in between
496 				 * getting the timeout and arriving
497 				 * here, so we don't need to rotate.
498 				 */
499 				break;
500 
501 			if (d->bd_slen == 0) {
502 				splx(s);
503 				return (0);
504 			}
505 			ROTATE_BUFFERS(d);
506 			break;
507 		}
508 		if (error != 0)
509 			goto done;
510 	}
511 	/*
512 	 * At this point, we know we have something in the hold slot.
513 	 */
514 	splx(s);
515 
516 	/*
517 	 * Move data from hold buffer into user space.
518 	 * We know the entire buffer is transferred since
519 	 * we checked above that the read buffer is bpf_bufsize bytes.
520 	 */
521 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
522 
523 	s = splnet();
524 	d->bd_fbuf = d->bd_hbuf;
525 	d->bd_hbuf = 0;
526 	d->bd_hlen = 0;
527 done:
528 	splx(s);
529 	return (error);
530 }
531 
532 
533 /*
534  * If there are processes sleeping on this descriptor, wake them up.
535  */
536 static __inline void
537 bpf_wakeup(d)
538 	struct bpf_d *d;
539 {
540 	wakeup((caddr_t)d);
541 	if (d->bd_async)
542 		fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
543 
544 	selnotify(&d->bd_sel, 0);
545 	/* XXX */
546 	d->bd_sel.sel_pid = 0;
547 }
548 
549 
550 static void
551 bpf_timed_out(arg)
552 	void *arg;
553 {
554 	struct bpf_d *d = (struct bpf_d *)arg;
555 	int s;
556 
557 	s = splnet();
558 	if (d->bd_state == BPF_WAITING) {
559 		d->bd_state = BPF_TIMED_OUT;
560 		if (d->bd_slen != 0)
561 			bpf_wakeup(d);
562 	}
563 	splx(s);
564 }
565 
566 
567 int
568 bpfwrite(dev, uio, ioflag)
569 	dev_t dev;
570 	struct uio *uio;
571 	int ioflag;
572 {
573 	struct bpf_d *d = &bpf_dtab[minor(dev)];
574 	struct ifnet *ifp;
575 	struct mbuf *m;
576 	int error, s;
577 	static struct sockaddr_storage dst;
578 
579 	if (d->bd_bif == 0)
580 		return (ENXIO);
581 
582 	ifp = d->bd_bif->bif_ifp;
583 
584 	if (uio->uio_resid == 0)
585 		return (0);
586 
587 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp->if_mtu, &m,
588 		(struct sockaddr *) &dst);
589 	if (error)
590 		return (error);
591 
592 	if (m->m_pkthdr.len > ifp->if_mtu)
593 		return (EMSGSIZE);
594 
595 	if (d->bd_hdrcmplt)
596 		dst.ss_family = pseudo_AF_HDRCMPLT;
597 
598 	s = splsoftnet();
599 	error = (*ifp->if_output)(ifp, m, (struct sockaddr *) &dst, NULL);
600 	splx(s);
601 	/*
602 	 * The driver frees the mbuf.
603 	 */
604 	return (error);
605 }
606 
607 /*
608  * Reset a descriptor by flushing its packet buffer and clearing the
609  * receive and drop counts.  Should be called at splnet.
610  */
611 static void
612 reset_d(d)
613 	struct bpf_d *d;
614 {
615 	if (d->bd_hbuf) {
616 		/* Free the hold buffer. */
617 		d->bd_fbuf = d->bd_hbuf;
618 		d->bd_hbuf = 0;
619 	}
620 	d->bd_slen = 0;
621 	d->bd_hlen = 0;
622 	d->bd_rcount = 0;
623 	d->bd_dcount = 0;
624 	d->bd_ccount = 0;
625 }
626 
627 #ifdef BPF_KERN_FILTER
628 extern struct bpf_insn *bpf_tcp_filter;
629 extern struct bpf_insn *bpf_udp_filter;
630 #endif
631 
632 /*
633  *  FIONREAD		Check for read packet available.
634  *  BIOCGBLEN		Get buffer len [for read()].
635  *  BIOCSETF		Set ethernet read filter.
636  *  BIOCFLUSH		Flush read packet buffer.
637  *  BIOCPROMISC		Put interface into promiscuous mode.
638  *  BIOCGDLT		Get link layer type.
639  *  BIOCGETIF		Get interface name.
640  *  BIOCSETIF		Set interface.
641  *  BIOCSRTIMEOUT	Set read timeout.
642  *  BIOCGRTIMEOUT	Get read timeout.
643  *  BIOCGSTATS		Get packet stats.
644  *  BIOCIMMEDIATE	Set immediate mode.
645  *  BIOCVERSION		Get filter language version.
646  *  BIOGHDRCMPLT	Get "header already complete" flag.
647  *  BIOSHDRCMPLT	Set "header already complete" flag.
648  */
649 /* ARGSUSED */
650 int
651 bpfioctl(dev, cmd, addr, flag, p)
652 	dev_t dev;
653 	u_long cmd;
654 	caddr_t addr;
655 	int flag;
656 	struct proc *p;
657 {
658 	struct bpf_d *d = &bpf_dtab[minor(dev)];
659 	int s, error = 0;
660 #ifdef BPF_KERN_FILTER
661 	struct bpf_insn **p;
662 #endif
663 
664 	s = splnet();
665 	if (d->bd_state == BPF_WAITING)
666 		callout_stop(&d->bd_callout);
667 	d->bd_state = BPF_IDLE;
668 	splx(s);
669 
670 	switch (cmd) {
671 
672 	default:
673 		error = EINVAL;
674 		break;
675 
676 	/*
677 	 * Check for read packet available.
678 	 */
679 	case FIONREAD:
680 		{
681 			int n;
682 
683 			s = splnet();
684 			n = d->bd_slen;
685 			if (d->bd_hbuf)
686 				n += d->bd_hlen;
687 			splx(s);
688 
689 			*(int *)addr = n;
690 			break;
691 		}
692 
693 	/*
694 	 * Get buffer len [for read()].
695 	 */
696 	case BIOCGBLEN:
697 		*(u_int *)addr = d->bd_bufsize;
698 		break;
699 
700 	/*
701 	 * Set buffer length.
702 	 */
703 	case BIOCSBLEN:
704 		if (d->bd_bif != 0)
705 			error = EINVAL;
706 		else {
707 			u_int size = *(u_int *)addr;
708 
709 			if (size > bpf_maxbufsize)
710 				*(u_int *)addr = size = bpf_maxbufsize;
711 			else if (size < BPF_MINBUFSIZE)
712 				*(u_int *)addr = size = BPF_MINBUFSIZE;
713 			d->bd_bufsize = size;
714 		}
715 		break;
716 
717 	/*
718 	 * Set link layer read filter.
719 	 */
720 	case BIOCSETF:
721 		error = bpf_setf(d, (struct bpf_program *)addr);
722 		break;
723 
724 #ifdef BPF_KERN_FILTER
725 	/*
726 	 * Set TCP or UDP reject filter.
727 	 */
728 	case BIOCSTCPF:
729 	case BIOCSUDPF:
730 		if (!suser()) {
731 			error = EPERM;
732 			break;
733 		}
734 
735 		/* Validate and store filter */
736 		error = bpf_setf(d, (struct bpf_program *)addr);
737 
738 		/* Free possible old filter */
739 		if (cmd == BIOCSTCPF)
740 			p = &bpf_tcp_filter;
741 		else
742 			p = &bpf_udp_filter;
743 		if (*p != NULL)
744 			free((caddr_t)*p, M_DEVBUF);
745 
746 		/* Steal new filter (noop if error) */
747 		s = splnet();
748 		*p = d->bd_filter;
749 		d->bd_filter = NULL;
750 		splx(s);
751 		break;
752 #endif
753 
754 	/*
755 	 * Flush read packet buffer.
756 	 */
757 	case BIOCFLUSH:
758 		s = splnet();
759 		reset_d(d);
760 		splx(s);
761 		break;
762 
763 	/*
764 	 * Put interface into promiscuous mode.
765 	 */
766 	case BIOCPROMISC:
767 		if (d->bd_bif == 0) {
768 			/*
769 			 * No interface attached yet.
770 			 */
771 			error = EINVAL;
772 			break;
773 		}
774 		s = splnet();
775 		if (d->bd_promisc == 0) {
776 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
777 			if (error == 0)
778 				d->bd_promisc = 1;
779 		}
780 		splx(s);
781 		break;
782 
783 	/*
784 	 * Get device parameters.
785 	 */
786 	case BIOCGDLT:
787 		if (d->bd_bif == 0)
788 			error = EINVAL;
789 		else
790 			*(u_int *)addr = d->bd_bif->bif_dlt;
791 		break;
792 
793 	/*
794 	 * Get a list of supported device parameters.
795 	 */
796 	case BIOCGDLTLIST:
797 		if (d->bd_bif == 0)
798 			error = EINVAL;
799 		else
800 			error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
801 		break;
802 
803 	/*
804 	 * Set device parameters.
805 	 */
806 	case BIOCSDLT:
807 		if (d->bd_bif == 0)
808 			error = EINVAL;
809 		else
810 			error = bpf_setdlt(d, *(u_int *)addr);
811 		break;
812 
813 	/*
814 	 * Set interface name.
815 	 */
816 	case BIOCGETIF:
817 		if (d->bd_bif == 0)
818 			error = EINVAL;
819 		else
820 			bpf_ifname(d->bd_bif->bif_ifp, (struct ifreq *)addr);
821 		break;
822 
823 	/*
824 	 * Set interface.
825 	 */
826 	case BIOCSETIF:
827 		error = bpf_setif(d, (struct ifreq *)addr);
828 		break;
829 
830 	/*
831 	 * Set read timeout.
832 	 */
833 	case BIOCSRTIMEOUT:
834 		{
835 			struct timeval *tv = (struct timeval *)addr;
836 
837 			/* Compute number of ticks. */
838 			d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
839 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
840 				d->bd_rtout = 1;
841 			break;
842 		}
843 
844 	/*
845 	 * Get read timeout.
846 	 */
847 	case BIOCGRTIMEOUT:
848 		{
849 			struct timeval *tv = (struct timeval *)addr;
850 
851 			tv->tv_sec = d->bd_rtout / hz;
852 			tv->tv_usec = (d->bd_rtout % hz) * tick;
853 			break;
854 		}
855 
856 	/*
857 	 * Get packet stats.
858 	 */
859 	case BIOCGSTATS:
860 		{
861 			struct bpf_stat *bs = (struct bpf_stat *)addr;
862 
863 			bs->bs_recv = d->bd_rcount;
864 			bs->bs_drop = d->bd_dcount;
865 			bs->bs_capt = d->bd_ccount;
866 			break;
867 		}
868 
869 	case BIOCGSTATSOLD:
870 		{
871 			struct bpf_stat_old *bs = (struct bpf_stat_old *)addr;
872 
873 			bs->bs_recv = d->bd_rcount;
874 			bs->bs_drop = d->bd_dcount;
875 			break;
876 		}
877 
878 	/*
879 	 * Set immediate mode.
880 	 */
881 	case BIOCIMMEDIATE:
882 		d->bd_immediate = *(u_int *)addr;
883 		break;
884 
885 	case BIOCVERSION:
886 		{
887 			struct bpf_version *bv = (struct bpf_version *)addr;
888 
889 			bv->bv_major = BPF_MAJOR_VERSION;
890 			bv->bv_minor = BPF_MINOR_VERSION;
891 			break;
892 		}
893 
894 	case BIOCGHDRCMPLT:	/* get "header already complete" flag */
895 		*(u_int *)addr = d->bd_hdrcmplt;
896 		break;
897 
898 	case BIOCSHDRCMPLT:	/* set "header already complete" flag */
899 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
900 		break;
901 
902 	/*
903 	 * Get "see sent packets" flag
904 	 */
905 	case BIOCGSEESENT:
906 		*(u_int *)addr = d->bd_seesent;
907 		break;
908 
909 	/*
910 	 * Set "see sent" packets flag
911 	 */
912 	case BIOCSSEESENT:
913 		d->bd_seesent = *(u_int *)addr;
914 		break;
915 
916 	case FIONBIO:		/* Non-blocking I/O */
917 		/*
918 		 * No need to do anything special as we use IO_NDELAY in
919 		 * bpfread() as an indication of whether or not to block
920 		 * the read.
921 		 */
922 		break;
923 
924 	case FIOASYNC:		/* Send signal on receive packets */
925 		d->bd_async = *(int *)addr;
926 		break;
927 
928 	case TIOCSPGRP:		/* Process or group to send signals to */
929 	case FIOSETOWN:
930 		error = fsetown(p, &d->bd_pgid, cmd, addr);
931 		break;
932 
933 	case TIOCGPGRP:
934 	case FIOGETOWN:
935 		error = fgetown(p, d->bd_pgid, cmd, addr);
936 		break;
937 	}
938 	return (error);
939 }
940 
941 /*
942  * Set d's packet filter program to fp.  If this file already has a filter,
943  * free it and replace it.  Returns EINVAL for bogus requests.
944  */
945 int
946 bpf_setf(d, fp)
947 	struct bpf_d *d;
948 	struct bpf_program *fp;
949 {
950 	struct bpf_insn *fcode, *old;
951 	u_int flen, size;
952 	int s;
953 
954 	old = d->bd_filter;
955 	if (fp->bf_insns == 0) {
956 		if (fp->bf_len != 0)
957 			return (EINVAL);
958 		s = splnet();
959 		d->bd_filter = 0;
960 		reset_d(d);
961 		splx(s);
962 		if (old != 0)
963 			free((caddr_t)old, M_DEVBUF);
964 		return (0);
965 	}
966 	flen = fp->bf_len;
967 	if (flen > BPF_MAXINSNS)
968 		return (EINVAL);
969 
970 	size = flen * sizeof(*fp->bf_insns);
971 	fcode = (struct bpf_insn *)malloc(size, M_DEVBUF, M_WAITOK);
972 	if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) == 0 &&
973 	    bpf_validate(fcode, (int)flen)) {
974 		s = splnet();
975 		d->bd_filter = fcode;
976 		reset_d(d);
977 		splx(s);
978 		if (old != 0)
979 			free((caddr_t)old, M_DEVBUF);
980 
981 		return (0);
982 	}
983 	free((caddr_t)fcode, M_DEVBUF);
984 	return (EINVAL);
985 }
986 
987 /*
988  * Detach a file from its current interface (if attached at all) and attach
989  * to the interface indicated by the name stored in ifr.
990  * Return an errno or 0.
991  */
992 static int
993 bpf_setif(d, ifr)
994 	struct bpf_d *d;
995 	struct ifreq *ifr;
996 {
997 	struct bpf_if *bp;
998 	char *cp;
999 	int unit_seen, i, s, error;
1000 
1001 	/*
1002 	 * Make sure the provided name has a unit number, and default
1003 	 * it to '0' if not specified.
1004 	 * XXX This is ugly ... do this differently?
1005 	 */
1006 	unit_seen = 0;
1007 	cp = ifr->ifr_name;
1008 	cp[sizeof(ifr->ifr_name) - 1] = '\0';	/* sanity */
1009 	while (*cp++)
1010 		if (*cp >= '0' && *cp <= '9')
1011 			unit_seen = 1;
1012 	if (!unit_seen) {
1013 		/* Make sure to leave room for the '\0'. */
1014 		for (i = 0; i < (IFNAMSIZ - 1); ++i) {
1015 			if ((ifr->ifr_name[i] >= 'a' &&
1016 			     ifr->ifr_name[i] <= 'z') ||
1017 			    (ifr->ifr_name[i] >= 'A' &&
1018 			     ifr->ifr_name[i] <= 'Z'))
1019 				continue;
1020 			ifr->ifr_name[i] = '0';
1021 		}
1022 	}
1023 
1024 	/*
1025 	 * Look through attached interfaces for the named one.
1026 	 */
1027 	for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
1028 		struct ifnet *ifp = bp->bif_ifp;
1029 
1030 		if (ifp == 0 ||
1031 		    strcmp(ifp->if_xname, ifr->ifr_name) != 0)
1032 			continue;
1033 		/* skip additional entry */
1034 		if (bp->bif_driverp != (struct bpf_if **)&ifp->if_bpf)
1035 			continue;
1036 		/*
1037 		 * We found the requested interface.
1038 		 * If it's not up, return an error.
1039 		 * Allocate the packet buffers if we need to.
1040 		 * If we're already attached to requested interface,
1041 		 * just flush the buffer.
1042 		 */
1043 		if ((ifp->if_flags & IFF_UP) == 0)
1044 			return (ENETDOWN);
1045 
1046 		if (d->bd_sbuf == 0) {
1047 			error = bpf_allocbufs(d);
1048 			if (error != 0)
1049 				return (error);
1050 		}
1051 		s = splnet();
1052 		if (bp != d->bd_bif) {
1053 			if (d->bd_bif)
1054 				/*
1055 				 * Detach if attached to something else.
1056 				 */
1057 				bpf_detachd(d);
1058 
1059 			bpf_attachd(d, bp);
1060 		}
1061 		reset_d(d);
1062 		splx(s);
1063 		return (0);
1064 	}
1065 	/* Not found. */
1066 	return (ENXIO);
1067 }
1068 
1069 /*
1070  * Copy the interface name to the ifreq.
1071  */
1072 static void
1073 bpf_ifname(ifp, ifr)
1074 	struct ifnet *ifp;
1075 	struct ifreq *ifr;
1076 {
1077 
1078 	memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
1079 }
1080 
1081 /*
1082  * Support for poll() system call
1083  *
1084  * Return true iff the specific operation will not block indefinitely - with
1085  * the assumption that it is safe to positively acknowledge a request for the
1086  * ability to write to the BPF device.
1087  * Otherwise, return false but make a note that a selwakeup() must be done.
1088  */
1089 int
1090 bpfpoll(dev, events, p)
1091 	dev_t dev;
1092 	int events;
1093 	struct proc *p;
1094 {
1095 	struct bpf_d *d = &bpf_dtab[minor(dev)];
1096 	int s = splnet();
1097 	int revents;
1098 
1099 	revents = events & (POLLOUT | POLLWRNORM);
1100 	if (events & (POLLIN | POLLRDNORM)) {
1101 		/*
1102 		 * An imitation of the FIONREAD ioctl code.
1103 		 */
1104 		if ((d->bd_hlen != 0) ||
1105 		    (d->bd_immediate && d->bd_slen != 0)) {
1106 			revents |= events & (POLLIN | POLLRDNORM);
1107 		} else if (d->bd_state == BPF_TIMED_OUT) {
1108 			if (d->bd_slen != 0)
1109 				revents |= events & (POLLIN | POLLRDNORM);
1110 			else
1111 				revents |= events & POLLIN;
1112 		} else {
1113 			selrecord(p, &d->bd_sel);
1114 			/* Start the read timeout if necessary */
1115 			if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1116 				callout_reset(&d->bd_callout, d->bd_rtout,
1117 					      bpf_timed_out, d);
1118 				d->bd_state = BPF_WAITING;
1119 			}
1120 		}
1121 	}
1122 
1123 	splx(s);
1124 	return (revents);
1125 }
1126 
1127 static void
1128 filt_bpfrdetach(struct knote *kn)
1129 {
1130 	struct bpf_d *d = kn->kn_hook;
1131 	int s;
1132 
1133 	s = splnet();
1134 	SLIST_REMOVE(&d->bd_sel.sel_klist, kn, knote, kn_selnext);
1135 	splx(s);
1136 }
1137 
1138 static int
1139 filt_bpfread(struct knote *kn, long hint)
1140 {
1141 	struct bpf_d *d = kn->kn_hook;
1142 
1143 	kn->kn_data = d->bd_hlen;
1144 	if (d->bd_immediate)
1145 		kn->kn_data += d->bd_slen;
1146 	return (kn->kn_data > 0);
1147 }
1148 
1149 static const struct filterops bpfread_filtops =
1150 	{ 1, NULL, filt_bpfrdetach, filt_bpfread };
1151 
1152 int
1153 bpfkqfilter(dev, kn)
1154 	dev_t dev;
1155 	struct knote *kn;
1156 {
1157 	struct bpf_d *d = &bpf_dtab[minor(dev)];
1158 	struct klist *klist;
1159 	int s;
1160 
1161 	switch (kn->kn_filter) {
1162 	case EVFILT_READ:
1163 		klist = &d->bd_sel.sel_klist;
1164 		kn->kn_fop = &bpfread_filtops;
1165 		break;
1166 
1167 	default:
1168 		return (1);
1169 	}
1170 
1171 	kn->kn_hook = d;
1172 
1173 	s = splnet();
1174 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1175 	splx(s);
1176 
1177 	return (0);
1178 }
1179 
1180 /*
1181  * Incoming linkage from device drivers.  Process the packet pkt, of length
1182  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
1183  * by each process' filter, and if accepted, stashed into the corresponding
1184  * buffer.
1185  */
1186 void
1187 bpf_tap(arg, pkt, pktlen)
1188 	caddr_t arg;
1189 	u_char *pkt;
1190 	u_int pktlen;
1191 {
1192 	struct bpf_if *bp;
1193 	struct bpf_d *d;
1194 	u_int slen;
1195 	/*
1196 	 * Note that the ipl does not have to be raised at this point.
1197 	 * The only problem that could arise here is that if two different
1198 	 * interfaces shared any data.  This is not the case.
1199 	 */
1200 	bp = (struct bpf_if *)arg;
1201 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1202 		++d->bd_rcount;
1203 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
1204 		if (slen != 0)
1205 			catchpacket(d, pkt, pktlen, slen, memcpy);
1206 	}
1207 }
1208 
1209 /*
1210  * Copy data from an mbuf chain into a buffer.  This code is derived
1211  * from m_copydata in sys/uipc_mbuf.c.
1212  */
1213 static void *
1214 bpf_mcpy(dst_arg, src_arg, len)
1215 	void *dst_arg;
1216 	const void *src_arg;
1217 	size_t len;
1218 {
1219 	const struct mbuf *m;
1220 	u_int count;
1221 	u_char *dst;
1222 
1223 	m = src_arg;
1224 	dst = dst_arg;
1225 	while (len > 0) {
1226 		if (m == 0)
1227 			panic("bpf_mcpy");
1228 		count = min(m->m_len, len);
1229 		memcpy((caddr_t)dst, mtod(m, caddr_t), count);
1230 		m = m->m_next;
1231 		dst += count;
1232 		len -= count;
1233 	}
1234 	return (dst_arg);
1235 }
1236 
1237 /*
1238  * Dispatch a packet to all the listeners on interface bp.
1239  *
1240  * marg    pointer to the packet, either a data buffer or an mbuf chain
1241  * buflen  buffer length, if marg is a data buffer
1242  * cpfn    a function that can copy marg into the listener's buffer
1243  * pktlen  length of the packet
1244  * rcvif   either NULL or the interface the packet came in on.
1245  */
1246 static __inline void
1247 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
1248     void *marg, u_int pktlen, u_int buflen, struct ifnet *rcvif)
1249 {
1250 	u_int slen;
1251 	struct bpf_d *d;
1252 
1253 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1254 		if (!d->bd_seesent && (rcvif == NULL))
1255 			continue;
1256 		++d->bd_rcount;
1257 		slen = bpf_filter(d->bd_filter, marg, pktlen, buflen);
1258 		if (slen != 0)
1259 			catchpacket(d, marg, pktlen, slen, cpfn);
1260 	}
1261 }
1262 
1263 /*
1264  * Incoming linkage from device drivers, when the head of the packet is in
1265  * a buffer, and the tail is in an mbuf chain.
1266  */
1267 void
1268 bpf_mtap2(arg, data, dlen, m)
1269 	caddr_t arg;
1270 	void *data;
1271 	u_int dlen;
1272 	struct mbuf *m;
1273 {
1274 	struct bpf_if *bp = (struct bpf_if *)arg;
1275 	u_int pktlen;
1276 	struct mbuf mb;
1277 
1278 	pktlen = m_length(m) + dlen;
1279 
1280 	/*
1281 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
1282 	 * Note that we cut corners here; we only setup what's
1283 	 * absolutely needed--this mbuf should never go anywhere else.
1284 	 */
1285 	(void)memset(&mb, 0, sizeof(mb));
1286 	mb.m_next = m;
1287 	mb.m_data = data;
1288 	mb.m_len = dlen;
1289 
1290 	bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, m->m_pkthdr.rcvif);
1291 }
1292 
1293 /*
1294  * Incoming linkage from device drivers, when packet is in an mbuf chain.
1295  */
1296 void
1297 bpf_mtap(arg, m)
1298 	caddr_t arg;
1299 	struct mbuf *m;
1300 {
1301 	void *(*cpfn) __P((void *, const void *, size_t));
1302 	struct bpf_if *bp = (struct bpf_if *)arg;
1303 	u_int pktlen, buflen;
1304 	void *marg;
1305 
1306 	pktlen = m_length(m);
1307 
1308 	if (pktlen == m->m_len) {
1309 		cpfn = memcpy;
1310 		marg = mtod(m, void *);
1311 		buflen = pktlen;
1312 	} else {
1313 		cpfn = bpf_mcpy;
1314 		marg = m;
1315 		buflen = 0;
1316 	}
1317 
1318 	bpf_deliver(bp, cpfn, marg, pktlen, buflen, m->m_pkthdr.rcvif);
1319 }
1320 
1321 /*
1322  * Move the packet data from interface memory (pkt) into the
1323  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
1324  * otherwise 0.  "copy" is the routine called to do the actual data
1325  * transfer.  memcpy is passed in to copy contiguous chunks, while
1326  * bpf_mcpy is passed in to copy mbuf chains.  In the latter case,
1327  * pkt is really an mbuf.
1328  */
1329 static void
1330 catchpacket(d, pkt, pktlen, snaplen, cpfn)
1331 	struct bpf_d *d;
1332 	u_char *pkt;
1333 	u_int pktlen, snaplen;
1334 	void *(*cpfn) __P((void *, const void *, size_t));
1335 {
1336 	struct bpf_hdr *hp;
1337 	int totlen, curlen;
1338 	int hdrlen = d->bd_bif->bif_hdrlen;
1339 
1340 	++d->bd_ccount;
1341 	/*
1342 	 * Figure out how many bytes to move.  If the packet is
1343 	 * greater or equal to the snapshot length, transfer that
1344 	 * much.  Otherwise, transfer the whole packet (unless
1345 	 * we hit the buffer size limit).
1346 	 */
1347 	totlen = hdrlen + min(snaplen, pktlen);
1348 	if (totlen > d->bd_bufsize)
1349 		totlen = d->bd_bufsize;
1350 
1351 	/*
1352 	 * Round up the end of the previous packet to the next longword.
1353 	 */
1354 	curlen = BPF_WORDALIGN(d->bd_slen);
1355 	if (curlen + totlen > d->bd_bufsize) {
1356 		/*
1357 		 * This packet will overflow the storage buffer.
1358 		 * Rotate the buffers if we can, then wakeup any
1359 		 * pending reads.
1360 		 */
1361 		if (d->bd_fbuf == 0) {
1362 			/*
1363 			 * We haven't completed the previous read yet,
1364 			 * so drop the packet.
1365 			 */
1366 			++d->bd_dcount;
1367 			return;
1368 		}
1369 		ROTATE_BUFFERS(d);
1370 		bpf_wakeup(d);
1371 		curlen = 0;
1372 	}
1373 
1374 	/*
1375 	 * Append the bpf header.
1376 	 */
1377 	hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
1378 	microtime(&hp->bh_tstamp);
1379 	hp->bh_datalen = pktlen;
1380 	hp->bh_hdrlen = hdrlen;
1381 	/*
1382 	 * Copy the packet data into the store buffer and update its length.
1383 	 */
1384 	(*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
1385 	d->bd_slen = curlen + totlen;
1386 
1387 	/*
1388 	 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
1389 	 * will cause filt_bpfread() to be called with it adjusted.
1390 	 */
1391 	if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
1392 		/*
1393 		 * Immediate mode is set, or the read timeout has
1394 		 * already expired during a select call.  A packet
1395 		 * arrived, so the reader should be woken up.
1396 		 */
1397 		bpf_wakeup(d);
1398 }
1399 
1400 /*
1401  * Initialize all nonzero fields of a descriptor.
1402  */
1403 static int
1404 bpf_allocbufs(d)
1405 	struct bpf_d *d;
1406 {
1407 
1408 	d->bd_fbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
1409 	if (!d->bd_fbuf)
1410 		return (ENOBUFS);
1411 	d->bd_sbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
1412 	if (!d->bd_sbuf) {
1413 		free(d->bd_fbuf, M_DEVBUF);
1414 		return (ENOBUFS);
1415 	}
1416 	d->bd_slen = 0;
1417 	d->bd_hlen = 0;
1418 	return (0);
1419 }
1420 
1421 /*
1422  * Free buffers currently in use by a descriptor.
1423  * Called on close.
1424  */
1425 static void
1426 bpf_freed(d)
1427 	struct bpf_d *d;
1428 {
1429 	/*
1430 	 * We don't need to lock out interrupts since this descriptor has
1431 	 * been detached from its interface and it yet hasn't been marked
1432 	 * free.
1433 	 */
1434 	if (d->bd_sbuf != 0) {
1435 		free(d->bd_sbuf, M_DEVBUF);
1436 		if (d->bd_hbuf != 0)
1437 			free(d->bd_hbuf, M_DEVBUF);
1438 		if (d->bd_fbuf != 0)
1439 			free(d->bd_fbuf, M_DEVBUF);
1440 	}
1441 	if (d->bd_filter)
1442 		free((caddr_t)d->bd_filter, M_DEVBUF);
1443 
1444 	D_MARKFREE(d);
1445 }
1446 
1447 /*
1448  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
1449  * fixed size of the link header (variable length headers not yet supported).
1450  */
1451 void
1452 bpfattach(ifp, dlt, hdrlen)
1453 	struct ifnet *ifp;
1454 	u_int dlt, hdrlen;
1455 {
1456 
1457 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
1458 }
1459 
1460 /*
1461  * Attach additional dlt for a interface to bpf.  dlt is the link layer type;
1462  * hdrlen is the fixed size of the link header for the specified dlt
1463  * (variable length headers not yet supported).
1464  */
1465 void
1466 bpfattach2(ifp, dlt, hdrlen, driverp)
1467 	struct ifnet *ifp;
1468 	u_int dlt, hdrlen;
1469 	caddr_t *driverp;
1470 {
1471 	struct bpf_if *bp;
1472 	bp = (struct bpf_if *)malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
1473 	if (bp == 0)
1474 		panic("bpfattach");
1475 
1476 	bp->bif_dlist = 0;
1477 	bp->bif_driverp = (struct bpf_if **)driverp;
1478 	bp->bif_ifp = ifp;
1479 	bp->bif_dlt = dlt;
1480 
1481 	bp->bif_next = bpf_iflist;
1482 	bpf_iflist = bp;
1483 
1484 	*bp->bif_driverp = 0;
1485 
1486 	/*
1487 	 * Compute the length of the bpf header.  This is not necessarily
1488 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1489 	 * that the network layer header begins on a longword boundary (for
1490 	 * performance reasons and to alleviate alignment restrictions).
1491 	 */
1492 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1493 
1494 #if 0
1495 	printf("bpf: %s attached\n", ifp->if_xname);
1496 #endif
1497 }
1498 
1499 /*
1500  * Remove an interface from bpf.
1501  */
1502 void
1503 bpfdetach(ifp)
1504 	struct ifnet *ifp;
1505 {
1506 	struct bpf_if *bp, **pbp;
1507 	struct bpf_d *d;
1508 	int i, s, cmaj;
1509 
1510 	/* locate the major number */
1511 	cmaj = cdevsw_lookup_major(&bpf_cdevsw);
1512 
1513 	/* Nuke the vnodes for any open instances */
1514 	for (i = 0; i < NBPFILTER; ++i) {
1515 		d = &bpf_dtab[i];
1516 		if (!D_ISFREE(d) && d->bd_bif != NULL &&
1517 		    d->bd_bif->bif_ifp == ifp) {
1518 			/*
1519 			 * Detach the descriptor from an interface now.
1520 			 * It will be free'ed later by close routine.
1521 			 */
1522 			s = splnet();
1523 			d->bd_promisc = 0;	/* we can't touch device. */
1524 			bpf_detachd(d);
1525 			splx(s);
1526 			vdevgone(cmaj, i, i, VCHR);
1527 		}
1528 	}
1529 
1530   again:
1531 	for (bp = bpf_iflist, pbp = &bpf_iflist;
1532 	     bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
1533 		if (bp->bif_ifp == ifp) {
1534 			*pbp = bp->bif_next;
1535 			free(bp, M_DEVBUF);
1536 			goto again;
1537 		}
1538 	}
1539 }
1540 
1541 /*
1542  * Change the data link type of a interface.
1543  */
1544 void
1545 bpf_change_type(ifp, dlt, hdrlen)
1546 	struct ifnet *ifp;
1547 	u_int dlt, hdrlen;
1548 {
1549 	struct bpf_if *bp;
1550 
1551 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1552 		if (bp->bif_driverp == (struct bpf_if **)&ifp->if_bpf)
1553 			break;
1554 	}
1555 	if (bp == NULL)
1556 		panic("bpf_change_type");
1557 
1558 	bp->bif_dlt = dlt;
1559 
1560 	/*
1561 	 * Compute the length of the bpf header.  This is not necessarily
1562 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1563 	 * that the network layer header begins on a longword boundary (for
1564 	 * performance reasons and to alleviate alignment restrictions).
1565 	 */
1566 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1567 }
1568 
1569 /*
1570  * Get a list of available data link type of the interface.
1571  */
1572 static int
1573 bpf_getdltlist(d, bfl)
1574 	struct bpf_d *d;
1575 	struct bpf_dltlist *bfl;
1576 {
1577 	int n, error;
1578 	struct ifnet *ifp;
1579 	struct bpf_if *bp;
1580 
1581 	ifp = d->bd_bif->bif_ifp;
1582 	n = 0;
1583 	error = 0;
1584 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1585 		if (bp->bif_ifp != ifp)
1586 			continue;
1587 		if (bfl->bfl_list != NULL) {
1588 			if (n >= bfl->bfl_len)
1589 				return ENOMEM;
1590 			error = copyout(&bp->bif_dlt,
1591 			    bfl->bfl_list + n, sizeof(u_int));
1592 		}
1593 		n++;
1594 	}
1595 	bfl->bfl_len = n;
1596 	return error;
1597 }
1598 
1599 /*
1600  * Set the data link type of a BPF instance.
1601  */
1602 static int
1603 bpf_setdlt(d, dlt)
1604 	struct bpf_d *d;
1605 	u_int dlt;
1606 {
1607 	int s, error, opromisc;
1608 	struct ifnet *ifp;
1609 	struct bpf_if *bp;
1610 
1611 	if (d->bd_bif->bif_dlt == dlt)
1612 		return 0;
1613 	ifp = d->bd_bif->bif_ifp;
1614 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1615 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
1616 			break;
1617 	}
1618 	if (bp == NULL)
1619 		return EINVAL;
1620 	s = splnet();
1621 	opromisc = d->bd_promisc;
1622 	bpf_detachd(d);
1623 	bpf_attachd(d, bp);
1624 	reset_d(d);
1625 	if (opromisc) {
1626 		error = ifpromisc(bp->bif_ifp, 1);
1627 		if (error)
1628 			printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
1629 			    bp->bif_ifp->if_xname, error);
1630 		else
1631 			d->bd_promisc = 1;
1632 	}
1633 	splx(s);
1634 	return 0;
1635 }
1636 
1637 static int
1638 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
1639 {
1640 	int newsize, error;
1641 	struct sysctlnode node;
1642 
1643 	node = *rnode;
1644 	node.sysctl_data = &newsize;
1645 	newsize = bpf_maxbufsize;
1646 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1647 	if (error || newp == NULL)
1648 		return (error);
1649 
1650 	if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
1651 		return (EINVAL);
1652 
1653 	bpf_maxbufsize = newsize;
1654 
1655 	return (0);
1656 }
1657 
1658 SYSCTL_SETUP(sysctl_net_bfp_setup, "sysctl net.bpf subtree setup")
1659 {
1660 	struct sysctlnode *node;
1661 
1662 	sysctl_createv(clog, 0, NULL, NULL,
1663 		       CTLFLAG_PERMANENT,
1664 		       CTLTYPE_NODE, "net", NULL,
1665 		       NULL, 0, NULL, 0,
1666 		       CTL_NET, CTL_EOL);
1667 
1668 	node = NULL;
1669 	sysctl_createv(clog, 0, NULL, &node,
1670 		       CTLFLAG_PERMANENT,
1671 		       CTLTYPE_NODE, "bpf",
1672 		       SYSCTL_DESCR("BPF options"),
1673 		       NULL, 0, NULL, 0,
1674 		       CTL_NET, CTL_CREATE, CTL_EOL);
1675 	if (node != NULL)
1676 		sysctl_createv(clog, 0, NULL, NULL,
1677 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1678 			CTLTYPE_INT, "maxbufsize",
1679 			SYSCTL_DESCR("Maximum size for data capture buffer"),
1680 			sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
1681 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
1682 }
1683