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