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