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