Home | History | Annotate | Line # | Download | only in net
bpf.c revision 1.82.2.3
      1 /*	$NetBSD: bpf.c,v 1.82.2.3 2004/08/12 11:42:20 skrll 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. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)bpf.c	8.4 (Berkeley) 1/9/95
     37  * static char rcsid[] =
     38  * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
     39  */
     40 
     41 #include <sys/cdefs.h>
     42 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.82.2.3 2004/08/12 11:42:20 skrll Exp $");
     43 
     44 #include "bpfilter.h"
     45 
     46 #include <sys/param.h>
     47 #include <sys/systm.h>
     48 #include <sys/mbuf.h>
     49 #include <sys/buf.h>
     50 #include <sys/time.h>
     51 #include <sys/proc.h>
     52 #include <sys/user.h>
     53 #include <sys/ioctl.h>
     54 #include <sys/conf.h>
     55 #include <sys/vnode.h>
     56 
     57 #include <sys/file.h>
     58 #include <sys/tty.h>
     59 #include <sys/uio.h>
     60 
     61 #include <sys/protosw.h>
     62 #include <sys/socket.h>
     63 #include <sys/errno.h>
     64 #include <sys/kernel.h>
     65 #include <sys/poll.h>
     66 #include <sys/sysctl.h>
     67 
     68 #include <net/if.h>
     69 
     70 #include <net/bpf.h>
     71 #include <net/bpfdesc.h>
     72 
     73 #include <net/if_arc.h>
     74 #include <net/if_ether.h>
     75 
     76 #include <netinet/in.h>
     77 #include <netinet/if_inarp.h>
     78 
     79 #if defined(_KERNEL_OPT)
     80 #include "opt_bpf.h"
     81 #endif
     82 
     83 #ifndef BPF_BUFSIZE
     84 /*
     85  * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
     86  * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
     87  */
     88 # define BPF_BUFSIZE 32768
     89 #endif
     90 
     91 #define PRINET  26			/* interruptible */
     92 
     93 /*
     94  * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
     95  * XXX the default values should be computed dynamically based
     96  * on available memory size and available mbuf clusters.
     97  */
     98 int bpf_bufsize = BPF_BUFSIZE;
     99 int bpf_maxbufsize = BPF_DFLTBUFSIZE;	/* XXX set dynamically, see above */
    100 
    101 /*
    102  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
    103  *  bpf_dtab holds the descriptors, indexed by minor device #
    104  */
    105 struct bpf_if	*bpf_iflist;
    106 struct bpf_d	bpf_dtab[NBPFILTER];
    107 
    108 static int	bpf_allocbufs __P((struct bpf_d *));
    109 static void	bpf_deliver(struct bpf_if *,
    110 		            void *(*cpfn)(void *, const void *, size_t),
    111 			    void *, u_int, u_int, struct ifnet *);
    112 static void	bpf_freed __P((struct bpf_d *));
    113 static void	bpf_ifname __P((struct ifnet *, struct ifreq *));
    114 static void	*bpf_mcpy __P((void *, const void *, size_t));
    115 static int	bpf_movein __P((struct uio *, int, int,
    116 			        struct mbuf **, struct sockaddr *));
    117 static void	bpf_attachd __P((struct bpf_d *, struct bpf_if *));
    118 static void	bpf_detachd __P((struct bpf_d *));
    119 static int	bpf_setif __P((struct bpf_d *, struct ifreq *));
    120 static void	bpf_timed_out __P((void *));
    121 static __inline void
    122 		bpf_wakeup __P((struct bpf_d *));
    123 static void	catchpacket __P((struct bpf_d *, u_char *, u_int, u_int,
    124 				 void *(*)(void *, const void *, size_t)));
    125 static void	reset_d __P((struct bpf_d *));
    126 static int	bpf_getdltlist __P((struct bpf_d *, struct bpf_dltlist *));
    127 static int	bpf_setdlt __P((struct bpf_d *, u_int));
    128 
    129 dev_type_open(bpfopen);
    130 dev_type_close(bpfclose);
    131 dev_type_read(bpfread);
    132 dev_type_write(bpfwrite);
    133 dev_type_ioctl(bpfioctl);
    134 dev_type_poll(bpfpoll);
    135 dev_type_kqfilter(bpfkqfilter);
    136 
    137 const struct cdevsw bpf_cdevsw = {
    138 	bpfopen, bpfclose, bpfread, bpfwrite, bpfioctl,
    139 	nostop, notty, bpfpoll, nommap, bpfkqfilter,
    140 };
    141 
    142 static int
    143 bpf_movein(uio, linktype, mtu, mp, sockp)
    144 	struct uio *uio;
    145 	int linktype;
    146 	int mtu;
    147 	struct mbuf **mp;
    148 	struct sockaddr *sockp;
    149 {
    150 	struct mbuf *m;
    151 	int error;
    152 	int len;
    153 	int hlen;
    154 	int align;
    155 
    156 	/*
    157 	 * Build a sockaddr based on the data link layer type.
    158 	 * We do this at this level because the ethernet header
    159 	 * is copied directly into the data field of the sockaddr.
    160 	 * In the case of SLIP, there is no header and the packet
    161 	 * is forwarded as is.
    162 	 * Also, we are careful to leave room at the front of the mbuf
    163 	 * for the link level header.
    164 	 */
    165 	switch (linktype) {
    166 
    167 	case DLT_SLIP:
    168 		sockp->sa_family = AF_INET;
    169 		hlen = 0;
    170 		align = 0;
    171 		break;
    172 
    173 	case DLT_PPP:
    174 		sockp->sa_family = AF_UNSPEC;
    175 		hlen = 0;
    176 		align = 0;
    177 		break;
    178 
    179 	case DLT_EN10MB:
    180 		sockp->sa_family = AF_UNSPEC;
    181 		/* XXX Would MAXLINKHDR be better? */
    182  		/* 6(dst)+6(src)+2(type) */
    183 		hlen = sizeof(struct ether_header);
    184 		align = 2;
    185 		break;
    186 
    187 	case DLT_ARCNET:
    188 		sockp->sa_family = AF_UNSPEC;
    189 		hlen = ARC_HDRLEN;
    190 		align = 5;
    191 		break;
    192 
    193 	case DLT_FDDI:
    194 		sockp->sa_family = AF_LINK;
    195 		/* XXX 4(FORMAC)+6(dst)+6(src) */
    196 		hlen = 16;
    197 		align = 0;
    198 		break;
    199 
    200 	case DLT_ECONET:
    201 		sockp->sa_family = AF_UNSPEC;
    202 		hlen = 6;
    203 		align = 2;
    204 		break;
    205 
    206 	case DLT_NULL:
    207 		sockp->sa_family = AF_UNSPEC;
    208 		hlen = 0;
    209 		align = 0;
    210 		break;
    211 
    212 	default:
    213 		return (EIO);
    214 	}
    215 
    216 	len = uio->uio_resid;
    217 	/*
    218 	 * If there aren't enough bytes for a link level header or the
    219 	 * packet length exceeds the interface mtu, return an error.
    220 	 */
    221 	if (len < hlen || len - hlen > mtu)
    222 		return (EMSGSIZE);
    223 
    224 	/*
    225 	 * XXX Avoid complicated buffer chaining ---
    226 	 * bail if it won't fit in a single mbuf.
    227 	 * (Take into account possible alignment bytes)
    228 	 */
    229 	if ((unsigned)len > MCLBYTES - align)
    230 		return (EIO);
    231 
    232 	m = m_gethdr(M_WAIT, MT_DATA);
    233 	m->m_pkthdr.rcvif = 0;
    234 	m->m_pkthdr.len = len - hlen;
    235 	if (len > MHLEN - align) {
    236 		m_clget(m, M_WAIT);
    237 		if ((m->m_flags & M_EXT) == 0) {
    238 			error = ENOBUFS;
    239 			goto bad;
    240 		}
    241 	}
    242 
    243 	/* Insure the data is properly aligned */
    244 	if (align > 0) {
    245 		m->m_data += align;
    246 		m->m_len -= align;
    247 	}
    248 
    249 	error = uiomove(mtod(m, caddr_t), len, uio);
    250 	if (error)
    251 		goto bad;
    252 	if (hlen != 0) {
    253 		memcpy(sockp->sa_data, mtod(m, caddr_t), hlen);
    254 		m->m_data += hlen; /* XXX */
    255 		len -= hlen;
    256 	}
    257 	m->m_len = len;
    258 	*mp = m;
    259 	return (0);
    260 
    261 bad:
    262 	m_freem(m);
    263 	return (error);
    264 }
    265 
    266 /*
    267  * Attach file to the bpf interface, i.e. make d listen on bp.
    268  * Must be called at splnet.
    269  */
    270 static void
    271 bpf_attachd(d, bp)
    272 	struct bpf_d *d;
    273 	struct bpf_if *bp;
    274 {
    275 	/*
    276 	 * Point d at bp, and add d to the interface's list of listeners.
    277 	 * Finally, point the driver's bpf cookie at the interface so
    278 	 * it will divert packets to bpf.
    279 	 */
    280 	d->bd_bif = bp;
    281 	d->bd_next = bp->bif_dlist;
    282 	bp->bif_dlist = d;
    283 
    284 	*bp->bif_driverp = bp;
    285 }
    286 
    287 /*
    288  * Detach a file from its interface.
    289  */
    290 static void
    291 bpf_detachd(d)
    292 	struct bpf_d *d;
    293 {
    294 	struct bpf_d **p;
    295 	struct bpf_if *bp;
    296 
    297 	bp = d->bd_bif;
    298 	/*
    299 	 * Check if this descriptor had requested promiscuous mode.
    300 	 * If so, turn it off.
    301 	 */
    302 	if (d->bd_promisc) {
    303 		int error;
    304 
    305 		d->bd_promisc = 0;
    306 		/*
    307 		 * Take device out of promiscuous mode.  Since we were
    308 		 * able to enter promiscuous mode, we should be able
    309 		 * to turn it off.  But we can get an error if
    310 		 * the interface was configured down, so only panic
    311 		 * if we don't get an unexpected error.
    312 		 */
    313   		error = ifpromisc(bp->bif_ifp, 0);
    314 		if (error && error != EINVAL)
    315 			panic("bpf: ifpromisc failed");
    316 	}
    317 	/* Remove d from the interface's descriptor list. */
    318 	p = &bp->bif_dlist;
    319 	while (*p != d) {
    320 		p = &(*p)->bd_next;
    321 		if (*p == 0)
    322 			panic("bpf_detachd: descriptor not in list");
    323 	}
    324 	*p = (*p)->bd_next;
    325 	if (bp->bif_dlist == 0)
    326 		/*
    327 		 * Let the driver know that there are no more listeners.
    328 		 */
    329 		*d->bd_bif->bif_driverp = 0;
    330 	d->bd_bif = 0;
    331 }
    332 
    333 
    334 /*
    335  * Mark a descriptor free by making it point to itself.
    336  * This is probably cheaper than marking with a constant since
    337  * the address should be in a register anyway.
    338  */
    339 #define D_ISFREE(d) ((d) == (d)->bd_next)
    340 #define D_MARKFREE(d) ((d)->bd_next = (d))
    341 #define D_MARKUSED(d) ((d)->bd_next = 0)
    342 
    343 /*
    344  * bpfilterattach() is called at boot time.
    345  */
    346 /* ARGSUSED */
    347 void
    348 bpfilterattach(n)
    349 	int n;
    350 {
    351 	int i;
    352 	/*
    353 	 * Mark all the descriptors free.
    354 	 */
    355 	for (i = 0; i < NBPFILTER; ++i)
    356 		D_MARKFREE(&bpf_dtab[i]);
    357 
    358 }
    359 
    360 /*
    361  * Open ethernet device.  Returns ENXIO for illegal minor device number,
    362  * EBUSY if file is open by another process.
    363  */
    364 /* ARGSUSED */
    365 int
    366 bpfopen(dev, flag, mode, l)
    367 	dev_t dev;
    368 	int flag;
    369 	int mode;
    370 	struct lwp *l;
    371 {
    372 	struct bpf_d *d;
    373 
    374 	if (minor(dev) >= NBPFILTER)
    375 		return (ENXIO);
    376 	/*
    377 	 * Each minor can be opened by only one process.  If the requested
    378 	 * minor is in use, return EBUSY.
    379 	 */
    380 	d = &bpf_dtab[minor(dev)];
    381 	if (!D_ISFREE(d))
    382 		return (EBUSY);
    383 
    384 	/* Mark "free" and do most initialization. */
    385 	memset((char *)d, 0, sizeof(*d));
    386 	d->bd_bufsize = bpf_bufsize;
    387 	d->bd_seesent = 1;
    388 	callout_init(&d->bd_callout);
    389 
    390 	return (0);
    391 }
    392 
    393 /*
    394  * Close the descriptor by detaching it from its interface,
    395  * deallocating its buffers, and marking it free.
    396  */
    397 /* ARGSUSED */
    398 int
    399 bpfclose(dev, flag, mode, l)
    400 	dev_t dev;
    401 	int flag;
    402 	int mode;
    403 	struct lwp *l;
    404 {
    405 	struct bpf_d *d = &bpf_dtab[minor(dev)];
    406 	int s;
    407 
    408 	s = splnet();
    409 	if (d->bd_state == BPF_WAITING)
    410 		callout_stop(&d->bd_callout);
    411 	d->bd_state = BPF_IDLE;
    412 	if (d->bd_bif)
    413 		bpf_detachd(d);
    414 	splx(s);
    415 	bpf_freed(d);
    416 
    417 	return (0);
    418 }
    419 
    420 /*
    421  * Rotate the packet buffers in descriptor d.  Move the store buffer
    422  * into the hold slot, and the free buffer into the store slot.
    423  * Zero the length of the new store buffer.
    424  */
    425 #define ROTATE_BUFFERS(d) \
    426 	(d)->bd_hbuf = (d)->bd_sbuf; \
    427 	(d)->bd_hlen = (d)->bd_slen; \
    428 	(d)->bd_sbuf = (d)->bd_fbuf; \
    429 	(d)->bd_slen = 0; \
    430 	(d)->bd_fbuf = 0;
    431 /*
    432  *  bpfread - read next chunk of packets from buffers
    433  */
    434 int
    435 bpfread(dev, uio, ioflag)
    436 	dev_t dev;
    437 	struct uio *uio;
    438 	int ioflag;
    439 {
    440 	struct bpf_d *d = &bpf_dtab[minor(dev)];
    441 	int timed_out;
    442 	int error;
    443 	int s;
    444 
    445 	/*
    446 	 * Restrict application to use a buffer the same size as
    447 	 * as kernel buffers.
    448 	 */
    449 	if (uio->uio_resid != d->bd_bufsize)
    450 		return (EINVAL);
    451 
    452 	s = splnet();
    453 	if (d->bd_state == BPF_WAITING)
    454 		callout_stop(&d->bd_callout);
    455 	timed_out = (d->bd_state == BPF_TIMED_OUT);
    456 	d->bd_state = BPF_IDLE;
    457 	/*
    458 	 * If the hold buffer is empty, then do a timed sleep, which
    459 	 * ends when the timeout expires or when enough packets
    460 	 * have arrived to fill the store buffer.
    461 	 */
    462 	while (d->bd_hbuf == 0) {
    463 		if (ioflag & IO_NDELAY) {
    464 			if (d->bd_slen == 0) {
    465 				splx(s);
    466 				return (EWOULDBLOCK);
    467 			}
    468 			ROTATE_BUFFERS(d);
    469 			break;
    470 		}
    471 
    472 		if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
    473 			/*
    474 			 * A packet(s) either arrived since the previous
    475 			 * read or arrived while we were asleep.
    476 			 * Rotate the buffers and return what's here.
    477 			 */
    478 			ROTATE_BUFFERS(d);
    479 			break;
    480 		}
    481 		error = tsleep((caddr_t)d, PRINET|PCATCH, "bpf",
    482 				d->bd_rtout);
    483 		if (error == EINTR || error == ERESTART) {
    484 			splx(s);
    485 			return (error);
    486 		}
    487 		if (error == EWOULDBLOCK) {
    488 			/*
    489 			 * On a timeout, return what's in the buffer,
    490 			 * which may be nothing.  If there is something
    491 			 * in the store buffer, we can rotate the buffers.
    492 			 */
    493 			if (d->bd_hbuf)
    494 				/*
    495 				 * We filled up the buffer in between
    496 				 * getting the timeout and arriving
    497 				 * here, so we don't need to rotate.
    498 				 */
    499 				break;
    500 
    501 			if (d->bd_slen == 0) {
    502 				splx(s);
    503 				return (0);
    504 			}
    505 			ROTATE_BUFFERS(d);
    506 			break;
    507 		}
    508 		if (error != 0)
    509 			goto done;
    510 	}
    511 	/*
    512 	 * At this point, we know we have something in the hold slot.
    513 	 */
    514 	splx(s);
    515 
    516 	/*
    517 	 * Move data from hold buffer into user space.
    518 	 * We know the entire buffer is transferred since
    519 	 * we checked above that the read buffer is bpf_bufsize bytes.
    520 	 */
    521 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
    522 
    523 	s = splnet();
    524 	d->bd_fbuf = d->bd_hbuf;
    525 	d->bd_hbuf = 0;
    526 	d->bd_hlen = 0;
    527 done:
    528 	splx(s);
    529 	return (error);
    530 }
    531 
    532 
    533 /*
    534  * If there are processes sleeping on this descriptor, wake them up.
    535  */
    536 static __inline void
    537 bpf_wakeup(d)
    538 	struct bpf_d *d;
    539 {
    540 	wakeup((caddr_t)d);
    541 	if (d->bd_async)
    542 		fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
    543 
    544 	selnotify(&d->bd_sel, 0);
    545 	/* XXX */
    546 	d->bd_sel.sel_pid = 0;
    547 }
    548 
    549 
    550 static void
    551 bpf_timed_out(arg)
    552 	void *arg;
    553 {
    554 	struct bpf_d *d = (struct bpf_d *)arg;
    555 	int s;
    556 
    557 	s = splnet();
    558 	if (d->bd_state == BPF_WAITING) {
    559 		d->bd_state = BPF_TIMED_OUT;
    560 		if (d->bd_slen != 0)
    561 			bpf_wakeup(d);
    562 	}
    563 	splx(s);
    564 }
    565 
    566 
    567 int
    568 bpfwrite(dev, uio, ioflag)
    569 	dev_t dev;
    570 	struct uio *uio;
    571 	int ioflag;
    572 {
    573 	struct bpf_d *d = &bpf_dtab[minor(dev)];
    574 	struct ifnet *ifp;
    575 	struct mbuf *m;
    576 	int error, s;
    577 	static struct sockaddr_storage dst;
    578 
    579 	if (d->bd_bif == 0)
    580 		return (ENXIO);
    581 
    582 	ifp = d->bd_bif->bif_ifp;
    583 
    584 	if (uio->uio_resid == 0)
    585 		return (0);
    586 
    587 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp->if_mtu, &m,
    588 		(struct sockaddr *) &dst);
    589 	if (error)
    590 		return (error);
    591 
    592 	if (m->m_pkthdr.len > ifp->if_mtu)
    593 		return (EMSGSIZE);
    594 
    595 	if (d->bd_hdrcmplt)
    596 		dst.ss_family = pseudo_AF_HDRCMPLT;
    597 
    598 	s = splsoftnet();
    599 	error = (*ifp->if_output)(ifp, m, (struct sockaddr *) &dst, NULL);
    600 	splx(s);
    601 	/*
    602 	 * The driver frees the mbuf.
    603 	 */
    604 	return (error);
    605 }
    606 
    607 /*
    608  * Reset a descriptor by flushing its packet buffer and clearing the
    609  * receive and drop counts.  Should be called at splnet.
    610  */
    611 static void
    612 reset_d(d)
    613 	struct bpf_d *d;
    614 {
    615 	if (d->bd_hbuf) {
    616 		/* Free the hold buffer. */
    617 		d->bd_fbuf = d->bd_hbuf;
    618 		d->bd_hbuf = 0;
    619 	}
    620 	d->bd_slen = 0;
    621 	d->bd_hlen = 0;
    622 	d->bd_rcount = 0;
    623 	d->bd_dcount = 0;
    624 	d->bd_ccount = 0;
    625 }
    626 
    627 #ifdef BPF_KERN_FILTER
    628 extern struct bpf_insn *bpf_tcp_filter;
    629 extern struct bpf_insn *bpf_udp_filter;
    630 #endif
    631 
    632 /*
    633  *  FIONREAD		Check for read packet available.
    634  *  BIOCGBLEN		Get buffer len [for read()].
    635  *  BIOCSETF		Set ethernet read filter.
    636  *  BIOCFLUSH		Flush read packet buffer.
    637  *  BIOCPROMISC		Put interface into promiscuous mode.
    638  *  BIOCGDLT		Get link layer type.
    639  *  BIOCGETIF		Get interface name.
    640  *  BIOCSETIF		Set interface.
    641  *  BIOCSRTIMEOUT	Set read timeout.
    642  *  BIOCGRTIMEOUT	Get read timeout.
    643  *  BIOCGSTATS		Get packet stats.
    644  *  BIOCIMMEDIATE	Set immediate mode.
    645  *  BIOCVERSION		Get filter language version.
    646  *  BIOGHDRCMPLT	Get "header already complete" flag.
    647  *  BIOSHDRCMPLT	Set "header already complete" flag.
    648  */
    649 /* ARGSUSED */
    650 int
    651 bpfioctl(dev, cmd, addr, flag, l)
    652 	dev_t dev;
    653 	u_long cmd;
    654 	caddr_t addr;
    655 	int flag;
    656 	struct lwp *l;
    657 {
    658 	struct bpf_d *d = &bpf_dtab[minor(dev)];
    659 	int s, error = 0;
    660 #ifdef BPF_KERN_FILTER
    661 	struct bpf_insn **p;
    662 #endif
    663 
    664 	s = splnet();
    665 	if (d->bd_state == BPF_WAITING)
    666 		callout_stop(&d->bd_callout);
    667 	d->bd_state = BPF_IDLE;
    668 	splx(s);
    669 
    670 	switch (cmd) {
    671 
    672 	default:
    673 		error = EINVAL;
    674 		break;
    675 
    676 	/*
    677 	 * Check for read packet available.
    678 	 */
    679 	case FIONREAD:
    680 		{
    681 			int n;
    682 
    683 			s = splnet();
    684 			n = d->bd_slen;
    685 			if (d->bd_hbuf)
    686 				n += d->bd_hlen;
    687 			splx(s);
    688 
    689 			*(int *)addr = n;
    690 			break;
    691 		}
    692 
    693 	/*
    694 	 * Get buffer len [for read()].
    695 	 */
    696 	case BIOCGBLEN:
    697 		*(u_int *)addr = d->bd_bufsize;
    698 		break;
    699 
    700 	/*
    701 	 * Set buffer length.
    702 	 */
    703 	case BIOCSBLEN:
    704 		if (d->bd_bif != 0)
    705 			error = EINVAL;
    706 		else {
    707 			u_int size = *(u_int *)addr;
    708 
    709 			if (size > bpf_maxbufsize)
    710 				*(u_int *)addr = size = bpf_maxbufsize;
    711 			else if (size < BPF_MINBUFSIZE)
    712 				*(u_int *)addr = size = BPF_MINBUFSIZE;
    713 			d->bd_bufsize = size;
    714 		}
    715 		break;
    716 
    717 	/*
    718 	 * Set link layer read filter.
    719 	 */
    720 	case BIOCSETF:
    721 		error = bpf_setf(d, (struct bpf_program *)addr);
    722 		break;
    723 
    724 #ifdef BPF_KERN_FILTER
    725 	/*
    726 	 * Set TCP or UDP reject filter.
    727 	 */
    728 	case BIOCSTCPF:
    729 	case BIOCSUDPF:
    730 		if (!suser()) {
    731 			error = EPERM;
    732 			break;
    733 		}
    734 
    735 		/* Validate and store filter */
    736 		error = bpf_setf(d, (struct bpf_program *)addr);
    737 
    738 		/* Free possible old filter */
    739 		if (cmd == BIOCSTCPF)
    740 			p = &bpf_tcp_filter;
    741 		else
    742 			p = &bpf_udp_filter;
    743 		if (*p != NULL)
    744 			free((caddr_t)*p, M_DEVBUF);
    745 
    746 		/* Steal new filter (noop if error) */
    747 		s = splnet();
    748 		*p = d->bd_filter;
    749 		d->bd_filter = NULL;
    750 		splx(s);
    751 		break;
    752 #endif
    753 
    754 	/*
    755 	 * Flush read packet buffer.
    756 	 */
    757 	case BIOCFLUSH:
    758 		s = splnet();
    759 		reset_d(d);
    760 		splx(s);
    761 		break;
    762 
    763 	/*
    764 	 * Put interface into promiscuous mode.
    765 	 */
    766 	case BIOCPROMISC:
    767 		if (d->bd_bif == 0) {
    768 			/*
    769 			 * No interface attached yet.
    770 			 */
    771 			error = EINVAL;
    772 			break;
    773 		}
    774 		s = splnet();
    775 		if (d->bd_promisc == 0) {
    776 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
    777 			if (error == 0)
    778 				d->bd_promisc = 1;
    779 		}
    780 		splx(s);
    781 		break;
    782 
    783 	/*
    784 	 * Get device parameters.
    785 	 */
    786 	case BIOCGDLT:
    787 		if (d->bd_bif == 0)
    788 			error = EINVAL;
    789 		else
    790 			*(u_int *)addr = d->bd_bif->bif_dlt;
    791 		break;
    792 
    793 	/*
    794 	 * Get a list of supported device parameters.
    795 	 */
    796 	case BIOCGDLTLIST:
    797 		if (d->bd_bif == 0)
    798 			error = EINVAL;
    799 		else
    800 			error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
    801 		break;
    802 
    803 	/*
    804 	 * Set device parameters.
    805 	 */
    806 	case BIOCSDLT:
    807 		if (d->bd_bif == 0)
    808 			error = EINVAL;
    809 		else
    810 			error = bpf_setdlt(d, *(u_int *)addr);
    811 		break;
    812 
    813 	/*
    814 	 * Set interface name.
    815 	 */
    816 	case BIOCGETIF:
    817 		if (d->bd_bif == 0)
    818 			error = EINVAL;
    819 		else
    820 			bpf_ifname(d->bd_bif->bif_ifp, (struct ifreq *)addr);
    821 		break;
    822 
    823 	/*
    824 	 * Set interface.
    825 	 */
    826 	case BIOCSETIF:
    827 		error = bpf_setif(d, (struct ifreq *)addr);
    828 		break;
    829 
    830 	/*
    831 	 * Set read timeout.
    832 	 */
    833 	case BIOCSRTIMEOUT:
    834 		{
    835 			struct timeval *tv = (struct timeval *)addr;
    836 
    837 			/* Compute number of ticks. */
    838 			d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
    839 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
    840 				d->bd_rtout = 1;
    841 			break;
    842 		}
    843 
    844 	/*
    845 	 * Get read timeout.
    846 	 */
    847 	case BIOCGRTIMEOUT:
    848 		{
    849 			struct timeval *tv = (struct timeval *)addr;
    850 
    851 			tv->tv_sec = d->bd_rtout / hz;
    852 			tv->tv_usec = (d->bd_rtout % hz) * tick;
    853 			break;
    854 		}
    855 
    856 	/*
    857 	 * Get packet stats.
    858 	 */
    859 	case BIOCGSTATS:
    860 		{
    861 			struct bpf_stat *bs = (struct bpf_stat *)addr;
    862 
    863 			bs->bs_recv = d->bd_rcount;
    864 			bs->bs_drop = d->bd_dcount;
    865 			bs->bs_capt = d->bd_ccount;
    866 			break;
    867 		}
    868 
    869 	case BIOCGSTATSOLD:
    870 		{
    871 			struct bpf_stat_old *bs = (struct bpf_stat_old *)addr;
    872 
    873 			bs->bs_recv = d->bd_rcount;
    874 			bs->bs_drop = d->bd_dcount;
    875 			break;
    876 		}
    877 
    878 	/*
    879 	 * Set immediate mode.
    880 	 */
    881 	case BIOCIMMEDIATE:
    882 		d->bd_immediate = *(u_int *)addr;
    883 		break;
    884 
    885 	case BIOCVERSION:
    886 		{
    887 			struct bpf_version *bv = (struct bpf_version *)addr;
    888 
    889 			bv->bv_major = BPF_MAJOR_VERSION;
    890 			bv->bv_minor = BPF_MINOR_VERSION;
    891 			break;
    892 		}
    893 
    894 	case BIOCGHDRCMPLT:	/* get "header already complete" flag */
    895 		*(u_int *)addr = d->bd_hdrcmplt;
    896 		break;
    897 
    898 	case BIOCSHDRCMPLT:	/* set "header already complete" flag */
    899 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
    900 		break;
    901 
    902 	/*
    903 	 * Get "see sent packets" flag
    904 	 */
    905 	case BIOCGSEESENT:
    906 		*(u_int *)addr = d->bd_seesent;
    907 		break;
    908 
    909 	/*
    910 	 * Set "see sent" packets flag
    911 	 */
    912 	case BIOCSSEESENT:
    913 		d->bd_seesent = *(u_int *)addr;
    914 		break;
    915 
    916 	case FIONBIO:		/* Non-blocking I/O */
    917 		/*
    918 		 * No need to do anything special as we use IO_NDELAY in
    919 		 * bpfread() as an indication of whether or not to block
    920 		 * the read.
    921 		 */
    922 		break;
    923 
    924 	case FIOASYNC:		/* Send signal on receive packets */
    925 		d->bd_async = *(int *)addr;
    926 		break;
    927 
    928 	case TIOCSPGRP:		/* Process or group to send signals to */
    929 	case FIOSETOWN:
    930 		error = fsetown(l->l_proc, &d->bd_pgid, cmd, addr);
    931 		break;
    932 
    933 	case TIOCGPGRP:
    934 	case FIOGETOWN:
    935 		error = fgetown(l->l_proc, d->bd_pgid, cmd, addr);
    936 		break;
    937 	}
    938 	return (error);
    939 }
    940 
    941 /*
    942  * Set d's packet filter program to fp.  If this file already has a filter,
    943  * free it and replace it.  Returns EINVAL for bogus requests.
    944  */
    945 int
    946 bpf_setf(d, fp)
    947 	struct bpf_d *d;
    948 	struct bpf_program *fp;
    949 {
    950 	struct bpf_insn *fcode, *old;
    951 	u_int flen, size;
    952 	int s;
    953 
    954 	old = d->bd_filter;
    955 	if (fp->bf_insns == 0) {
    956 		if (fp->bf_len != 0)
    957 			return (EINVAL);
    958 		s = splnet();
    959 		d->bd_filter = 0;
    960 		reset_d(d);
    961 		splx(s);
    962 		if (old != 0)
    963 			free((caddr_t)old, M_DEVBUF);
    964 		return (0);
    965 	}
    966 	flen = fp->bf_len;
    967 	if (flen > BPF_MAXINSNS)
    968 		return (EINVAL);
    969 
    970 	size = flen * sizeof(*fp->bf_insns);
    971 	fcode = (struct bpf_insn *)malloc(size, M_DEVBUF, M_WAITOK);
    972 	if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) == 0 &&
    973 	    bpf_validate(fcode, (int)flen)) {
    974 		s = splnet();
    975 		d->bd_filter = fcode;
    976 		reset_d(d);
    977 		splx(s);
    978 		if (old != 0)
    979 			free((caddr_t)old, M_DEVBUF);
    980 
    981 		return (0);
    982 	}
    983 	free((caddr_t)fcode, M_DEVBUF);
    984 	return (EINVAL);
    985 }
    986 
    987 /*
    988  * Detach a file from its current interface (if attached at all) and attach
    989  * to the interface indicated by the name stored in ifr.
    990  * Return an errno or 0.
    991  */
    992 static int
    993 bpf_setif(d, ifr)
    994 	struct bpf_d *d;
    995 	struct ifreq *ifr;
    996 {
    997 	struct bpf_if *bp;
    998 	char *cp;
    999 	int unit_seen, i, s, error;
   1000 
   1001 	/*
   1002 	 * Make sure the provided name has a unit number, and default
   1003 	 * it to '0' if not specified.
   1004 	 * XXX This is ugly ... do this differently?
   1005 	 */
   1006 	unit_seen = 0;
   1007 	cp = ifr->ifr_name;
   1008 	cp[sizeof(ifr->ifr_name) - 1] = '\0';	/* sanity */
   1009 	while (*cp++)
   1010 		if (*cp >= '0' && *cp <= '9')
   1011 			unit_seen = 1;
   1012 	if (!unit_seen) {
   1013 		/* Make sure to leave room for the '\0'. */
   1014 		for (i = 0; i < (IFNAMSIZ - 1); ++i) {
   1015 			if ((ifr->ifr_name[i] >= 'a' &&
   1016 			     ifr->ifr_name[i] <= 'z') ||
   1017 			    (ifr->ifr_name[i] >= 'A' &&
   1018 			     ifr->ifr_name[i] <= 'Z'))
   1019 				continue;
   1020 			ifr->ifr_name[i] = '0';
   1021 		}
   1022 	}
   1023 
   1024 	/*
   1025 	 * Look through attached interfaces for the named one.
   1026 	 */
   1027 	for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
   1028 		struct ifnet *ifp = bp->bif_ifp;
   1029 
   1030 		if (ifp == 0 ||
   1031 		    strcmp(ifp->if_xname, ifr->ifr_name) != 0)
   1032 			continue;
   1033 		/* skip additional entry */
   1034 		if (bp->bif_driverp != (struct bpf_if **)&ifp->if_bpf)
   1035 			continue;
   1036 		/*
   1037 		 * We found the requested interface.
   1038 		 * Allocate the packet buffers if we need to.
   1039 		 * If we're already attached to requested interface,
   1040 		 * just flush the buffer.
   1041 		 */
   1042 		if (d->bd_sbuf == 0) {
   1043 			error = bpf_allocbufs(d);
   1044 			if (error != 0)
   1045 				return (error);
   1046 		}
   1047 		s = splnet();
   1048 		if (bp != d->bd_bif) {
   1049 			if (d->bd_bif)
   1050 				/*
   1051 				 * Detach if attached to something else.
   1052 				 */
   1053 				bpf_detachd(d);
   1054 
   1055 			bpf_attachd(d, bp);
   1056 		}
   1057 		reset_d(d);
   1058 		splx(s);
   1059 		return (0);
   1060 	}
   1061 	/* Not found. */
   1062 	return (ENXIO);
   1063 }
   1064 
   1065 /*
   1066  * Copy the interface name to the ifreq.
   1067  */
   1068 static void
   1069 bpf_ifname(ifp, ifr)
   1070 	struct ifnet *ifp;
   1071 	struct ifreq *ifr;
   1072 {
   1073 
   1074 	memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
   1075 }
   1076 
   1077 /*
   1078  * Support for poll() system call
   1079  *
   1080  * Return true iff the specific operation will not block indefinitely - with
   1081  * the assumption that it is safe to positively acknowledge a request for the
   1082  * ability to write to the BPF device.
   1083  * Otherwise, return false but make a note that a selwakeup() must be done.
   1084  */
   1085 int
   1086 bpfpoll(dev, events, l)
   1087 	dev_t dev;
   1088 	int events;
   1089 	struct lwp *l;
   1090 {
   1091 	struct bpf_d *d = &bpf_dtab[minor(dev)];
   1092 	int s = splnet();
   1093 	int revents;
   1094 
   1095 	revents = events & (POLLOUT | POLLWRNORM);
   1096 	if (events & (POLLIN | POLLRDNORM)) {
   1097 		/*
   1098 		 * An imitation of the FIONREAD ioctl code.
   1099 		 */
   1100 		if ((d->bd_hlen != 0) ||
   1101 		    (d->bd_immediate && d->bd_slen != 0)) {
   1102 			revents |= events & (POLLIN | POLLRDNORM);
   1103 		} else if (d->bd_state == BPF_TIMED_OUT) {
   1104 			if (d->bd_slen != 0)
   1105 				revents |= events & (POLLIN | POLLRDNORM);
   1106 			else
   1107 				revents |= events & POLLIN;
   1108 		} else {
   1109 			selrecord(l, &d->bd_sel);
   1110 			/* Start the read timeout if necessary */
   1111 			if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
   1112 				callout_reset(&d->bd_callout, d->bd_rtout,
   1113 					      bpf_timed_out, d);
   1114 				d->bd_state = BPF_WAITING;
   1115 			}
   1116 		}
   1117 	}
   1118 
   1119 	splx(s);
   1120 	return (revents);
   1121 }
   1122 
   1123 static void
   1124 filt_bpfrdetach(struct knote *kn)
   1125 {
   1126 	struct bpf_d *d = kn->kn_hook;
   1127 	int s;
   1128 
   1129 	s = splnet();
   1130 	SLIST_REMOVE(&d->bd_sel.sel_klist, kn, knote, kn_selnext);
   1131 	splx(s);
   1132 }
   1133 
   1134 static int
   1135 filt_bpfread(struct knote *kn, long hint)
   1136 {
   1137 	struct bpf_d *d = kn->kn_hook;
   1138 
   1139 	kn->kn_data = d->bd_hlen;
   1140 	if (d->bd_immediate)
   1141 		kn->kn_data += d->bd_slen;
   1142 	return (kn->kn_data > 0);
   1143 }
   1144 
   1145 static const struct filterops bpfread_filtops =
   1146 	{ 1, NULL, filt_bpfrdetach, filt_bpfread };
   1147 
   1148 int
   1149 bpfkqfilter(dev, kn)
   1150 	dev_t dev;
   1151 	struct knote *kn;
   1152 {
   1153 	struct bpf_d *d = &bpf_dtab[minor(dev)];
   1154 	struct klist *klist;
   1155 	int s;
   1156 
   1157 	switch (kn->kn_filter) {
   1158 	case EVFILT_READ:
   1159 		klist = &d->bd_sel.sel_klist;
   1160 		kn->kn_fop = &bpfread_filtops;
   1161 		break;
   1162 
   1163 	default:
   1164 		return (1);
   1165 	}
   1166 
   1167 	kn->kn_hook = d;
   1168 
   1169 	s = splnet();
   1170 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1171 	splx(s);
   1172 
   1173 	return (0);
   1174 }
   1175 
   1176 /*
   1177  * Incoming linkage from device drivers.  Process the packet pkt, of length
   1178  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
   1179  * by each process' filter, and if accepted, stashed into the corresponding
   1180  * buffer.
   1181  */
   1182 void
   1183 bpf_tap(arg, pkt, pktlen)
   1184 	caddr_t arg;
   1185 	u_char *pkt;
   1186 	u_int pktlen;
   1187 {
   1188 	struct bpf_if *bp;
   1189 	struct bpf_d *d;
   1190 	u_int slen;
   1191 	/*
   1192 	 * Note that the ipl does not have to be raised at this point.
   1193 	 * The only problem that could arise here is that if two different
   1194 	 * interfaces shared any data.  This is not the case.
   1195 	 */
   1196 	bp = (struct bpf_if *)arg;
   1197 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1198 		++d->bd_rcount;
   1199 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
   1200 		if (slen != 0)
   1201 			catchpacket(d, pkt, pktlen, slen, memcpy);
   1202 	}
   1203 }
   1204 
   1205 /*
   1206  * Copy data from an mbuf chain into a buffer.  This code is derived
   1207  * from m_copydata in sys/uipc_mbuf.c.
   1208  */
   1209 static void *
   1210 bpf_mcpy(dst_arg, src_arg, len)
   1211 	void *dst_arg;
   1212 	const void *src_arg;
   1213 	size_t len;
   1214 {
   1215 	const struct mbuf *m;
   1216 	u_int count;
   1217 	u_char *dst;
   1218 
   1219 	m = src_arg;
   1220 	dst = dst_arg;
   1221 	while (len > 0) {
   1222 		if (m == 0)
   1223 			panic("bpf_mcpy");
   1224 		count = min(m->m_len, len);
   1225 		memcpy((caddr_t)dst, mtod(m, caddr_t), count);
   1226 		m = m->m_next;
   1227 		dst += count;
   1228 		len -= count;
   1229 	}
   1230 	return (dst_arg);
   1231 }
   1232 
   1233 /*
   1234  * Dispatch a packet to all the listeners on interface bp.
   1235  *
   1236  * marg    pointer to the packet, either a data buffer or an mbuf chain
   1237  * buflen  buffer length, if marg is a data buffer
   1238  * cpfn    a function that can copy marg into the listener's buffer
   1239  * pktlen  length of the packet
   1240  * rcvif   either NULL or the interface the packet came in on.
   1241  */
   1242 static __inline void
   1243 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
   1244     void *marg, u_int pktlen, u_int buflen, struct ifnet *rcvif)
   1245 {
   1246 	u_int slen;
   1247 	struct bpf_d *d;
   1248 
   1249 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1250 		if (!d->bd_seesent && (rcvif == NULL))
   1251 			continue;
   1252 		++d->bd_rcount;
   1253 		slen = bpf_filter(d->bd_filter, marg, pktlen, buflen);
   1254 		if (slen != 0)
   1255 			catchpacket(d, marg, pktlen, slen, cpfn);
   1256 	}
   1257 }
   1258 
   1259 /*
   1260  * Incoming linkage from device drivers, when the head of the packet is in
   1261  * a buffer, and the tail is in an mbuf chain.
   1262  */
   1263 void
   1264 bpf_mtap2(arg, data, dlen, m)
   1265 	caddr_t arg;
   1266 	void *data;
   1267 	u_int dlen;
   1268 	struct mbuf *m;
   1269 {
   1270 	struct bpf_if *bp = (struct bpf_if *)arg;
   1271 	u_int pktlen;
   1272 	struct mbuf mb;
   1273 
   1274 	pktlen = m_length(m) + dlen;
   1275 
   1276 	/*
   1277 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
   1278 	 * Note that we cut corners here; we only setup what's
   1279 	 * absolutely needed--this mbuf should never go anywhere else.
   1280 	 */
   1281 	(void)memset(&mb, 0, sizeof(mb));
   1282 	mb.m_next = m;
   1283 	mb.m_data = data;
   1284 	mb.m_len = dlen;
   1285 
   1286 	bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, m->m_pkthdr.rcvif);
   1287 }
   1288 
   1289 /*
   1290  * Incoming linkage from device drivers, when packet is in an mbuf chain.
   1291  */
   1292 void
   1293 bpf_mtap(arg, m)
   1294 	caddr_t arg;
   1295 	struct mbuf *m;
   1296 {
   1297 	void *(*cpfn) __P((void *, const void *, size_t));
   1298 	struct bpf_if *bp = (struct bpf_if *)arg;
   1299 	u_int pktlen, buflen;
   1300 	void *marg;
   1301 
   1302 	pktlen = m_length(m);
   1303 
   1304 	if (pktlen == m->m_len) {
   1305 		cpfn = memcpy;
   1306 		marg = mtod(m, void *);
   1307 		buflen = pktlen;
   1308 	} else {
   1309 		cpfn = bpf_mcpy;
   1310 		marg = m;
   1311 		buflen = 0;
   1312 	}
   1313 
   1314 	bpf_deliver(bp, cpfn, marg, pktlen, buflen, m->m_pkthdr.rcvif);
   1315 }
   1316 
   1317 /*
   1318  * Move the packet data from interface memory (pkt) into the
   1319  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
   1320  * otherwise 0.  "copy" is the routine called to do the actual data
   1321  * transfer.  memcpy is passed in to copy contiguous chunks, while
   1322  * bpf_mcpy is passed in to copy mbuf chains.  In the latter case,
   1323  * pkt is really an mbuf.
   1324  */
   1325 static void
   1326 catchpacket(d, pkt, pktlen, snaplen, cpfn)
   1327 	struct bpf_d *d;
   1328 	u_char *pkt;
   1329 	u_int pktlen, snaplen;
   1330 	void *(*cpfn) __P((void *, const void *, size_t));
   1331 {
   1332 	struct bpf_hdr *hp;
   1333 	int totlen, curlen;
   1334 	int hdrlen = d->bd_bif->bif_hdrlen;
   1335 
   1336 	++d->bd_ccount;
   1337 	/*
   1338 	 * Figure out how many bytes to move.  If the packet is
   1339 	 * greater or equal to the snapshot length, transfer that
   1340 	 * much.  Otherwise, transfer the whole packet (unless
   1341 	 * we hit the buffer size limit).
   1342 	 */
   1343 	totlen = hdrlen + min(snaplen, pktlen);
   1344 	if (totlen > d->bd_bufsize)
   1345 		totlen = d->bd_bufsize;
   1346 
   1347 	/*
   1348 	 * Round up the end of the previous packet to the next longword.
   1349 	 */
   1350 	curlen = BPF_WORDALIGN(d->bd_slen);
   1351 	if (curlen + totlen > d->bd_bufsize) {
   1352 		/*
   1353 		 * This packet will overflow the storage buffer.
   1354 		 * Rotate the buffers if we can, then wakeup any
   1355 		 * pending reads.
   1356 		 */
   1357 		if (d->bd_fbuf == 0) {
   1358 			/*
   1359 			 * We haven't completed the previous read yet,
   1360 			 * so drop the packet.
   1361 			 */
   1362 			++d->bd_dcount;
   1363 			return;
   1364 		}
   1365 		ROTATE_BUFFERS(d);
   1366 		bpf_wakeup(d);
   1367 		curlen = 0;
   1368 	}
   1369 
   1370 	/*
   1371 	 * Append the bpf header.
   1372 	 */
   1373 	hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
   1374 	microtime(&hp->bh_tstamp);
   1375 	hp->bh_datalen = pktlen;
   1376 	hp->bh_hdrlen = hdrlen;
   1377 	/*
   1378 	 * Copy the packet data into the store buffer and update its length.
   1379 	 */
   1380 	(*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
   1381 	d->bd_slen = curlen + totlen;
   1382 
   1383 	/*
   1384 	 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
   1385 	 * will cause filt_bpfread() to be called with it adjusted.
   1386 	 */
   1387 	if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
   1388 		/*
   1389 		 * Immediate mode is set, or the read timeout has
   1390 		 * already expired during a select call.  A packet
   1391 		 * arrived, so the reader should be woken up.
   1392 		 */
   1393 		bpf_wakeup(d);
   1394 }
   1395 
   1396 /*
   1397  * Initialize all nonzero fields of a descriptor.
   1398  */
   1399 static int
   1400 bpf_allocbufs(d)
   1401 	struct bpf_d *d;
   1402 {
   1403 
   1404 	d->bd_fbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
   1405 	if (!d->bd_fbuf)
   1406 		return (ENOBUFS);
   1407 	d->bd_sbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
   1408 	if (!d->bd_sbuf) {
   1409 		free(d->bd_fbuf, M_DEVBUF);
   1410 		return (ENOBUFS);
   1411 	}
   1412 	d->bd_slen = 0;
   1413 	d->bd_hlen = 0;
   1414 	return (0);
   1415 }
   1416 
   1417 /*
   1418  * Free buffers currently in use by a descriptor.
   1419  * Called on close.
   1420  */
   1421 static void
   1422 bpf_freed(d)
   1423 	struct bpf_d *d;
   1424 {
   1425 	/*
   1426 	 * We don't need to lock out interrupts since this descriptor has
   1427 	 * been detached from its interface and it yet hasn't been marked
   1428 	 * free.
   1429 	 */
   1430 	if (d->bd_sbuf != 0) {
   1431 		free(d->bd_sbuf, M_DEVBUF);
   1432 		if (d->bd_hbuf != 0)
   1433 			free(d->bd_hbuf, M_DEVBUF);
   1434 		if (d->bd_fbuf != 0)
   1435 			free(d->bd_fbuf, M_DEVBUF);
   1436 	}
   1437 	if (d->bd_filter)
   1438 		free((caddr_t)d->bd_filter, M_DEVBUF);
   1439 
   1440 	D_MARKFREE(d);
   1441 }
   1442 
   1443 /*
   1444  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
   1445  * fixed size of the link header (variable length headers not yet supported).
   1446  */
   1447 void
   1448 bpfattach(ifp, dlt, hdrlen)
   1449 	struct ifnet *ifp;
   1450 	u_int dlt, hdrlen;
   1451 {
   1452 
   1453 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
   1454 }
   1455 
   1456 /*
   1457  * Attach additional dlt for a interface to bpf.  dlt is the link layer type;
   1458  * hdrlen is the fixed size of the link header for the specified dlt
   1459  * (variable length headers not yet supported).
   1460  */
   1461 void
   1462 bpfattach2(ifp, dlt, hdrlen, driverp)
   1463 	struct ifnet *ifp;
   1464 	u_int dlt, hdrlen;
   1465 	caddr_t *driverp;
   1466 {
   1467 	struct bpf_if *bp;
   1468 	bp = (struct bpf_if *)malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
   1469 	if (bp == 0)
   1470 		panic("bpfattach");
   1471 
   1472 	bp->bif_dlist = 0;
   1473 	bp->bif_driverp = (struct bpf_if **)driverp;
   1474 	bp->bif_ifp = ifp;
   1475 	bp->bif_dlt = dlt;
   1476 
   1477 	bp->bif_next = bpf_iflist;
   1478 	bpf_iflist = bp;
   1479 
   1480 	*bp->bif_driverp = 0;
   1481 
   1482 	/*
   1483 	 * Compute the length of the bpf header.  This is not necessarily
   1484 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1485 	 * that the network layer header begins on a longword boundary (for
   1486 	 * performance reasons and to alleviate alignment restrictions).
   1487 	 */
   1488 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1489 
   1490 #if 0
   1491 	printf("bpf: %s attached\n", ifp->if_xname);
   1492 #endif
   1493 }
   1494 
   1495 /*
   1496  * Remove an interface from bpf.
   1497  */
   1498 void
   1499 bpfdetach(ifp)
   1500 	struct ifnet *ifp;
   1501 {
   1502 	struct bpf_if *bp, **pbp;
   1503 	struct bpf_d *d;
   1504 	int i, s, cmaj;
   1505 
   1506 	/* locate the major number */
   1507 	cmaj = cdevsw_lookup_major(&bpf_cdevsw);
   1508 
   1509 	/* Nuke the vnodes for any open instances */
   1510 	for (i = 0; i < NBPFILTER; ++i) {
   1511 		d = &bpf_dtab[i];
   1512 		if (!D_ISFREE(d) && d->bd_bif != NULL &&
   1513 		    d->bd_bif->bif_ifp == ifp) {
   1514 			/*
   1515 			 * Detach the descriptor from an interface now.
   1516 			 * It will be free'ed later by close routine.
   1517 			 */
   1518 			s = splnet();
   1519 			d->bd_promisc = 0;	/* we can't touch device. */
   1520 			bpf_detachd(d);
   1521 			splx(s);
   1522 			vdevgone(cmaj, i, i, VCHR);
   1523 		}
   1524 	}
   1525 
   1526   again:
   1527 	for (bp = bpf_iflist, pbp = &bpf_iflist;
   1528 	     bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
   1529 		if (bp->bif_ifp == ifp) {
   1530 			*pbp = bp->bif_next;
   1531 			free(bp, M_DEVBUF);
   1532 			goto again;
   1533 		}
   1534 	}
   1535 }
   1536 
   1537 /*
   1538  * Change the data link type of a interface.
   1539  */
   1540 void
   1541 bpf_change_type(ifp, dlt, hdrlen)
   1542 	struct ifnet *ifp;
   1543 	u_int dlt, hdrlen;
   1544 {
   1545 	struct bpf_if *bp;
   1546 
   1547 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1548 		if (bp->bif_driverp == (struct bpf_if **)&ifp->if_bpf)
   1549 			break;
   1550 	}
   1551 	if (bp == NULL)
   1552 		panic("bpf_change_type");
   1553 
   1554 	bp->bif_dlt = dlt;
   1555 
   1556 	/*
   1557 	 * Compute the length of the bpf header.  This is not necessarily
   1558 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1559 	 * that the network layer header begins on a longword boundary (for
   1560 	 * performance reasons and to alleviate alignment restrictions).
   1561 	 */
   1562 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1563 }
   1564 
   1565 /*
   1566  * Get a list of available data link type of the interface.
   1567  */
   1568 static int
   1569 bpf_getdltlist(d, bfl)
   1570 	struct bpf_d *d;
   1571 	struct bpf_dltlist *bfl;
   1572 {
   1573 	int n, error;
   1574 	struct ifnet *ifp;
   1575 	struct bpf_if *bp;
   1576 
   1577 	ifp = d->bd_bif->bif_ifp;
   1578 	n = 0;
   1579 	error = 0;
   1580 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1581 		if (bp->bif_ifp != ifp)
   1582 			continue;
   1583 		if (bfl->bfl_list != NULL) {
   1584 			if (n >= bfl->bfl_len)
   1585 				return ENOMEM;
   1586 			error = copyout(&bp->bif_dlt,
   1587 			    bfl->bfl_list + n, sizeof(u_int));
   1588 		}
   1589 		n++;
   1590 	}
   1591 	bfl->bfl_len = n;
   1592 	return error;
   1593 }
   1594 
   1595 /*
   1596  * Set the data link type of a BPF instance.
   1597  */
   1598 static int
   1599 bpf_setdlt(d, dlt)
   1600 	struct bpf_d *d;
   1601 	u_int dlt;
   1602 {
   1603 	int s, error, opromisc;
   1604 	struct ifnet *ifp;
   1605 	struct bpf_if *bp;
   1606 
   1607 	if (d->bd_bif->bif_dlt == dlt)
   1608 		return 0;
   1609 	ifp = d->bd_bif->bif_ifp;
   1610 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1611 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
   1612 			break;
   1613 	}
   1614 	if (bp == NULL)
   1615 		return EINVAL;
   1616 	s = splnet();
   1617 	opromisc = d->bd_promisc;
   1618 	bpf_detachd(d);
   1619 	bpf_attachd(d, bp);
   1620 	reset_d(d);
   1621 	if (opromisc) {
   1622 		error = ifpromisc(bp->bif_ifp, 1);
   1623 		if (error)
   1624 			printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
   1625 			    bp->bif_ifp->if_xname, error);
   1626 		else
   1627 			d->bd_promisc = 1;
   1628 	}
   1629 	splx(s);
   1630 	return 0;
   1631 }
   1632 
   1633 static int
   1634 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
   1635 {
   1636 	int newsize, error;
   1637 	struct sysctlnode node;
   1638 
   1639 	node = *rnode;
   1640 	node.sysctl_data = &newsize;
   1641 	newsize = bpf_maxbufsize;
   1642 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1643 	if (error || newp == NULL)
   1644 		return (error);
   1645 
   1646 	if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
   1647 		return (EINVAL);
   1648 
   1649 	bpf_maxbufsize = newsize;
   1650 
   1651 	return (0);
   1652 }
   1653 
   1654 SYSCTL_SETUP(sysctl_net_bfp_setup, "sysctl net.bpf subtree setup")
   1655 {
   1656 	struct sysctlnode *node;
   1657 
   1658 	sysctl_createv(clog, 0, NULL, NULL,
   1659 		       CTLFLAG_PERMANENT,
   1660 		       CTLTYPE_NODE, "net", NULL,
   1661 		       NULL, 0, NULL, 0,
   1662 		       CTL_NET, CTL_EOL);
   1663 
   1664 	node = NULL;
   1665 	sysctl_createv(clog, 0, NULL, &node,
   1666 		       CTLFLAG_PERMANENT,
   1667 		       CTLTYPE_NODE, "bpf",
   1668 		       SYSCTL_DESCR("BPF options"),
   1669 		       NULL, 0, NULL, 0,
   1670 		       CTL_NET, CTL_CREATE, CTL_EOL);
   1671 	if (node != NULL)
   1672 		sysctl_createv(clog, 0, NULL, NULL,
   1673 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1674 			CTLTYPE_INT, "maxbufsize",
   1675 			SYSCTL_DESCR("Maximum size for data capture buffer"),
   1676 			sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
   1677 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1678 }
   1679