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