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