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