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