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