Home | History | Annotate | Line # | Download | only in net
bpf.c revision 1.116
      1 /*	$NetBSD: bpf.c,v 1.116 2006/05/10 21:53:18 mrg 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.116 2006/05/10 21:53:18 mrg 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 
     68 #include <net/if.h>
     69 #include <net/slip.h>
     70 
     71 #include <net/bpf.h>
     72 #include <net/bpfdesc.h>
     73 
     74 #include <net/if_arc.h>
     75 #include <net/if_ether.h>
     76 
     77 #include <netinet/in.h>
     78 #include <netinet/if_inarp.h>
     79 
     80 #if defined(_KERNEL_OPT)
     81 #include "opt_bpf.h"
     82 #include "sl.h"
     83 #include "strip.h"
     84 #endif
     85 
     86 #ifndef BPF_BUFSIZE
     87 /*
     88  * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
     89  * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
     90  */
     91 # define BPF_BUFSIZE 32768
     92 #endif
     93 
     94 #define PRINET  26			/* interruptible */
     95 
     96 /*
     97  * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
     98  * XXX the default values should be computed dynamically based
     99  * on available memory size and available mbuf clusters.
    100  */
    101 int bpf_bufsize = BPF_BUFSIZE;
    102 int bpf_maxbufsize = BPF_DFLTBUFSIZE;	/* XXX set dynamically, see above */
    103 
    104 
    105 /*
    106  * Global BPF statistics returned by net.bpf.stats sysctl.
    107  */
    108 struct bpf_stat	bpf_gstats;
    109 
    110 /*
    111  * Use a mutex to avoid a race condition between gathering the stats/peers
    112  * and opening/closing the device.
    113  */
    114 struct simplelock bpf_slock;
    115 
    116 /*
    117  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
    118  *  bpf_dtab holds the descriptors, indexed by minor device #
    119  */
    120 struct bpf_if	*bpf_iflist;
    121 LIST_HEAD(, bpf_d) bpf_list;
    122 
    123 static int	bpf_allocbufs(struct bpf_d *);
    124 static void	bpf_deliver(struct bpf_if *,
    125 		            void *(*cpfn)(void *, const void *, size_t),
    126 			    void *, u_int, u_int, struct ifnet *);
    127 static void	bpf_freed(struct bpf_d *);
    128 static void	bpf_ifname(struct ifnet *, struct ifreq *);
    129 static void	*bpf_mcpy(void *, const void *, size_t);
    130 static int	bpf_movein(struct uio *, int, int,
    131 			        struct mbuf **, struct sockaddr *);
    132 static void	bpf_attachd(struct bpf_d *, struct bpf_if *);
    133 static void	bpf_detachd(struct bpf_d *);
    134 static int	bpf_setif(struct bpf_d *, struct ifreq *);
    135 static void	bpf_timed_out(void *);
    136 static inline void
    137 		bpf_wakeup(struct bpf_d *);
    138 static void	catchpacket(struct bpf_d *, u_char *, u_int, u_int,
    139 				 void *(*)(void *, const void *, size_t));
    140 static void	reset_d(struct bpf_d *);
    141 static int	bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
    142 static int	bpf_setdlt(struct bpf_d *, u_int);
    143 
    144 static int	bpf_read(struct file *, off_t *, struct uio *, struct ucred *,
    145     int);
    146 static int	bpf_write(struct file *, off_t *, struct uio *, struct ucred *,
    147     int);
    148 static int	bpf_ioctl(struct file *, u_long, void *, struct lwp *);
    149 static int	bpf_poll(struct file *, int, struct lwp *);
    150 static int	bpf_close(struct file *, struct lwp *);
    151 static int	bpf_kqfilter(struct file *, struct knote *);
    152 
    153 static const struct fileops bpf_fileops = {
    154 	bpf_read,
    155 	bpf_write,
    156 	bpf_ioctl,
    157 	fnullop_fcntl,
    158 	bpf_poll,
    159 	fbadop_stat,
    160 	bpf_close,
    161 	bpf_kqfilter,
    162 };
    163 
    164 dev_type_open(bpfopen);
    165 
    166 const struct cdevsw bpf_cdevsw = {
    167 	bpfopen, noclose, noread, nowrite, noioctl,
    168 	nostop, notty, nopoll, nommap, nokqfilter,
    169 };
    170 
    171 static int
    172 bpf_movein(struct uio *uio, int linktype, int mtu, struct mbuf **mp,
    173 	   struct sockaddr *sockp)
    174 {
    175 	struct mbuf *m;
    176 	int error;
    177 	int len;
    178 	int hlen;
    179 	int align;
    180 
    181 	/*
    182 	 * Build a sockaddr based on the data link layer type.
    183 	 * We do this at this level because the ethernet header
    184 	 * is copied directly into the data field of the sockaddr.
    185 	 * In the case of SLIP, there is no header and the packet
    186 	 * is forwarded as is.
    187 	 * Also, we are careful to leave room at the front of the mbuf
    188 	 * for the link level header.
    189 	 */
    190 	switch (linktype) {
    191 
    192 	case DLT_SLIP:
    193 		sockp->sa_family = AF_INET;
    194 		hlen = 0;
    195 		align = 0;
    196 		break;
    197 
    198 	case DLT_PPP:
    199 		sockp->sa_family = AF_UNSPEC;
    200 		hlen = 0;
    201 		align = 0;
    202 		break;
    203 
    204 	case DLT_EN10MB:
    205 		sockp->sa_family = AF_UNSPEC;
    206 		/* XXX Would MAXLINKHDR be better? */
    207  		/* 6(dst)+6(src)+2(type) */
    208 		hlen = sizeof(struct ether_header);
    209 		align = 2;
    210 		break;
    211 
    212 	case DLT_ARCNET:
    213 		sockp->sa_family = AF_UNSPEC;
    214 		hlen = ARC_HDRLEN;
    215 		align = 5;
    216 		break;
    217 
    218 	case DLT_FDDI:
    219 		sockp->sa_family = AF_LINK;
    220 		/* XXX 4(FORMAC)+6(dst)+6(src) */
    221 		hlen = 16;
    222 		align = 0;
    223 		break;
    224 
    225 	case DLT_ECONET:
    226 		sockp->sa_family = AF_UNSPEC;
    227 		hlen = 6;
    228 		align = 2;
    229 		break;
    230 
    231 	case DLT_NULL:
    232 		sockp->sa_family = AF_UNSPEC;
    233 		hlen = 0;
    234 		align = 0;
    235 		break;
    236 
    237 	default:
    238 		return (EIO);
    239 	}
    240 
    241 	len = uio->uio_resid;
    242 	/*
    243 	 * If there aren't enough bytes for a link level header or the
    244 	 * packet length exceeds the interface mtu, return an error.
    245 	 */
    246 	if (len < hlen || len - hlen > mtu)
    247 		return (EMSGSIZE);
    248 
    249 	/*
    250 	 * XXX Avoid complicated buffer chaining ---
    251 	 * bail if it won't fit in a single mbuf.
    252 	 * (Take into account possible alignment bytes)
    253 	 */
    254 	if ((unsigned)len > MCLBYTES - align)
    255 		return (EIO);
    256 
    257 	m = m_gethdr(M_WAIT, MT_DATA);
    258 	m->m_pkthdr.rcvif = 0;
    259 	m->m_pkthdr.len = len - hlen;
    260 	if (len > MHLEN - align) {
    261 		m_clget(m, M_WAIT);
    262 		if ((m->m_flags & M_EXT) == 0) {
    263 			error = ENOBUFS;
    264 			goto bad;
    265 		}
    266 	}
    267 
    268 	/* Insure the data is properly aligned */
    269 	if (align > 0) {
    270 		m->m_data += align;
    271 		m->m_len -= align;
    272 	}
    273 
    274 	error = uiomove(mtod(m, void *), len, uio);
    275 	if (error)
    276 		goto bad;
    277 	if (hlen != 0) {
    278 		memcpy(sockp->sa_data, mtod(m, void *), hlen);
    279 		m->m_data += hlen; /* XXX */
    280 		len -= hlen;
    281 	}
    282 	m->m_len = len;
    283 	*mp = m;
    284 	return (0);
    285 
    286 bad:
    287 	m_freem(m);
    288 	return (error);
    289 }
    290 
    291 /*
    292  * Attach file to the bpf interface, i.e. make d listen on bp.
    293  * Must be called at splnet.
    294  */
    295 static void
    296 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
    297 {
    298 	/*
    299 	 * Point d at bp, and add d to the interface's list of listeners.
    300 	 * Finally, point the driver's bpf cookie at the interface so
    301 	 * it will divert packets to bpf.
    302 	 */
    303 	d->bd_bif = bp;
    304 	d->bd_next = bp->bif_dlist;
    305 	bp->bif_dlist = d;
    306 
    307 	*bp->bif_driverp = bp;
    308 }
    309 
    310 /*
    311  * Detach a file from its interface.
    312  */
    313 static void
    314 bpf_detachd(struct bpf_d *d)
    315 {
    316 	struct bpf_d **p;
    317 	struct bpf_if *bp;
    318 
    319 	bp = d->bd_bif;
    320 	/*
    321 	 * Check if this descriptor had requested promiscuous mode.
    322 	 * If so, turn it off.
    323 	 */
    324 	if (d->bd_promisc) {
    325 		int error;
    326 
    327 		d->bd_promisc = 0;
    328 		/*
    329 		 * Take device out of promiscuous mode.  Since we were
    330 		 * able to enter promiscuous mode, we should be able
    331 		 * to turn it off.  But we can get an error if
    332 		 * the interface was configured down, so only panic
    333 		 * if we don't get an unexpected error.
    334 		 */
    335   		error = ifpromisc(bp->bif_ifp, 0);
    336 		if (error && error != EINVAL)
    337 			panic("bpf: ifpromisc failed");
    338 	}
    339 	/* Remove d from the interface's descriptor list. */
    340 	p = &bp->bif_dlist;
    341 	while (*p != d) {
    342 		p = &(*p)->bd_next;
    343 		if (*p == 0)
    344 			panic("bpf_detachd: descriptor not in list");
    345 	}
    346 	*p = (*p)->bd_next;
    347 	if (bp->bif_dlist == 0)
    348 		/*
    349 		 * Let the driver know that there are no more listeners.
    350 		 */
    351 		*d->bd_bif->bif_driverp = 0;
    352 	d->bd_bif = 0;
    353 }
    354 
    355 
    356 /*
    357  * Mark a descriptor free by making it point to itself.
    358  * This is probably cheaper than marking with a constant since
    359  * the address should be in a register anyway.
    360  */
    361 
    362 /*
    363  * bpfilterattach() is called at boot time.
    364  */
    365 /* ARGSUSED */
    366 void
    367 bpfilterattach(int n)
    368 {
    369 	simple_lock_init(&bpf_slock);
    370 
    371 	simple_lock(&bpf_slock);
    372 	LIST_INIT(&bpf_list);
    373 	simple_unlock(&bpf_slock);
    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 = falloc(l->l_proc, &fp, &fd)) != 0)
    393 		return error;
    394 
    395 	d = malloc(sizeof(*d), M_DEVBUF, M_WAITOK);
    396 	(void)memset(d, 0, sizeof(*d));
    397 	d->bd_bufsize = bpf_bufsize;
    398 	d->bd_seesent = 1;
    399 	d->bd_pid = l->l_proc->p_pid;
    400 	callout_init(&d->bd_callout);
    401 
    402 	simple_lock(&bpf_slock);
    403 	LIST_INSERT_HEAD(&bpf_list, d, bd_list);
    404 	simple_unlock(&bpf_slock);
    405 
    406 	return fdclone(l, fp, fd, flag, &bpf_fileops, d);
    407 }
    408 
    409 /*
    410  * Close the descriptor by detaching it from its interface,
    411  * deallocating its buffers, and marking it free.
    412  */
    413 /* ARGSUSED */
    414 static int
    415 bpf_close(struct file *fp, struct lwp *l)
    416 {
    417 	struct bpf_d *d = fp->f_data;
    418 	int s;
    419 
    420 	/*
    421 	 * Refresh the PID associated with this bpf file.
    422 	 */
    423 	d->bd_pid = l->l_proc->p_pid;
    424 
    425 	s = splnet();
    426 	if (d->bd_state == BPF_WAITING)
    427 		callout_stop(&d->bd_callout);
    428 	d->bd_state = BPF_IDLE;
    429 	if (d->bd_bif)
    430 		bpf_detachd(d);
    431 	splx(s);
    432 	bpf_freed(d);
    433 	simple_lock(&bpf_slock);
    434 	LIST_REMOVE(d, bd_list);
    435 	simple_unlock(&bpf_slock);
    436 	free(d, M_DEVBUF);
    437 	fp->f_data = NULL;
    438 
    439 	return (0);
    440 }
    441 
    442 /*
    443  * Rotate the packet buffers in descriptor d.  Move the store buffer
    444  * into the hold slot, and the free buffer into the store slot.
    445  * Zero the length of the new store buffer.
    446  */
    447 #define ROTATE_BUFFERS(d) \
    448 	(d)->bd_hbuf = (d)->bd_sbuf; \
    449 	(d)->bd_hlen = (d)->bd_slen; \
    450 	(d)->bd_sbuf = (d)->bd_fbuf; \
    451 	(d)->bd_slen = 0; \
    452 	(d)->bd_fbuf = 0;
    453 /*
    454  *  bpfread - read next chunk of packets from buffers
    455  */
    456 static int
    457 bpf_read(struct file *fp, off_t *offp, struct uio *uio,
    458 	 struct ucred *cred, int flags)
    459 {
    460 	struct bpf_d *d = fp->f_data;
    461 	int timed_out;
    462 	int error;
    463 	int s;
    464 
    465 	/*
    466 	 * Restrict application to use a buffer the same size as
    467 	 * as kernel buffers.
    468 	 */
    469 	if (uio->uio_resid != d->bd_bufsize)
    470 		return (EINVAL);
    471 
    472 	s = splnet();
    473 	if (d->bd_state == BPF_WAITING)
    474 		callout_stop(&d->bd_callout);
    475 	timed_out = (d->bd_state == BPF_TIMED_OUT);
    476 	d->bd_state = BPF_IDLE;
    477 	/*
    478 	 * If the hold buffer is empty, then do a timed sleep, which
    479 	 * ends when the timeout expires or when enough packets
    480 	 * have arrived to fill the store buffer.
    481 	 */
    482 	while (d->bd_hbuf == 0) {
    483 		if (fp->f_flag & FNONBLOCK) {
    484 			if (d->bd_slen == 0) {
    485 				splx(s);
    486 				return (EWOULDBLOCK);
    487 			}
    488 			ROTATE_BUFFERS(d);
    489 			break;
    490 		}
    491 
    492 		if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
    493 			/*
    494 			 * A packet(s) either arrived since the previous
    495 			 * read or arrived while we were asleep.
    496 			 * Rotate the buffers and return what's here.
    497 			 */
    498 			ROTATE_BUFFERS(d);
    499 			break;
    500 		}
    501 		error = tsleep(d, PRINET|PCATCH, "bpf",
    502 				d->bd_rtout);
    503 		if (error == EINTR || error == ERESTART) {
    504 			splx(s);
    505 			return (error);
    506 		}
    507 		if (error == EWOULDBLOCK) {
    508 			/*
    509 			 * On a timeout, return what's in the buffer,
    510 			 * which may be nothing.  If there is something
    511 			 * in the store buffer, we can rotate the buffers.
    512 			 */
    513 			if (d->bd_hbuf)
    514 				/*
    515 				 * We filled up the buffer in between
    516 				 * getting the timeout and arriving
    517 				 * here, so we don't need to rotate.
    518 				 */
    519 				break;
    520 
    521 			if (d->bd_slen == 0) {
    522 				splx(s);
    523 				return (0);
    524 			}
    525 			ROTATE_BUFFERS(d);
    526 			break;
    527 		}
    528 		if (error != 0)
    529 			goto done;
    530 	}
    531 	/*
    532 	 * At this point, we know we have something in the hold slot.
    533 	 */
    534 	splx(s);
    535 
    536 	/*
    537 	 * Move data from hold buffer into user space.
    538 	 * We know the entire buffer is transferred since
    539 	 * we checked above that the read buffer is bpf_bufsize bytes.
    540 	 */
    541 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
    542 
    543 	s = splnet();
    544 	d->bd_fbuf = d->bd_hbuf;
    545 	d->bd_hbuf = 0;
    546 	d->bd_hlen = 0;
    547 done:
    548 	splx(s);
    549 	return (error);
    550 }
    551 
    552 
    553 /*
    554  * If there are processes sleeping on this descriptor, wake them up.
    555  */
    556 static inline void
    557 bpf_wakeup(struct bpf_d *d)
    558 {
    559 	wakeup(d);
    560 	if (d->bd_async)
    561 		fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
    562 
    563 	selnotify(&d->bd_sel, 0);
    564 	/* XXX */
    565 	d->bd_sel.sel_pid = 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 	  struct ucred *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 (bp->bif_driverp != (struct bpf_if **)&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 	/*
   1163 	 * Note that the ipl does not have to be raised at this point.
   1164 	 * The only problem that could arise here is that if two different
   1165 	 * interfaces shared any data.  This is not the case.
   1166 	 */
   1167 	bp = arg;
   1168 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1169 		++d->bd_rcount;
   1170 		++bpf_gstats.bs_recv;
   1171 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
   1172 		if (slen != 0)
   1173 			catchpacket(d, pkt, pktlen, slen, memcpy);
   1174 	}
   1175 }
   1176 
   1177 /*
   1178  * Copy data from an mbuf chain into a buffer.  This code is derived
   1179  * from m_copydata in sys/uipc_mbuf.c.
   1180  */
   1181 static void *
   1182 bpf_mcpy(void *dst_arg, const void *src_arg, size_t len)
   1183 {
   1184 	const struct mbuf *m;
   1185 	u_int count;
   1186 	u_char *dst;
   1187 
   1188 	m = src_arg;
   1189 	dst = dst_arg;
   1190 	while (len > 0) {
   1191 		if (m == 0)
   1192 			panic("bpf_mcpy");
   1193 		count = min(m->m_len, len);
   1194 		memcpy(dst, mtod(m, void *), count);
   1195 		m = m->m_next;
   1196 		dst += count;
   1197 		len -= count;
   1198 	}
   1199 	return (dst_arg);
   1200 }
   1201 
   1202 /*
   1203  * Dispatch a packet to all the listeners on interface bp.
   1204  *
   1205  * marg    pointer to the packet, either a data buffer or an mbuf chain
   1206  * buflen  buffer length, if marg is a data buffer
   1207  * cpfn    a function that can copy marg into the listener's buffer
   1208  * pktlen  length of the packet
   1209  * rcvif   either NULL or the interface the packet came in on.
   1210  */
   1211 static inline void
   1212 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
   1213 	    void *marg, u_int pktlen, u_int buflen, struct ifnet *rcvif)
   1214 {
   1215 	u_int slen;
   1216 	struct bpf_d *d;
   1217 
   1218 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1219 		if (!d->bd_seesent && (rcvif == NULL))
   1220 			continue;
   1221 		++d->bd_rcount;
   1222 		++bpf_gstats.bs_recv;
   1223 		slen = bpf_filter(d->bd_filter, marg, pktlen, buflen);
   1224 		if (slen != 0)
   1225 			catchpacket(d, marg, pktlen, slen, cpfn);
   1226 	}
   1227 }
   1228 
   1229 /*
   1230  * Incoming linkage from device drivers, when the head of the packet is in
   1231  * a buffer, and the tail is in an mbuf chain.
   1232  */
   1233 void
   1234 bpf_mtap2(void *arg, void *data, u_int dlen, struct mbuf *m)
   1235 {
   1236 	struct bpf_if *bp = arg;
   1237 	u_int pktlen;
   1238 	struct mbuf mb;
   1239 
   1240 	pktlen = m_length(m) + dlen;
   1241 
   1242 	/*
   1243 	 * Craft on-stack mbuf suitable for passing to bpf_filter.
   1244 	 * Note that we cut corners here; we only setup what's
   1245 	 * absolutely needed--this mbuf should never go anywhere else.
   1246 	 */
   1247 	(void)memset(&mb, 0, sizeof(mb));
   1248 	mb.m_next = m;
   1249 	mb.m_data = data;
   1250 	mb.m_len = dlen;
   1251 
   1252 	bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, m->m_pkthdr.rcvif);
   1253 }
   1254 
   1255 /*
   1256  * Incoming linkage from device drivers, when packet is in an mbuf chain.
   1257  */
   1258 void
   1259 bpf_mtap(void *arg, struct mbuf *m)
   1260 {
   1261 	void *(*cpfn)(void *, const void *, size_t);
   1262 	struct bpf_if *bp = arg;
   1263 	u_int pktlen, buflen;
   1264 	void *marg;
   1265 
   1266 	pktlen = m_length(m);
   1267 
   1268 	if (pktlen == m->m_len) {
   1269 		cpfn = memcpy;
   1270 		marg = mtod(m, void *);
   1271 		buflen = pktlen;
   1272 	} else {
   1273 		cpfn = bpf_mcpy;
   1274 		marg = m;
   1275 		buflen = 0;
   1276 	}
   1277 
   1278 	bpf_deliver(bp, cpfn, marg, pktlen, buflen, m->m_pkthdr.rcvif);
   1279 }
   1280 
   1281 /*
   1282  * We need to prepend the address family as
   1283  * a four byte field.  Cons up a dummy header
   1284  * to pacify bpf.  This is safe because bpf
   1285  * will only read from the mbuf (i.e., it won't
   1286  * try to free it or keep a pointer a to it).
   1287  */
   1288 void
   1289 bpf_mtap_af(void *arg, u_int32_t af, struct mbuf *m)
   1290 {
   1291 	struct mbuf m0;
   1292 
   1293 	m0.m_flags = 0;
   1294 	m0.m_next = m;
   1295 	m0.m_len = 4;
   1296 	m0.m_data = (char *)&af;
   1297 
   1298 	bpf_mtap(arg, &m0);
   1299 }
   1300 
   1301 void
   1302 bpf_mtap_et(void *arg, u_int16_t et, struct mbuf *m)
   1303 {
   1304 	struct mbuf m0;
   1305 
   1306 	m0.m_flags = 0;
   1307 	m0.m_next = m;
   1308 	m0.m_len = 14;
   1309 	m0.m_data = m0.m_dat;
   1310 
   1311 	((u_int32_t *)m0.m_data)[0] = 0;
   1312 	((u_int32_t *)m0.m_data)[1] = 0;
   1313 	((u_int32_t *)m0.m_data)[2] = 0;
   1314 	((u_int16_t *)m0.m_data)[6] = et;
   1315 
   1316 	bpf_mtap(arg, &m0);
   1317 }
   1318 
   1319 #if NSL > 0 || NSTRIP > 0
   1320 /*
   1321  * Put the SLIP pseudo-"link header" in place.
   1322  * Note this M_PREPEND() should never fail,
   1323  * swince we know we always have enough space
   1324  * in the input buffer.
   1325  */
   1326 void
   1327 bpf_mtap_sl_in(void *arg, u_char *chdr, struct mbuf **m)
   1328 {
   1329 	int s;
   1330 	u_char *hp;
   1331 
   1332 	M_PREPEND(*m, SLIP_HDRLEN, M_DONTWAIT);
   1333 	if (*m == NULL)
   1334 		return;
   1335 
   1336 	hp = mtod(*m, u_char *);
   1337 	hp[SLX_DIR] = SLIPDIR_IN;
   1338 	(void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
   1339 
   1340 	s = splnet();
   1341 	bpf_mtap(arg, *m);
   1342 	splx(s);
   1343 
   1344 	m_adj(*m, SLIP_HDRLEN);
   1345 }
   1346 
   1347 /*
   1348  * Put the SLIP pseudo-"link header" in
   1349  * place.  The compressed header is now
   1350  * at the beginning of the mbuf.
   1351  */
   1352 void
   1353 bpf_mtap_sl_out(void *arg, u_char *chdr, struct mbuf *m)
   1354 {
   1355 	struct mbuf m0;
   1356 	u_char *hp;
   1357 	int s;
   1358 
   1359 	m0.m_flags = 0;
   1360 	m0.m_next = m;
   1361 	m0.m_data = m0.m_dat;
   1362 	m0.m_len = SLIP_HDRLEN;
   1363 
   1364 	hp = mtod(&m0, u_char *);
   1365 
   1366 	hp[SLX_DIR] = SLIPDIR_OUT;
   1367 	(void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
   1368 
   1369 	s = splnet();
   1370 	bpf_mtap(arg, &m0);
   1371 	splx(s);
   1372 	m_freem(m);
   1373 }
   1374 #endif
   1375 
   1376 /*
   1377  * Move the packet data from interface memory (pkt) into the
   1378  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
   1379  * otherwise 0.  "copy" is the routine called to do the actual data
   1380  * transfer.  memcpy is passed in to copy contiguous chunks, while
   1381  * bpf_mcpy is passed in to copy mbuf chains.  In the latter case,
   1382  * pkt is really an mbuf.
   1383  */
   1384 static void
   1385 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
   1386 	    void *(*cpfn)(void *, const void *, size_t))
   1387 {
   1388 	struct bpf_hdr *hp;
   1389 	int totlen, curlen;
   1390 	int hdrlen = d->bd_bif->bif_hdrlen;
   1391 
   1392 	++d->bd_ccount;
   1393 	++bpf_gstats.bs_capt;
   1394 	/*
   1395 	 * Figure out how many bytes to move.  If the packet is
   1396 	 * greater or equal to the snapshot length, transfer that
   1397 	 * much.  Otherwise, transfer the whole packet (unless
   1398 	 * we hit the buffer size limit).
   1399 	 */
   1400 	totlen = hdrlen + min(snaplen, pktlen);
   1401 	if (totlen > d->bd_bufsize)
   1402 		totlen = d->bd_bufsize;
   1403 
   1404 	/*
   1405 	 * Round up the end of the previous packet to the next longword.
   1406 	 */
   1407 	curlen = BPF_WORDALIGN(d->bd_slen);
   1408 	if (curlen + totlen > d->bd_bufsize) {
   1409 		/*
   1410 		 * This packet will overflow the storage buffer.
   1411 		 * Rotate the buffers if we can, then wakeup any
   1412 		 * pending reads.
   1413 		 */
   1414 		if (d->bd_fbuf == 0) {
   1415 			/*
   1416 			 * We haven't completed the previous read yet,
   1417 			 * so drop the packet.
   1418 			 */
   1419 			++d->bd_dcount;
   1420 			++bpf_gstats.bs_drop;
   1421 			return;
   1422 		}
   1423 		ROTATE_BUFFERS(d);
   1424 		bpf_wakeup(d);
   1425 		curlen = 0;
   1426 	}
   1427 
   1428 	/*
   1429 	 * Append the bpf header.
   1430 	 */
   1431 	hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
   1432 	microtime(&hp->bh_tstamp);
   1433 	hp->bh_datalen = pktlen;
   1434 	hp->bh_hdrlen = hdrlen;
   1435 	/*
   1436 	 * Copy the packet data into the store buffer and update its length.
   1437 	 */
   1438 	(*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
   1439 	d->bd_slen = curlen + totlen;
   1440 
   1441 	/*
   1442 	 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
   1443 	 * will cause filt_bpfread() to be called with it adjusted.
   1444 	 */
   1445 	if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
   1446 		/*
   1447 		 * Immediate mode is set, or the read timeout has
   1448 		 * already expired during a select call.  A packet
   1449 		 * arrived, so the reader should be woken up.
   1450 		 */
   1451 		bpf_wakeup(d);
   1452 }
   1453 
   1454 /*
   1455  * Initialize all nonzero fields of a descriptor.
   1456  */
   1457 static int
   1458 bpf_allocbufs(struct bpf_d *d)
   1459 {
   1460 
   1461 	d->bd_fbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
   1462 	if (!d->bd_fbuf)
   1463 		return (ENOBUFS);
   1464 	d->bd_sbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
   1465 	if (!d->bd_sbuf) {
   1466 		free(d->bd_fbuf, M_DEVBUF);
   1467 		return (ENOBUFS);
   1468 	}
   1469 	d->bd_slen = 0;
   1470 	d->bd_hlen = 0;
   1471 	return (0);
   1472 }
   1473 
   1474 /*
   1475  * Free buffers currently in use by a descriptor.
   1476  * Called on close.
   1477  */
   1478 static void
   1479 bpf_freed(struct bpf_d *d)
   1480 {
   1481 	/*
   1482 	 * We don't need to lock out interrupts since this descriptor has
   1483 	 * been detached from its interface and it yet hasn't been marked
   1484 	 * free.
   1485 	 */
   1486 	if (d->bd_sbuf != 0) {
   1487 		free(d->bd_sbuf, M_DEVBUF);
   1488 		if (d->bd_hbuf != 0)
   1489 			free(d->bd_hbuf, M_DEVBUF);
   1490 		if (d->bd_fbuf != 0)
   1491 			free(d->bd_fbuf, M_DEVBUF);
   1492 	}
   1493 	if (d->bd_filter)
   1494 		free(d->bd_filter, M_DEVBUF);
   1495 }
   1496 
   1497 /*
   1498  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
   1499  * fixed size of the link header (variable length headers not yet supported).
   1500  */
   1501 void
   1502 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
   1503 {
   1504 
   1505 	bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
   1506 }
   1507 
   1508 /*
   1509  * Attach additional dlt for a interface to bpf.  dlt is the link layer type;
   1510  * hdrlen is the fixed size of the link header for the specified dlt
   1511  * (variable length headers not yet supported).
   1512  */
   1513 void
   1514 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, void *driverp)
   1515 {
   1516 	struct bpf_if *bp;
   1517 	bp = malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
   1518 	if (bp == 0)
   1519 		panic("bpfattach");
   1520 
   1521 	bp->bif_dlist = 0;
   1522 	bp->bif_driverp = driverp;
   1523 	bp->bif_ifp = ifp;
   1524 	bp->bif_dlt = dlt;
   1525 
   1526 	bp->bif_next = bpf_iflist;
   1527 	bpf_iflist = bp;
   1528 
   1529 	*bp->bif_driverp = 0;
   1530 
   1531 	/*
   1532 	 * Compute the length of the bpf header.  This is not necessarily
   1533 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1534 	 * that the network layer header begins on a longword boundary (for
   1535 	 * performance reasons and to alleviate alignment restrictions).
   1536 	 */
   1537 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1538 
   1539 #if 0
   1540 	printf("bpf: %s attached\n", ifp->if_xname);
   1541 #endif
   1542 }
   1543 
   1544 /*
   1545  * Remove an interface from bpf.
   1546  */
   1547 void
   1548 bpfdetach(struct ifnet *ifp)
   1549 {
   1550 	struct bpf_if *bp, **pbp;
   1551 	struct bpf_d *d;
   1552 	int s;
   1553 
   1554 	/* Nuke the vnodes for any open instances */
   1555 	for (d = LIST_FIRST(&bpf_list); d != NULL; d = LIST_NEXT(d, bd_list)) {
   1556 		if (d->bd_bif != NULL && d->bd_bif->bif_ifp == ifp) {
   1557 			/*
   1558 			 * Detach the descriptor from an interface now.
   1559 			 * It will be free'ed later by close routine.
   1560 			 */
   1561 			s = splnet();
   1562 			d->bd_promisc = 0;	/* we can't touch device. */
   1563 			bpf_detachd(d);
   1564 			splx(s);
   1565 		}
   1566 	}
   1567 
   1568   again:
   1569 	for (bp = bpf_iflist, pbp = &bpf_iflist;
   1570 	     bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
   1571 		if (bp->bif_ifp == ifp) {
   1572 			*pbp = bp->bif_next;
   1573 			free(bp, M_DEVBUF);
   1574 			goto again;
   1575 		}
   1576 	}
   1577 }
   1578 
   1579 /*
   1580  * Change the data link type of a interface.
   1581  */
   1582 void
   1583 bpf_change_type(struct ifnet *ifp, u_int dlt, u_int hdrlen)
   1584 {
   1585 	struct bpf_if *bp;
   1586 
   1587 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1588 		if (bp->bif_driverp == (struct bpf_if **)&ifp->if_bpf)
   1589 			break;
   1590 	}
   1591 	if (bp == NULL)
   1592 		panic("bpf_change_type");
   1593 
   1594 	bp->bif_dlt = dlt;
   1595 
   1596 	/*
   1597 	 * Compute the length of the bpf header.  This is not necessarily
   1598 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1599 	 * that the network layer header begins on a longword boundary (for
   1600 	 * performance reasons and to alleviate alignment restrictions).
   1601 	 */
   1602 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1603 }
   1604 
   1605 /*
   1606  * Get a list of available data link type of the interface.
   1607  */
   1608 static int
   1609 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
   1610 {
   1611 	int n, error;
   1612 	struct ifnet *ifp;
   1613 	struct bpf_if *bp;
   1614 
   1615 	ifp = d->bd_bif->bif_ifp;
   1616 	n = 0;
   1617 	error = 0;
   1618 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1619 		if (bp->bif_ifp != ifp)
   1620 			continue;
   1621 		if (bfl->bfl_list != NULL) {
   1622 			if (n >= bfl->bfl_len)
   1623 				return ENOMEM;
   1624 			error = copyout(&bp->bif_dlt,
   1625 			    bfl->bfl_list + n, sizeof(u_int));
   1626 		}
   1627 		n++;
   1628 	}
   1629 	bfl->bfl_len = n;
   1630 	return error;
   1631 }
   1632 
   1633 /*
   1634  * Set the data link type of a BPF instance.
   1635  */
   1636 static int
   1637 bpf_setdlt(struct bpf_d *d, u_int dlt)
   1638 {
   1639 	int s, error, opromisc;
   1640 	struct ifnet *ifp;
   1641 	struct bpf_if *bp;
   1642 
   1643 	if (d->bd_bif->bif_dlt == dlt)
   1644 		return 0;
   1645 	ifp = d->bd_bif->bif_ifp;
   1646 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1647 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
   1648 			break;
   1649 	}
   1650 	if (bp == NULL)
   1651 		return EINVAL;
   1652 	s = splnet();
   1653 	opromisc = d->bd_promisc;
   1654 	bpf_detachd(d);
   1655 	bpf_attachd(d, bp);
   1656 	reset_d(d);
   1657 	if (opromisc) {
   1658 		error = ifpromisc(bp->bif_ifp, 1);
   1659 		if (error)
   1660 			printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
   1661 			    bp->bif_ifp->if_xname, error);
   1662 		else
   1663 			d->bd_promisc = 1;
   1664 	}
   1665 	splx(s);
   1666 	return 0;
   1667 }
   1668 
   1669 static int
   1670 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
   1671 {
   1672 	int newsize, error;
   1673 	struct sysctlnode node;
   1674 
   1675 	node = *rnode;
   1676 	node.sysctl_data = &newsize;
   1677 	newsize = bpf_maxbufsize;
   1678 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1679 	if (error || newp == NULL)
   1680 		return (error);
   1681 
   1682 	if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
   1683 		return (EINVAL);
   1684 
   1685 	bpf_maxbufsize = newsize;
   1686 
   1687 	return (0);
   1688 }
   1689 
   1690 static int
   1691 sysctl_net_bpf_peers(SYSCTLFN_ARGS)
   1692 {
   1693 	int    error, elem_count;
   1694 	struct bpf_d	 *dp;
   1695 	struct bpf_d_ext  dpe;
   1696 	size_t len, needed, elem_size, out_size;
   1697 	char   *sp;
   1698 
   1699 	if (namelen == 1 && name[0] == CTL_QUERY)
   1700 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   1701 
   1702 	if (namelen != 2)
   1703 		return (EINVAL);
   1704 
   1705 	if ((error = suser(l->l_proc->p_ucred, &l->l_proc->p_acflag)))
   1706 		return (error);
   1707 
   1708 	len = (oldp != NULL) ? *oldlenp : 0;
   1709 	sp = oldp;
   1710 	elem_size = name[0];
   1711 	elem_count = name[1];
   1712 	out_size = MIN(sizeof(dpe), elem_size);
   1713 	needed = 0;
   1714 
   1715 	if (elem_size < 1 || elem_count < 0)
   1716 		return (EINVAL);
   1717 
   1718 	simple_lock(&bpf_slock);
   1719 	LIST_FOREACH(dp, &bpf_list, bd_list) {
   1720 		if (len >= elem_size && elem_count > 0) {
   1721 #define BPF_EXT(field)	dpe.bde_ ## field = dp->bd_ ## field
   1722 			BPF_EXT(bufsize);
   1723 			BPF_EXT(promisc);
   1724 			BPF_EXT(promisc);
   1725 			BPF_EXT(state);
   1726 			BPF_EXT(immediate);
   1727 			BPF_EXT(hdrcmplt);
   1728 			BPF_EXT(seesent);
   1729 			BPF_EXT(pid);
   1730 			BPF_EXT(rcount);
   1731 			BPF_EXT(dcount);
   1732 			BPF_EXT(ccount);
   1733 #undef BPF_EXT
   1734 			if (dp->bd_bif)
   1735 				(void)strlcpy(dpe.bde_ifname,
   1736 				    dp->bd_bif->bif_ifp->if_xname,
   1737 				    IFNAMSIZ - 1);
   1738 			else
   1739 				dpe.bde_ifname[0] = '\0';
   1740 
   1741 			error = copyout(&dpe, sp, out_size);
   1742 			if (error)
   1743 				break;
   1744 			sp += elem_size;
   1745 			len -= elem_size;
   1746 		}
   1747 		if (elem_count > 0) {
   1748 			needed += elem_size;
   1749 			if (elem_count != INT_MAX)
   1750 				elem_count--;
   1751 		}
   1752 	}
   1753 	simple_unlock(&bpf_slock);
   1754 
   1755 	*oldlenp = needed;
   1756 
   1757 	return (error);
   1758 }
   1759 
   1760 SYSCTL_SETUP(sysctl_net_bpf_setup, "sysctl net.bpf subtree setup")
   1761 {
   1762 	const struct sysctlnode *node;
   1763 
   1764 	sysctl_createv(clog, 0, NULL, NULL,
   1765 		       CTLFLAG_PERMANENT,
   1766 		       CTLTYPE_NODE, "net", NULL,
   1767 		       NULL, 0, NULL, 0,
   1768 		       CTL_NET, CTL_EOL);
   1769 
   1770 	node = NULL;
   1771 	sysctl_createv(clog, 0, NULL, &node,
   1772 		       CTLFLAG_PERMANENT,
   1773 		       CTLTYPE_NODE, "bpf",
   1774 		       SYSCTL_DESCR("BPF options"),
   1775 		       NULL, 0, NULL, 0,
   1776 		       CTL_NET, CTL_CREATE, CTL_EOL);
   1777 	if (node != NULL) {
   1778 		sysctl_createv(clog, 0, NULL, NULL,
   1779 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1780 			CTLTYPE_INT, "maxbufsize",
   1781 			SYSCTL_DESCR("Maximum size for data capture buffer"),
   1782 			sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
   1783 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1784 		sysctl_createv(clog, 0, NULL, NULL,
   1785 			CTLFLAG_PERMANENT,
   1786 			CTLTYPE_STRUCT, "stats",
   1787 			SYSCTL_DESCR("BPF stats"),
   1788 			NULL, 0, &bpf_gstats, sizeof(bpf_gstats),
   1789 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1790 		sysctl_createv(clog, 0, NULL, NULL,
   1791 			CTLFLAG_PERMANENT,
   1792 			CTLTYPE_STRUCT, "peers",
   1793 			SYSCTL_DESCR("BPF peers"),
   1794 			sysctl_net_bpf_peers, 0, NULL, 0,
   1795 			CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
   1796 	}
   1797 
   1798 }
   1799