xref: /netbsd-src/sys/net/bpf.c (revision 5e4c038a45edbc7d63b7c2daa76e29f88b64a4e3)
1 /*	$NetBSD: bpf.c,v 1.64 2002/03/23 15:55:21 darrenr 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. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *	@(#)bpf.c	8.4 (Berkeley) 1/9/95
41  * static char rcsid[] =
42  * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
43  */
44 
45 #include <sys/cdefs.h>
46 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.64 2002/03/23 15:55:21 darrenr Exp $");
47 
48 #include "bpfilter.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/mbuf.h>
53 #include <sys/buf.h>
54 #include <sys/time.h>
55 #include <sys/proc.h>
56 #include <sys/user.h>
57 #include <sys/ioctl.h>
58 #include <sys/map.h>
59 #include <sys/conf.h>
60 #include <sys/vnode.h>
61 
62 #include <sys/file.h>
63 #include <sys/tty.h>
64 #include <sys/uio.h>
65 
66 #include <sys/protosw.h>
67 #include <sys/socket.h>
68 #include <sys/errno.h>
69 #include <sys/kernel.h>
70 #include <sys/poll.h>
71 
72 #include <net/if.h>
73 
74 #include <net/bpf.h>
75 #include <net/bpfdesc.h>
76 
77 #include <net/if_arc.h>
78 #include <net/if_ether.h>
79 
80 #include <netinet/in.h>
81 #include <netinet/if_inarp.h>
82 
83 #ifndef BPF_BUFSIZE
84 # define BPF_BUFSIZE 8192		/* 4096 too small for FDDI frames */
85 #endif
86 
87 #define PRINET  26			/* interruptible */
88 
89 /*
90  * The default read buffer size is patchable.
91  */
92 int bpf_bufsize = BPF_BUFSIZE;
93 
94 /*
95  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
96  *  bpf_dtab holds the descriptors, indexed by minor device #
97  */
98 struct bpf_if	*bpf_iflist;
99 struct bpf_d	bpf_dtab[NBPFILTER];
100 
101 static int	bpf_allocbufs __P((struct bpf_d *));
102 static void	bpf_freed __P((struct bpf_d *));
103 static void	bpf_ifname __P((struct ifnet *, struct ifreq *));
104 static void	*bpf_mcpy __P((void *, const void *, size_t));
105 static int	bpf_movein __P((struct uio *, int, int,
106 			        struct mbuf **, struct sockaddr *));
107 static void	bpf_attachd __P((struct bpf_d *, struct bpf_if *));
108 static void	bpf_detachd __P((struct bpf_d *));
109 static int	bpf_setif __P((struct bpf_d *, struct ifreq *));
110 int		bpfpoll __P((dev_t, int, struct proc *));
111 static __inline void
112 		bpf_wakeup __P((struct bpf_d *));
113 static void	catchpacket __P((struct bpf_d *, u_char *, u_int, u_int,
114 				 void *(*)(void *, const void *, size_t)));
115 static void	reset_d __P((struct bpf_d *));
116 
117 static int
118 bpf_movein(uio, linktype, mtu, mp, sockp)
119 	struct uio *uio;
120 	int linktype;
121 	int mtu;
122 	struct mbuf **mp;
123 	struct sockaddr *sockp;
124 {
125 	struct mbuf *m;
126 	int error;
127 	int len;
128 	int hlen;
129 	int align;
130 
131 	/*
132 	 * Build a sockaddr based on the data link layer type.
133 	 * We do this at this level because the ethernet header
134 	 * is copied directly into the data field of the sockaddr.
135 	 * In the case of SLIP, there is no header and the packet
136 	 * is forwarded as is.
137 	 * Also, we are careful to leave room at the front of the mbuf
138 	 * for the link level header.
139 	 */
140 	switch (linktype) {
141 
142 	case DLT_SLIP:
143 		sockp->sa_family = AF_INET;
144 		hlen = 0;
145 		align = 0;
146 		break;
147 
148 	case DLT_PPP:
149 		sockp->sa_family = AF_UNSPEC;
150 		hlen = 0;
151 		align = 0;
152 		break;
153 
154 	case DLT_EN10MB:
155 		sockp->sa_family = AF_UNSPEC;
156 		/* XXX Would MAXLINKHDR be better? */
157  		/* 6(dst)+6(src)+2(type) */
158 		hlen = sizeof(struct ether_header);
159 		align = 2;
160 		break;
161 
162 	case DLT_ARCNET:
163 		sockp->sa_family = AF_UNSPEC;
164 		hlen = ARC_HDRLEN;
165 		align = 5;
166 		break;
167 
168 	case DLT_FDDI:
169 		sockp->sa_family = AF_LINK;
170 		/* XXX 4(FORMAC)+6(dst)+6(src) */
171 		hlen = 16;
172 		align = 0;
173 		break;
174 
175 	case DLT_ECONET:
176 		sockp->sa_family = AF_UNSPEC;
177 		hlen = 6;
178 		align = 2;
179 		break;
180 
181 	case DLT_NULL:
182 		sockp->sa_family = AF_UNSPEC;
183 		hlen = 0;
184 		align = 0;
185 		break;
186 
187 	default:
188 		return (EIO);
189 	}
190 
191 	len = uio->uio_resid;
192 	/*
193 	 * If there aren't enough bytes for a link level header or the
194 	 * packet length exceeds the interface mtu, return an error.
195 	 */
196 	if (len < hlen || len - hlen > mtu)
197 		return (EMSGSIZE);
198 
199 	/*
200 	 * XXX Avoid complicated buffer chaining ---
201 	 * bail if it won't fit in a single mbuf.
202 	 * (Take into account possible alignment bytes)
203 	 */
204 	if ((unsigned)len > MCLBYTES - align)
205 		return (EIO);
206 
207 	MGETHDR(m, M_WAIT, MT_DATA);
208 	if (m == 0)
209 		return (ENOBUFS);
210 	m->m_pkthdr.rcvif = 0;
211 	m->m_pkthdr.len = len - hlen;
212 	if (len > MHLEN - align) {
213 		MCLGET(m, M_WAIT);
214 		if ((m->m_flags & M_EXT) == 0) {
215 			error = ENOBUFS;
216 			goto bad;
217 		}
218 	}
219 
220 	/* Insure the data is properly aligned */
221 	if (align > 0) {
222 		m->m_data += align;
223 		m->m_len -= align;
224 	}
225 
226 	error = uiomove(mtod(m, caddr_t), len, uio);
227 	if (error)
228 		goto bad;
229 	if (hlen != 0) {
230 		memcpy(sockp->sa_data, mtod(m, caddr_t), hlen);
231 		m->m_data += hlen; /* XXX */
232 		len -= hlen;
233 	}
234 	m->m_len = len;
235 	*mp = m;
236 	return (0);
237 
238 bad:
239 	m_freem(m);
240 	return (error);
241 }
242 
243 /*
244  * Attach file to the bpf interface, i.e. make d listen on bp.
245  * Must be called at splnet.
246  */
247 static void
248 bpf_attachd(d, bp)
249 	struct bpf_d *d;
250 	struct bpf_if *bp;
251 {
252 	/*
253 	 * Point d at bp, and add d to the interface's list of listeners.
254 	 * Finally, point the driver's bpf cookie at the interface so
255 	 * it will divert packets to bpf.
256 	 */
257 	d->bd_bif = bp;
258 	d->bd_next = bp->bif_dlist;
259 	bp->bif_dlist = d;
260 
261 	*bp->bif_driverp = bp;
262 }
263 
264 /*
265  * Detach a file from its interface.
266  */
267 static void
268 bpf_detachd(d)
269 	struct bpf_d *d;
270 {
271 	struct bpf_d **p;
272 	struct bpf_if *bp;
273 
274 	bp = d->bd_bif;
275 	/*
276 	 * Check if this descriptor had requested promiscuous mode.
277 	 * If so, turn it off.
278 	 */
279 	if (d->bd_promisc) {
280 		int error;
281 
282 		d->bd_promisc = 0;
283 		/*
284 		 * Take device out of promiscuous mode.  Since we were
285 		 * able to enter promiscuous mode, we should be able
286 		 * to turn it off.  But we can get an error if
287 		 * the interface was configured down, so only panic
288 		 * if we don't get an unexpected error.
289 		 */
290   		error = ifpromisc(bp->bif_ifp, 0);
291 		if (error && error != EINVAL)
292 			panic("bpf: ifpromisc failed");
293 	}
294 	/* Remove d from the interface's descriptor list. */
295 	p = &bp->bif_dlist;
296 	while (*p != d) {
297 		p = &(*p)->bd_next;
298 		if (*p == 0)
299 			panic("bpf_detachd: descriptor not in list");
300 	}
301 	*p = (*p)->bd_next;
302 	if (bp->bif_dlist == 0)
303 		/*
304 		 * Let the driver know that there are no more listeners.
305 		 */
306 		*d->bd_bif->bif_driverp = 0;
307 	d->bd_bif = 0;
308 }
309 
310 
311 /*
312  * Mark a descriptor free by making it point to itself.
313  * This is probably cheaper than marking with a constant since
314  * the address should be in a register anyway.
315  */
316 #define D_ISFREE(d) ((d) == (d)->bd_next)
317 #define D_MARKFREE(d) ((d)->bd_next = (d))
318 #define D_MARKUSED(d) ((d)->bd_next = 0)
319 
320 /*
321  * bpfilterattach() is called at boot time.
322  */
323 /* ARGSUSED */
324 void
325 bpfilterattach(n)
326 	int n;
327 {
328 	int i;
329 	/*
330 	 * Mark all the descriptors free.
331 	 */
332 	for (i = 0; i < NBPFILTER; ++i)
333 		D_MARKFREE(&bpf_dtab[i]);
334 
335 }
336 
337 /*
338  * Open ethernet device.  Returns ENXIO for illegal minor device number,
339  * EBUSY if file is open by another process.
340  */
341 /* ARGSUSED */
342 int
343 bpfopen(dev, flag, mode, p)
344 	dev_t dev;
345 	int flag;
346 	int mode;
347 	struct proc *p;
348 {
349 	struct bpf_d *d;
350 
351 	if (minor(dev) >= NBPFILTER)
352 		return (ENXIO);
353 	/*
354 	 * Each minor can be opened by only one process.  If the requested
355 	 * minor is in use, return EBUSY.
356 	 */
357 	d = &bpf_dtab[minor(dev)];
358 	if (!D_ISFREE(d))
359 		return (EBUSY);
360 
361 	/* Mark "free" and do most initialization. */
362 	memset((char *)d, 0, sizeof(*d));
363 	d->bd_bufsize = bpf_bufsize;
364 
365 	return (0);
366 }
367 
368 /*
369  * Close the descriptor by detaching it from its interface,
370  * deallocating its buffers, and marking it free.
371  */
372 /* ARGSUSED */
373 int
374 bpfclose(dev, flag, mode, p)
375 	dev_t dev;
376 	int flag;
377 	int mode;
378 	struct proc *p;
379 {
380 	struct bpf_d *d = &bpf_dtab[minor(dev)];
381 	int s;
382 
383 	s = splnet();
384 	if (d->bd_bif)
385 		bpf_detachd(d);
386 	splx(s);
387 	bpf_freed(d);
388 
389 	return (0);
390 }
391 
392 /*
393  * Rotate the packet buffers in descriptor d.  Move the store buffer
394  * into the hold slot, and the free buffer into the store slot.
395  * Zero the length of the new store buffer.
396  */
397 #define ROTATE_BUFFERS(d) \
398 	(d)->bd_hbuf = (d)->bd_sbuf; \
399 	(d)->bd_hlen = (d)->bd_slen; \
400 	(d)->bd_sbuf = (d)->bd_fbuf; \
401 	(d)->bd_slen = 0; \
402 	(d)->bd_fbuf = 0;
403 /*
404  *  bpfread - read next chunk of packets from buffers
405  */
406 int
407 bpfread(dev, uio, ioflag)
408 	dev_t dev;
409 	struct uio *uio;
410 	int ioflag;
411 {
412 	struct bpf_d *d = &bpf_dtab[minor(dev)];
413 	int error;
414 	int s;
415 
416 	/*
417 	 * Restrict application to use a buffer the same size as
418 	 * as kernel buffers.
419 	 */
420 	if (uio->uio_resid != d->bd_bufsize)
421 		return (EINVAL);
422 
423 	s = splnet();
424 	/*
425 	 * If the hold buffer is empty, then do a timed sleep, which
426 	 * ends when the timeout expires or when enough packets
427 	 * have arrived to fill the store buffer.
428 	 */
429 	while (d->bd_hbuf == 0) {
430 		if (d->bd_immediate) {
431 			if (d->bd_slen == 0) {
432 				splx(s);
433 				return (EWOULDBLOCK);
434 			}
435 			/*
436 			 * A packet(s) either arrived since the previous
437 			 * read or arrived while we were asleep.
438 			 * Rotate the buffers and return what's here.
439 			 */
440 			ROTATE_BUFFERS(d);
441 			break;
442 		}
443 		if (d->bd_rtout != -1)
444 			error = tsleep((caddr_t)d, PRINET|PCATCH, "bpf",
445 					  d->bd_rtout);
446 		else {
447 			if (d->bd_rtout == -1) {
448 				/* User requested non-blocking I/O */
449 				error = EWOULDBLOCK;
450 			} else
451 				error = 0;
452 		}
453 		if (error == EINTR || error == ERESTART) {
454 			splx(s);
455 			return (error);
456 		}
457 		if (error == EWOULDBLOCK) {
458 			/*
459 			 * On a timeout, return what's in the buffer,
460 			 * which may be nothing.  If there is something
461 			 * in the store buffer, we can rotate the buffers.
462 			 */
463 			if (d->bd_hbuf)
464 				/*
465 				 * We filled up the buffer in between
466 				 * getting the timeout and arriving
467 				 * here, so we don't need to rotate.
468 				 */
469 				break;
470 
471 			if (d->bd_slen == 0) {
472 				splx(s);
473 				return (0);
474 			}
475 			ROTATE_BUFFERS(d);
476 			break;
477 		}
478 		if (error != 0)
479 			goto done;
480 	}
481 	/*
482 	 * At this point, we know we have something in the hold slot.
483 	 */
484 	splx(s);
485 
486 	/*
487 	 * Move data from hold buffer into user space.
488 	 * We know the entire buffer is transferred since
489 	 * we checked above that the read buffer is bpf_bufsize bytes.
490 	 */
491 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
492 
493 	s = splnet();
494 	d->bd_fbuf = d->bd_hbuf;
495 	d->bd_hbuf = 0;
496 	d->bd_hlen = 0;
497 done:
498 	splx(s);
499 	return (error);
500 }
501 
502 
503 /*
504  * If there are processes sleeping on this descriptor, wake them up.
505  */
506 static __inline void
507 bpf_wakeup(d)
508 	struct bpf_d *d;
509 {
510 	struct proc *p;
511 
512 	wakeup((caddr_t)d);
513 	if (d->bd_async) {
514 		if (d->bd_pgid > 0)
515 			gsignal (d->bd_pgid, SIGIO);
516 		else if (d->bd_pgid && (p = pfind (-d->bd_pgid)) != NULL)
517 			psignal (p, SIGIO);
518 	}
519 
520 	selwakeup(&d->bd_sel);
521 	/* XXX */
522 	d->bd_sel.si_pid = 0;
523 }
524 
525 int
526 bpfwrite(dev, uio, ioflag)
527 	dev_t dev;
528 	struct uio *uio;
529 	int ioflag;
530 {
531 	struct bpf_d *d = &bpf_dtab[minor(dev)];
532 	struct ifnet *ifp;
533 	struct mbuf *m;
534 	int error, s;
535 	static struct sockaddr_storage dst;
536 
537 	if (d->bd_bif == 0)
538 		return (ENXIO);
539 
540 	ifp = d->bd_bif->bif_ifp;
541 
542 	if (uio->uio_resid == 0)
543 		return (0);
544 
545 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp->if_mtu, &m,
546 		(struct sockaddr *) &dst);
547 	if (error)
548 		return (error);
549 
550 	if (m->m_pkthdr.len > ifp->if_mtu)
551 		return (EMSGSIZE);
552 
553 	if (d->bd_hdrcmplt)
554 		dst.ss_family = pseudo_AF_HDRCMPLT;
555 
556 	s = splsoftnet();
557 	error = (*ifp->if_output)(ifp, m, (struct sockaddr *) &dst, NULL);
558 	splx(s);
559 	/*
560 	 * The driver frees the mbuf.
561 	 */
562 	return (error);
563 }
564 
565 /*
566  * Reset a descriptor by flushing its packet buffer and clearing the
567  * receive and drop counts.  Should be called at splnet.
568  */
569 static void
570 reset_d(d)
571 	struct bpf_d *d;
572 {
573 	if (d->bd_hbuf) {
574 		/* Free the hold buffer. */
575 		d->bd_fbuf = d->bd_hbuf;
576 		d->bd_hbuf = 0;
577 	}
578 	d->bd_slen = 0;
579 	d->bd_hlen = 0;
580 	d->bd_rcount = 0;
581 	d->bd_dcount = 0;
582 }
583 
584 #ifdef BPF_KERN_FILTER
585 extern struct bpf_insn *bpf_tcp_filter;
586 extern struct bpf_insn *bpf_udp_filter;
587 #endif
588 
589 /*
590  *  FIONREAD		Check for read packet available.
591  *  BIOCGBLEN		Get buffer len [for read()].
592  *  BIOCSETF		Set ethernet read filter.
593  *  BIOCFLUSH		Flush read packet buffer.
594  *  BIOCPROMISC		Put interface into promiscuous mode.
595  *  BIOCGDLT		Get link layer type.
596  *  BIOCGETIF		Get interface name.
597  *  BIOCSETIF		Set interface.
598  *  BIOCSRTIMEOUT	Set read timeout.
599  *  BIOCGRTIMEOUT	Get read timeout.
600  *  BIOCGSTATS		Get packet stats.
601  *  BIOCIMMEDIATE	Set immediate mode.
602  *  BIOCVERSION		Get filter language version.
603  *  BIOGHDRCMPLT	Get "header already complete" flag.
604  *  BIOSHDRCMPLT	Set "header already complete" flag.
605  */
606 /* ARGSUSED */
607 int
608 bpfioctl(dev, cmd, addr, flag, p)
609 	dev_t dev;
610 	u_long cmd;
611 	caddr_t addr;
612 	int flag;
613 	struct proc *p;
614 {
615 	struct bpf_d *d = &bpf_dtab[minor(dev)];
616 	int s, error = 0;
617 #ifdef BPF_KERN_FILTER
618 	struct bpf_insn **p;
619 #endif
620 
621 	switch (cmd) {
622 
623 	default:
624 		error = EINVAL;
625 		break;
626 
627 	/*
628 	 * Check for read packet available.
629 	 */
630 	case FIONREAD:
631 		{
632 			int n;
633 
634 			s = splnet();
635 			n = d->bd_slen;
636 			if (d->bd_hbuf)
637 				n += d->bd_hlen;
638 			splx(s);
639 
640 			*(int *)addr = n;
641 			break;
642 		}
643 
644 	/*
645 	 * Get buffer len [for read()].
646 	 */
647 	case BIOCGBLEN:
648 		*(u_int *)addr = d->bd_bufsize;
649 		break;
650 
651 	/*
652 	 * Set buffer length.
653 	 */
654 	case BIOCSBLEN:
655 		if (d->bd_bif != 0)
656 			error = EINVAL;
657 		else {
658 			u_int size = *(u_int *)addr;
659 
660 			if (size > BPF_MAXBUFSIZE)
661 				*(u_int *)addr = size = BPF_MAXBUFSIZE;
662 			else if (size < BPF_MINBUFSIZE)
663 				*(u_int *)addr = size = BPF_MINBUFSIZE;
664 			d->bd_bufsize = size;
665 		}
666 		break;
667 
668 	/*
669 	 * Set link layer read filter.
670 	 */
671 	case BIOCSETF:
672 		error = bpf_setf(d, (struct bpf_program *)addr);
673 		break;
674 
675 #ifdef BPF_KERN_FILTER
676 	/*
677 	 * Set TCP or UDP reject filter.
678 	 */
679 	case BIOCSTCPF:
680 	case BIOCSUDPF:
681 		if (!suser()) {
682 			error = EPERM;
683 			break;
684 		}
685 
686 		/* Validate and store filter */
687 		error = bpf_setf(d, (struct bpf_program *)addr);
688 
689 		/* Free possible old filter */
690 		if (cmd == BIOCSTCPF)
691 			p = &bpf_tcp_filter;
692 		else
693 			p = &bpf_udp_filter;
694 		if (*p != NULL)
695 			free((caddr_t)*p, M_DEVBUF);
696 
697 		/* Steal new filter (noop if error) */
698 		s = splnet();
699 		*p = d->bd_filter;
700 		d->bd_filter = NULL;
701 		splx(s);
702 		break;
703 #endif
704 
705 	/*
706 	 * Flush read packet buffer.
707 	 */
708 	case BIOCFLUSH:
709 		s = splnet();
710 		reset_d(d);
711 		splx(s);
712 		break;
713 
714 	/*
715 	 * Put interface into promiscuous mode.
716 	 */
717 	case BIOCPROMISC:
718 		if (d->bd_bif == 0) {
719 			/*
720 			 * No interface attached yet.
721 			 */
722 			error = EINVAL;
723 			break;
724 		}
725 		s = splnet();
726 		if (d->bd_promisc == 0) {
727 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
728 			if (error == 0)
729 				d->bd_promisc = 1;
730 		}
731 		splx(s);
732 		break;
733 
734 	/*
735 	 * Get device parameters.
736 	 */
737 	case BIOCGDLT:
738 		if (d->bd_bif == 0)
739 			error = EINVAL;
740 		else
741 			*(u_int *)addr = d->bd_bif->bif_dlt;
742 		break;
743 
744 	/*
745 	 * Set interface name.
746 	 */
747 	case BIOCGETIF:
748 		if (d->bd_bif == 0)
749 			error = EINVAL;
750 		else
751 			bpf_ifname(d->bd_bif->bif_ifp, (struct ifreq *)addr);
752 		break;
753 
754 	/*
755 	 * Set interface.
756 	 */
757 	case BIOCSETIF:
758 		error = bpf_setif(d, (struct ifreq *)addr);
759 		break;
760 
761 	/*
762 	 * Set read timeout.
763 	 */
764 	case BIOCSRTIMEOUT:
765 		{
766 			struct timeval *tv = (struct timeval *)addr;
767 
768 			/* Compute number of ticks. */
769 			d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
770 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
771 				d->bd_rtout = 1;
772 			break;
773 		}
774 
775 	/*
776 	 * Get read timeout.
777 	 */
778 	case BIOCGRTIMEOUT:
779 		{
780 			struct timeval *tv = (struct timeval *)addr;
781 
782 			tv->tv_sec = d->bd_rtout / hz;
783 			tv->tv_usec = (d->bd_rtout % hz) * tick;
784 			break;
785 		}
786 
787 	/*
788 	 * Get packet stats.
789 	 */
790 	case BIOCGSTATS:
791 		{
792 			struct bpf_stat *bs = (struct bpf_stat *)addr;
793 
794 			bs->bs_recv = d->bd_rcount;
795 			bs->bs_drop = d->bd_dcount;
796 			break;
797 		}
798 
799 	/*
800 	 * Set immediate mode.
801 	 */
802 	case BIOCIMMEDIATE:
803 		d->bd_immediate = *(u_int *)addr;
804 		break;
805 
806 	case BIOCVERSION:
807 		{
808 			struct bpf_version *bv = (struct bpf_version *)addr;
809 
810 			bv->bv_major = BPF_MAJOR_VERSION;
811 			bv->bv_minor = BPF_MINOR_VERSION;
812 			break;
813 		}
814 
815 	case BIOCGHDRCMPLT:	/* get "header already complete" flag */
816 		*(u_int *)addr = d->bd_hdrcmplt;
817 		break;
818 
819 	case BIOCSHDRCMPLT:	/* set "header already complete" flag */
820 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
821 		break;
822 
823 	case FIONBIO:		/* Non-blocking I/O */
824 		if (*(int *)addr)
825 			d->bd_rtout = -1;
826 		else
827 			d->bd_rtout = 0;
828 		break;
829 
830 	case FIOASYNC:		/* Send signal on receive packets */
831 		d->bd_async = *(int *)addr;
832 		break;
833 
834 	/*
835 	 * N.B.  ioctl (FIOSETOWN) and fcntl (F_SETOWN) both end up doing
836 	 * the equivalent of a TIOCSPGRP and hence end up here.  *However*
837 	 * TIOCSPGRP's arg is a process group if it's positive and a process
838 	 * id if it's negative.  This is exactly the opposite of what the
839 	 * other two functions want!  Therefore there is code in ioctl and
840 	 * fcntl to negate the arg before calling here.
841 	 */
842 	case TIOCSPGRP:		/* Process or group to send signals to */
843 		d->bd_pgid = *(int *)addr;
844 		break;
845 
846 	case TIOCGPGRP:
847 		*(int *)addr = d->bd_pgid;
848 		break;
849 	}
850 	return (error);
851 }
852 
853 /*
854  * Set d's packet filter program to fp.  If this file already has a filter,
855  * free it and replace it.  Returns EINVAL for bogus requests.
856  */
857 int
858 bpf_setf(d, fp)
859 	struct bpf_d *d;
860 	struct bpf_program *fp;
861 {
862 	struct bpf_insn *fcode, *old;
863 	u_int flen, size;
864 	int s;
865 
866 	old = d->bd_filter;
867 	if (fp->bf_insns == 0) {
868 		if (fp->bf_len != 0)
869 			return (EINVAL);
870 		s = splnet();
871 		d->bd_filter = 0;
872 		reset_d(d);
873 		splx(s);
874 		if (old != 0)
875 			free((caddr_t)old, M_DEVBUF);
876 		return (0);
877 	}
878 	flen = fp->bf_len;
879 	if (flen > BPF_MAXINSNS)
880 		return (EINVAL);
881 
882 	size = flen * sizeof(*fp->bf_insns);
883 	fcode = (struct bpf_insn *)malloc(size, M_DEVBUF, M_WAITOK);
884 	if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) == 0 &&
885 	    bpf_validate(fcode, (int)flen)) {
886 		s = splnet();
887 		d->bd_filter = fcode;
888 		reset_d(d);
889 		splx(s);
890 		if (old != 0)
891 			free((caddr_t)old, M_DEVBUF);
892 
893 		return (0);
894 	}
895 	free((caddr_t)fcode, M_DEVBUF);
896 	return (EINVAL);
897 }
898 
899 /*
900  * Detach a file from its current interface (if attached at all) and attach
901  * to the interface indicated by the name stored in ifr.
902  * Return an errno or 0.
903  */
904 static int
905 bpf_setif(d, ifr)
906 	struct bpf_d *d;
907 	struct ifreq *ifr;
908 {
909 	struct bpf_if *bp;
910 	char *cp;
911 	int unit_seen, i, s, error;
912 
913 	/*
914 	 * Make sure the provided name has a unit number, and default
915 	 * it to '0' if not specified.
916 	 * XXX This is ugly ... do this differently?
917 	 */
918 	unit_seen = 0;
919 	cp = ifr->ifr_name;
920 	cp[sizeof(ifr->ifr_name) - 1] = '\0';	/* sanity */
921 	while (*cp++)
922 		if (*cp >= '0' && *cp <= '9')
923 			unit_seen = 1;
924 	if (!unit_seen) {
925 		/* Make sure to leave room for the '\0'. */
926 		for (i = 0; i < (IFNAMSIZ - 1); ++i) {
927 			if ((ifr->ifr_name[i] >= 'a' &&
928 			     ifr->ifr_name[i] <= 'z') ||
929 			    (ifr->ifr_name[i] >= 'A' &&
930 			     ifr->ifr_name[i] <= 'Z'))
931 				continue;
932 			ifr->ifr_name[i] = '0';
933 		}
934 	}
935 
936 	/*
937 	 * Look through attached interfaces for the named one.
938 	 */
939 	for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
940 		struct ifnet *ifp = bp->bif_ifp;
941 
942 		if (ifp == 0 ||
943 		    strcmp(ifp->if_xname, ifr->ifr_name) != 0)
944 			continue;
945 		/*
946 		 * We found the requested interface.
947 		 * If it's not up, return an error.
948 		 * Allocate the packet buffers if we need to.
949 		 * If we're already attached to requested interface,
950 		 * just flush the buffer.
951 		 */
952 		if ((ifp->if_flags & IFF_UP) == 0)
953 			return (ENETDOWN);
954 
955 		if (d->bd_sbuf == 0) {
956 			error = bpf_allocbufs(d);
957 			if (error != 0)
958 				return (error);
959 		}
960 		s = splnet();
961 		if (bp != d->bd_bif) {
962 			if (d->bd_bif)
963 				/*
964 				 * Detach if attached to something else.
965 				 */
966 				bpf_detachd(d);
967 
968 			bpf_attachd(d, bp);
969 		}
970 		reset_d(d);
971 		splx(s);
972 		return (0);
973 	}
974 	/* Not found. */
975 	return (ENXIO);
976 }
977 
978 /*
979  * Copy the interface name to the ifreq.
980  */
981 static void
982 bpf_ifname(ifp, ifr)
983 	struct ifnet *ifp;
984 	struct ifreq *ifr;
985 {
986 
987 	memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
988 }
989 
990 /*
991  * Support for poll() system call
992  *
993  * Return true iff the specific operation will not block indefinitely - with
994  * the assumption that it is safe to positively acknowledge a request for the
995  * ability to write to the BPF device.
996  * Otherwise, return false but make a note that a selwakeup() must be done.
997  */
998 int
999 bpfpoll(dev, events, p)
1000 	dev_t dev;
1001 	int events;
1002 	struct proc *p;
1003 {
1004 	struct bpf_d *d = &bpf_dtab[minor(dev)];
1005 	int s = splnet();
1006 	int revents;
1007 
1008 	revents = events & (POLLOUT | POLLWRNORM);
1009 	if (events & (POLLIN | POLLRDNORM)) {
1010 		/*
1011 		 * An imitation of the FIONREAD ioctl code.
1012 		 */
1013 		if (d->bd_hlen != 0 || (d->bd_immediate && d->bd_slen != 0))
1014 			revents |= events & (POLLIN | POLLRDNORM);
1015 		else
1016 			selrecord(p, &d->bd_sel);
1017 	}
1018 
1019 	splx(s);
1020 	return (revents);
1021 }
1022 
1023 /*
1024  * Incoming linkage from device drivers.  Process the packet pkt, of length
1025  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
1026  * by each process' filter, and if accepted, stashed into the corresponding
1027  * buffer.
1028  */
1029 void
1030 bpf_tap(arg, pkt, pktlen)
1031 	caddr_t arg;
1032 	u_char *pkt;
1033 	u_int pktlen;
1034 {
1035 	struct bpf_if *bp;
1036 	struct bpf_d *d;
1037 	u_int slen;
1038 	/*
1039 	 * Note that the ipl does not have to be raised at this point.
1040 	 * The only problem that could arise here is that if two different
1041 	 * interfaces shared any data.  This is not the case.
1042 	 */
1043 	bp = (struct bpf_if *)arg;
1044 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1045 		++d->bd_rcount;
1046 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
1047 		if (slen != 0)
1048 			catchpacket(d, pkt, pktlen, slen, memcpy);
1049 	}
1050 }
1051 
1052 /*
1053  * Copy data from an mbuf chain into a buffer.  This code is derived
1054  * from m_copydata in sys/uipc_mbuf.c.
1055  */
1056 static void *
1057 bpf_mcpy(dst_arg, src_arg, len)
1058 	void *dst_arg;
1059 	const void *src_arg;
1060 	size_t len;
1061 {
1062 	const struct mbuf *m;
1063 	u_int count;
1064 	u_char *dst;
1065 
1066 	m = src_arg;
1067 	dst = dst_arg;
1068 	while (len > 0) {
1069 		if (m == 0)
1070 			panic("bpf_mcpy");
1071 		count = min(m->m_len, len);
1072 		memcpy((caddr_t)dst, mtod(m, caddr_t), count);
1073 		m = m->m_next;
1074 		dst += count;
1075 		len -= count;
1076 	}
1077 	return(dst_arg);
1078 }
1079 
1080 /*
1081  * Incoming linkage from device drivers, when packet is in an mbuf chain.
1082  */
1083 void
1084 bpf_mtap(arg, m)
1085 	caddr_t arg;
1086 	struct mbuf *m;
1087 {
1088 	struct bpf_if *bp = (struct bpf_if *)arg;
1089 	struct bpf_d *d;
1090 	u_int pktlen, slen;
1091 	struct mbuf *m0;
1092 
1093 	pktlen = 0;
1094 	for (m0 = m; m0 != 0; m0 = m0->m_next)
1095 		pktlen += m0->m_len;
1096 
1097 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1098 		++d->bd_rcount;
1099 		slen = bpf_filter(d->bd_filter, (u_char *)m, pktlen, 0);
1100 		if (slen != 0)
1101 			catchpacket(d, (u_char *)m, pktlen, slen, bpf_mcpy);
1102 	}
1103 }
1104 
1105 /*
1106  * Move the packet data from interface memory (pkt) into the
1107  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
1108  * otherwise 0.  "copy" is the routine called to do the actual data
1109  * transfer.  memcpy is passed in to copy contiguous chunks, while
1110  * bpf_mcpy is passed in to copy mbuf chains.  In the latter case,
1111  * pkt is really an mbuf.
1112  */
1113 static void
1114 catchpacket(d, pkt, pktlen, snaplen, cpfn)
1115 	struct bpf_d *d;
1116 	u_char *pkt;
1117 	u_int pktlen, snaplen;
1118 	void *(*cpfn) __P((void *, const void *, size_t));
1119 {
1120 	struct bpf_hdr *hp;
1121 	int totlen, curlen;
1122 	int hdrlen = d->bd_bif->bif_hdrlen;
1123 	/*
1124 	 * Figure out how many bytes to move.  If the packet is
1125 	 * greater or equal to the snapshot length, transfer that
1126 	 * much.  Otherwise, transfer the whole packet (unless
1127 	 * we hit the buffer size limit).
1128 	 */
1129 	totlen = hdrlen + min(snaplen, pktlen);
1130 	if (totlen > d->bd_bufsize)
1131 		totlen = d->bd_bufsize;
1132 
1133 	/*
1134 	 * Round up the end of the previous packet to the next longword.
1135 	 */
1136 	curlen = BPF_WORDALIGN(d->bd_slen);
1137 	if (curlen + totlen > d->bd_bufsize) {
1138 		/*
1139 		 * This packet will overflow the storage buffer.
1140 		 * Rotate the buffers if we can, then wakeup any
1141 		 * pending reads.
1142 		 */
1143 		if (d->bd_fbuf == 0) {
1144 			/*
1145 			 * We haven't completed the previous read yet,
1146 			 * so drop the packet.
1147 			 */
1148 			++d->bd_dcount;
1149 			return;
1150 		}
1151 		ROTATE_BUFFERS(d);
1152 		bpf_wakeup(d);
1153 		curlen = 0;
1154 	}
1155 	else if (d->bd_immediate)
1156 		/*
1157 		 * Immediate mode is set.  A packet arrived so any
1158 		 * reads should be woken up.
1159 		 */
1160 		bpf_wakeup(d);
1161 
1162 	/*
1163 	 * Append the bpf header.
1164 	 */
1165 	hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
1166 	microtime(&hp->bh_tstamp);
1167 	hp->bh_datalen = pktlen;
1168 	hp->bh_hdrlen = hdrlen;
1169 	/*
1170 	 * Copy the packet data into the store buffer and update its length.
1171 	 */
1172 	(*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
1173 	d->bd_slen = curlen + totlen;
1174 }
1175 
1176 /*
1177  * Initialize all nonzero fields of a descriptor.
1178  */
1179 static int
1180 bpf_allocbufs(d)
1181 	struct bpf_d *d;
1182 {
1183 
1184 	d->bd_fbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_WAITOK);
1185 	d->bd_sbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_WAITOK);
1186 	d->bd_slen = 0;
1187 	d->bd_hlen = 0;
1188 	return (0);
1189 }
1190 
1191 /*
1192  * Free buffers currently in use by a descriptor.
1193  * Called on close.
1194  */
1195 static void
1196 bpf_freed(d)
1197 	struct bpf_d *d;
1198 {
1199 	/*
1200 	 * We don't need to lock out interrupts since this descriptor has
1201 	 * been detached from its interface and it yet hasn't been marked
1202 	 * free.
1203 	 */
1204 	if (d->bd_sbuf != 0) {
1205 		free(d->bd_sbuf, M_DEVBUF);
1206 		if (d->bd_hbuf != 0)
1207 			free(d->bd_hbuf, M_DEVBUF);
1208 		if (d->bd_fbuf != 0)
1209 			free(d->bd_fbuf, M_DEVBUF);
1210 	}
1211 	if (d->bd_filter)
1212 		free((caddr_t)d->bd_filter, M_DEVBUF);
1213 
1214 	D_MARKFREE(d);
1215 }
1216 
1217 /*
1218  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
1219  * fixed size of the link header (variable length headers not yet supported).
1220  */
1221 void
1222 bpfattach(ifp, dlt, hdrlen)
1223 	struct ifnet *ifp;
1224 	u_int dlt, hdrlen;
1225 {
1226 	struct bpf_if *bp;
1227 	bp = (struct bpf_if *)malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
1228 	if (bp == 0)
1229 		panic("bpfattach");
1230 
1231 	bp->bif_dlist = 0;
1232 	bp->bif_driverp = (struct bpf_if **)&ifp->if_bpf;
1233 	bp->bif_ifp = ifp;
1234 	bp->bif_dlt = dlt;
1235 
1236 	bp->bif_next = bpf_iflist;
1237 	bpf_iflist = bp;
1238 
1239 	*bp->bif_driverp = 0;
1240 
1241 	/*
1242 	 * Compute the length of the bpf header.  This is not necessarily
1243 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1244 	 * that the network layer header begins on a longword boundary (for
1245 	 * performance reasons and to alleviate alignment restrictions).
1246 	 */
1247 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1248 
1249 #if 0
1250 	printf("bpf: %s attached\n", ifp->if_xname);
1251 #endif
1252 }
1253 
1254 /*
1255  * Remove an interface from bpf.
1256  */
1257 void
1258 bpfdetach(ifp)
1259 	struct ifnet *ifp;
1260 {
1261 	struct bpf_if *bp, **pbp;
1262 	struct bpf_d *d;
1263 	int i, s, cmaj;
1264 
1265 	/* locate the major number */
1266 	for (cmaj = 0; cmaj <= nchrdev; cmaj++)
1267 		if (cdevsw[cmaj].d_open == bpfopen)
1268 			break;
1269 
1270 	/* Nuke the vnodes for any open instances */
1271 	for (i = 0; i < NBPFILTER; ++i) {
1272 		d = &bpf_dtab[i];
1273 		if (!D_ISFREE(d) && d->bd_bif != NULL &&
1274 		    d->bd_bif->bif_ifp == ifp) {
1275 			/*
1276 			 * Detach the descriptor from an interface now.
1277 			 * It will be free'ed later by close routine.
1278 			 */
1279 			s = splnet();
1280 			d->bd_promisc = 0;	/* we can't touch device. */
1281 			bpf_detachd(d);
1282 			splx(s);
1283 			vdevgone(cmaj, i, i, VCHR);
1284 		}
1285 	}
1286 
1287 	for (bp = bpf_iflist, pbp = &bpf_iflist;
1288 	     bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
1289 		if (bp->bif_ifp == ifp) {
1290 			*pbp = bp->bif_next;
1291 			free(bp, M_DEVBUF);
1292 			break;
1293 		}
1294 	}
1295 }
1296 
1297 /*
1298  * Change the data link type of a BPF instance.
1299  */
1300 void
1301 bpf_change_type(ifp, dlt, hdrlen)
1302 	struct ifnet *ifp;
1303 	u_int dlt, hdrlen;
1304 {
1305 	struct bpf_if *bp;
1306 
1307 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1308 		if (bp->bif_driverp == (struct bpf_if **)&ifp->if_bpf)
1309 			break;
1310 	}
1311 	if (bp == NULL)
1312 		panic("bpf_change_type");
1313 
1314 	bp->bif_dlt = dlt;
1315 
1316 	/*
1317 	 * Compute the length of the bpf header.  This is not necessarily
1318 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1319 	 * that the network layer header begins on a longword boundary (for
1320 	 * performance reasons and to alleviate alignment restrictions).
1321 	 */
1322 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1323 }
1324