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