Expand PMF_FN_* macros.
[netbsd-mini2440.git] / sys / net / bpf.c
blobf8be8403e326e8ab70db3d4007485d214085416b
1 /* $NetBSD: bpf.c,v 1.149 2009/12/09 21:32:59 dsl Exp $ */
3 /*
4 * Copyright (c) 1990, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
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.
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.
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.
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 ";
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.149 2009/12/09 21:32:59 dsl Exp $");
44 #if defined(_KERNEL_OPT)
45 #include "opt_bpf.h"
46 #include "sl.h"
47 #include "strip.h"
48 #endif
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/mbuf.h>
53 #include <sys/buf.h>
54 #include <sys/time.h>
55 #include <sys/proc.h>
56 #include <sys/ioctl.h>
57 #include <sys/conf.h>
58 #include <sys/vnode.h>
59 #include <sys/queue.h>
60 #include <sys/stat.h>
62 #include <sys/file.h>
63 #include <sys/filedesc.h>
64 #include <sys/tty.h>
65 #include <sys/uio.h>
67 #include <sys/protosw.h>
68 #include <sys/socket.h>
69 #include <sys/errno.h>
70 #include <sys/kernel.h>
71 #include <sys/poll.h>
72 #include <sys/sysctl.h>
73 #include <sys/kauth.h>
75 #include <net/if.h>
76 #include <net/slip.h>
78 #include <net/bpf.h>
79 #include <net/bpfdesc.h>
81 #include <net/if_arc.h>
82 #include <net/if_ether.h>
84 #include <netinet/in.h>
85 #include <netinet/if_inarp.h>
88 #include <compat/sys/sockio.h>
90 #ifndef BPF_BUFSIZE
92 * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
93 * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
95 # define BPF_BUFSIZE 32768
96 #endif
98 #define PRINET 26 /* interruptible */
101 * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
102 * XXX the default values should be computed dynamically based
103 * on available memory size and available mbuf clusters.
105 int bpf_bufsize = BPF_BUFSIZE;
106 int bpf_maxbufsize = BPF_DFLTBUFSIZE; /* XXX set dynamically, see above */
110 * Global BPF statistics returned by net.bpf.stats sysctl.
112 struct bpf_stat bpf_gstats;
115 * Use a mutex to avoid a race condition between gathering the stats/peers
116 * and opening/closing the device.
118 static kmutex_t bpf_mtx;
121 * bpf_iflist is the list of interfaces; each corresponds to an ifnet
122 * bpf_dtab holds the descriptors, indexed by minor device #
124 struct bpf_if *bpf_iflist;
125 LIST_HEAD(, bpf_d) bpf_list;
127 static int bpf_allocbufs(struct bpf_d *);
128 static void bpf_deliver(struct bpf_if *,
129 void *(*cpfn)(void *, const void *, size_t),
130 void *, u_int, u_int, struct ifnet *);
131 static void bpf_freed(struct bpf_d *);
132 static void bpf_ifname(struct ifnet *, struct ifreq *);
133 static void *bpf_mcpy(void *, const void *, size_t);
134 static int bpf_movein(struct uio *, int, int,
135 struct mbuf **, struct sockaddr *);
136 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
137 static void bpf_detachd(struct bpf_d *);
138 static int bpf_setif(struct bpf_d *, struct ifreq *);
139 static void bpf_timed_out(void *);
140 static inline void
141 bpf_wakeup(struct bpf_d *);
142 static void catchpacket(struct bpf_d *, u_char *, u_int, u_int,
143 void *(*)(void *, const void *, size_t), struct timespec *);
144 static void reset_d(struct bpf_d *);
145 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
146 static int bpf_setdlt(struct bpf_d *, u_int);
148 static int bpf_read(struct file *, off_t *, struct uio *, kauth_cred_t,
149 int);
150 static int bpf_write(struct file *, off_t *, struct uio *, kauth_cred_t,
151 int);
152 static int bpf_ioctl(struct file *, u_long, void *);
153 static int bpf_poll(struct file *, int);
154 static int bpf_stat(struct file *, struct stat *);
155 static int bpf_close(struct file *);
156 static int bpf_kqfilter(struct file *, struct knote *);
157 static void bpf_softintr(void *);
159 static const struct fileops bpf_fileops = {
160 .fo_read = bpf_read,
161 .fo_write = bpf_write,
162 .fo_ioctl = bpf_ioctl,
163 .fo_fcntl = fnullop_fcntl,
164 .fo_poll = bpf_poll,
165 .fo_stat = bpf_stat,
166 .fo_close = bpf_close,
167 .fo_kqfilter = bpf_kqfilter,
168 .fo_restart = fnullop_restart,
171 dev_type_open(bpfopen);
173 const struct cdevsw bpf_cdevsw = {
174 bpfopen, noclose, noread, nowrite, noioctl,
175 nostop, notty, nopoll, nommap, nokqfilter, D_OTHER
178 static int
179 bpf_movein(struct uio *uio, int linktype, int mtu, struct mbuf **mp,
180 struct sockaddr *sockp)
182 struct mbuf *m;
183 int error;
184 int len;
185 int hlen;
186 int align;
189 * Build a sockaddr based on the data link layer type.
190 * We do this at this level because the ethernet header
191 * is copied directly into the data field of the sockaddr.
192 * In the case of SLIP, there is no header and the packet
193 * is forwarded as is.
194 * Also, we are careful to leave room at the front of the mbuf
195 * for the link level header.
197 switch (linktype) {
199 case DLT_SLIP:
200 sockp->sa_family = AF_INET;
201 hlen = 0;
202 align = 0;
203 break;
205 case DLT_PPP:
206 sockp->sa_family = AF_UNSPEC;
207 hlen = 0;
208 align = 0;
209 break;
211 case DLT_EN10MB:
212 sockp->sa_family = AF_UNSPEC;
213 /* XXX Would MAXLINKHDR be better? */
214 /* 6(dst)+6(src)+2(type) */
215 hlen = sizeof(struct ether_header);
216 align = 2;
217 break;
219 case DLT_ARCNET:
220 sockp->sa_family = AF_UNSPEC;
221 hlen = ARC_HDRLEN;
222 align = 5;
223 break;
225 case DLT_FDDI:
226 sockp->sa_family = AF_LINK;
227 /* XXX 4(FORMAC)+6(dst)+6(src) */
228 hlen = 16;
229 align = 0;
230 break;
232 case DLT_ECONET:
233 sockp->sa_family = AF_UNSPEC;
234 hlen = 6;
235 align = 2;
236 break;
238 case DLT_NULL:
239 sockp->sa_family = AF_UNSPEC;
240 hlen = 0;
241 align = 0;
242 break;
244 default:
245 return (EIO);
248 len = uio->uio_resid;
250 * If there aren't enough bytes for a link level header or the
251 * packet length exceeds the interface mtu, return an error.
253 if (len < hlen || len - hlen > mtu)
254 return (EMSGSIZE);
257 * XXX Avoid complicated buffer chaining ---
258 * bail if it won't fit in a single mbuf.
259 * (Take into account possible alignment bytes)
261 if ((unsigned)len > MCLBYTES - align)
262 return (EIO);
264 m = m_gethdr(M_WAIT, MT_DATA);
265 m->m_pkthdr.rcvif = 0;
266 m->m_pkthdr.len = len - hlen;
267 if (len > MHLEN - align) {
268 m_clget(m, M_WAIT);
269 if ((m->m_flags & M_EXT) == 0) {
270 error = ENOBUFS;
271 goto bad;
275 /* Insure the data is properly aligned */
276 if (align > 0) {
277 m->m_data += align;
278 m->m_len -= align;
281 error = uiomove(mtod(m, void *), len, uio);
282 if (error)
283 goto bad;
284 if (hlen != 0) {
285 memcpy(sockp->sa_data, mtod(m, void *), hlen);
286 m->m_data += hlen; /* XXX */
287 len -= hlen;
289 m->m_len = len;
290 *mp = m;
291 return (0);
293 bad:
294 m_freem(m);
295 return (error);
299 * Attach file to the bpf interface, i.e. make d listen on bp.
300 * Must be called at splnet.
302 static void
303 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
306 * Point d at bp, and add d to the interface's list of listeners.
307 * Finally, point the driver's bpf cookie at the interface so
308 * it will divert packets to bpf.
310 d->bd_bif = bp;
311 d->bd_next = bp->bif_dlist;
312 bp->bif_dlist = d;
314 *bp->bif_driverp = bp;
318 * Detach a file from its interface.
320 static void
321 bpf_detachd(struct bpf_d *d)
323 struct bpf_d **p;
324 struct bpf_if *bp;
326 bp = d->bd_bif;
328 * Check if this descriptor had requested promiscuous mode.
329 * If so, turn it off.
331 if (d->bd_promisc) {
332 int error;
334 d->bd_promisc = 0;
336 * Take device out of promiscuous mode. Since we were
337 * able to enter promiscuous mode, we should be able
338 * to turn it off. But we can get an error if
339 * the interface was configured down, so only panic
340 * if we don't get an unexpected error.
342 error = ifpromisc(bp->bif_ifp, 0);
343 if (error && error != EINVAL)
344 panic("%s: ifpromisc failed: %d", __func__, error);
346 /* Remove d from the interface's descriptor list. */
347 p = &bp->bif_dlist;
348 while (*p != d) {
349 p = &(*p)->bd_next;
350 if (*p == 0)
351 panic("%s: descriptor not in list", __func__);
353 *p = (*p)->bd_next;
354 if (bp->bif_dlist == 0)
356 * Let the driver know that there are no more listeners.
358 *d->bd_bif->bif_driverp = 0;
359 d->bd_bif = 0;
364 * Mark a descriptor free by making it point to itself.
365 * This is probably cheaper than marking with a constant since
366 * the address should be in a register anyway.
370 * bpfilterattach() is called at boot time.
372 /* ARGSUSED */
373 void
374 bpfilterattach(int n)
376 mutex_init(&bpf_mtx, MUTEX_DEFAULT, IPL_NONE);
378 mutex_enter(&bpf_mtx);
379 LIST_INIT(&bpf_list);
380 mutex_exit(&bpf_mtx);
382 bpf_gstats.bs_recv = 0;
383 bpf_gstats.bs_drop = 0;
384 bpf_gstats.bs_capt = 0;
388 * Open ethernet device. Clones.
390 /* ARGSUSED */
392 bpfopen(dev_t dev, int flag, int mode, struct lwp *l)
394 struct bpf_d *d;
395 struct file *fp;
396 int error, fd;
398 /* falloc() will use the descriptor for us. */
399 if ((error = fd_allocfile(&fp, &fd)) != 0)
400 return error;
402 d = malloc(sizeof(*d), M_DEVBUF, M_WAITOK|M_ZERO);
403 d->bd_bufsize = bpf_bufsize;
404 d->bd_seesent = 1;
405 d->bd_pid = l->l_proc->p_pid;
406 getnanotime(&d->bd_btime);
407 d->bd_atime = d->bd_mtime = d->bd_btime;
408 callout_init(&d->bd_callout, 0);
409 selinit(&d->bd_sel);
410 d->bd_sih = softint_establish(SOFTINT_CLOCK, bpf_softintr, d);
412 mutex_enter(&bpf_mtx);
413 LIST_INSERT_HEAD(&bpf_list, d, bd_list);
414 mutex_exit(&bpf_mtx);
416 return fd_clone(fp, fd, flag, &bpf_fileops, d);
420 * Close the descriptor by detaching it from its interface,
421 * deallocating its buffers, and marking it free.
423 /* ARGSUSED */
424 static int
425 bpf_close(struct file *fp)
427 struct bpf_d *d = fp->f_data;
428 int s;
430 KERNEL_LOCK(1, NULL);
433 * Refresh the PID associated with this bpf file.
435 d->bd_pid = curproc->p_pid;
437 s = splnet();
438 if (d->bd_state == BPF_WAITING)
439 callout_stop(&d->bd_callout);
440 d->bd_state = BPF_IDLE;
441 if (d->bd_bif)
442 bpf_detachd(d);
443 splx(s);
444 bpf_freed(d);
445 mutex_enter(&bpf_mtx);
446 LIST_REMOVE(d, bd_list);
447 mutex_exit(&bpf_mtx);
448 callout_destroy(&d->bd_callout);
449 seldestroy(&d->bd_sel);
450 softint_disestablish(d->bd_sih);
451 free(d, M_DEVBUF);
452 fp->f_data = NULL;
454 KERNEL_UNLOCK_ONE(NULL);
456 return (0);
460 * Rotate the packet buffers in descriptor d. Move the store buffer
461 * into the hold slot, and the free buffer into the store slot.
462 * Zero the length of the new store buffer.
464 #define ROTATE_BUFFERS(d) \
465 (d)->bd_hbuf = (d)->bd_sbuf; \
466 (d)->bd_hlen = (d)->bd_slen; \
467 (d)->bd_sbuf = (d)->bd_fbuf; \
468 (d)->bd_slen = 0; \
469 (d)->bd_fbuf = 0;
471 * bpfread - read next chunk of packets from buffers
473 static int
474 bpf_read(struct file *fp, off_t *offp, struct uio *uio,
475 kauth_cred_t cred, int flags)
477 struct bpf_d *d = fp->f_data;
478 int timed_out;
479 int error;
480 int s;
482 getnanotime(&d->bd_atime);
484 * Restrict application to use a buffer the same size as
485 * the kernel buffers.
487 if (uio->uio_resid != d->bd_bufsize)
488 return (EINVAL);
490 KERNEL_LOCK(1, NULL);
491 s = splnet();
492 if (d->bd_state == BPF_WAITING)
493 callout_stop(&d->bd_callout);
494 timed_out = (d->bd_state == BPF_TIMED_OUT);
495 d->bd_state = BPF_IDLE;
497 * If the hold buffer is empty, then do a timed sleep, which
498 * ends when the timeout expires or when enough packets
499 * have arrived to fill the store buffer.
501 while (d->bd_hbuf == 0) {
502 if (fp->f_flag & FNONBLOCK) {
503 if (d->bd_slen == 0) {
504 splx(s);
505 KERNEL_UNLOCK_ONE(NULL);
506 return (EWOULDBLOCK);
508 ROTATE_BUFFERS(d);
509 break;
512 if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
514 * A packet(s) either arrived since the previous
515 * read or arrived while we were asleep.
516 * Rotate the buffers and return what's here.
518 ROTATE_BUFFERS(d);
519 break;
521 error = tsleep(d, PRINET|PCATCH, "bpf",
522 d->bd_rtout);
523 if (error == EINTR || error == ERESTART) {
524 splx(s);
525 KERNEL_UNLOCK_ONE(NULL);
526 return (error);
528 if (error == EWOULDBLOCK) {
530 * On a timeout, return what's in the buffer,
531 * which may be nothing. If there is something
532 * in the store buffer, we can rotate the buffers.
534 if (d->bd_hbuf)
536 * We filled up the buffer in between
537 * getting the timeout and arriving
538 * here, so we don't need to rotate.
540 break;
542 if (d->bd_slen == 0) {
543 splx(s);
544 KERNEL_UNLOCK_ONE(NULL);
545 return (0);
547 ROTATE_BUFFERS(d);
548 break;
550 if (error != 0)
551 goto done;
554 * At this point, we know we have something in the hold slot.
556 splx(s);
559 * Move data from hold buffer into user space.
560 * We know the entire buffer is transferred since
561 * we checked above that the read buffer is bpf_bufsize bytes.
563 error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
565 s = splnet();
566 d->bd_fbuf = d->bd_hbuf;
567 d->bd_hbuf = 0;
568 d->bd_hlen = 0;
569 done:
570 splx(s);
571 KERNEL_UNLOCK_ONE(NULL);
572 return (error);
577 * If there are processes sleeping on this descriptor, wake them up.
579 static inline void
580 bpf_wakeup(struct bpf_d *d)
582 wakeup(d);
583 if (d->bd_async)
584 softint_schedule(d->bd_sih);
585 selnotify(&d->bd_sel, 0, 0);
588 static void
589 bpf_softintr(void *cookie)
591 struct bpf_d *d;
593 d = cookie;
594 if (d->bd_async)
595 fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
598 static void
599 bpf_timed_out(void *arg)
601 struct bpf_d *d = arg;
602 int s;
604 s = splnet();
605 if (d->bd_state == BPF_WAITING) {
606 d->bd_state = BPF_TIMED_OUT;
607 if (d->bd_slen != 0)
608 bpf_wakeup(d);
610 splx(s);
614 static int
615 bpf_write(struct file *fp, off_t *offp, struct uio *uio,
616 kauth_cred_t cred, int flags)
618 struct bpf_d *d = fp->f_data;
619 struct ifnet *ifp;
620 struct mbuf *m;
621 int error, s;
622 static struct sockaddr_storage dst;
624 m = NULL; /* XXX gcc */
626 KERNEL_LOCK(1, NULL);
628 if (d->bd_bif == 0) {
629 KERNEL_UNLOCK_ONE(NULL);
630 return (ENXIO);
632 getnanotime(&d->bd_mtime);
634 ifp = d->bd_bif->bif_ifp;
636 if (uio->uio_resid == 0) {
637 KERNEL_UNLOCK_ONE(NULL);
638 return (0);
641 error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp->if_mtu, &m,
642 (struct sockaddr *) &dst);
643 if (error) {
644 KERNEL_UNLOCK_ONE(NULL);
645 return (error);
648 if (m->m_pkthdr.len > ifp->if_mtu) {
649 KERNEL_UNLOCK_ONE(NULL);
650 m_freem(m);
651 return (EMSGSIZE);
654 if (d->bd_hdrcmplt)
655 dst.ss_family = pseudo_AF_HDRCMPLT;
657 s = splsoftnet();
658 error = (*ifp->if_output)(ifp, m, (struct sockaddr *) &dst, NULL);
659 splx(s);
660 KERNEL_UNLOCK_ONE(NULL);
662 * The driver frees the mbuf.
664 return (error);
668 * Reset a descriptor by flushing its packet buffer and clearing the
669 * receive and drop counts. Should be called at splnet.
671 static void
672 reset_d(struct bpf_d *d)
674 if (d->bd_hbuf) {
675 /* Free the hold buffer. */
676 d->bd_fbuf = d->bd_hbuf;
677 d->bd_hbuf = 0;
679 d->bd_slen = 0;
680 d->bd_hlen = 0;
681 d->bd_rcount = 0;
682 d->bd_dcount = 0;
683 d->bd_ccount = 0;
687 * FIONREAD Check for read packet available.
688 * BIOCGBLEN Get buffer len [for read()].
689 * BIOCSETF Set ethernet read filter.
690 * BIOCFLUSH Flush read packet buffer.
691 * BIOCPROMISC Put interface into promiscuous mode.
692 * BIOCGDLT Get link layer type.
693 * BIOCGETIF Get interface name.
694 * BIOCSETIF Set interface.
695 * BIOCSRTIMEOUT Set read timeout.
696 * BIOCGRTIMEOUT Get read timeout.
697 * BIOCGSTATS Get packet stats.
698 * BIOCIMMEDIATE Set immediate mode.
699 * BIOCVERSION Get filter language version.
700 * BIOCGHDRCMPLT Get "header already complete" flag.
701 * BIOCSHDRCMPLT Set "header already complete" flag.
703 /* ARGSUSED */
704 static int
705 bpf_ioctl(struct file *fp, u_long cmd, void *addr)
707 struct bpf_d *d = fp->f_data;
708 int s, error = 0;
711 * Refresh the PID associated with this bpf file.
713 KERNEL_LOCK(1, NULL);
714 d->bd_pid = curproc->p_pid;
716 s = splnet();
717 if (d->bd_state == BPF_WAITING)
718 callout_stop(&d->bd_callout);
719 d->bd_state = BPF_IDLE;
720 splx(s);
722 switch (cmd) {
724 default:
725 error = EINVAL;
726 break;
729 * Check for read packet available.
731 case FIONREAD:
733 int n;
735 s = splnet();
736 n = d->bd_slen;
737 if (d->bd_hbuf)
738 n += d->bd_hlen;
739 splx(s);
741 *(int *)addr = n;
742 break;
746 * Get buffer len [for read()].
748 case BIOCGBLEN:
749 *(u_int *)addr = d->bd_bufsize;
750 break;
753 * Set buffer length.
755 case BIOCSBLEN:
756 if (d->bd_bif != 0)
757 error = EINVAL;
758 else {
759 u_int size = *(u_int *)addr;
761 if (size > bpf_maxbufsize)
762 *(u_int *)addr = size = bpf_maxbufsize;
763 else if (size < BPF_MINBUFSIZE)
764 *(u_int *)addr = size = BPF_MINBUFSIZE;
765 d->bd_bufsize = size;
767 break;
770 * Set link layer read filter.
772 case BIOCSETF:
773 error = bpf_setf(d, addr);
774 break;
777 * Flush read packet buffer.
779 case BIOCFLUSH:
780 s = splnet();
781 reset_d(d);
782 splx(s);
783 break;
786 * Put interface into promiscuous mode.
788 case BIOCPROMISC:
789 if (d->bd_bif == 0) {
791 * No interface attached yet.
793 error = EINVAL;
794 break;
796 s = splnet();
797 if (d->bd_promisc == 0) {
798 error = ifpromisc(d->bd_bif->bif_ifp, 1);
799 if (error == 0)
800 d->bd_promisc = 1;
802 splx(s);
803 break;
806 * Get device parameters.
808 case BIOCGDLT:
809 if (d->bd_bif == 0)
810 error = EINVAL;
811 else
812 *(u_int *)addr = d->bd_bif->bif_dlt;
813 break;
816 * Get a list of supported device parameters.
818 case BIOCGDLTLIST:
819 if (d->bd_bif == 0)
820 error = EINVAL;
821 else
822 error = bpf_getdltlist(d, addr);
823 break;
826 * Set device parameters.
828 case BIOCSDLT:
829 if (d->bd_bif == 0)
830 error = EINVAL;
831 else
832 error = bpf_setdlt(d, *(u_int *)addr);
833 break;
836 * Set interface name.
838 #ifdef OBIOCGETIF
839 case OBIOCGETIF:
840 #endif
841 case BIOCGETIF:
842 if (d->bd_bif == 0)
843 error = EINVAL;
844 else
845 bpf_ifname(d->bd_bif->bif_ifp, addr);
846 break;
849 * Set interface.
851 #ifdef OBIOCSETIF
852 case OBIOCSETIF:
853 #endif
854 case BIOCSETIF:
855 error = bpf_setif(d, addr);
856 break;
859 * Set read timeout.
861 case BIOCSRTIMEOUT:
863 struct timeval *tv = addr;
865 /* Compute number of ticks. */
866 d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
867 if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
868 d->bd_rtout = 1;
869 break;
872 #ifdef BIOCGORTIMEOUT
874 * Get read timeout.
876 case BIOCGORTIMEOUT:
878 struct timeval50 *tv = addr;
880 tv->tv_sec = d->bd_rtout / hz;
881 tv->tv_usec = (d->bd_rtout % hz) * tick;
882 break;
884 #endif
886 #ifdef BIOCSORTIMEOUT
888 * Set read timeout.
890 case BIOCSORTIMEOUT:
892 struct timeval50 *tv = addr;
894 /* Compute number of ticks. */
895 d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
896 if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
897 d->bd_rtout = 1;
898 break;
900 #endif
903 * Get read timeout.
905 case BIOCGRTIMEOUT:
907 struct timeval *tv = addr;
909 tv->tv_sec = d->bd_rtout / hz;
910 tv->tv_usec = (d->bd_rtout % hz) * tick;
911 break;
914 * Get packet stats.
916 case BIOCGSTATS:
918 struct bpf_stat *bs = addr;
920 bs->bs_recv = d->bd_rcount;
921 bs->bs_drop = d->bd_dcount;
922 bs->bs_capt = d->bd_ccount;
923 break;
926 case BIOCGSTATSOLD:
928 struct bpf_stat_old *bs = addr;
930 bs->bs_recv = d->bd_rcount;
931 bs->bs_drop = d->bd_dcount;
932 break;
936 * Set immediate mode.
938 case BIOCIMMEDIATE:
939 d->bd_immediate = *(u_int *)addr;
940 break;
942 case BIOCVERSION:
944 struct bpf_version *bv = addr;
946 bv->bv_major = BPF_MAJOR_VERSION;
947 bv->bv_minor = BPF_MINOR_VERSION;
948 break;
951 case BIOCGHDRCMPLT: /* get "header already complete" flag */
952 *(u_int *)addr = d->bd_hdrcmplt;
953 break;
955 case BIOCSHDRCMPLT: /* set "header already complete" flag */
956 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
957 break;
960 * Get "see sent packets" flag
962 case BIOCGSEESENT:
963 *(u_int *)addr = d->bd_seesent;
964 break;
967 * Set "see sent" packets flag
969 case BIOCSSEESENT:
970 d->bd_seesent = *(u_int *)addr;
971 break;
973 case FIONBIO: /* Non-blocking I/O */
975 * No need to do anything special as we use IO_NDELAY in
976 * bpfread() as an indication of whether or not to block
977 * the read.
979 break;
981 case FIOASYNC: /* Send signal on receive packets */
982 d->bd_async = *(int *)addr;
983 break;
985 case TIOCSPGRP: /* Process or group to send signals to */
986 case FIOSETOWN:
987 error = fsetown(&d->bd_pgid, cmd, addr);
988 break;
990 case TIOCGPGRP:
991 case FIOGETOWN:
992 error = fgetown(d->bd_pgid, cmd, addr);
993 break;
995 KERNEL_UNLOCK_ONE(NULL);
996 return (error);
1000 * Set d's packet filter program to fp. If this file already has a filter,
1001 * free it and replace it. Returns EINVAL for bogus requests.
1004 bpf_setf(struct bpf_d *d, struct bpf_program *fp)
1006 struct bpf_insn *fcode, *old;
1007 u_int flen, size;
1008 int s;
1010 old = d->bd_filter;
1011 if (fp->bf_insns == 0) {
1012 if (fp->bf_len != 0)
1013 return (EINVAL);
1014 s = splnet();
1015 d->bd_filter = 0;
1016 reset_d(d);
1017 splx(s);
1018 if (old != 0)
1019 free(old, M_DEVBUF);
1020 return (0);
1022 flen = fp->bf_len;
1023 if (flen > BPF_MAXINSNS)
1024 return (EINVAL);
1026 size = flen * sizeof(*fp->bf_insns);
1027 fcode = malloc(size, M_DEVBUF, M_WAITOK);
1028 if (copyin(fp->bf_insns, fcode, size) == 0 &&
1029 bpf_validate(fcode, (int)flen)) {
1030 s = splnet();
1031 d->bd_filter = fcode;
1032 reset_d(d);
1033 splx(s);
1034 if (old != 0)
1035 free(old, M_DEVBUF);
1037 return (0);
1039 free(fcode, M_DEVBUF);
1040 return (EINVAL);
1044 * Detach a file from its current interface (if attached at all) and attach
1045 * to the interface indicated by the name stored in ifr.
1046 * Return an errno or 0.
1048 static int
1049 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1051 struct bpf_if *bp;
1052 char *cp;
1053 int unit_seen, i, s, error;
1056 * Make sure the provided name has a unit number, and default
1057 * it to '0' if not specified.
1058 * XXX This is ugly ... do this differently?
1060 unit_seen = 0;
1061 cp = ifr->ifr_name;
1062 cp[sizeof(ifr->ifr_name) - 1] = '\0'; /* sanity */
1063 while (*cp++)
1064 if (*cp >= '0' && *cp <= '9')
1065 unit_seen = 1;
1066 if (!unit_seen) {
1067 /* Make sure to leave room for the '\0'. */
1068 for (i = 0; i < (IFNAMSIZ - 1); ++i) {
1069 if ((ifr->ifr_name[i] >= 'a' &&
1070 ifr->ifr_name[i] <= 'z') ||
1071 (ifr->ifr_name[i] >= 'A' &&
1072 ifr->ifr_name[i] <= 'Z'))
1073 continue;
1074 ifr->ifr_name[i] = '0';
1079 * Look through attached interfaces for the named one.
1081 for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
1082 struct ifnet *ifp = bp->bif_ifp;
1084 if (ifp == 0 ||
1085 strcmp(ifp->if_xname, ifr->ifr_name) != 0)
1086 continue;
1087 /* skip additional entry */
1088 if ((void **)bp->bif_driverp != &ifp->if_bpf)
1089 continue;
1091 * We found the requested interface.
1092 * Allocate the packet buffers if we need to.
1093 * If we're already attached to requested interface,
1094 * just flush the buffer.
1096 if (d->bd_sbuf == 0) {
1097 error = bpf_allocbufs(d);
1098 if (error != 0)
1099 return (error);
1101 s = splnet();
1102 if (bp != d->bd_bif) {
1103 if (d->bd_bif)
1105 * Detach if attached to something else.
1107 bpf_detachd(d);
1109 bpf_attachd(d, bp);
1111 reset_d(d);
1112 splx(s);
1113 return (0);
1115 /* Not found. */
1116 return (ENXIO);
1120 * Copy the interface name to the ifreq.
1122 static void
1123 bpf_ifname(struct ifnet *ifp, struct ifreq *ifr)
1125 memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
1128 static int
1129 bpf_stat(struct file *fp, struct stat *st)
1131 struct bpf_d *d = fp->f_data;
1133 (void)memset(st, 0, sizeof(*st));
1134 KERNEL_LOCK(1, NULL);
1135 st->st_dev = makedev(cdevsw_lookup_major(&bpf_cdevsw), d->bd_pid);
1136 st->st_atimespec = d->bd_atime;
1137 st->st_mtimespec = d->bd_mtime;
1138 st->st_ctimespec = st->st_birthtimespec = d->bd_btime;
1139 st->st_uid = kauth_cred_geteuid(fp->f_cred);
1140 st->st_gid = kauth_cred_getegid(fp->f_cred);
1141 KERNEL_UNLOCK_ONE(NULL);
1142 return 0;
1146 * Support for poll() system call
1148 * Return true iff the specific operation will not block indefinitely - with
1149 * the assumption that it is safe to positively acknowledge a request for the
1150 * ability to write to the BPF device.
1151 * Otherwise, return false but make a note that a selnotify() must be done.
1153 static int
1154 bpf_poll(struct file *fp, int events)
1156 struct bpf_d *d = fp->f_data;
1157 int s = splnet();
1158 int revents;
1161 * Refresh the PID associated with this bpf file.
1163 KERNEL_LOCK(1, NULL);
1164 d->bd_pid = curproc->p_pid;
1166 revents = events & (POLLOUT | POLLWRNORM);
1167 if (events & (POLLIN | POLLRDNORM)) {
1169 * An imitation of the FIONREAD ioctl code.
1171 if (d->bd_hlen != 0 ||
1172 ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1173 d->bd_slen != 0)) {
1174 revents |= events & (POLLIN | POLLRDNORM);
1175 } else {
1176 selrecord(curlwp, &d->bd_sel);
1177 /* Start the read timeout if necessary */
1178 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1179 callout_reset(&d->bd_callout, d->bd_rtout,
1180 bpf_timed_out, d);
1181 d->bd_state = BPF_WAITING;
1186 KERNEL_UNLOCK_ONE(NULL);
1187 splx(s);
1188 return (revents);
1191 static void
1192 filt_bpfrdetach(struct knote *kn)
1194 struct bpf_d *d = kn->kn_hook;
1195 int s;
1197 KERNEL_LOCK(1, NULL);
1198 s = splnet();
1199 SLIST_REMOVE(&d->bd_sel.sel_klist, kn, knote, kn_selnext);
1200 splx(s);
1201 KERNEL_UNLOCK_ONE(NULL);
1204 static int
1205 filt_bpfread(struct knote *kn, long hint)
1207 struct bpf_d *d = kn->kn_hook;
1208 int rv;
1210 KERNEL_LOCK(1, NULL);
1211 kn->kn_data = d->bd_hlen;
1212 if (d->bd_immediate)
1213 kn->kn_data += d->bd_slen;
1214 rv = (kn->kn_data > 0);
1215 KERNEL_UNLOCK_ONE(NULL);
1216 return rv;
1219 static const struct filterops bpfread_filtops =
1220 { 1, NULL, filt_bpfrdetach, filt_bpfread };
1222 static int
1223 bpf_kqfilter(struct file *fp, struct knote *kn)
1225 struct bpf_d *d = fp->f_data;
1226 struct klist *klist;
1227 int s;
1229 KERNEL_LOCK(1, NULL);
1231 switch (kn->kn_filter) {
1232 case EVFILT_READ:
1233 klist = &d->bd_sel.sel_klist;
1234 kn->kn_fop = &bpfread_filtops;
1235 break;
1237 default:
1238 KERNEL_UNLOCK_ONE(NULL);
1239 return (EINVAL);
1242 kn->kn_hook = d;
1244 s = splnet();
1245 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1246 splx(s);
1247 KERNEL_UNLOCK_ONE(NULL);
1249 return (0);
1253 * Incoming linkage from device drivers. Process the packet pkt, of length
1254 * pktlen, which is stored in a contiguous buffer. The packet is parsed
1255 * by each process' filter, and if accepted, stashed into the corresponding
1256 * buffer.
1258 void
1259 bpf_tap(void *arg, u_char *pkt, u_int pktlen)
1261 struct bpf_if *bp;
1262 struct bpf_d *d;
1263 u_int slen;
1264 struct timespec ts;
1265 int gottime=0;
1268 * Note that the ipl does not have to be raised at this point.
1269 * The only problem that could arise here is that if two different
1270 * interfaces shared any data. This is not the case.
1272 bp = arg;
1273 for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1274 ++d->bd_rcount;
1275 ++bpf_gstats.bs_recv;
1276 slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
1277 if (slen != 0) {
1278 if (!gottime) {
1279 nanotime(&ts);
1280 gottime = 1;
1282 catchpacket(d, pkt, pktlen, slen, memcpy, &ts);
1288 * Copy data from an mbuf chain into a buffer. This code is derived
1289 * from m_copydata in sys/uipc_mbuf.c.
1291 static void *
1292 bpf_mcpy(void *dst_arg, const void *src_arg, size_t len)
1294 const struct mbuf *m;
1295 u_int count;
1296 u_char *dst;
1298 m = src_arg;
1299 dst = dst_arg;
1300 while (len > 0) {
1301 if (m == NULL)
1302 panic("bpf_mcpy");
1303 count = min(m->m_len, len);
1304 memcpy(dst, mtod(m, const void *), count);
1305 m = m->m_next;
1306 dst += count;
1307 len -= count;
1309 return dst_arg;
1313 * Dispatch a packet to all the listeners on interface bp.
1315 * marg pointer to the packet, either a data buffer or an mbuf chain
1316 * buflen buffer length, if marg is a data buffer
1317 * cpfn a function that can copy marg into the listener's buffer
1318 * pktlen length of the packet
1319 * rcvif either NULL or the interface the packet came in on.
1321 static inline void
1322 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
1323 void *marg, u_int pktlen, u_int buflen, struct ifnet *rcvif)
1325 u_int slen;
1326 struct bpf_d *d;
1327 struct timespec ts;
1328 int gottime = 0;
1330 for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1331 if (!d->bd_seesent && (rcvif == NULL))
1332 continue;
1333 ++d->bd_rcount;
1334 ++bpf_gstats.bs_recv;
1335 slen = bpf_filter(d->bd_filter, marg, pktlen, buflen);
1336 if (slen != 0) {
1337 if(!gottime) {
1338 nanotime(&ts);
1339 gottime = 1;
1341 catchpacket(d, marg, pktlen, slen, cpfn, &ts);
1347 * Incoming linkage from device drivers, when the head of the packet is in
1348 * a buffer, and the tail is in an mbuf chain.
1350 void
1351 bpf_mtap2(void *arg, void *data, u_int dlen, struct mbuf *m)
1353 struct bpf_if *bp = arg;
1354 u_int pktlen;
1355 struct mbuf mb;
1357 pktlen = m_length(m) + dlen;
1360 * Craft on-stack mbuf suitable for passing to bpf_filter.
1361 * Note that we cut corners here; we only setup what's
1362 * absolutely needed--this mbuf should never go anywhere else.
1364 (void)memset(&mb, 0, sizeof(mb));
1365 mb.m_next = m;
1366 mb.m_data = data;
1367 mb.m_len = dlen;
1369 bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, m->m_pkthdr.rcvif);
1373 * Incoming linkage from device drivers, when packet is in an mbuf chain.
1375 void
1376 bpf_mtap(void *arg, struct mbuf *m)
1378 void *(*cpfn)(void *, const void *, size_t);
1379 struct bpf_if *bp = arg;
1380 u_int pktlen, buflen;
1381 void *marg;
1383 pktlen = m_length(m);
1385 if (pktlen == m->m_len) {
1386 cpfn = (void *)memcpy;
1387 marg = mtod(m, void *);
1388 buflen = pktlen;
1389 } else {
1390 /*###1299 [cc] warning: assignment from incompatible pointer type%%%*/
1391 cpfn = bpf_mcpy;
1392 marg = m;
1393 buflen = 0;
1396 bpf_deliver(bp, cpfn, marg, pktlen, buflen, m->m_pkthdr.rcvif);
1400 * We need to prepend the address family as
1401 * a four byte field. Cons up a dummy header
1402 * to pacify bpf. This is safe because bpf
1403 * will only read from the mbuf (i.e., it won't
1404 * try to free it or keep a pointer a to it).
1406 void
1407 bpf_mtap_af(void *arg, uint32_t af, struct mbuf *m)
1409 struct mbuf m0;
1411 m0.m_flags = 0;
1412 m0.m_next = m;
1413 m0.m_len = 4;
1414 m0.m_data = (char *)&af;
1416 bpf_mtap(arg, &m0);
1419 void
1420 bpf_mtap_et(void *arg, uint16_t et, struct mbuf *m)
1422 struct mbuf m0;
1424 m0.m_flags = 0;
1425 m0.m_next = m;
1426 m0.m_len = 14;
1427 m0.m_data = m0.m_dat;
1429 ((uint32_t *)m0.m_data)[0] = 0;
1430 ((uint32_t *)m0.m_data)[1] = 0;
1431 ((uint32_t *)m0.m_data)[2] = 0;
1432 ((uint16_t *)m0.m_data)[6] = et;
1434 bpf_mtap(arg, &m0);
1437 #if NSL > 0 || NSTRIP > 0
1439 * Put the SLIP pseudo-"link header" in place.
1440 * Note this M_PREPEND() should never fail,
1441 * swince we know we always have enough space
1442 * in the input buffer.
1444 void
1445 bpf_mtap_sl_in(void *arg, u_char *chdr, struct mbuf **m)
1447 int s;
1448 u_char *hp;
1450 M_PREPEND(*m, SLIP_HDRLEN, M_DONTWAIT);
1451 if (*m == NULL)
1452 return;
1454 hp = mtod(*m, u_char *);
1455 hp[SLX_DIR] = SLIPDIR_IN;
1456 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1458 s = splnet();
1459 bpf_mtap(arg, *m);
1460 splx(s);
1462 m_adj(*m, SLIP_HDRLEN);
1466 * Put the SLIP pseudo-"link header" in
1467 * place. The compressed header is now
1468 * at the beginning of the mbuf.
1470 void
1471 bpf_mtap_sl_out(void *arg, u_char *chdr, struct mbuf *m)
1473 struct mbuf m0;
1474 u_char *hp;
1475 int s;
1477 m0.m_flags = 0;
1478 m0.m_next = m;
1479 m0.m_data = m0.m_dat;
1480 m0.m_len = SLIP_HDRLEN;
1482 hp = mtod(&m0, u_char *);
1484 hp[SLX_DIR] = SLIPDIR_OUT;
1485 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1487 s = splnet();
1488 bpf_mtap(arg, &m0);
1489 splx(s);
1490 m_freem(m);
1492 #endif
1495 * Move the packet data from interface memory (pkt) into the
1496 * store buffer. Return 1 if it's time to wakeup a listener (buffer full),
1497 * otherwise 0. "copy" is the routine called to do the actual data
1498 * transfer. memcpy is passed in to copy contiguous chunks, while
1499 * bpf_mcpy is passed in to copy mbuf chains. In the latter case,
1500 * pkt is really an mbuf.
1502 static void
1503 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
1504 void *(*cpfn)(void *, const void *, size_t), struct timespec *ts)
1506 struct bpf_hdr *hp;
1507 int totlen, curlen;
1508 int hdrlen = d->bd_bif->bif_hdrlen;
1509 int do_wakeup = 0;
1511 ++d->bd_ccount;
1512 ++bpf_gstats.bs_capt;
1514 * Figure out how many bytes to move. If the packet is
1515 * greater or equal to the snapshot length, transfer that
1516 * much. Otherwise, transfer the whole packet (unless
1517 * we hit the buffer size limit).
1519 totlen = hdrlen + min(snaplen, pktlen);
1520 if (totlen > d->bd_bufsize)
1521 totlen = d->bd_bufsize;
1524 * Round up the end of the previous packet to the next longword.
1526 curlen = BPF_WORDALIGN(d->bd_slen);
1527 if (curlen + totlen > d->bd_bufsize) {
1529 * This packet will overflow the storage buffer.
1530 * Rotate the buffers if we can, then wakeup any
1531 * pending reads.
1533 if (d->bd_fbuf == 0) {
1535 * We haven't completed the previous read yet,
1536 * so drop the packet.
1538 ++d->bd_dcount;
1539 ++bpf_gstats.bs_drop;
1540 return;
1542 ROTATE_BUFFERS(d);
1543 do_wakeup = 1;
1544 curlen = 0;
1545 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT) {
1547 * Immediate mode is set, or the read timeout has
1548 * already expired during a select call. A packet
1549 * arrived, so the reader should be woken up.
1551 do_wakeup = 1;
1555 * Append the bpf header.
1557 hp = (struct bpf_hdr *)((char *)d->bd_sbuf + curlen);
1558 hp->bh_tstamp.tv_sec = ts->tv_sec;
1559 hp->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
1560 hp->bh_datalen = pktlen;
1561 hp->bh_hdrlen = hdrlen;
1563 * Copy the packet data into the store buffer and update its length.
1565 (*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
1566 d->bd_slen = curlen + totlen;
1569 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
1570 * will cause filt_bpfread() to be called with it adjusted.
1572 if (do_wakeup)
1573 bpf_wakeup(d);
1577 * Initialize all nonzero fields of a descriptor.
1579 static int
1580 bpf_allocbufs(struct bpf_d *d)
1583 d->bd_fbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
1584 if (!d->bd_fbuf)
1585 return (ENOBUFS);
1586 d->bd_sbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
1587 if (!d->bd_sbuf) {
1588 free(d->bd_fbuf, M_DEVBUF);
1589 return (ENOBUFS);
1591 d->bd_slen = 0;
1592 d->bd_hlen = 0;
1593 return (0);
1597 * Free buffers currently in use by a descriptor.
1598 * Called on close.
1600 static void
1601 bpf_freed(struct bpf_d *d)
1604 * We don't need to lock out interrupts since this descriptor has
1605 * been detached from its interface and it yet hasn't been marked
1606 * free.
1608 if (d->bd_sbuf != 0) {
1609 free(d->bd_sbuf, M_DEVBUF);
1610 if (d->bd_hbuf != 0)
1611 free(d->bd_hbuf, M_DEVBUF);
1612 if (d->bd_fbuf != 0)
1613 free(d->bd_fbuf, M_DEVBUF);
1615 if (d->bd_filter)
1616 free(d->bd_filter, M_DEVBUF);
1620 * Attach an interface to bpf. dlt is the link layer type; hdrlen is the
1621 * fixed size of the link header (variable length headers not yet supported).
1623 void
1624 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1627 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
1631 * Attach additional dlt for a interface to bpf. dlt is the link layer type;
1632 * hdrlen is the fixed size of the link header for the specified dlt
1633 * (variable length headers not yet supported).
1635 void
1636 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, void *driverp)
1638 struct bpf_if *bp;
1639 bp = malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
1640 if (bp == 0)
1641 panic("bpfattach");
1643 bp->bif_dlist = 0;
1644 bp->bif_driverp = driverp;
1645 bp->bif_ifp = ifp;
1646 bp->bif_dlt = dlt;
1648 bp->bif_next = bpf_iflist;
1649 bpf_iflist = bp;
1651 *bp->bif_driverp = 0;
1654 * Compute the length of the bpf header. This is not necessarily
1655 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1656 * that the network layer header begins on a longword boundary (for
1657 * performance reasons and to alleviate alignment restrictions).
1659 bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1661 #if 0
1662 printf("bpf: %s attached\n", ifp->if_xname);
1663 #endif
1667 * Remove an interface from bpf.
1669 void
1670 bpfdetach(struct ifnet *ifp)
1672 struct bpf_if *bp, **pbp;
1673 struct bpf_d *d;
1674 int s;
1676 /* Nuke the vnodes for any open instances */
1677 LIST_FOREACH(d, &bpf_list, bd_list) {
1678 if (d->bd_bif != NULL && d->bd_bif->bif_ifp == ifp) {
1680 * Detach the descriptor from an interface now.
1681 * It will be free'ed later by close routine.
1683 s = splnet();
1684 d->bd_promisc = 0; /* we can't touch device. */
1685 bpf_detachd(d);
1686 splx(s);
1690 again:
1691 for (bp = bpf_iflist, pbp = &bpf_iflist;
1692 bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
1693 if (bp->bif_ifp == ifp) {
1694 *pbp = bp->bif_next;
1695 free(bp, M_DEVBUF);
1696 goto again;
1702 * Change the data link type of a interface.
1704 void
1705 bpf_change_type(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1707 struct bpf_if *bp;
1709 for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1710 if ((void **)bp->bif_driverp == &ifp->if_bpf)
1711 break;
1713 if (bp == NULL)
1714 panic("bpf_change_type");
1716 bp->bif_dlt = dlt;
1719 * Compute the length of the bpf header. This is not necessarily
1720 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1721 * that the network layer header begins on a longword boundary (for
1722 * performance reasons and to alleviate alignment restrictions).
1724 bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1728 * Get a list of available data link type of the interface.
1730 static int
1731 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
1733 int n, error;
1734 struct ifnet *ifp;
1735 struct bpf_if *bp;
1737 ifp = d->bd_bif->bif_ifp;
1738 n = 0;
1739 error = 0;
1740 for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1741 if (bp->bif_ifp != ifp)
1742 continue;
1743 if (bfl->bfl_list != NULL) {
1744 if (n >= bfl->bfl_len)
1745 return ENOMEM;
1746 error = copyout(&bp->bif_dlt,
1747 bfl->bfl_list + n, sizeof(u_int));
1749 n++;
1751 bfl->bfl_len = n;
1752 return error;
1756 * Set the data link type of a BPF instance.
1758 static int
1759 bpf_setdlt(struct bpf_d *d, u_int dlt)
1761 int s, error, opromisc;
1762 struct ifnet *ifp;
1763 struct bpf_if *bp;
1765 if (d->bd_bif->bif_dlt == dlt)
1766 return 0;
1767 ifp = d->bd_bif->bif_ifp;
1768 for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1769 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
1770 break;
1772 if (bp == NULL)
1773 return EINVAL;
1774 s = splnet();
1775 opromisc = d->bd_promisc;
1776 bpf_detachd(d);
1777 bpf_attachd(d, bp);
1778 reset_d(d);
1779 if (opromisc) {
1780 error = ifpromisc(bp->bif_ifp, 1);
1781 if (error)
1782 printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
1783 bp->bif_ifp->if_xname, error);
1784 else
1785 d->bd_promisc = 1;
1787 splx(s);
1788 return 0;
1791 static int
1792 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
1794 int newsize, error;
1795 struct sysctlnode node;
1797 node = *rnode;
1798 node.sysctl_data = &newsize;
1799 newsize = bpf_maxbufsize;
1800 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1801 if (error || newp == NULL)
1802 return (error);
1804 if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
1805 return (EINVAL);
1807 bpf_maxbufsize = newsize;
1809 return (0);
1812 static int
1813 sysctl_net_bpf_peers(SYSCTLFN_ARGS)
1815 int error, elem_count;
1816 struct bpf_d *dp;
1817 struct bpf_d_ext dpe;
1818 size_t len, needed, elem_size, out_size;
1819 char *sp;
1821 if (namelen == 1 && name[0] == CTL_QUERY)
1822 return (sysctl_query(SYSCTLFN_CALL(rnode)));
1824 if (namelen != 2)
1825 return (EINVAL);
1827 /* BPF peers is privileged information. */
1828 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
1829 KAUTH_REQ_NETWORK_INTERFACE_GETPRIV, NULL, NULL, NULL);
1830 if (error)
1831 return (EPERM);
1833 len = (oldp != NULL) ? *oldlenp : 0;
1834 sp = oldp;
1835 elem_size = name[0];
1836 elem_count = name[1];
1837 out_size = MIN(sizeof(dpe), elem_size);
1838 needed = 0;
1840 if (elem_size < 1 || elem_count < 0)
1841 return (EINVAL);
1843 mutex_enter(&bpf_mtx);
1844 LIST_FOREACH(dp, &bpf_list, bd_list) {
1845 if (len >= elem_size && elem_count > 0) {
1846 #define BPF_EXT(field) dpe.bde_ ## field = dp->bd_ ## field
1847 BPF_EXT(bufsize);
1848 BPF_EXT(promisc);
1849 BPF_EXT(promisc);
1850 BPF_EXT(state);
1851 BPF_EXT(immediate);
1852 BPF_EXT(hdrcmplt);
1853 BPF_EXT(seesent);
1854 BPF_EXT(pid);
1855 BPF_EXT(rcount);
1856 BPF_EXT(dcount);
1857 BPF_EXT(ccount);
1858 #undef BPF_EXT
1859 if (dp->bd_bif)
1860 (void)strlcpy(dpe.bde_ifname,
1861 dp->bd_bif->bif_ifp->if_xname,
1862 IFNAMSIZ - 1);
1863 else
1864 dpe.bde_ifname[0] = '\0';
1866 error = copyout(&dpe, sp, out_size);
1867 if (error)
1868 break;
1869 sp += elem_size;
1870 len -= elem_size;
1872 needed += elem_size;
1873 if (elem_count > 0 && elem_count != INT_MAX)
1874 elem_count--;
1876 mutex_exit(&bpf_mtx);
1878 *oldlenp = needed;
1880 return (error);
1883 SYSCTL_SETUP(sysctl_net_bpf_setup, "sysctl net.bpf subtree setup")
1885 const struct sysctlnode *node;
1887 sysctl_createv(clog, 0, NULL, NULL,
1888 CTLFLAG_PERMANENT,
1889 CTLTYPE_NODE, "net", NULL,
1890 NULL, 0, NULL, 0,
1891 CTL_NET, CTL_EOL);
1893 node = NULL;
1894 sysctl_createv(clog, 0, NULL, &node,
1895 CTLFLAG_PERMANENT,
1896 CTLTYPE_NODE, "bpf",
1897 SYSCTL_DESCR("BPF options"),
1898 NULL, 0, NULL, 0,
1899 CTL_NET, CTL_CREATE, CTL_EOL);
1900 if (node != NULL) {
1901 sysctl_createv(clog, 0, NULL, NULL,
1902 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1903 CTLTYPE_INT, "maxbufsize",
1904 SYSCTL_DESCR("Maximum size for data capture buffer"),
1905 sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
1906 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
1907 sysctl_createv(clog, 0, NULL, NULL,
1908 CTLFLAG_PERMANENT,
1909 CTLTYPE_STRUCT, "stats",
1910 SYSCTL_DESCR("BPF stats"),
1911 NULL, 0, &bpf_gstats, sizeof(bpf_gstats),
1912 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
1913 sysctl_createv(clog, 0, NULL, NULL,
1914 CTLFLAG_PERMANENT,
1915 CTLTYPE_STRUCT, "peers",
1916 SYSCTL_DESCR("BPF peers"),
1917 sysctl_net_bpf_peers, 0, NULL, 0,
1918 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);