Home | History | Annotate | Line # | Download | only in net
bpf.c revision 1.153
      1 /*	$NetBSD: bpf.c,v 1.153 2010/01/19 22:08:00 pooka 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.153 2010/01/19 22:08:00 pooka Exp $");
     43 
     44 #if defined(_KERNEL_OPT)
     45 #include "opt_bpf.h"
     46 #include "sl.h"
     47 #include "strip.h"
     48 #endif
     49 
     50 #include <sys/param.h>
     51 #include <sys/systm.h>
     52 #include <sys/mbuf.h>
     53 #include <sys/buf.h>
     54 #include <sys/time.h>
     55 #include <sys/proc.h>
     56 #include <sys/ioctl.h>
     57 #include <sys/conf.h>
     58 #include <sys/vnode.h>
     59 #include <sys/queue.h>
     60 #include <sys/stat.h>
     61 
     62 #include <sys/file.h>
     63 #include <sys/filedesc.h>
     64 #include <sys/tty.h>
     65 #include <sys/uio.h>
     66 
     67 #include <sys/protosw.h>
     68 #include <sys/socket.h>
     69 #include <sys/errno.h>
     70 #include <sys/kernel.h>
     71 #include <sys/poll.h>
     72 #include <sys/sysctl.h>
     73 #include <sys/kauth.h>
     74 
     75 #include <net/if.h>
     76 #include <net/slip.h>
     77 
     78 #include <net/bpf.h>
     79 #include <net/bpfdesc.h>
     80 
     81 #include <net/if_arc.h>
     82 #include <net/if_ether.h>
     83 
     84 #include <netinet/in.h>
     85 #include <netinet/if_inarp.h>
     86 
     87 
     88 #include <compat/sys/sockio.h>
     89 
     90 #ifndef BPF_BUFSIZE
     91 /*
     92  * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
     93  * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
     94  */
     95 # define BPF_BUFSIZE 32768
     96 #endif
     97 
     98 #define PRINET  26			/* interruptible */
     99 
    100 /*
    101  * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
    102  * XXX the default values should be computed dynamically based
    103  * on available memory size and available mbuf clusters.
    104  */
    105 int bpf_bufsize = BPF_BUFSIZE;
    106 int bpf_maxbufsize = BPF_DFLTBUFSIZE;	/* XXX set dynamically, see above */
    107 
    108 
    109 /*
    110  * Global BPF statistics returned by net.bpf.stats sysctl.
    111  */
    112 struct bpf_stat	bpf_gstats;
    113 
    114 /*
    115  * Use a mutex to avoid a race condition between gathering the stats/peers
    116  * and opening/closing the device.
    117  */
    118 static kmutex_t bpf_mtx;
    119 
    120 /*
    121  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
    122  *  bpf_dtab holds the descriptors, indexed by minor device #
    123  */
    124 struct bpf_if	*bpf_iflist;
    125 LIST_HEAD(, bpf_d) bpf_list;
    126 
    127 static int	bpf_allocbufs(struct bpf_d *);
    128 static void	bpf_deliver(struct bpf_if *,
    129 		            void *(*cpfn)(void *, const void *, size_t),
    130 			    void *, u_int, u_int, struct ifnet *);
    131 static void	bpf_freed(struct bpf_d *);
    132 static void	bpf_ifname(struct ifnet *, struct ifreq *);
    133 static void	*bpf_mcpy(void *, const void *, size_t);
    134 static int	bpf_movein(struct uio *, int, int,
    135 			        struct mbuf **, struct sockaddr *);
    136 static void	bpf_attachd(struct bpf_d *, struct bpf_if *);
    137 static void	bpf_detachd(struct bpf_d *);
    138 static int	bpf_setif(struct bpf_d *, struct ifreq *);
    139 static void	bpf_timed_out(void *);
    140 static inline void
    141 		bpf_wakeup(struct bpf_d *);
    142 static void	catchpacket(struct bpf_d *, u_char *, u_int, u_int,
    143     void *(*)(void *, const void *, size_t), struct timespec *);
    144 static void	reset_d(struct bpf_d *);
    145 static int	bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
    146 static int	bpf_setdlt(struct bpf_d *, u_int);
    147 
    148 static int	bpf_read(struct file *, off_t *, struct uio *, kauth_cred_t,
    149     int);
    150 static int	bpf_write(struct file *, off_t *, struct uio *, kauth_cred_t,
    151     int);
    152 static int	bpf_ioctl(struct file *, u_long, void *);
    153 static int	bpf_poll(struct file *, int);
    154 static int	bpf_stat(struct file *, struct stat *);
    155 static int	bpf_close(struct file *);
    156 static int	bpf_kqfilter(struct file *, struct knote *);
    157 static void	bpf_softintr(void *);
    158 
    159 static const struct fileops bpf_fileops = {
    160 	.fo_read = bpf_read,
    161 	.fo_write = bpf_write,
    162 	.fo_ioctl = bpf_ioctl,
    163 	.fo_fcntl = fnullop_fcntl,
    164 	.fo_poll = bpf_poll,
    165 	.fo_stat = bpf_stat,
    166 	.fo_close = bpf_close,
    167 	.fo_kqfilter = bpf_kqfilter,
    168 	.fo_restart = fnullop_restart,
    169 };
    170 
    171 dev_type_open(bpfopen);
    172 
    173 const struct cdevsw bpf_cdevsw = {
    174 	bpfopen, noclose, noread, nowrite, noioctl,
    175 	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER
    176 };
    177 
    178 static int
    179 bpf_movein(struct uio *uio, int linktype, int mtu, struct mbuf **mp,
    180 	   struct sockaddr *sockp)
    181 {
    182 	struct mbuf *m;
    183 	int error;
    184 	int len;
    185 	int hlen;
    186 	int align;
    187 
    188 	/*
    189 	 * Build a sockaddr based on the data link layer type.
    190 	 * We do this at this level because the ethernet header
    191 	 * is copied directly into the data field of the sockaddr.
    192 	 * In the case of SLIP, there is no header and the packet
    193 	 * is forwarded as is.
    194 	 * Also, we are careful to leave room at the front of the mbuf
    195 	 * for the link level header.
    196 	 */
    197 	switch (linktype) {
    198 
    199 	case DLT_SLIP:
    200 		sockp->sa_family = AF_INET;
    201 		hlen = 0;
    202 		align = 0;
    203 		break;
    204 
    205 	case DLT_PPP:
    206 		sockp->sa_family = AF_UNSPEC;
    207 		hlen = 0;
    208 		align = 0;
    209 		break;
    210 
    211 	case DLT_EN10MB:
    212 		sockp->sa_family = AF_UNSPEC;
    213 		/* XXX Would MAXLINKHDR be better? */
    214  		/* 6(dst)+6(src)+2(type) */
    215 		hlen = sizeof(struct ether_header);
    216 		align = 2;
    217 		break;
    218 
    219 	case DLT_ARCNET:
    220 		sockp->sa_family = AF_UNSPEC;
    221 		hlen = ARC_HDRLEN;
    222 		align = 5;
    223 		break;
    224 
    225 	case DLT_FDDI:
    226 		sockp->sa_family = AF_LINK;
    227 		/* XXX 4(FORMAC)+6(dst)+6(src) */
    228 		hlen = 16;
    229 		align = 0;
    230 		break;
    231 
    232 	case DLT_ECONET:
    233 		sockp->sa_family = AF_UNSPEC;
    234 		hlen = 6;
    235 		align = 2;
    236 		break;
    237 
    238 	case DLT_NULL:
    239 		sockp->sa_family = AF_UNSPEC;
    240 		hlen = 0;
    241 		align = 0;
    242 		break;
    243 
    244 	default:
    245 		return (EIO);
    246 	}
    247 
    248 	len = uio->uio_resid;
    249 	/*
    250 	 * If there aren't enough bytes for a link level header or the
    251 	 * packet length exceeds the interface mtu, return an error.
    252 	 */
    253 	if (len < hlen || len - hlen > mtu)
    254 		return (EMSGSIZE);
    255 
    256 	/*
    257 	 * XXX Avoid complicated buffer chaining ---
    258 	 * bail if it won't fit in a single mbuf.
    259 	 * (Take into account possible alignment bytes)
    260 	 */
    261 	if ((unsigned)len > MCLBYTES - align)
    262 		return (EIO);
    263 
    264 	m = m_gethdr(M_WAIT, MT_DATA);
    265 	m->m_pkthdr.rcvif = 0;
    266 	m->m_pkthdr.len = len - hlen;
    267 	if (len > MHLEN - align) {
    268 		m_clget(m, M_WAIT);
    269 		if ((m->m_flags & M_EXT) == 0) {
    270 			error = ENOBUFS;
    271 			goto bad;
    272 		}
    273 	}
    274 
    275 	/* Insure the data is properly aligned */
    276 	if (align > 0) {
    277 		m->m_data += align;
    278 		m->m_len -= align;
    279 	}
    280 
    281 	error = uiomove(mtod(m, void *), len, uio);
    282 	if (error)
    283 		goto bad;
    284 	if (hlen != 0) {
    285 		memcpy(sockp->sa_data, mtod(m, void *), hlen);
    286 		m->m_data += hlen; /* XXX */
    287 		len -= hlen;
    288 	}
    289 	m->m_len = len;
    290 	*mp = m;
    291 	return (0);
    292 
    293 bad:
    294 	m_freem(m);
    295 	return (error);
    296 }
    297 
    298 /*
    299  * Attach file to the bpf interface, i.e. make d listen on bp.
    300  * Must be called at splnet.
    301  */
    302 static void
    303 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
    304 {
    305 	/*
    306 	 * Point d at bp, and add d to the interface's list of listeners.
    307 	 * Finally, point the driver's bpf cookie at the interface so
    308 	 * it will divert packets to bpf.
    309 	 */
    310 	d->bd_bif = bp;
    311 	d->bd_next = bp->bif_dlist;
    312 	bp->bif_dlist = d;
    313 
    314 	*bp->bif_driverp = bp;
    315 }
    316 
    317 /*
    318  * Detach a file from its interface.
    319  */
    320 static void
    321 bpf_detachd(struct bpf_d *d)
    322 {
    323 	struct bpf_d **p;
    324 	struct bpf_if *bp;
    325 
    326 	bp = d->bd_bif;
    327 	/*
    328 	 * Check if this descriptor had requested promiscuous mode.
    329 	 * If so, turn it off.
    330 	 */
    331 	if (d->bd_promisc) {
    332 		int error;
    333 
    334 		d->bd_promisc = 0;
    335 		/*
    336 		 * Take device out of promiscuous mode.  Since we were
    337 		 * able to enter promiscuous mode, we should be able
    338 		 * to turn it off.  But we can get an error if
    339 		 * the interface was configured down, so only panic
    340 		 * if we don't get an unexpected error.
    341 		 */
    342   		error = ifpromisc(bp->bif_ifp, 0);
    343 		if (error && error != EINVAL)
    344 			panic("%s: ifpromisc failed: %d", __func__, error);
    345 	}
    346 	/* Remove d from the interface's descriptor list. */
    347 	p = &bp->bif_dlist;
    348 	while (*p != d) {
    349 		p = &(*p)->bd_next;
    350 		if (*p == 0)
    351 			panic("%s: descriptor not in list", __func__);
    352 	}
    353 	*p = (*p)->bd_next;
    354 	if (bp->bif_dlist == 0)
    355 		/*
    356 		 * Let the driver know that there are no more listeners.
    357 		 */
    358 		*d->bd_bif->bif_driverp = 0;
    359 	d->bd_bif = 0;
    360 }
    361 
    362 
    363 /*
    364  * bpfilterattach() is called at boot time.
    365  */
    366 /* ARGSUSED */
    367 void
    368 bpfilterattach(int n)
    369 {
    370 
    371 	mutex_init(&bpf_mtx, MUTEX_DEFAULT, IPL_NONE);
    372 
    373 	LIST_INIT(&bpf_list);
    374 
    375 	bpf_gstats.bs_recv = 0;
    376 	bpf_gstats.bs_drop = 0;
    377 	bpf_gstats.bs_capt = 0;
    378 }
    379 
    380 /*
    381  * Open ethernet device. Clones.
    382  */
    383 /* ARGSUSED */
    384 int
    385 bpfopen(dev_t dev, int flag, int mode, struct lwp *l)
    386 {
    387 	struct bpf_d *d;
    388 	struct file *fp;
    389 	int error, fd;
    390 
    391 	/* falloc() will use the descriptor for us. */
    392 	if ((error = fd_allocfile(&fp, &fd)) != 0)
    393 		return error;
    394 
    395 	d = malloc(sizeof(*d), M_DEVBUF, M_WAITOK|M_ZERO);
    396 	d->bd_bufsize = bpf_bufsize;
    397 	d->bd_seesent = 1;
    398 	d->bd_pid = l->l_proc->p_pid;
    399 	getnanotime(&d->bd_btime);
    400 	d->bd_atime = d->bd_mtime = d->bd_btime;
    401 	callout_init(&d->bd_callout, 0);
    402 	selinit(&d->bd_sel);
    403 	d->bd_sih = softint_establish(SOFTINT_CLOCK, bpf_softintr, d);
    404 
    405 	mutex_enter(&bpf_mtx);
    406 	LIST_INSERT_HEAD(&bpf_list, d, bd_list);
    407 	mutex_exit(&bpf_mtx);
    408 
    409 	return fd_clone(fp, fd, flag, &bpf_fileops, d);
    410 }
    411 
    412 /*
    413  * Close the descriptor by detaching it from its interface,
    414  * deallocating its buffers, and marking it free.
    415  */
    416 /* ARGSUSED */
    417 static int
    418 bpf_close(struct file *fp)
    419 {
    420 	struct bpf_d *d = fp->f_data;
    421 	int s;
    422 
    423 	KERNEL_LOCK(1, NULL);
    424 
    425 	/*
    426 	 * Refresh the PID associated with this bpf file.
    427 	 */
    428 	d->bd_pid = curproc->p_pid;
    429 
    430 	s = splnet();
    431 	if (d->bd_state == BPF_WAITING)
    432 		callout_stop(&d->bd_callout);
    433 	d->bd_state = BPF_IDLE;
    434 	if (d->bd_bif)
    435 		bpf_detachd(d);
    436 	splx(s);
    437 	bpf_freed(d);
    438 	mutex_enter(&bpf_mtx);
    439 	LIST_REMOVE(d, bd_list);
    440 	mutex_exit(&bpf_mtx);
    441 	callout_destroy(&d->bd_callout);
    442 	seldestroy(&d->bd_sel);
    443 	softint_disestablish(d->bd_sih);
    444 	free(d, M_DEVBUF);
    445 	fp->f_data = NULL;
    446 
    447 	KERNEL_UNLOCK_ONE(NULL);
    448 
    449 	return (0);
    450 }
    451 
    452 /*
    453  * Rotate the packet buffers in descriptor d.  Move the store buffer
    454  * into the hold slot, and the free buffer into the store slot.
    455  * Zero the length of the new store buffer.
    456  */
    457 #define ROTATE_BUFFERS(d) \
    458 	(d)->bd_hbuf = (d)->bd_sbuf; \
    459 	(d)->bd_hlen = (d)->bd_slen; \
    460 	(d)->bd_sbuf = (d)->bd_fbuf; \
    461 	(d)->bd_slen = 0; \
    462 	(d)->bd_fbuf = 0;
    463 /*
    464  *  bpfread - read next chunk of packets from buffers
    465  */
    466 static int
    467 bpf_read(struct file *fp, off_t *offp, struct uio *uio,
    468     kauth_cred_t cred, int flags)
    469 {
    470 	struct bpf_d *d = fp->f_data;
    471 	int timed_out;
    472 	int error;
    473 	int s;
    474 
    475 	getnanotime(&d->bd_atime);
    476 	/*
    477 	 * Restrict application to use a buffer the same size as
    478 	 * the kernel buffers.
    479 	 */
    480 	if (uio->uio_resid != d->bd_bufsize)
    481 		return (EINVAL);
    482 
    483 	KERNEL_LOCK(1, NULL);
    484 	s = splnet();
    485 	if (d->bd_state == BPF_WAITING)
    486 		callout_stop(&d->bd_callout);
    487 	timed_out = (d->bd_state == BPF_TIMED_OUT);
    488 	d->bd_state = BPF_IDLE;
    489 	/*
    490 	 * If the hold buffer is empty, then do a timed sleep, which
    491 	 * ends when the timeout expires or when enough packets
    492 	 * have arrived to fill the store buffer.
    493 	 */
    494 	while (d->bd_hbuf == 0) {
    495 		if (fp->f_flag & FNONBLOCK) {
    496 			if (d->bd_slen == 0) {
    497 				splx(s);
    498 				KERNEL_UNLOCK_ONE(NULL);
    499 				return (EWOULDBLOCK);
    500 			}
    501 			ROTATE_BUFFERS(d);
    502 			break;
    503 		}
    504 
    505 		if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
    506 			/*
    507 			 * A packet(s) either arrived since the previous
    508 			 * read or arrived while we were asleep.
    509 			 * Rotate the buffers and return what's here.
    510 			 */
    511 			ROTATE_BUFFERS(d);
    512 			break;
    513 		}
    514 		error = tsleep(d, PRINET|PCATCH, "bpf",
    515 				d->bd_rtout);
    516 		if (error == EINTR || error == ERESTART) {
    517 			splx(s);
    518 			KERNEL_UNLOCK_ONE(NULL);
    519 			return (error);
    520 		}
    521 		if (error == EWOULDBLOCK) {
    522 			/*
    523 			 * On a timeout, return what's in the buffer,
    524 			 * which may be nothing.  If there is something
    525 			 * in the store buffer, we can rotate the buffers.
    526 			 */
    527 			if (d->bd_hbuf)
    528 				/*
    529 				 * We filled up the buffer in between
    530 				 * getting the timeout and arriving
    531 				 * here, so we don't need to rotate.
    532 				 */
    533 				break;
    534 
    535 			if (d->bd_slen == 0) {
    536 				splx(s);
    537 				KERNEL_UNLOCK_ONE(NULL);
    538 				return (0);
    539 			}
    540 			ROTATE_BUFFERS(d);
    541 			break;
    542 		}
    543 		if (error != 0)
    544 			goto done;
    545 	}
    546 	/*
    547 	 * At this point, we know we have something in the hold slot.
    548 	 */
    549 	splx(s);
    550 
    551 	/*
    552 	 * Move data from hold buffer into user space.
    553 	 * We know the entire buffer is transferred since
    554 	 * we checked above that the read buffer is bpf_bufsize bytes.
    555 	 */
    556 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
    557 
    558 	s = splnet();
    559 	d->bd_fbuf = d->bd_hbuf;
    560 	d->bd_hbuf = 0;
    561 	d->bd_hlen = 0;
    562 done:
    563 	splx(s);
    564 	KERNEL_UNLOCK_ONE(NULL);
    565 	return (error);
    566 }
    567 
    568 
    569 /*
    570  * If there are processes sleeping on this descriptor, wake them up.
    571  */
    572 static inline void
    573 bpf_wakeup(struct bpf_d *d)
    574 {
    575 	wakeup(d);
    576 	if (d->bd_async)
    577 		softint_schedule(d->bd_sih);
    578 	selnotify(&d->bd_sel, 0, 0);
    579 }
    580 
    581 static void
    582 bpf_softintr(void *cookie)
    583 {
    584 	struct bpf_d *d;
    585 
    586 	d = cookie;
    587 	if (d->bd_async)
    588 		fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
    589 }
    590 
    591 static void
    592 bpf_timed_out(void *arg)
    593 {
    594 	struct bpf_d *d = arg;
    595 	int s;
    596 
    597 	s = splnet();
    598 	if (d->bd_state == BPF_WAITING) {
    599 		d->bd_state = BPF_TIMED_OUT;
    600 		if (d->bd_slen != 0)
    601 			bpf_wakeup(d);
    602 	}
    603 	splx(s);
    604 }
    605 
    606 
    607 static int
    608 bpf_write(struct file *fp, off_t *offp, struct uio *uio,
    609     kauth_cred_t cred, int flags)
    610 {
    611 	struct bpf_d *d = fp->f_data;
    612 	struct ifnet *ifp;
    613 	struct mbuf *m;
    614 	int error, s;
    615 	static struct sockaddr_storage dst;
    616 
    617 	m = NULL;	/* XXX gcc */
    618 
    619 	KERNEL_LOCK(1, NULL);
    620 
    621 	if (d->bd_bif == 0) {
    622 		KERNEL_UNLOCK_ONE(NULL);
    623 		return (ENXIO);
    624 	}
    625 	getnanotime(&d->bd_mtime);
    626 
    627 	ifp = d->bd_bif->bif_ifp;
    628 
    629 	if (uio->uio_resid == 0) {
    630 		KERNEL_UNLOCK_ONE(NULL);
    631 		return (0);
    632 	}
    633 
    634 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp->if_mtu, &m,
    635 		(struct sockaddr *) &dst);
    636 	if (error) {
    637 		KERNEL_UNLOCK_ONE(NULL);
    638 		return (error);
    639 	}
    640 
    641 	if (m->m_pkthdr.len > ifp->if_mtu) {
    642 		KERNEL_UNLOCK_ONE(NULL);
    643 		m_freem(m);
    644 		return (EMSGSIZE);
    645 	}
    646 
    647 	if (d->bd_hdrcmplt)
    648 		dst.ss_family = pseudo_AF_HDRCMPLT;
    649 
    650 	s = splsoftnet();
    651 	error = (*ifp->if_output)(ifp, m, (struct sockaddr *) &dst, NULL);
    652 	splx(s);
    653 	KERNEL_UNLOCK_ONE(NULL);
    654 	/*
    655 	 * The driver frees the mbuf.
    656 	 */
    657 	return (error);
    658 }
    659 
    660 /*
    661  * Reset a descriptor by flushing its packet buffer and clearing the
    662  * receive and drop counts.  Should be called at splnet.
    663  */
    664 static void
    665 reset_d(struct bpf_d *d)
    666 {
    667 	if (d->bd_hbuf) {
    668 		/* Free the hold buffer. */
    669 		d->bd_fbuf = d->bd_hbuf;
    670 		d->bd_hbuf = 0;
    671 	}
    672 	d->bd_slen = 0;
    673 	d->bd_hlen = 0;
    674 	d->bd_rcount = 0;
    675 	d->bd_dcount = 0;
    676 	d->bd_ccount = 0;
    677 }
    678 
    679 /*
    680  *  FIONREAD		Check for read packet available.
    681  *  BIOCGBLEN		Get buffer len [for read()].
    682  *  BIOCSETF		Set ethernet read filter.
    683  *  BIOCFLUSH		Flush read packet buffer.
    684  *  BIOCPROMISC		Put interface into promiscuous mode.
    685  *  BIOCGDLT		Get link layer type.
    686  *  BIOCGETIF		Get interface name.
    687  *  BIOCSETIF		Set interface.
    688  *  BIOCSRTIMEOUT	Set read timeout.
    689  *  BIOCGRTIMEOUT	Get read timeout.
    690  *  BIOCGSTATS		Get packet stats.
    691  *  BIOCIMMEDIATE	Set immediate mode.
    692  *  BIOCVERSION		Get filter language version.
    693  *  BIOCGHDRCMPLT	Get "header already complete" flag.
    694  *  BIOCSHDRCMPLT	Set "header already complete" flag.
    695  */
    696 /* ARGSUSED */
    697 static int
    698 bpf_ioctl(struct file *fp, u_long cmd, void *addr)
    699 {
    700 	struct bpf_d *d = fp->f_data;
    701 	int s, error = 0;
    702 
    703 	/*
    704 	 * Refresh the PID associated with this bpf file.
    705 	 */
    706 	KERNEL_LOCK(1, NULL);
    707 	d->bd_pid = curproc->p_pid;
    708 
    709 	s = splnet();
    710 	if (d->bd_state == BPF_WAITING)
    711 		callout_stop(&d->bd_callout);
    712 	d->bd_state = BPF_IDLE;
    713 	splx(s);
    714 
    715 	switch (cmd) {
    716 
    717 	default:
    718 		error = EINVAL;
    719 		break;
    720 
    721 	/*
    722 	 * Check for read packet available.
    723 	 */
    724 	case FIONREAD:
    725 		{
    726 			int n;
    727 
    728 			s = splnet();
    729 			n = d->bd_slen;
    730 			if (d->bd_hbuf)
    731 				n += d->bd_hlen;
    732 			splx(s);
    733 
    734 			*(int *)addr = n;
    735 			break;
    736 		}
    737 
    738 	/*
    739 	 * Get buffer len [for read()].
    740 	 */
    741 	case BIOCGBLEN:
    742 		*(u_int *)addr = d->bd_bufsize;
    743 		break;
    744 
    745 	/*
    746 	 * Set buffer length.
    747 	 */
    748 	case BIOCSBLEN:
    749 		if (d->bd_bif != 0)
    750 			error = EINVAL;
    751 		else {
    752 			u_int size = *(u_int *)addr;
    753 
    754 			if (size > bpf_maxbufsize)
    755 				*(u_int *)addr = size = bpf_maxbufsize;
    756 			else if (size < BPF_MINBUFSIZE)
    757 				*(u_int *)addr = size = BPF_MINBUFSIZE;
    758 			d->bd_bufsize = size;
    759 		}
    760 		break;
    761 
    762 	/*
    763 	 * Set link layer read filter.
    764 	 */
    765 	case BIOCSETF:
    766 		error = bpf_setf(d, addr);
    767 		break;
    768 
    769 	/*
    770 	 * Flush read packet buffer.
    771 	 */
    772 	case BIOCFLUSH:
    773 		s = splnet();
    774 		reset_d(d);
    775 		splx(s);
    776 		break;
    777 
    778 	/*
    779 	 * Put interface into promiscuous mode.
    780 	 */
    781 	case BIOCPROMISC:
    782 		if (d->bd_bif == 0) {
    783 			/*
    784 			 * No interface attached yet.
    785 			 */
    786 			error = EINVAL;
    787 			break;
    788 		}
    789 		s = splnet();
    790 		if (d->bd_promisc == 0) {
    791 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
    792 			if (error == 0)
    793 				d->bd_promisc = 1;
    794 		}
    795 		splx(s);
    796 		break;
    797 
    798 	/*
    799 	 * Get device parameters.
    800 	 */
    801 	case BIOCGDLT:
    802 		if (d->bd_bif == 0)
    803 			error = EINVAL;
    804 		else
    805 			*(u_int *)addr = d->bd_bif->bif_dlt;
    806 		break;
    807 
    808 	/*
    809 	 * Get a list of supported device parameters.
    810 	 */
    811 	case BIOCGDLTLIST:
    812 		if (d->bd_bif == 0)
    813 			error = EINVAL;
    814 		else
    815 			error = bpf_getdltlist(d, addr);
    816 		break;
    817 
    818 	/*
    819 	 * Set device parameters.
    820 	 */
    821 	case BIOCSDLT:
    822 		if (d->bd_bif == 0)
    823 			error = EINVAL;
    824 		else
    825 			error = bpf_setdlt(d, *(u_int *)addr);
    826 		break;
    827 
    828 	/*
    829 	 * Set interface name.
    830 	 */
    831 #ifdef OBIOCGETIF
    832 	case OBIOCGETIF:
    833 #endif
    834 	case BIOCGETIF:
    835 		if (d->bd_bif == 0)
    836 			error = EINVAL;
    837 		else
    838 			bpf_ifname(d->bd_bif->bif_ifp, addr);
    839 		break;
    840 
    841 	/*
    842 	 * Set interface.
    843 	 */
    844 #ifdef OBIOCSETIF
    845 	case OBIOCSETIF:
    846 #endif
    847 	case BIOCSETIF:
    848 		error = bpf_setif(d, addr);
    849 		break;
    850 
    851 	/*
    852 	 * Set read timeout.
    853 	 */
    854 	case BIOCSRTIMEOUT:
    855 		{
    856 			struct timeval *tv = addr;
    857 
    858 			/* Compute number of ticks. */
    859 			d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
    860 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
    861 				d->bd_rtout = 1;
    862 			break;
    863 		}
    864 
    865 #ifdef BIOCGORTIMEOUT
    866 	/*
    867 	 * Get read timeout.
    868 	 */
    869 	case BIOCGORTIMEOUT:
    870 		{
    871 			struct timeval50 *tv = addr;
    872 
    873 			tv->tv_sec = d->bd_rtout / hz;
    874 			tv->tv_usec = (d->bd_rtout % hz) * tick;
    875 			break;
    876 		}
    877 #endif
    878 
    879 #ifdef BIOCSORTIMEOUT
    880 	/*
    881 	 * Set read timeout.
    882 	 */
    883 	case BIOCSORTIMEOUT:
    884 		{
    885 			struct timeval50 *tv = addr;
    886 
    887 			/* Compute number of ticks. */
    888 			d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
    889 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
    890 				d->bd_rtout = 1;
    891 			break;
    892 		}
    893 #endif
    894 
    895 	/*
    896 	 * Get read timeout.
    897 	 */
    898 	case BIOCGRTIMEOUT:
    899 		{
    900 			struct timeval *tv = addr;
    901 
    902 			tv->tv_sec = d->bd_rtout / hz;
    903 			tv->tv_usec = (d->bd_rtout % hz) * tick;
    904 			break;
    905 		}
    906 	/*
    907 	 * Get packet stats.
    908 	 */
    909 	case BIOCGSTATS:
    910 		{
    911 			struct bpf_stat *bs = addr;
    912 
    913 			bs->bs_recv = d->bd_rcount;
    914 			bs->bs_drop = d->bd_dcount;
    915 			bs->bs_capt = d->bd_ccount;
    916 			break;
    917 		}
    918 
    919 	case BIOCGSTATSOLD:
    920 		{
    921 			struct bpf_stat_old *bs = addr;
    922 
    923 			bs->bs_recv = d->bd_rcount;
    924 			bs->bs_drop = d->bd_dcount;
    925 			break;
    926 		}
    927 
    928 	/*
    929 	 * Set immediate mode.
    930 	 */
    931 	case BIOCIMMEDIATE:
    932 		d->bd_immediate = *(u_int *)addr;
    933 		break;
    934 
    935 	case BIOCVERSION:
    936 		{
    937 			struct bpf_version *bv = addr;
    938 
    939 			bv->bv_major = BPF_MAJOR_VERSION;
    940 			bv->bv_minor = BPF_MINOR_VERSION;
    941 			break;
    942 		}
    943 
    944 	case BIOCGHDRCMPLT:	/* get "header already complete" flag */
    945 		*(u_int *)addr = d->bd_hdrcmplt;
    946 		break;
    947 
    948 	case BIOCSHDRCMPLT:	/* set "header already complete" flag */
    949 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
    950 		break;
    951 
    952 	/*
    953 	 * Get "see sent packets" flag
    954 	 */
    955 	case BIOCGSEESENT:
    956 		*(u_int *)addr = d->bd_seesent;
    957 		break;
    958 
    959 	/*
    960 	 * Set "see sent" packets flag
    961 	 */
    962 	case BIOCSSEESENT:
    963 		d->bd_seesent = *(u_int *)addr;
    964 		break;
    965 
    966 	case FIONBIO:		/* Non-blocking I/O */
    967 		/*
    968 		 * No need to do anything special as we use IO_NDELAY in
    969 		 * bpfread() as an indication of whether or not to block
    970 		 * the read.
    971 		 */
    972 		break;
    973 
    974 	case FIOASYNC:		/* Send signal on receive packets */
    975 		d->bd_async = *(int *)addr;
    976 		break;
    977 
    978 	case TIOCSPGRP:		/* Process or group to send signals to */
    979 	case FIOSETOWN:
    980 		error = fsetown(&d->bd_pgid, cmd, addr);
    981 		break;
    982 
    983 	case TIOCGPGRP:
    984 	case FIOGETOWN:
    985 		error = fgetown(d->bd_pgid, cmd, addr);
    986 		break;
    987 	}
    988 	KERNEL_UNLOCK_ONE(NULL);
    989 	return (error);
    990 }
    991 
    992 /*
    993  * Set d's packet filter program to fp.  If this file already has a filter,
    994  * free it and replace it.  Returns EINVAL for bogus requests.
    995  */
    996 int
    997 bpf_setf(struct bpf_d *d, struct bpf_program *fp)
    998 {
    999 	struct bpf_insn *fcode, *old;
   1000 	u_int flen, size;
   1001 	int s;
   1002 
   1003 	old = d->bd_filter;
   1004 	if (fp->bf_insns == 0) {
   1005 		if (fp->bf_len != 0)
   1006 			return (EINVAL);
   1007 		s = splnet();
   1008 		d->bd_filter = 0;
   1009 		reset_d(d);
   1010 		splx(s);
   1011 		if (old != 0)
   1012 			free(old, M_DEVBUF);
   1013 		return (0);
   1014 	}
   1015 	flen = fp->bf_len;
   1016 	if (flen > BPF_MAXINSNS)
   1017 		return (EINVAL);
   1018 
   1019 	size = flen * sizeof(*fp->bf_insns);
   1020 	fcode = malloc(size, M_DEVBUF, M_WAITOK);
   1021 	if (copyin(fp->bf_insns, fcode, size) == 0 &&
   1022 	    bpf_validate(fcode, (int)flen)) {
   1023 		s = splnet();
   1024 		d->bd_filter = fcode;
   1025 		reset_d(d);
   1026 		splx(s);
   1027 		if (old != 0)
   1028 			free(old, M_DEVBUF);
   1029 
   1030 		return (0);
   1031 	}
   1032 	free(fcode, M_DEVBUF);
   1033 	return (EINVAL);
   1034 }
   1035 
   1036 /*
   1037  * Detach a file from its current interface (if attached at all) and attach
   1038  * to the interface indicated by the name stored in ifr.
   1039  * Return an errno or 0.
   1040  */
   1041 static int
   1042 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
   1043 {
   1044 	struct bpf_if *bp;
   1045 	char *cp;
   1046 	int unit_seen, i, s, error;
   1047 
   1048 	/*
   1049 	 * Make sure the provided name has a unit number, and default
   1050 	 * it to '0' if not specified.
   1051 	 * XXX This is ugly ... do this differently?
   1052 	 */
   1053 	unit_seen = 0;
   1054 	cp = ifr->ifr_name;
   1055 	cp[sizeof(ifr->ifr_name) - 1] = '\0';	/* sanity */
   1056 	while (*cp++)
   1057 		if (*cp >= '0' && *cp <= '9')
   1058 			unit_seen = 1;
   1059 	if (!unit_seen) {
   1060 		/* Make sure to leave room for the '\0'. */
   1061 		for (i = 0; i < (IFNAMSIZ - 1); ++i) {
   1062 			if ((ifr->ifr_name[i] >= 'a' &&
   1063 			     ifr->ifr_name[i] <= 'z') ||
   1064 			    (ifr->ifr_name[i] >= 'A' &&
   1065 			     ifr->ifr_name[i] <= 'Z'))
   1066 				continue;
   1067 			ifr->ifr_name[i] = '0';
   1068 		}
   1069 	}
   1070 
   1071 	/*
   1072 	 * Look through attached interfaces for the named one.
   1073 	 */
   1074 	for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
   1075 		struct ifnet *ifp = bp->bif_ifp;
   1076 
   1077 		if (ifp == 0 ||
   1078 		    strcmp(ifp->if_xname, ifr->ifr_name) != 0)
   1079 			continue;
   1080 		/* skip additional entry */
   1081 		if (bp->bif_driverp != &ifp->if_bpf)
   1082 			continue;
   1083 		/*
   1084 		 * We found the requested interface.
   1085 		 * Allocate the packet buffers if we need to.
   1086 		 * If we're already attached to requested interface,
   1087 		 * just flush the buffer.
   1088 		 */
   1089 		if (d->bd_sbuf == 0) {
   1090 			error = bpf_allocbufs(d);
   1091 			if (error != 0)
   1092 				return (error);
   1093 		}
   1094 		s = splnet();
   1095 		if (bp != d->bd_bif) {
   1096 			if (d->bd_bif)
   1097 				/*
   1098 				 * Detach if attached to something else.
   1099 				 */
   1100 				bpf_detachd(d);
   1101 
   1102 			bpf_attachd(d, bp);
   1103 		}
   1104 		reset_d(d);
   1105 		splx(s);
   1106 		return (0);
   1107 	}
   1108 	/* Not found. */
   1109 	return (ENXIO);
   1110 }
   1111 
   1112 /*
   1113  * Copy the interface name to the ifreq.
   1114  */
   1115 static void
   1116 bpf_ifname(struct ifnet *ifp, struct ifreq *ifr)
   1117 {
   1118 	memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
   1119 }
   1120 
   1121 static int
   1122 bpf_stat(struct file *fp, struct stat *st)
   1123 {
   1124 	struct bpf_d *d = fp->f_data;
   1125 
   1126 	(void)memset(st, 0, sizeof(*st));
   1127 	KERNEL_LOCK(1, NULL);
   1128 	st->st_dev = makedev(cdevsw_lookup_major(&bpf_cdevsw), d->bd_pid);
   1129 	st->st_atimespec = d->bd_atime;
   1130 	st->st_mtimespec = d->bd_mtime;
   1131 	st->st_ctimespec = st->st_birthtimespec = d->bd_btime;
   1132 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
   1133 	st->st_gid = kauth_cred_getegid(fp->f_cred);
   1134 	KERNEL_UNLOCK_ONE(NULL);
   1135 	return 0;
   1136 }
   1137 
   1138 /*
   1139  * Support for poll() system call
   1140  *
   1141  * Return true iff the specific operation will not block indefinitely - with
   1142  * the assumption that it is safe to positively acknowledge a request for the
   1143  * ability to write to the BPF device.
   1144  * Otherwise, return false but make a note that a selnotify() must be done.
   1145  */
   1146 static int
   1147 bpf_poll(struct file *fp, int events)
   1148 {
   1149 	struct bpf_d *d = fp->f_data;
   1150 	int s = splnet();
   1151 	int revents;
   1152 
   1153 	/*
   1154 	 * Refresh the PID associated with this bpf file.
   1155 	 */
   1156 	KERNEL_LOCK(1, NULL);
   1157 	d->bd_pid = curproc->p_pid;
   1158 
   1159 	revents = events & (POLLOUT | POLLWRNORM);
   1160 	if (events & (POLLIN | POLLRDNORM)) {
   1161 		/*
   1162 		 * An imitation of the FIONREAD ioctl code.
   1163 		 */
   1164 		if (d->bd_hlen != 0 ||
   1165 		    ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
   1166 		     d->bd_slen != 0)) {
   1167 			revents |= events & (POLLIN | POLLRDNORM);
   1168 		} else {
   1169 			selrecord(curlwp, &d->bd_sel);
   1170 			/* Start the read timeout if necessary */
   1171 			if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
   1172 				callout_reset(&d->bd_callout, d->bd_rtout,
   1173 					      bpf_timed_out, d);
   1174 				d->bd_state = BPF_WAITING;
   1175 			}
   1176 		}
   1177 	}
   1178 
   1179 	KERNEL_UNLOCK_ONE(NULL);
   1180 	splx(s);
   1181 	return (revents);
   1182 }
   1183 
   1184 static void
   1185 filt_bpfrdetach(struct knote *kn)
   1186 {
   1187 	struct bpf_d *d = kn->kn_hook;
   1188 	int s;
   1189 
   1190 	KERNEL_LOCK(1, NULL);
   1191 	s = splnet();
   1192 	SLIST_REMOVE(&d->bd_sel.sel_klist, kn, knote, kn_selnext);
   1193 	splx(s);
   1194 	KERNEL_UNLOCK_ONE(NULL);
   1195 }
   1196 
   1197 static int
   1198 filt_bpfread(struct knote *kn, long hint)
   1199 {
   1200 	struct bpf_d *d = kn->kn_hook;
   1201 	int rv;
   1202 
   1203 	KERNEL_LOCK(1, NULL);
   1204 	kn->kn_data = d->bd_hlen;
   1205 	if (d->bd_immediate)
   1206 		kn->kn_data += d->bd_slen;
   1207 	rv = (kn->kn_data > 0);
   1208 	KERNEL_UNLOCK_ONE(NULL);
   1209 	return rv;
   1210 }
   1211 
   1212 static const struct filterops bpfread_filtops =
   1213 	{ 1, NULL, filt_bpfrdetach, filt_bpfread };
   1214 
   1215 static int
   1216 bpf_kqfilter(struct file *fp, struct knote *kn)
   1217 {
   1218 	struct bpf_d *d = fp->f_data;
   1219 	struct klist *klist;
   1220 	int s;
   1221 
   1222 	KERNEL_LOCK(1, NULL);
   1223 
   1224 	switch (kn->kn_filter) {
   1225 	case EVFILT_READ:
   1226 		klist = &d->bd_sel.sel_klist;
   1227 		kn->kn_fop = &bpfread_filtops;
   1228 		break;
   1229 
   1230 	default:
   1231 		KERNEL_UNLOCK_ONE(NULL);
   1232 		return (EINVAL);
   1233 	}
   1234 
   1235 	kn->kn_hook = d;
   1236 
   1237 	s = splnet();
   1238 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1239 	splx(s);
   1240 	KERNEL_UNLOCK_ONE(NULL);
   1241 
   1242 	return (0);
   1243 }
   1244 
   1245 /*
   1246  * Incoming linkage from device drivers.  Process the packet pkt, of length
   1247  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
   1248  * by each process' filter, and if accepted, stashed into the corresponding
   1249  * buffer.
   1250  */
   1251 static void
   1252 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
   1253 {
   1254 	struct bpf_d *d;
   1255 	u_int slen;
   1256 	struct timespec ts;
   1257 	int gottime=0;
   1258 
   1259 	/*
   1260 	 * Note that the ipl does not have to be raised at this point.
   1261 	 * The only problem that could arise here is that if two different
   1262 	 * interfaces shared any data.  This is not the case.
   1263 	 */
   1264 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1265 		++d->bd_rcount;
   1266 		++bpf_gstats.bs_recv;
   1267 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
   1268 		if (slen != 0) {
   1269 			if (!gottime) {
   1270 				nanotime(&ts);
   1271 				gottime = 1;
   1272 			}
   1273 			catchpacket(d, pkt, pktlen, slen, memcpy, &ts);
   1274 		}
   1275 	}
   1276 }
   1277 
   1278 /*
   1279  * Copy data from an mbuf chain into a buffer.  This code is derived
   1280  * from m_copydata in sys/uipc_mbuf.c.
   1281  */
   1282 static void *
   1283 bpf_mcpy(void *dst_arg, const void *src_arg, size_t len)
   1284 {
   1285 	const struct mbuf *m;
   1286 	u_int count;
   1287 	u_char *dst;
   1288 
   1289 	m = src_arg;
   1290 	dst = dst_arg;
   1291 	while (len > 0) {
   1292 		if (m == NULL)
   1293 			panic("bpf_mcpy");
   1294 		count = min(m->m_len, len);
   1295 		memcpy(dst, mtod(m, const void *), count);
   1296 		m = m->m_next;
   1297 		dst += count;
   1298 		len -= count;
   1299 	}
   1300 	return dst_arg;
   1301 }
   1302 
   1303 /*
   1304  * Dispatch a packet to all the listeners on interface bp.
   1305  *
   1306  * marg    pointer to the packet, either a data buffer or an mbuf chain
   1307  * buflen  buffer length, if marg is a data buffer
   1308  * cpfn    a function that can copy marg into the listener's buffer
   1309  * pktlen  length of the packet
   1310  * rcvif   either NULL or the interface the packet came in on.
   1311  */
   1312 static inline void
   1313 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
   1314 	    void *marg, u_int pktlen, u_int buflen, struct ifnet *rcvif)
   1315 {
   1316 	u_int slen;
   1317 	struct bpf_d *d;
   1318 	struct timespec ts;
   1319 	int gottime = 0;
   1320 
   1321 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1322 		if (!d->bd_seesent && (rcvif == NULL))
   1323 			continue;
   1324 		++d->bd_rcount;
   1325 		++bpf_gstats.bs_recv;
   1326 		slen = bpf_filter(d->bd_filter, marg, pktlen, buflen);
   1327 		if (slen != 0) {
   1328 			if(!gottime) {
   1329 				nanotime(&ts);
   1330 				gottime = 1;
   1331 			}
   1332 			catchpacket(d, marg, pktlen, slen, cpfn, &ts);
   1333 		}
   1334 	}
   1335 }
   1336 
   1337 /*
   1338  * Incoming linkage from device drivers, when the head of the packet is in
   1339  * a buffer, and the tail is in an mbuf chain.
   1340  */
   1341 static void
   1342 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
   1343 {
   1344 	u_int pktlen;
   1345 	struct mbuf mb;
   1346 
   1347 	pktlen = m_length(m) + dlen;
   1348 
   1349 	/*
   1350 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
   1351 	 * Note that we cut corners here; we only setup what's
   1352 	 * absolutely needed--this mbuf should never go anywhere else.
   1353 	 */
   1354 	(void)memset(&mb, 0, sizeof(mb));
   1355 	mb.m_next = m;
   1356 	mb.m_data = data;
   1357 	mb.m_len = dlen;
   1358 
   1359 	bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, m->m_pkthdr.rcvif);
   1360 }
   1361 
   1362 /*
   1363  * Incoming linkage from device drivers, when packet is in an mbuf chain.
   1364  */
   1365 static void
   1366 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
   1367 {
   1368 	void *(*cpfn)(void *, const void *, size_t);
   1369 	u_int pktlen, buflen;
   1370 	void *marg;
   1371 
   1372 	pktlen = m_length(m);
   1373 
   1374 	if (pktlen == m->m_len) {
   1375 		cpfn = (void *)memcpy;
   1376 		marg = mtod(m, void *);
   1377 		buflen = pktlen;
   1378 	} else {
   1379 /*###1299 [cc] warning: assignment from incompatible pointer type%%%*/
   1380 		cpfn = bpf_mcpy;
   1381 		marg = m;
   1382 		buflen = 0;
   1383 	}
   1384 
   1385 	bpf_deliver(bp, cpfn, marg, pktlen, buflen, m->m_pkthdr.rcvif);
   1386 }
   1387 
   1388 /*
   1389  * We need to prepend the address family as
   1390  * a four byte field.  Cons up a dummy header
   1391  * to pacify bpf.  This is safe because bpf
   1392  * will only read from the mbuf (i.e., it won't
   1393  * try to free it or keep a pointer a to it).
   1394  */
   1395 static void
   1396 bpf_mtap_af(struct bpf_if *bp, uint32_t af, struct mbuf *m)
   1397 {
   1398 	struct mbuf m0;
   1399 
   1400 	m0.m_flags = 0;
   1401 	m0.m_next = m;
   1402 	m0.m_len = 4;
   1403 	m0.m_data = (char *)&af;
   1404 
   1405 	bpf_mtap(bp, &m0);
   1406 }
   1407 
   1408 static void
   1409 bpf_mtap_et(struct bpf_if *bp, uint16_t et, struct mbuf *m)
   1410 {
   1411 	struct mbuf m0;
   1412 
   1413 	m0.m_flags = 0;
   1414 	m0.m_next = m;
   1415 	m0.m_len = 14;
   1416 	m0.m_data = m0.m_dat;
   1417 
   1418 	((uint32_t *)m0.m_data)[0] = 0;
   1419 	((uint32_t *)m0.m_data)[1] = 0;
   1420 	((uint32_t *)m0.m_data)[2] = 0;
   1421 	((uint16_t *)m0.m_data)[6] = et;
   1422 
   1423 	bpf_mtap(bp, &m0);
   1424 }
   1425 
   1426 /*
   1427  * Put the SLIP pseudo-"link header" in place.
   1428  * Note this M_PREPEND() should never fail,
   1429  * swince we know we always have enough space
   1430  * in the input buffer.
   1431  */
   1432 static void
   1433 bpf_mtap_sl_in(struct bpf_if *bp, u_char *chdr, struct mbuf **m)
   1434 {
   1435 	int s;
   1436 	u_char *hp;
   1437 
   1438 	M_PREPEND(*m, SLIP_HDRLEN, M_DONTWAIT);
   1439 	if (*m == NULL)
   1440 		return;
   1441 
   1442 	hp = mtod(*m, u_char *);
   1443 	hp[SLX_DIR] = SLIPDIR_IN;
   1444 	(void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
   1445 
   1446 	s = splnet();
   1447 	bpf_mtap(bp, *m);
   1448 	splx(s);
   1449 
   1450 	m_adj(*m, SLIP_HDRLEN);
   1451 }
   1452 
   1453 /*
   1454  * Put the SLIP pseudo-"link header" in
   1455  * place.  The compressed header is now
   1456  * at the beginning of the mbuf.
   1457  */
   1458 static void
   1459 bpf_mtap_sl_out(struct bpf_if *bp, u_char *chdr, struct mbuf *m)
   1460 {
   1461 	struct mbuf m0;
   1462 	u_char *hp;
   1463 	int s;
   1464 
   1465 	m0.m_flags = 0;
   1466 	m0.m_next = m;
   1467 	m0.m_data = m0.m_dat;
   1468 	m0.m_len = SLIP_HDRLEN;
   1469 
   1470 	hp = mtod(&m0, u_char *);
   1471 
   1472 	hp[SLX_DIR] = SLIPDIR_OUT;
   1473 	(void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
   1474 
   1475 	s = splnet();
   1476 	bpf_mtap(bp, &m0);
   1477 	splx(s);
   1478 	m_freem(m);
   1479 }
   1480 
   1481 /*
   1482  * Move the packet data from interface memory (pkt) into the
   1483  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
   1484  * otherwise 0.  "copy" is the routine called to do the actual data
   1485  * transfer.  memcpy is passed in to copy contiguous chunks, while
   1486  * bpf_mcpy is passed in to copy mbuf chains.  In the latter case,
   1487  * pkt is really an mbuf.
   1488  */
   1489 static void
   1490 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
   1491     void *(*cpfn)(void *, const void *, size_t), struct timespec *ts)
   1492 {
   1493 	struct bpf_hdr *hp;
   1494 	int totlen, curlen;
   1495 	int hdrlen = d->bd_bif->bif_hdrlen;
   1496 	int do_wakeup = 0;
   1497 
   1498 	++d->bd_ccount;
   1499 	++bpf_gstats.bs_capt;
   1500 	/*
   1501 	 * Figure out how many bytes to move.  If the packet is
   1502 	 * greater or equal to the snapshot length, transfer that
   1503 	 * much.  Otherwise, transfer the whole packet (unless
   1504 	 * we hit the buffer size limit).
   1505 	 */
   1506 	totlen = hdrlen + min(snaplen, pktlen);
   1507 	if (totlen > d->bd_bufsize)
   1508 		totlen = d->bd_bufsize;
   1509 
   1510 	/*
   1511 	 * Round up the end of the previous packet to the next longword.
   1512 	 */
   1513 	curlen = BPF_WORDALIGN(d->bd_slen);
   1514 	if (curlen + totlen > d->bd_bufsize) {
   1515 		/*
   1516 		 * This packet will overflow the storage buffer.
   1517 		 * Rotate the buffers if we can, then wakeup any
   1518 		 * pending reads.
   1519 		 */
   1520 		if (d->bd_fbuf == 0) {
   1521 			/*
   1522 			 * We haven't completed the previous read yet,
   1523 			 * so drop the packet.
   1524 			 */
   1525 			++d->bd_dcount;
   1526 			++bpf_gstats.bs_drop;
   1527 			return;
   1528 		}
   1529 		ROTATE_BUFFERS(d);
   1530 		do_wakeup = 1;
   1531 		curlen = 0;
   1532 	} else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT) {
   1533 		/*
   1534 		 * Immediate mode is set, or the read timeout has
   1535 		 * already expired during a select call.  A packet
   1536 		 * arrived, so the reader should be woken up.
   1537 		 */
   1538 		do_wakeup = 1;
   1539 	}
   1540 
   1541 	/*
   1542 	 * Append the bpf header.
   1543 	 */
   1544 	hp = (struct bpf_hdr *)((char *)d->bd_sbuf + curlen);
   1545 	hp->bh_tstamp.tv_sec = ts->tv_sec;
   1546 	hp->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
   1547 	hp->bh_datalen = pktlen;
   1548 	hp->bh_hdrlen = hdrlen;
   1549 	/*
   1550 	 * Copy the packet data into the store buffer and update its length.
   1551 	 */
   1552 	(*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
   1553 	d->bd_slen = curlen + totlen;
   1554 
   1555 	/*
   1556 	 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
   1557 	 * will cause filt_bpfread() to be called with it adjusted.
   1558 	 */
   1559 	if (do_wakeup)
   1560 		bpf_wakeup(d);
   1561 }
   1562 
   1563 /*
   1564  * Initialize all nonzero fields of a descriptor.
   1565  */
   1566 static int
   1567 bpf_allocbufs(struct bpf_d *d)
   1568 {
   1569 
   1570 	d->bd_fbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
   1571 	if (!d->bd_fbuf)
   1572 		return (ENOBUFS);
   1573 	d->bd_sbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
   1574 	if (!d->bd_sbuf) {
   1575 		free(d->bd_fbuf, M_DEVBUF);
   1576 		return (ENOBUFS);
   1577 	}
   1578 	d->bd_slen = 0;
   1579 	d->bd_hlen = 0;
   1580 	return (0);
   1581 }
   1582 
   1583 /*
   1584  * Free buffers currently in use by a descriptor.
   1585  * Called on close.
   1586  */
   1587 static void
   1588 bpf_freed(struct bpf_d *d)
   1589 {
   1590 	/*
   1591 	 * We don't need to lock out interrupts since this descriptor has
   1592 	 * been detached from its interface and it yet hasn't been marked
   1593 	 * free.
   1594 	 */
   1595 	if (d->bd_sbuf != 0) {
   1596 		free(d->bd_sbuf, M_DEVBUF);
   1597 		if (d->bd_hbuf != 0)
   1598 			free(d->bd_hbuf, M_DEVBUF);
   1599 		if (d->bd_fbuf != 0)
   1600 			free(d->bd_fbuf, M_DEVBUF);
   1601 	}
   1602 	if (d->bd_filter)
   1603 		free(d->bd_filter, M_DEVBUF);
   1604 }
   1605 
   1606 /*
   1607  * Attach an interface to bpf.  dlt is the link layer type;
   1608  * hdrlen is the fixed size of the link header for the specified dlt
   1609  * (variable length headers not yet supported).
   1610  */
   1611 static void
   1612 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
   1613 {
   1614 	struct bpf_if *bp;
   1615 	bp = malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
   1616 	if (bp == 0)
   1617 		panic("bpfattach");
   1618 
   1619 	bp->bif_dlist = 0;
   1620 	bp->bif_driverp = driverp;
   1621 	bp->bif_ifp = ifp;
   1622 	bp->bif_dlt = dlt;
   1623 
   1624 	bp->bif_next = bpf_iflist;
   1625 	bpf_iflist = bp;
   1626 
   1627 	*bp->bif_driverp = 0;
   1628 
   1629 	/*
   1630 	 * Compute the length of the bpf header.  This is not necessarily
   1631 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1632 	 * that the network layer header begins on a longword boundary (for
   1633 	 * performance reasons and to alleviate alignment restrictions).
   1634 	 */
   1635 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1636 
   1637 #if 0
   1638 	printf("bpf: %s attached\n", ifp->if_xname);
   1639 #endif
   1640 }
   1641 
   1642 /*
   1643  * Remove an interface from bpf.
   1644  */
   1645 static void
   1646 bpfdetach(struct ifnet *ifp)
   1647 {
   1648 	struct bpf_if *bp, **pbp;
   1649 	struct bpf_d *d;
   1650 	int s;
   1651 
   1652 	/* Nuke the vnodes for any open instances */
   1653 	LIST_FOREACH(d, &bpf_list, bd_list) {
   1654 		if (d->bd_bif != NULL && d->bd_bif->bif_ifp == ifp) {
   1655 			/*
   1656 			 * Detach the descriptor from an interface now.
   1657 			 * It will be free'ed later by close routine.
   1658 			 */
   1659 			s = splnet();
   1660 			d->bd_promisc = 0;	/* we can't touch device. */
   1661 			bpf_detachd(d);
   1662 			splx(s);
   1663 		}
   1664 	}
   1665 
   1666   again:
   1667 	for (bp = bpf_iflist, pbp = &bpf_iflist;
   1668 	     bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
   1669 		if (bp->bif_ifp == ifp) {
   1670 			*pbp = bp->bif_next;
   1671 			free(bp, M_DEVBUF);
   1672 			goto again;
   1673 		}
   1674 	}
   1675 }
   1676 
   1677 /*
   1678  * Change the data link type of a interface.
   1679  */
   1680 static void
   1681 bpf_change_type(struct ifnet *ifp, u_int dlt, u_int hdrlen)
   1682 {
   1683 	struct bpf_if *bp;
   1684 
   1685 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1686 		if (bp->bif_driverp == &ifp->if_bpf)
   1687 			break;
   1688 	}
   1689 	if (bp == NULL)
   1690 		panic("bpf_change_type");
   1691 
   1692 	bp->bif_dlt = dlt;
   1693 
   1694 	/*
   1695 	 * Compute the length of the bpf header.  This is not necessarily
   1696 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1697 	 * that the network layer header begins on a longword boundary (for
   1698 	 * performance reasons and to alleviate alignment restrictions).
   1699 	 */
   1700 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1701 }
   1702 
   1703 /*
   1704  * Get a list of available data link type of the interface.
   1705  */
   1706 static int
   1707 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
   1708 {
   1709 	int n, error;
   1710 	struct ifnet *ifp;
   1711 	struct bpf_if *bp;
   1712 
   1713 	ifp = d->bd_bif->bif_ifp;
   1714 	n = 0;
   1715 	error = 0;
   1716 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1717 		if (bp->bif_ifp != ifp)
   1718 			continue;
   1719 		if (bfl->bfl_list != NULL) {
   1720 			if (n >= bfl->bfl_len)
   1721 				return ENOMEM;
   1722 			error = copyout(&bp->bif_dlt,
   1723 			    bfl->bfl_list + n, sizeof(u_int));
   1724 		}
   1725 		n++;
   1726 	}
   1727 	bfl->bfl_len = n;
   1728 	return error;
   1729 }
   1730 
   1731 /*
   1732  * Set the data link type of a BPF instance.
   1733  */
   1734 static int
   1735 bpf_setdlt(struct bpf_d *d, u_int dlt)
   1736 {
   1737 	int s, error, opromisc;
   1738 	struct ifnet *ifp;
   1739 	struct bpf_if *bp;
   1740 
   1741 	if (d->bd_bif->bif_dlt == dlt)
   1742 		return 0;
   1743 	ifp = d->bd_bif->bif_ifp;
   1744 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1745 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
   1746 			break;
   1747 	}
   1748 	if (bp == NULL)
   1749 		return EINVAL;
   1750 	s = splnet();
   1751 	opromisc = d->bd_promisc;
   1752 	bpf_detachd(d);
   1753 	bpf_attachd(d, bp);
   1754 	reset_d(d);
   1755 	if (opromisc) {
   1756 		error = ifpromisc(bp->bif_ifp, 1);
   1757 		if (error)
   1758 			printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
   1759 			    bp->bif_ifp->if_xname, error);
   1760 		else
   1761 			d->bd_promisc = 1;
   1762 	}
   1763 	splx(s);
   1764 	return 0;
   1765 }
   1766 
   1767 static int
   1768 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
   1769 {
   1770 	int newsize, error;
   1771 	struct sysctlnode node;
   1772 
   1773 	node = *rnode;
   1774 	node.sysctl_data = &newsize;
   1775 	newsize = bpf_maxbufsize;
   1776 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1777 	if (error || newp == NULL)
   1778 		return (error);
   1779 
   1780 	if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
   1781 		return (EINVAL);
   1782 
   1783 	bpf_maxbufsize = newsize;
   1784 
   1785 	return (0);
   1786 }
   1787 
   1788 static int
   1789 sysctl_net_bpf_peers(SYSCTLFN_ARGS)
   1790 {
   1791 	int    error, elem_count;
   1792 	struct bpf_d	 *dp;
   1793 	struct bpf_d_ext  dpe;
   1794 	size_t len, needed, elem_size, out_size;
   1795 	char   *sp;
   1796 
   1797 	if (namelen == 1 && name[0] == CTL_QUERY)
   1798 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   1799 
   1800 	if (namelen != 2)
   1801 		return (EINVAL);
   1802 
   1803 	/* BPF peers is privileged information. */
   1804 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
   1805 	    KAUTH_REQ_NETWORK_INTERFACE_GETPRIV, NULL, NULL, NULL);
   1806 	if (error)
   1807 		return (EPERM);
   1808 
   1809 	len = (oldp != NULL) ? *oldlenp : 0;
   1810 	sp = oldp;
   1811 	elem_size = name[0];
   1812 	elem_count = name[1];
   1813 	out_size = MIN(sizeof(dpe), elem_size);
   1814 	needed = 0;
   1815 
   1816 	if (elem_size < 1 || elem_count < 0)
   1817 		return (EINVAL);
   1818 
   1819 	mutex_enter(&bpf_mtx);
   1820 	LIST_FOREACH(dp, &bpf_list, bd_list) {
   1821 		if (len >= elem_size && elem_count > 0) {
   1822 #define BPF_EXT(field)	dpe.bde_ ## field = dp->bd_ ## field
   1823 			BPF_EXT(bufsize);
   1824 			BPF_EXT(promisc);
   1825 			BPF_EXT(promisc);
   1826 			BPF_EXT(state);
   1827 			BPF_EXT(immediate);
   1828 			BPF_EXT(hdrcmplt);
   1829 			BPF_EXT(seesent);
   1830 			BPF_EXT(pid);
   1831 			BPF_EXT(rcount);
   1832 			BPF_EXT(dcount);
   1833 			BPF_EXT(ccount);
   1834 #undef BPF_EXT
   1835 			if (dp->bd_bif)
   1836 				(void)strlcpy(dpe.bde_ifname,
   1837 				    dp->bd_bif->bif_ifp->if_xname,
   1838 				    IFNAMSIZ - 1);
   1839 			else
   1840 				dpe.bde_ifname[0] = '\0';
   1841 
   1842 			error = copyout(&dpe, sp, out_size);
   1843 			if (error)
   1844 				break;
   1845 			sp += elem_size;
   1846 			len -= elem_size;
   1847 		}
   1848 		needed += elem_size;
   1849 		if (elem_count > 0 && elem_count != INT_MAX)
   1850 			elem_count--;
   1851 	}
   1852 	mutex_exit(&bpf_mtx);
   1853 
   1854 	*oldlenp = needed;
   1855 
   1856 	return (error);
   1857 }
   1858 
   1859 SYSCTL_SETUP(sysctl_net_bpf_setup, "sysctl net.bpf subtree setup")
   1860 {
   1861 	const struct sysctlnode *node;
   1862 
   1863 	sysctl_createv(clog, 0, NULL, NULL,
   1864 		       CTLFLAG_PERMANENT,
   1865 		       CTLTYPE_NODE, "net", NULL,
   1866 		       NULL, 0, NULL, 0,
   1867 		       CTL_NET, CTL_EOL);
   1868 
   1869 	node = NULL;
   1870 	sysctl_createv(clog, 0, NULL, &node,
   1871 		       CTLFLAG_PERMANENT,
   1872 		       CTLTYPE_NODE, "bpf",
   1873 		       SYSCTL_DESCR("BPF options"),
   1874 		       NULL, 0, NULL, 0,
   1875 		       CTL_NET, CTL_CREATE, CTL_EOL);
   1876 	if (node != NULL) {
   1877 		sysctl_createv(clog, 0, NULL, NULL,
   1878 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1879 			CTLTYPE_INT, "maxbufsize",
   1880 			SYSCTL_DESCR("Maximum size for data capture buffer"),
   1881 			sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
   1882 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1883 		sysctl_createv(clog, 0, NULL, NULL,
   1884 			CTLFLAG_PERMANENT,
   1885 			CTLTYPE_STRUCT, "stats",
   1886 			SYSCTL_DESCR("BPF stats"),
   1887 			NULL, 0, &bpf_gstats, sizeof(bpf_gstats),
   1888 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1889 		sysctl_createv(clog, 0, NULL, NULL,
   1890 			CTLFLAG_PERMANENT,
   1891 			CTLTYPE_STRUCT, "peers",
   1892 			SYSCTL_DESCR("BPF peers"),
   1893 			sysctl_net_bpf_peers, 0, NULL, 0,
   1894 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1895 	}
   1896 
   1897 }
   1898 
   1899 struct bpf_ops bpf_ops_kernel = {
   1900 	.bpf_attach =		bpfattach,
   1901 	.bpf_detach =		bpfdetach,
   1902 	.bpf_change_type =	bpf_change_type,
   1903 
   1904 	.bpf_tap =		bpf_tap,
   1905 	.bpf_mtap =		bpf_mtap,
   1906 	.bpf_mtap2 =		bpf_mtap2,
   1907 	.bpf_mtap_af =		bpf_mtap_af,
   1908 	.bpf_mtap_et =		bpf_mtap_et,
   1909 	.bpf_mtap_sl_in =	bpf_mtap_sl_in,
   1910 	.bpf_mtap_sl_out =	bpf_mtap_sl_out,
   1911 };
   1912 
   1913 void
   1914 bpf_setops()
   1915 {
   1916 
   1917 	bpf_ops = &bpf_ops_kernel;
   1918 }
   1919