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