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