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