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