]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/net/bpf.c
MFC r279920:
[FreeBSD/stable/9.git] / sys / net / bpf.c
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)bpf.c       8.4 (Berkeley) 1/9/95
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_bpf.h"
41 #include "opt_compat.h"
42 #include "opt_netgraph.h"
43
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/lock.h>
47 #include <sys/rwlock.h>
48 #include <sys/systm.h>
49 #include <sys/conf.h>
50 #include <sys/fcntl.h>
51 #include <sys/jail.h>
52 #include <sys/malloc.h>
53 #include <sys/mbuf.h>
54 #include <sys/time.h>
55 #include <sys/priv.h>
56 #include <sys/proc.h>
57 #include <sys/signalvar.h>
58 #include <sys/filio.h>
59 #include <sys/sockio.h>
60 #include <sys/ttycom.h>
61 #include <sys/uio.h>
62
63 #include <sys/event.h>
64 #include <sys/file.h>
65 #include <sys/poll.h>
66 #include <sys/proc.h>
67
68 #include <sys/socket.h>
69
70 #include <net/if.h>
71 #define BPF_INTERNAL
72 #include <net/bpf.h>
73 #include <net/bpf_buffer.h>
74 #ifdef BPF_JITTER
75 #include <net/bpf_jitter.h>
76 #endif
77 #include <net/bpf_zerocopy.h>
78 #include <net/bpfdesc.h>
79 #include <net/vnet.h>
80
81 #include <netinet/in.h>
82 #include <netinet/if_ether.h>
83 #include <sys/kernel.h>
84 #include <sys/sysctl.h>
85
86 #include <net80211/ieee80211_freebsd.h>
87
88 #include <security/mac/mac_framework.h>
89
90 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
91
92 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
93
94 #define PRINET  26                      /* interruptible */
95
96 #define SIZEOF_BPF_HDR(type)    \
97     (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
98
99 #ifdef COMPAT_FREEBSD32
100 #include <sys/mount.h>
101 #include <compat/freebsd32/freebsd32.h>
102 #define BPF_ALIGNMENT32 sizeof(int32_t)
103 #define BPF_WORDALIGN32(x) (((x)+(BPF_ALIGNMENT32-1))&~(BPF_ALIGNMENT32-1))
104
105 #ifndef BURN_BRIDGES
106 /*
107  * 32-bit version of structure prepended to each packet.  We use this header
108  * instead of the standard one for 32-bit streams.  We mark the a stream as
109  * 32-bit the first time we see a 32-bit compat ioctl request.
110  */
111 struct bpf_hdr32 {
112         struct timeval32 bh_tstamp;     /* time stamp */
113         uint32_t        bh_caplen;      /* length of captured portion */
114         uint32_t        bh_datalen;     /* original length of packet */
115         uint16_t        bh_hdrlen;      /* length of bpf header (this struct
116                                            plus alignment padding) */
117 };
118 #endif
119
120 struct bpf_program32 {
121         u_int bf_len;
122         uint32_t bf_insns;
123 };
124
125 struct bpf_dltlist32 {
126         u_int   bfl_len;
127         u_int   bfl_list;
128 };
129
130 #define BIOCSETF32      _IOW('B', 103, struct bpf_program32)
131 #define BIOCSRTIMEOUT32 _IOW('B', 109, struct timeval32)
132 #define BIOCGRTIMEOUT32 _IOR('B', 110, struct timeval32)
133 #define BIOCGDLTLIST32  _IOWR('B', 121, struct bpf_dltlist32)
134 #define BIOCSETWF32     _IOW('B', 123, struct bpf_program32)
135 #define BIOCSETFNR32    _IOW('B', 130, struct bpf_program32)
136 #endif
137
138 /*
139  * bpf_iflist is a list of BPF interface structures, each corresponding to a
140  * specific DLT.  The same network interface might have several BPF interface
141  * structures registered by different layers in the stack (i.e., 802.11
142  * frames, ethernet frames, etc).
143  */
144 static LIST_HEAD(, bpf_if)      bpf_iflist;
145 static struct mtx       bpf_mtx;                /* bpf global lock */
146 static int              bpf_bpfd_cnt;
147
148 static void     bpf_attachd(struct bpf_d *, struct bpf_if *);
149 static void     bpf_detachd(struct bpf_d *);
150 static void     bpf_detachd_locked(struct bpf_d *);
151 static void     bpf_freed(struct bpf_d *);
152 static int      bpf_movein(struct uio *, int, struct ifnet *, struct mbuf **,
153                     struct sockaddr *, int *, struct bpf_insn *);
154 static int      bpf_setif(struct bpf_d *, struct ifreq *);
155 static void     bpf_timed_out(void *);
156 static __inline void
157                 bpf_wakeup(struct bpf_d *);
158 static void     catchpacket(struct bpf_d *, u_char *, u_int, u_int,
159                     void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
160                     struct bintime *);
161 static void     reset_d(struct bpf_d *);
162 static int      bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
163 static int      bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
164 static int      bpf_setdlt(struct bpf_d *, u_int);
165 static void     filt_bpfdetach(struct knote *);
166 static int      filt_bpfread(struct knote *, long);
167 static void     bpf_drvinit(void *);
168 static int      bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
169
170 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW, 0, "bpf sysctl");
171 int bpf_maxinsns = BPF_MAXINSNS;
172 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
173     &bpf_maxinsns, 0, "Maximum bpf program instructions");
174 static int bpf_zerocopy_enable = 0;
175 SYSCTL_INT(_net_bpf, OID_AUTO, zerocopy_enable, CTLFLAG_RW,
176     &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
177 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
178     bpf_stats_sysctl, "bpf statistics portal");
179
180 static VNET_DEFINE(int, bpf_optimize_writers) = 0;
181 #define V_bpf_optimize_writers VNET(bpf_optimize_writers)
182 SYSCTL_VNET_INT(_net_bpf, OID_AUTO, optimize_writers,
183     CTLFLAG_RW, &VNET_NAME(bpf_optimize_writers), 0,
184     "Do not send packets until BPF program is set");
185
186 static  d_open_t        bpfopen;
187 static  d_read_t        bpfread;
188 static  d_write_t       bpfwrite;
189 static  d_ioctl_t       bpfioctl;
190 static  d_poll_t        bpfpoll;
191 static  d_kqfilter_t    bpfkqfilter;
192
193 static struct cdevsw bpf_cdevsw = {
194         .d_version =    D_VERSION,
195         .d_open =       bpfopen,
196         .d_read =       bpfread,
197         .d_write =      bpfwrite,
198         .d_ioctl =      bpfioctl,
199         .d_poll =       bpfpoll,
200         .d_name =       "bpf",
201         .d_kqfilter =   bpfkqfilter,
202 };
203
204 static struct filterops bpfread_filtops = {
205         .f_isfd = 1,
206         .f_detach = filt_bpfdetach,
207         .f_event = filt_bpfread,
208 };
209
210 eventhandler_tag        bpf_ifdetach_cookie = NULL;
211
212 /*
213  * LOCKING MODEL USED BY BPF:
214  * Locks:
215  * 1) global lock (BPF_LOCK). Mutex, used to protect interface addition/removal,
216  * some global counters and every bpf_if reference.
217  * 2) Interface lock. Rwlock, used to protect list of BPF descriptors and their filters.
218  * 3) Descriptor lock. Mutex, used to protect BPF buffers and various structure fields
219  *   used by bpf_mtap code.
220  *
221  * Lock order:
222  *
223  * Global lock, interface lock, descriptor lock
224  *
225  * We have to acquire interface lock before descriptor main lock due to BPF_MTAP[2]
226  * working model. In many places (like bpf_detachd) we start with BPF descriptor
227  * (and we need to at least rlock it to get reliable interface pointer). This
228  * gives us potential LOR. As a result, we use global lock to protect from bpf_if
229  * change in every such place.
230  *
231  * Changing d->bd_bif is protected by 1) global lock, 2) interface lock and
232  * 3) descriptor main wlock.
233  * Reading bd_bif can be protected by any of these locks, typically global lock.
234  *
235  * Changing read/write BPF filter is protected by the same three locks,
236  * the same applies for reading.
237  *
238  * Sleeping in global lock is not allowed due to bpfdetach() using it.
239  */
240
241 /*
242  * Wrapper functions for various buffering methods.  If the set of buffer
243  * modes expands, we will probably want to introduce a switch data structure
244  * similar to protosw, et.
245  */
246 static void
247 bpf_append_bytes(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
248     u_int len)
249 {
250
251         BPFD_LOCK_ASSERT(d);
252
253         switch (d->bd_bufmode) {
254         case BPF_BUFMODE_BUFFER:
255                 return (bpf_buffer_append_bytes(d, buf, offset, src, len));
256
257         case BPF_BUFMODE_ZBUF:
258                 d->bd_zcopy++;
259                 return (bpf_zerocopy_append_bytes(d, buf, offset, src, len));
260
261         default:
262                 panic("bpf_buf_append_bytes");
263         }
264 }
265
266 static void
267 bpf_append_mbuf(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
268     u_int len)
269 {
270
271         BPFD_LOCK_ASSERT(d);
272
273         switch (d->bd_bufmode) {
274         case BPF_BUFMODE_BUFFER:
275                 return (bpf_buffer_append_mbuf(d, buf, offset, src, len));
276
277         case BPF_BUFMODE_ZBUF:
278                 d->bd_zcopy++;
279                 return (bpf_zerocopy_append_mbuf(d, buf, offset, src, len));
280
281         default:
282                 panic("bpf_buf_append_mbuf");
283         }
284 }
285
286 /*
287  * This function gets called when the free buffer is re-assigned.
288  */
289 static void
290 bpf_buf_reclaimed(struct bpf_d *d)
291 {
292
293         BPFD_LOCK_ASSERT(d);
294
295         switch (d->bd_bufmode) {
296         case BPF_BUFMODE_BUFFER:
297                 return;
298
299         case BPF_BUFMODE_ZBUF:
300                 bpf_zerocopy_buf_reclaimed(d);
301                 return;
302
303         default:
304                 panic("bpf_buf_reclaimed");
305         }
306 }
307
308 /*
309  * If the buffer mechanism has a way to decide that a held buffer can be made
310  * free, then it is exposed via the bpf_canfreebuf() interface.  (1) is
311  * returned if the buffer can be discarded, (0) is returned if it cannot.
312  */
313 static int
314 bpf_canfreebuf(struct bpf_d *d)
315 {
316
317         BPFD_LOCK_ASSERT(d);
318
319         switch (d->bd_bufmode) {
320         case BPF_BUFMODE_ZBUF:
321                 return (bpf_zerocopy_canfreebuf(d));
322         }
323         return (0);
324 }
325
326 /*
327  * Allow the buffer model to indicate that the current store buffer is
328  * immutable, regardless of the appearance of space.  Return (1) if the
329  * buffer is writable, and (0) if not.
330  */
331 static int
332 bpf_canwritebuf(struct bpf_d *d)
333 {
334         BPFD_LOCK_ASSERT(d);
335
336         switch (d->bd_bufmode) {
337         case BPF_BUFMODE_ZBUF:
338                 return (bpf_zerocopy_canwritebuf(d));
339         }
340         return (1);
341 }
342
343 /*
344  * Notify buffer model that an attempt to write to the store buffer has
345  * resulted in a dropped packet, in which case the buffer may be considered
346  * full.
347  */
348 static void
349 bpf_buffull(struct bpf_d *d)
350 {
351
352         BPFD_LOCK_ASSERT(d);
353
354         switch (d->bd_bufmode) {
355         case BPF_BUFMODE_ZBUF:
356                 bpf_zerocopy_buffull(d);
357                 break;
358         }
359 }
360
361 /*
362  * Notify the buffer model that a buffer has moved into the hold position.
363  */
364 void
365 bpf_bufheld(struct bpf_d *d)
366 {
367
368         BPFD_LOCK_ASSERT(d);
369
370         switch (d->bd_bufmode) {
371         case BPF_BUFMODE_ZBUF:
372                 bpf_zerocopy_bufheld(d);
373                 break;
374         }
375 }
376
377 static void
378 bpf_free(struct bpf_d *d)
379 {
380
381         switch (d->bd_bufmode) {
382         case BPF_BUFMODE_BUFFER:
383                 return (bpf_buffer_free(d));
384
385         case BPF_BUFMODE_ZBUF:
386                 return (bpf_zerocopy_free(d));
387
388         default:
389                 panic("bpf_buf_free");
390         }
391 }
392
393 static int
394 bpf_uiomove(struct bpf_d *d, caddr_t buf, u_int len, struct uio *uio)
395 {
396
397         if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
398                 return (EOPNOTSUPP);
399         return (bpf_buffer_uiomove(d, buf, len, uio));
400 }
401
402 static int
403 bpf_ioctl_sblen(struct bpf_d *d, u_int *i)
404 {
405
406         if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
407                 return (EOPNOTSUPP);
408         return (bpf_buffer_ioctl_sblen(d, i));
409 }
410
411 static int
412 bpf_ioctl_getzmax(struct thread *td, struct bpf_d *d, size_t *i)
413 {
414
415         if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
416                 return (EOPNOTSUPP);
417         return (bpf_zerocopy_ioctl_getzmax(td, d, i));
418 }
419
420 static int
421 bpf_ioctl_rotzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
422 {
423
424         if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
425                 return (EOPNOTSUPP);
426         return (bpf_zerocopy_ioctl_rotzbuf(td, d, bz));
427 }
428
429 static int
430 bpf_ioctl_setzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
431 {
432
433         if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
434                 return (EOPNOTSUPP);
435         return (bpf_zerocopy_ioctl_setzbuf(td, d, bz));
436 }
437
438 /*
439  * General BPF functions.
440  */
441 static int
442 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
443     struct sockaddr *sockp, int *hdrlen, struct bpf_insn *wfilter)
444 {
445         const struct ieee80211_bpf_params *p;
446         struct ether_header *eh;
447         struct mbuf *m;
448         int error;
449         int len;
450         int hlen;
451         int slen;
452
453         /*
454          * Build a sockaddr based on the data link layer type.
455          * We do this at this level because the ethernet header
456          * is copied directly into the data field of the sockaddr.
457          * In the case of SLIP, there is no header and the packet
458          * is forwarded as is.
459          * Also, we are careful to leave room at the front of the mbuf
460          * for the link level header.
461          */
462         switch (linktype) {
463
464         case DLT_SLIP:
465                 sockp->sa_family = AF_INET;
466                 hlen = 0;
467                 break;
468
469         case DLT_EN10MB:
470                 sockp->sa_family = AF_UNSPEC;
471                 /* XXX Would MAXLINKHDR be better? */
472                 hlen = ETHER_HDR_LEN;
473                 break;
474
475         case DLT_FDDI:
476                 sockp->sa_family = AF_IMPLINK;
477                 hlen = 0;
478                 break;
479
480         case DLT_RAW:
481                 sockp->sa_family = AF_UNSPEC;
482                 hlen = 0;
483                 break;
484
485         case DLT_NULL:
486                 /*
487                  * null interface types require a 4 byte pseudo header which
488                  * corresponds to the address family of the packet.
489                  */
490                 sockp->sa_family = AF_UNSPEC;
491                 hlen = 4;
492                 break;
493
494         case DLT_ATM_RFC1483:
495                 /*
496                  * en atm driver requires 4-byte atm pseudo header.
497                  * though it isn't standard, vpi:vci needs to be
498                  * specified anyway.
499                  */
500                 sockp->sa_family = AF_UNSPEC;
501                 hlen = 12;      /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
502                 break;
503
504         case DLT_PPP:
505                 sockp->sa_family = AF_UNSPEC;
506                 hlen = 4;       /* This should match PPP_HDRLEN */
507                 break;
508
509         case DLT_IEEE802_11:            /* IEEE 802.11 wireless */
510                 sockp->sa_family = AF_IEEE80211;
511                 hlen = 0;
512                 break;
513
514         case DLT_IEEE802_11_RADIO:      /* IEEE 802.11 wireless w/ phy params */
515                 sockp->sa_family = AF_IEEE80211;
516                 sockp->sa_len = 12;     /* XXX != 0 */
517                 hlen = sizeof(struct ieee80211_bpf_params);
518                 break;
519
520         default:
521                 return (EIO);
522         }
523
524         len = uio->uio_resid;
525
526         if (len - hlen > ifp->if_mtu)
527                 return (EMSGSIZE);
528
529         if ((unsigned)len > MJUM16BYTES)
530                 return (EIO);
531
532         if (len <= MHLEN)
533                 MGETHDR(m, M_WAIT, MT_DATA);
534         else if (len <= MCLBYTES)
535                 m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
536         else
537                 m = m_getjcl(M_WAIT, MT_DATA, M_PKTHDR,
538 #if (MJUMPAGESIZE > MCLBYTES)
539                     len <= MJUMPAGESIZE ? MJUMPAGESIZE :
540 #endif
541                     (len <= MJUM9BYTES ? MJUM9BYTES : MJUM16BYTES));
542         m->m_pkthdr.len = m->m_len = len;
543         m->m_pkthdr.rcvif = NULL;
544         *mp = m;
545
546         if (m->m_len < hlen) {
547                 error = EPERM;
548                 goto bad;
549         }
550
551         error = uiomove(mtod(m, u_char *), len, uio);
552         if (error)
553                 goto bad;
554
555         slen = bpf_filter(wfilter, mtod(m, u_char *), len, len);
556         if (slen == 0) {
557                 error = EPERM;
558                 goto bad;
559         }
560
561         /* Check for multicast destination */
562         switch (linktype) {
563         case DLT_EN10MB:
564                 eh = mtod(m, struct ether_header *);
565                 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
566                         if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
567                             ETHER_ADDR_LEN) == 0)
568                                 m->m_flags |= M_BCAST;
569                         else
570                                 m->m_flags |= M_MCAST;
571                 }
572                 break;
573         }
574
575         /*
576          * Make room for link header, and copy it to sockaddr
577          */
578         if (hlen != 0) {
579                 if (sockp->sa_family == AF_IEEE80211) {
580                         /*
581                          * Collect true length from the parameter header
582                          * NB: sockp is known to be zero'd so if we do a
583                          *     short copy unspecified parameters will be
584                          *     zero.
585                          * NB: packet may not be aligned after stripping
586                          *     bpf params
587                          * XXX check ibp_vers
588                          */
589                         p = mtod(m, const struct ieee80211_bpf_params *);
590                         hlen = p->ibp_len;
591                         if (hlen > sizeof(sockp->sa_data)) {
592                                 error = EINVAL;
593                                 goto bad;
594                         }
595                 }
596                 bcopy(m->m_data, sockp->sa_data, hlen);
597         }
598         *hdrlen = hlen;
599
600         return (0);
601 bad:
602         m_freem(m);
603         return (error);
604 }
605
606 /*
607  * Attach file to the bpf interface, i.e. make d listen on bp.
608  */
609 static void
610 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
611 {
612         int op_w;
613
614         BPF_LOCK_ASSERT();
615
616         /*
617          * Save sysctl value to protect from sysctl change
618          * between reads
619          */
620         op_w = V_bpf_optimize_writers;
621
622         if (d->bd_bif != NULL)
623                 bpf_detachd_locked(d);
624         /*
625          * Point d at bp, and add d to the interface's list.
626          * Since there are many applicaiotns using BPF for
627          * sending raw packets only (dhcpd, cdpd are good examples)
628          * we can delay adding d to the list of active listeners until
629          * some filter is configured.
630          */
631
632         BPFIF_WLOCK(bp);
633         BPFD_LOCK(d);
634
635         d->bd_bif = bp;
636
637         if (op_w != 0) {
638                 /* Add to writers-only list */
639                 LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
640                 /*
641                  * We decrement bd_writer on every filter set operation.
642                  * First BIOCSETF is done by pcap_open_live() to set up
643                  * snap length. After that appliation usually sets its own filter
644                  */
645                 d->bd_writer = 2;
646         } else
647                 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
648
649         BPFD_UNLOCK(d);
650         BPFIF_WUNLOCK(bp);
651
652         bpf_bpfd_cnt++;
653
654         CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
655             __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
656
657         if (op_w == 0)
658                 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
659 }
660
661 /*
662  * Check if we need to upgrade our descriptor @d from write-only mode.
663  */
664 static int
665 bpf_check_upgrade(u_long cmd, struct bpf_d *d, struct bpf_insn *fcode, int flen)
666 {
667         int is_snap, need_upgrade;
668
669         /*
670          * Check if we've already upgraded or new filter is empty.
671          */
672         if (d->bd_writer == 0 || fcode == NULL)
673                 return (0);
674
675         need_upgrade = 0;
676
677         /*
678          * Check if cmd looks like snaplen setting from
679          * pcap_bpf.c:pcap_open_live().
680          * Note we're not checking .k value here:
681          * while pcap_open_live() definitely sets to to non-zero value,
682          * we'd prefer to treat k=0 (deny ALL) case the same way: e.g.
683          * do not consider upgrading immediately
684          */
685         if (cmd == BIOCSETF && flen == 1 && fcode[0].code == (BPF_RET | BPF_K))
686                 is_snap = 1;
687         else
688                 is_snap = 0;
689
690         if (is_snap == 0) {
691                 /*
692                  * We're setting first filter and it doesn't look like
693                  * setting snaplen.  We're probably using bpf directly.
694                  * Upgrade immediately.
695                  */
696                 need_upgrade = 1;
697         } else {
698                 /*
699                  * Do not require upgrade by first BIOCSETF
700                  * (used to set snaplen) by pcap_open_live().
701                  */
702
703                 if (--d->bd_writer == 0) {
704                         /*
705                          * First snaplen filter has already
706                          * been set. This is probably catch-all
707                          * filter
708                          */
709                         need_upgrade = 1;
710                 }
711         }
712
713         CTR5(KTR_NET,
714             "%s: filter function set by pid %d, "
715             "bd_writer counter %d, snap %d upgrade %d",
716             __func__, d->bd_pid, d->bd_writer,
717             is_snap, need_upgrade);
718
719         return (need_upgrade);
720 }
721
722 /*
723  * Add d to the list of active bp filters.
724  * Reuqires bpf_attachd() to be called before
725  */
726 static void
727 bpf_upgraded(struct bpf_d *d)
728 {
729         struct bpf_if *bp;
730
731         BPF_LOCK_ASSERT();
732
733         bp = d->bd_bif;
734
735         /*
736          * Filter can be set several times without specifying interface.
737          * Mark d as reader and exit.
738          */
739         if (bp == NULL) {
740                 BPFD_LOCK(d);
741                 d->bd_writer = 0;
742                 BPFD_UNLOCK(d);
743                 return;
744         }
745
746         BPFIF_WLOCK(bp);
747         BPFD_LOCK(d);
748
749         /* Remove from writers-only list */
750         LIST_REMOVE(d, bd_next);
751         LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
752         /* Mark d as reader */
753         d->bd_writer = 0;
754
755         BPFD_UNLOCK(d);
756         BPFIF_WUNLOCK(bp);
757
758         CTR2(KTR_NET, "%s: upgrade required by pid %d", __func__, d->bd_pid);
759
760         EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
761 }
762
763 /*
764  * Detach a file from its interface.
765  */
766 static void
767 bpf_detachd(struct bpf_d *d)
768 {
769         BPF_LOCK();
770         bpf_detachd_locked(d);
771         BPF_UNLOCK();
772 }
773
774 static void
775 bpf_detachd_locked(struct bpf_d *d)
776 {
777         int error;
778         struct bpf_if *bp;
779         struct ifnet *ifp;
780
781         CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
782
783         BPF_LOCK_ASSERT();
784
785         /* Check if descriptor is attached */
786         if ((bp = d->bd_bif) == NULL)
787                 return;
788
789         BPFIF_WLOCK(bp);
790         BPFD_LOCK(d);
791
792         /* Save bd_writer value */
793         error = d->bd_writer;
794
795         /*
796          * Remove d from the interface's descriptor list.
797          */
798         LIST_REMOVE(d, bd_next);
799
800         ifp = bp->bif_ifp;
801         d->bd_bif = NULL;
802         BPFD_UNLOCK(d);
803         BPFIF_WUNLOCK(bp);
804
805         bpf_bpfd_cnt--;
806
807         /* Call event handler iff d is attached */
808         if (error == 0)
809                 EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
810
811         /*
812          * Check if this descriptor had requested promiscuous mode.
813          * If so, turn it off.
814          */
815         if (d->bd_promisc) {
816                 d->bd_promisc = 0;
817                 CURVNET_SET(ifp->if_vnet);
818                 error = ifpromisc(ifp, 0);
819                 CURVNET_RESTORE();
820                 if (error != 0 && error != ENXIO) {
821                         /*
822                          * ENXIO can happen if a pccard is unplugged
823                          * Something is really wrong if we were able to put
824                          * the driver into promiscuous mode, but can't
825                          * take it out.
826                          */
827                         if_printf(bp->bif_ifp,
828                                 "bpf_detach: ifpromisc failed (%d)\n", error);
829                 }
830         }
831 }
832
833 /*
834  * Close the descriptor by detaching it from its interface,
835  * deallocating its buffers, and marking it free.
836  */
837 static void
838 bpf_dtor(void *data)
839 {
840         struct bpf_d *d = data;
841
842         BPFD_LOCK(d);
843         if (d->bd_state == BPF_WAITING)
844                 callout_stop(&d->bd_callout);
845         d->bd_state = BPF_IDLE;
846         BPFD_UNLOCK(d);
847         funsetown(&d->bd_sigio);
848         bpf_detachd(d);
849 #ifdef MAC
850         mac_bpfdesc_destroy(d);
851 #endif /* MAC */
852         seldrain(&d->bd_sel);
853         knlist_destroy(&d->bd_sel.si_note);
854         callout_drain(&d->bd_callout);
855         bpf_freed(d);
856         free(d, M_BPF);
857 }
858
859 /*
860  * Open ethernet device.  Returns ENXIO for illegal minor device number,
861  * EBUSY if file is open by another process.
862  */
863 /* ARGSUSED */
864 static  int
865 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
866 {
867         struct bpf_d *d;
868         int error, size;
869
870         d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
871         error = devfs_set_cdevpriv(d, bpf_dtor);
872         if (error != 0) {
873                 free(d, M_BPF);
874                 return (error);
875         }
876
877         /*
878          * For historical reasons, perform a one-time initialization call to
879          * the buffer routines, even though we're not yet committed to a
880          * particular buffer method.
881          */
882         bpf_buffer_init(d);
883         d->bd_hbuf_in_use = 0;
884         d->bd_bufmode = BPF_BUFMODE_BUFFER;
885         d->bd_sig = SIGIO;
886         d->bd_direction = BPF_D_INOUT;
887         BPF_PID_REFRESH(d, td);
888 #ifdef MAC
889         mac_bpfdesc_init(d);
890         mac_bpfdesc_create(td->td_ucred, d);
891 #endif
892         mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
893         callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
894         knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
895
896         /* Allocate default buffers */
897         size = d->bd_bufsize;
898         bpf_buffer_ioctl_sblen(d, &size);
899
900         return (0);
901 }
902
903 /*
904  *  bpfread - read next chunk of packets from buffers
905  */
906 static  int
907 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
908 {
909         struct bpf_d *d;
910         int error;
911         int non_block;
912         int timed_out;
913
914         error = devfs_get_cdevpriv((void **)&d);
915         if (error != 0)
916                 return (error);
917
918         /*
919          * Restrict application to use a buffer the same size as
920          * as kernel buffers.
921          */
922         if (uio->uio_resid != d->bd_bufsize)
923                 return (EINVAL);
924
925         non_block = ((ioflag & O_NONBLOCK) != 0);
926
927         BPFD_LOCK(d);
928         BPF_PID_REFRESH_CUR(d);
929         if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
930                 BPFD_UNLOCK(d);
931                 return (EOPNOTSUPP);
932         }
933         if (d->bd_state == BPF_WAITING)
934                 callout_stop(&d->bd_callout);
935         timed_out = (d->bd_state == BPF_TIMED_OUT);
936         d->bd_state = BPF_IDLE;
937         while (d->bd_hbuf_in_use) {
938                 error = mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
939                     PRINET|PCATCH, "bd_hbuf", 0);
940                 if (error != 0) {
941                         BPFD_UNLOCK(d);
942                         return (error);
943                 }
944         }
945         /*
946          * If the hold buffer is empty, then do a timed sleep, which
947          * ends when the timeout expires or when enough packets
948          * have arrived to fill the store buffer.
949          */
950         while (d->bd_hbuf == NULL) {
951                 if (d->bd_slen != 0) {
952                         /*
953                          * A packet(s) either arrived since the previous
954                          * read or arrived while we were asleep.
955                          */
956                         if (d->bd_immediate || non_block || timed_out) {
957                                 /*
958                                  * Rotate the buffers and return what's here
959                                  * if we are in immediate mode, non-blocking
960                                  * flag is set, or this descriptor timed out.
961                                  */
962                                 ROTATE_BUFFERS(d);
963                                 break;
964                         }
965                 }
966
967                 /*
968                  * No data is available, check to see if the bpf device
969                  * is still pointed at a real interface.  If not, return
970                  * ENXIO so that the userland process knows to rebind
971                  * it before using it again.
972                  */
973                 if (d->bd_bif == NULL) {
974                         BPFD_UNLOCK(d);
975                         return (ENXIO);
976                 }
977
978                 if (non_block) {
979                         BPFD_UNLOCK(d);
980                         return (EWOULDBLOCK);
981                 }
982                 error = msleep(d, &d->bd_lock, PRINET|PCATCH,
983                      "bpf", d->bd_rtout);
984                 if (error == EINTR || error == ERESTART) {
985                         BPFD_UNLOCK(d);
986                         return (error);
987                 }
988                 if (error == EWOULDBLOCK) {
989                         /*
990                          * On a timeout, return what's in the buffer,
991                          * which may be nothing.  If there is something
992                          * in the store buffer, we can rotate the buffers.
993                          */
994                         if (d->bd_hbuf)
995                                 /*
996                                  * We filled up the buffer in between
997                                  * getting the timeout and arriving
998                                  * here, so we don't need to rotate.
999                                  */
1000                                 break;
1001
1002                         if (d->bd_slen == 0) {
1003                                 BPFD_UNLOCK(d);
1004                                 return (0);
1005                         }
1006                         ROTATE_BUFFERS(d);
1007                         break;
1008                 }
1009         }
1010         /*
1011          * At this point, we know we have something in the hold slot.
1012          */
1013         d->bd_hbuf_in_use = 1;
1014         BPFD_UNLOCK(d);
1015
1016         /*
1017          * Move data from hold buffer into user space.
1018          * We know the entire buffer is transferred since
1019          * we checked above that the read buffer is bpf_bufsize bytes.
1020          *
1021          * We do not have to worry about simultaneous reads because
1022          * we waited for sole access to the hold buffer above.
1023          */
1024         error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
1025
1026         BPFD_LOCK(d);
1027         KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
1028         d->bd_fbuf = d->bd_hbuf;
1029         d->bd_hbuf = NULL;
1030         d->bd_hlen = 0;
1031         bpf_buf_reclaimed(d);
1032         d->bd_hbuf_in_use = 0;
1033         wakeup(&d->bd_hbuf_in_use);
1034         BPFD_UNLOCK(d);
1035
1036         return (error);
1037 }
1038
1039 /*
1040  * If there are processes sleeping on this descriptor, wake them up.
1041  */
1042 static __inline void
1043 bpf_wakeup(struct bpf_d *d)
1044 {
1045
1046         BPFD_LOCK_ASSERT(d);
1047         if (d->bd_state == BPF_WAITING) {
1048                 callout_stop(&d->bd_callout);
1049                 d->bd_state = BPF_IDLE;
1050         }
1051         wakeup(d);
1052         if (d->bd_async && d->bd_sig && d->bd_sigio)
1053                 pgsigio(&d->bd_sigio, d->bd_sig, 0);
1054
1055         selwakeuppri(&d->bd_sel, PRINET);
1056         KNOTE_LOCKED(&d->bd_sel.si_note, 0);
1057 }
1058
1059 static void
1060 bpf_timed_out(void *arg)
1061 {
1062         struct bpf_d *d = (struct bpf_d *)arg;
1063
1064         BPFD_LOCK_ASSERT(d);
1065
1066         if (callout_pending(&d->bd_callout) || !callout_active(&d->bd_callout))
1067                 return;
1068         if (d->bd_state == BPF_WAITING) {
1069                 d->bd_state = BPF_TIMED_OUT;
1070                 if (d->bd_slen != 0)
1071                         bpf_wakeup(d);
1072         }
1073 }
1074
1075 static int
1076 bpf_ready(struct bpf_d *d)
1077 {
1078
1079         BPFD_LOCK_ASSERT(d);
1080
1081         if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
1082                 return (1);
1083         if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1084             d->bd_slen != 0)
1085                 return (1);
1086         return (0);
1087 }
1088
1089 static int
1090 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1091 {
1092         struct bpf_d *d;
1093         struct ifnet *ifp;
1094         struct mbuf *m, *mc;
1095         struct sockaddr dst;
1096         int error, hlen;
1097
1098         error = devfs_get_cdevpriv((void **)&d);
1099         if (error != 0)
1100                 return (error);
1101
1102         BPF_PID_REFRESH_CUR(d);
1103         d->bd_wcount++;
1104         /* XXX: locking required */
1105         if (d->bd_bif == NULL) {
1106                 d->bd_wdcount++;
1107                 return (ENXIO);
1108         }
1109
1110         ifp = d->bd_bif->bif_ifp;
1111
1112         if ((ifp->if_flags & IFF_UP) == 0) {
1113                 d->bd_wdcount++;
1114                 return (ENETDOWN);
1115         }
1116
1117         if (uio->uio_resid == 0) {
1118                 d->bd_wdcount++;
1119                 return (0);
1120         }
1121
1122         bzero(&dst, sizeof(dst));
1123         m = NULL;
1124         hlen = 0;
1125         /* XXX: bpf_movein() can sleep */
1126         error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp,
1127             &m, &dst, &hlen, d->bd_wfilter);
1128         if (error) {
1129                 d->bd_wdcount++;
1130                 return (error);
1131         }
1132         d->bd_wfcount++;
1133         if (d->bd_hdrcmplt)
1134                 dst.sa_family = pseudo_AF_HDRCMPLT;
1135
1136         if (d->bd_feedback) {
1137                 mc = m_dup(m, M_DONTWAIT);
1138                 if (mc != NULL)
1139                         mc->m_pkthdr.rcvif = ifp;
1140                 /* Set M_PROMISC for outgoing packets to be discarded. */
1141                 if (d->bd_direction == BPF_D_INOUT)
1142                         m->m_flags |= M_PROMISC;
1143         } else
1144                 mc = NULL;
1145
1146         m->m_pkthdr.len -= hlen;
1147         m->m_len -= hlen;
1148         m->m_data += hlen;      /* XXX */
1149
1150         CURVNET_SET(ifp->if_vnet);
1151 #ifdef MAC
1152         BPFD_LOCK(d);
1153         mac_bpfdesc_create_mbuf(d, m);
1154         if (mc != NULL)
1155                 mac_bpfdesc_create_mbuf(d, mc);
1156         BPFD_UNLOCK(d);
1157 #endif
1158
1159         error = (*ifp->if_output)(ifp, m, &dst, NULL);
1160         if (error)
1161                 d->bd_wdcount++;
1162
1163         if (mc != NULL) {
1164                 if (error == 0)
1165                         (*ifp->if_input)(ifp, mc);
1166                 else
1167                         m_freem(mc);
1168         }
1169         CURVNET_RESTORE();
1170
1171         return (error);
1172 }
1173
1174 /*
1175  * Reset a descriptor by flushing its packet buffer and clearing the receive
1176  * and drop counts.  This is doable for kernel-only buffers, but with
1177  * zero-copy buffers, we can't write to (or rotate) buffers that are
1178  * currently owned by userspace.  It would be nice if we could encapsulate
1179  * this logic in the buffer code rather than here.
1180  */
1181 static void
1182 reset_d(struct bpf_d *d)
1183 {
1184
1185         BPFD_LOCK_ASSERT(d);
1186
1187         while (d->bd_hbuf_in_use)
1188                 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1189                     "bd_hbuf", 0);
1190         if ((d->bd_hbuf != NULL) &&
1191             (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1192                 /* Free the hold buffer. */
1193                 d->bd_fbuf = d->bd_hbuf;
1194                 d->bd_hbuf = NULL;
1195                 d->bd_hlen = 0;
1196                 bpf_buf_reclaimed(d);
1197         }
1198         if (bpf_canwritebuf(d))
1199                 d->bd_slen = 0;
1200         d->bd_rcount = 0;
1201         d->bd_dcount = 0;
1202         d->bd_fcount = 0;
1203         d->bd_wcount = 0;
1204         d->bd_wfcount = 0;
1205         d->bd_wdcount = 0;
1206         d->bd_zcopy = 0;
1207 }
1208
1209 /*
1210  *  FIONREAD            Check for read packet available.
1211  *  SIOCGIFADDR         Get interface address - convenient hook to driver.
1212  *  BIOCGBLEN           Get buffer len [for read()].
1213  *  BIOCSETF            Set read filter.
1214  *  BIOCSETFNR          Set read filter without resetting descriptor.
1215  *  BIOCSETWF           Set write filter.
1216  *  BIOCFLUSH           Flush read packet buffer.
1217  *  BIOCPROMISC         Put interface into promiscuous mode.
1218  *  BIOCGDLT            Get link layer type.
1219  *  BIOCGETIF           Get interface name.
1220  *  BIOCSETIF           Set interface.
1221  *  BIOCSRTIMEOUT       Set read timeout.
1222  *  BIOCGRTIMEOUT       Get read timeout.
1223  *  BIOCGSTATS          Get packet stats.
1224  *  BIOCIMMEDIATE       Set immediate mode.
1225  *  BIOCVERSION         Get filter language version.
1226  *  BIOCGHDRCMPLT       Get "header already complete" flag
1227  *  BIOCSHDRCMPLT       Set "header already complete" flag
1228  *  BIOCGDIRECTION      Get packet direction flag
1229  *  BIOCSDIRECTION      Set packet direction flag
1230  *  BIOCGTSTAMP         Get time stamp format and resolution.
1231  *  BIOCSTSTAMP         Set time stamp format and resolution.
1232  *  BIOCLOCK            Set "locked" flag
1233  *  BIOCFEEDBACK        Set packet feedback mode.
1234  *  BIOCSETZBUF         Set current zero-copy buffer locations.
1235  *  BIOCGETZMAX         Get maximum zero-copy buffer size.
1236  *  BIOCROTZBUF         Force rotation of zero-copy buffer
1237  *  BIOCSETBUFMODE      Set buffer mode.
1238  *  BIOCGETBUFMODE      Get current buffer mode.
1239  */
1240 /* ARGSUSED */
1241 static  int
1242 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1243     struct thread *td)
1244 {
1245         struct bpf_d *d;
1246         int error;
1247
1248         error = devfs_get_cdevpriv((void **)&d);
1249         if (error != 0)
1250                 return (error);
1251
1252         /*
1253          * Refresh PID associated with this descriptor.
1254          */
1255         BPFD_LOCK(d);
1256         BPF_PID_REFRESH(d, td);
1257         if (d->bd_state == BPF_WAITING)
1258                 callout_stop(&d->bd_callout);
1259         d->bd_state = BPF_IDLE;
1260         BPFD_UNLOCK(d);
1261
1262         if (d->bd_locked == 1) {
1263                 switch (cmd) {
1264                 case BIOCGBLEN:
1265                 case BIOCFLUSH:
1266                 case BIOCGDLT:
1267                 case BIOCGDLTLIST:
1268 #ifdef COMPAT_FREEBSD32
1269                 case BIOCGDLTLIST32:
1270 #endif
1271                 case BIOCGETIF:
1272                 case BIOCGRTIMEOUT:
1273 #ifdef COMPAT_FREEBSD32
1274                 case BIOCGRTIMEOUT32:
1275 #endif
1276                 case BIOCGSTATS:
1277                 case BIOCVERSION:
1278                 case BIOCGRSIG:
1279                 case BIOCGHDRCMPLT:
1280                 case BIOCSTSTAMP:
1281                 case BIOCFEEDBACK:
1282                 case FIONREAD:
1283                 case BIOCLOCK:
1284                 case BIOCSRTIMEOUT:
1285 #ifdef COMPAT_FREEBSD32
1286                 case BIOCSRTIMEOUT32:
1287 #endif
1288                 case BIOCIMMEDIATE:
1289                 case TIOCGPGRP:
1290                 case BIOCROTZBUF:
1291                         break;
1292                 default:
1293                         return (EPERM);
1294                 }
1295         }
1296 #ifdef COMPAT_FREEBSD32
1297         /*
1298          * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1299          * that it will get 32-bit packet headers.
1300          */
1301         switch (cmd) {
1302         case BIOCSETF32:
1303         case BIOCSETFNR32:
1304         case BIOCSETWF32:
1305         case BIOCGDLTLIST32:
1306         case BIOCGRTIMEOUT32:
1307         case BIOCSRTIMEOUT32:
1308                 BPFD_LOCK(d);
1309                 d->bd_compat32 = 1;
1310                 BPFD_UNLOCK(d);
1311         }
1312 #endif
1313
1314         CURVNET_SET(TD_TO_VNET(td));
1315         switch (cmd) {
1316
1317         default:
1318                 error = EINVAL;
1319                 break;
1320
1321         /*
1322          * Check for read packet available.
1323          */
1324         case FIONREAD:
1325                 {
1326                         int n;
1327
1328                         BPFD_LOCK(d);
1329                         n = d->bd_slen;
1330                         while (d->bd_hbuf_in_use)
1331                                 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1332                                     PRINET, "bd_hbuf", 0);
1333                         if (d->bd_hbuf)
1334                                 n += d->bd_hlen;
1335                         BPFD_UNLOCK(d);
1336
1337                         *(int *)addr = n;
1338                         break;
1339                 }
1340
1341         case SIOCGIFADDR:
1342                 {
1343                         struct ifnet *ifp;
1344
1345                         if (d->bd_bif == NULL)
1346                                 error = EINVAL;
1347                         else {
1348                                 ifp = d->bd_bif->bif_ifp;
1349                                 error = (*ifp->if_ioctl)(ifp, cmd, addr);
1350                         }
1351                         break;
1352                 }
1353
1354         /*
1355          * Get buffer len [for read()].
1356          */
1357         case BIOCGBLEN:
1358                 BPFD_LOCK(d);
1359                 *(u_int *)addr = d->bd_bufsize;
1360                 BPFD_UNLOCK(d);
1361                 break;
1362
1363         /*
1364          * Set buffer length.
1365          */
1366         case BIOCSBLEN:
1367                 error = bpf_ioctl_sblen(d, (u_int *)addr);
1368                 break;
1369
1370         /*
1371          * Set link layer read filter.
1372          */
1373         case BIOCSETF:
1374         case BIOCSETFNR:
1375         case BIOCSETWF:
1376 #ifdef COMPAT_FREEBSD32
1377         case BIOCSETF32:
1378         case BIOCSETFNR32:
1379         case BIOCSETWF32:
1380 #endif
1381                 error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1382                 break;
1383
1384         /*
1385          * Flush read packet buffer.
1386          */
1387         case BIOCFLUSH:
1388                 BPFD_LOCK(d);
1389                 reset_d(d);
1390                 BPFD_UNLOCK(d);
1391                 break;
1392
1393         /*
1394          * Put interface into promiscuous mode.
1395          */
1396         case BIOCPROMISC:
1397                 if (d->bd_bif == NULL) {
1398                         /*
1399                          * No interface attached yet.
1400                          */
1401                         error = EINVAL;
1402                         break;
1403                 }
1404                 if (d->bd_promisc == 0) {
1405                         error = ifpromisc(d->bd_bif->bif_ifp, 1);
1406                         if (error == 0)
1407                                 d->bd_promisc = 1;
1408                 }
1409                 break;
1410
1411         /*
1412          * Get current data link type.
1413          */
1414         case BIOCGDLT:
1415                 BPF_LOCK();
1416                 if (d->bd_bif == NULL)
1417                         error = EINVAL;
1418                 else
1419                         *(u_int *)addr = d->bd_bif->bif_dlt;
1420                 BPF_UNLOCK();
1421                 break;
1422
1423         /*
1424          * Get a list of supported data link types.
1425          */
1426 #ifdef COMPAT_FREEBSD32
1427         case BIOCGDLTLIST32:
1428                 {
1429                         struct bpf_dltlist32 *list32;
1430                         struct bpf_dltlist dltlist;
1431
1432                         list32 = (struct bpf_dltlist32 *)addr;
1433                         dltlist.bfl_len = list32->bfl_len;
1434                         dltlist.bfl_list = PTRIN(list32->bfl_list);
1435                         BPF_LOCK();
1436                         if (d->bd_bif == NULL)
1437                                 error = EINVAL;
1438                         else {
1439                                 error = bpf_getdltlist(d, &dltlist);
1440                                 if (error == 0)
1441                                         list32->bfl_len = dltlist.bfl_len;
1442                         }
1443                         BPF_UNLOCK();
1444                         break;
1445                 }
1446 #endif
1447
1448         case BIOCGDLTLIST:
1449                 BPF_LOCK();
1450                 if (d->bd_bif == NULL)
1451                         error = EINVAL;
1452                 else
1453                         error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1454                 BPF_UNLOCK();
1455                 break;
1456
1457         /*
1458          * Set data link type.
1459          */
1460         case BIOCSDLT:
1461                 BPF_LOCK();
1462                 if (d->bd_bif == NULL)
1463                         error = EINVAL;
1464                 else
1465                         error = bpf_setdlt(d, *(u_int *)addr);
1466                 BPF_UNLOCK();
1467                 break;
1468
1469         /*
1470          * Get interface name.
1471          */
1472         case BIOCGETIF:
1473                 BPF_LOCK();
1474                 if (d->bd_bif == NULL)
1475                         error = EINVAL;
1476                 else {
1477                         struct ifnet *const ifp = d->bd_bif->bif_ifp;
1478                         struct ifreq *const ifr = (struct ifreq *)addr;
1479
1480                         strlcpy(ifr->ifr_name, ifp->if_xname,
1481                             sizeof(ifr->ifr_name));
1482                 }
1483                 BPF_UNLOCK();
1484                 break;
1485
1486         /*
1487          * Set interface.
1488          */
1489         case BIOCSETIF:
1490                 BPF_LOCK();
1491                 error = bpf_setif(d, (struct ifreq *)addr);
1492                 BPF_UNLOCK();
1493                 break;
1494
1495         /*
1496          * Set read timeout.
1497          */
1498         case BIOCSRTIMEOUT:
1499 #ifdef COMPAT_FREEBSD32
1500         case BIOCSRTIMEOUT32:
1501 #endif
1502                 {
1503                         struct timeval *tv = (struct timeval *)addr;
1504 #ifdef COMPAT_FREEBSD32
1505                         struct timeval32 *tv32;
1506                         struct timeval tv64;
1507
1508                         if (cmd == BIOCSRTIMEOUT32) {
1509                                 tv32 = (struct timeval32 *)addr;
1510                                 tv = &tv64;
1511                                 tv->tv_sec = tv32->tv_sec;
1512                                 tv->tv_usec = tv32->tv_usec;
1513                         } else
1514 #endif
1515                                 tv = (struct timeval *)addr;
1516
1517                         /*
1518                          * Subtract 1 tick from tvtohz() since this isn't
1519                          * a one-shot timer.
1520                          */
1521                         if ((error = itimerfix(tv)) == 0)
1522                                 d->bd_rtout = tvtohz(tv) - 1;
1523                         break;
1524                 }
1525
1526         /*
1527          * Get read timeout.
1528          */
1529         case BIOCGRTIMEOUT:
1530 #ifdef COMPAT_FREEBSD32
1531         case BIOCGRTIMEOUT32:
1532 #endif
1533                 {
1534                         struct timeval *tv;
1535 #ifdef COMPAT_FREEBSD32
1536                         struct timeval32 *tv32;
1537                         struct timeval tv64;
1538
1539                         if (cmd == BIOCGRTIMEOUT32)
1540                                 tv = &tv64;
1541                         else
1542 #endif
1543                                 tv = (struct timeval *)addr;
1544
1545                         tv->tv_sec = d->bd_rtout / hz;
1546                         tv->tv_usec = (d->bd_rtout % hz) * tick;
1547 #ifdef COMPAT_FREEBSD32
1548                         if (cmd == BIOCGRTIMEOUT32) {
1549                                 tv32 = (struct timeval32 *)addr;
1550                                 tv32->tv_sec = tv->tv_sec;
1551                                 tv32->tv_usec = tv->tv_usec;
1552                         }
1553 #endif
1554
1555                         break;
1556                 }
1557
1558         /*
1559          * Get packet stats.
1560          */
1561         case BIOCGSTATS:
1562                 {
1563                         struct bpf_stat *bs = (struct bpf_stat *)addr;
1564
1565                         /* XXXCSJP overflow */
1566                         bs->bs_recv = d->bd_rcount;
1567                         bs->bs_drop = d->bd_dcount;
1568                         break;
1569                 }
1570
1571         /*
1572          * Set immediate mode.
1573          */
1574         case BIOCIMMEDIATE:
1575                 BPFD_LOCK(d);
1576                 d->bd_immediate = *(u_int *)addr;
1577                 BPFD_UNLOCK(d);
1578                 break;
1579
1580         case BIOCVERSION:
1581                 {
1582                         struct bpf_version *bv = (struct bpf_version *)addr;
1583
1584                         bv->bv_major = BPF_MAJOR_VERSION;
1585                         bv->bv_minor = BPF_MINOR_VERSION;
1586                         break;
1587                 }
1588
1589         /*
1590          * Get "header already complete" flag
1591          */
1592         case BIOCGHDRCMPLT:
1593                 BPFD_LOCK(d);
1594                 *(u_int *)addr = d->bd_hdrcmplt;
1595                 BPFD_UNLOCK(d);
1596                 break;
1597
1598         /*
1599          * Set "header already complete" flag
1600          */
1601         case BIOCSHDRCMPLT:
1602                 BPFD_LOCK(d);
1603                 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1604                 BPFD_UNLOCK(d);
1605                 break;
1606
1607         /*
1608          * Get packet direction flag
1609          */
1610         case BIOCGDIRECTION:
1611                 BPFD_LOCK(d);
1612                 *(u_int *)addr = d->bd_direction;
1613                 BPFD_UNLOCK(d);
1614                 break;
1615
1616         /*
1617          * Set packet direction flag
1618          */
1619         case BIOCSDIRECTION:
1620                 {
1621                         u_int   direction;
1622
1623                         direction = *(u_int *)addr;
1624                         switch (direction) {
1625                         case BPF_D_IN:
1626                         case BPF_D_INOUT:
1627                         case BPF_D_OUT:
1628                                 BPFD_LOCK(d);
1629                                 d->bd_direction = direction;
1630                                 BPFD_UNLOCK(d);
1631                                 break;
1632                         default:
1633                                 error = EINVAL;
1634                         }
1635                 }
1636                 break;
1637
1638         /*
1639          * Get packet timestamp format and resolution.
1640          */
1641         case BIOCGTSTAMP:
1642                 BPFD_LOCK(d);
1643                 *(u_int *)addr = d->bd_tstamp;
1644                 BPFD_UNLOCK(d);
1645                 break;
1646
1647         /*
1648          * Set packet timestamp format and resolution.
1649          */
1650         case BIOCSTSTAMP:
1651                 {
1652                         u_int   func;
1653
1654                         func = *(u_int *)addr;
1655                         if (BPF_T_VALID(func))
1656                                 d->bd_tstamp = func;
1657                         else
1658                                 error = EINVAL;
1659                 }
1660                 break;
1661
1662         case BIOCFEEDBACK:
1663                 BPFD_LOCK(d);
1664                 d->bd_feedback = *(u_int *)addr;
1665                 BPFD_UNLOCK(d);
1666                 break;
1667
1668         case BIOCLOCK:
1669                 BPFD_LOCK(d);
1670                 d->bd_locked = 1;
1671                 BPFD_UNLOCK(d);
1672                 break;
1673
1674         case FIONBIO:           /* Non-blocking I/O */
1675                 break;
1676
1677         case FIOASYNC:          /* Send signal on receive packets */
1678                 BPFD_LOCK(d);
1679                 d->bd_async = *(int *)addr;
1680                 BPFD_UNLOCK(d);
1681                 break;
1682
1683         case FIOSETOWN:
1684                 /*
1685                  * XXX: Add some sort of locking here?
1686                  * fsetown() can sleep.
1687                  */
1688                 error = fsetown(*(int *)addr, &d->bd_sigio);
1689                 break;
1690
1691         case FIOGETOWN:
1692                 BPFD_LOCK(d);
1693                 *(int *)addr = fgetown(&d->bd_sigio);
1694                 BPFD_UNLOCK(d);
1695                 break;
1696
1697         /* This is deprecated, FIOSETOWN should be used instead. */
1698         case TIOCSPGRP:
1699                 error = fsetown(-(*(int *)addr), &d->bd_sigio);
1700                 break;
1701
1702         /* This is deprecated, FIOGETOWN should be used instead. */
1703         case TIOCGPGRP:
1704                 *(int *)addr = -fgetown(&d->bd_sigio);
1705                 break;
1706
1707         case BIOCSRSIG:         /* Set receive signal */
1708                 {
1709                         u_int sig;
1710
1711                         sig = *(u_int *)addr;
1712
1713                         if (sig >= NSIG)
1714                                 error = EINVAL;
1715                         else {
1716                                 BPFD_LOCK(d);
1717                                 d->bd_sig = sig;
1718                                 BPFD_UNLOCK(d);
1719                         }
1720                         break;
1721                 }
1722         case BIOCGRSIG:
1723                 BPFD_LOCK(d);
1724                 *(u_int *)addr = d->bd_sig;
1725                 BPFD_UNLOCK(d);
1726                 break;
1727
1728         case BIOCGETBUFMODE:
1729                 BPFD_LOCK(d);
1730                 *(u_int *)addr = d->bd_bufmode;
1731                 BPFD_UNLOCK(d);
1732                 break;
1733
1734         case BIOCSETBUFMODE:
1735                 /*
1736                  * Allow the buffering mode to be changed as long as we
1737                  * haven't yet committed to a particular mode.  Our
1738                  * definition of commitment, for now, is whether or not a
1739                  * buffer has been allocated or an interface attached, since
1740                  * that's the point where things get tricky.
1741                  */
1742                 switch (*(u_int *)addr) {
1743                 case BPF_BUFMODE_BUFFER:
1744                         break;
1745
1746                 case BPF_BUFMODE_ZBUF:
1747                         if (bpf_zerocopy_enable)
1748                                 break;
1749                         /* FALLSTHROUGH */
1750
1751                 default:
1752                         CURVNET_RESTORE();
1753                         return (EINVAL);
1754                 }
1755
1756                 BPFD_LOCK(d);
1757                 if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1758                     d->bd_fbuf != NULL || d->bd_bif != NULL) {
1759                         BPFD_UNLOCK(d);
1760                         CURVNET_RESTORE();
1761                         return (EBUSY);
1762                 }
1763                 d->bd_bufmode = *(u_int *)addr;
1764                 BPFD_UNLOCK(d);
1765                 break;
1766
1767         case BIOCGETZMAX:
1768                 error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1769                 break;
1770
1771         case BIOCSETZBUF:
1772                 error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1773                 break;
1774
1775         case BIOCROTZBUF:
1776                 error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1777                 break;
1778         }
1779         CURVNET_RESTORE();
1780         return (error);
1781 }
1782
1783 /*
1784  * Set d's packet filter program to fp.  If this file already has a filter,
1785  * free it and replace it.  Returns EINVAL for bogus requests.
1786  *
1787  * Note we need global lock here to serialize bpf_setf() and bpf_setif() calls
1788  * since reading d->bd_bif can't be protected by d or interface lock due to
1789  * lock order.
1790  *
1791  * Additionally, we have to acquire interface write lock due to bpf_mtap() uses
1792  * interface read lock to read all filers.
1793  *
1794  */
1795 static int
1796 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1797 {
1798 #ifdef COMPAT_FREEBSD32
1799         struct bpf_program fp_swab;
1800         struct bpf_program32 *fp32;
1801 #endif
1802         struct bpf_insn *fcode, *old;
1803 #ifdef BPF_JITTER
1804         bpf_jit_filter *jfunc, *ofunc;
1805 #endif
1806         size_t size;
1807         u_int flen;
1808         int need_upgrade;
1809
1810 #ifdef COMPAT_FREEBSD32
1811         switch (cmd) {
1812         case BIOCSETF32:
1813         case BIOCSETWF32:
1814         case BIOCSETFNR32:
1815                 fp32 = (struct bpf_program32 *)fp;
1816                 fp_swab.bf_len = fp32->bf_len;
1817                 fp_swab.bf_insns = (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1818                 fp = &fp_swab;
1819                 switch (cmd) {
1820                 case BIOCSETF32:
1821                         cmd = BIOCSETF;
1822                         break;
1823                 case BIOCSETWF32:
1824                         cmd = BIOCSETWF;
1825                         break;
1826                 }
1827                 break;
1828         }
1829 #endif
1830
1831         fcode = NULL;
1832 #ifdef BPF_JITTER
1833         jfunc = ofunc = NULL;
1834 #endif
1835         need_upgrade = 0;
1836
1837         /*
1838          * Check new filter validness before acquiring any locks.
1839          * Allocate memory for new filter, if needed.
1840          */
1841         flen = fp->bf_len;
1842         if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1843                 return (EINVAL);
1844         size = flen * sizeof(*fp->bf_insns);
1845         if (size > 0) {
1846                 /* We're setting up new filter.  Copy and check actual data. */
1847                 fcode = malloc(size, M_BPF, M_WAITOK);
1848                 if (copyin(fp->bf_insns, fcode, size) != 0 ||
1849                     !bpf_validate(fcode, flen)) {
1850                         free(fcode, M_BPF);
1851                         return (EINVAL);
1852                 }
1853 #ifdef BPF_JITTER
1854                 /* Filter is copied inside fcode and is perfectly valid. */
1855                 jfunc = bpf_jitter(fcode, flen);
1856 #endif
1857         }
1858
1859         BPF_LOCK();
1860
1861         /*
1862          * Set up new filter.
1863          * Protect filter change by interface lock.
1864          * Additionally, we are protected by global lock here.
1865          */
1866         if (d->bd_bif != NULL)
1867                 BPFIF_WLOCK(d->bd_bif);
1868         BPFD_LOCK(d);
1869         if (cmd == BIOCSETWF) {
1870                 old = d->bd_wfilter;
1871                 d->bd_wfilter = fcode;
1872         } else {
1873                 old = d->bd_rfilter;
1874                 d->bd_rfilter = fcode;
1875 #ifdef BPF_JITTER
1876                 ofunc = d->bd_bfilter;
1877                 d->bd_bfilter = jfunc;
1878 #endif
1879                 if (cmd == BIOCSETF)
1880                         reset_d(d);
1881
1882                 need_upgrade = bpf_check_upgrade(cmd, d, fcode, flen);
1883         }
1884         BPFD_UNLOCK(d);
1885         if (d->bd_bif != NULL)
1886                 BPFIF_WUNLOCK(d->bd_bif);
1887         if (old != NULL)
1888                 free(old, M_BPF);
1889 #ifdef BPF_JITTER
1890         if (ofunc != NULL)
1891                 bpf_destroy_jit_filter(ofunc);
1892 #endif
1893
1894         /* Move d to active readers list. */
1895         if (need_upgrade != 0)
1896                 bpf_upgraded(d);
1897
1898         BPF_UNLOCK();
1899         return (0);
1900 }
1901
1902 /*
1903  * Detach a file from its current interface (if attached at all) and attach
1904  * to the interface indicated by the name stored in ifr.
1905  * Return an errno or 0.
1906  */
1907 static int
1908 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1909 {
1910         struct bpf_if *bp;
1911         struct ifnet *theywant;
1912
1913         BPF_LOCK_ASSERT();
1914
1915         theywant = ifunit(ifr->ifr_name);
1916         if (theywant == NULL || theywant->if_bpf == NULL)
1917                 return (ENXIO);
1918
1919         bp = theywant->if_bpf;
1920
1921         /* Check if interface is not being detached from BPF */
1922         BPFIF_RLOCK(bp);
1923         if (bp->flags & BPFIF_FLAG_DYING) {
1924                 BPFIF_RUNLOCK(bp);
1925                 return (ENXIO);
1926         }
1927         BPFIF_RUNLOCK(bp);
1928
1929         /*
1930          * Behavior here depends on the buffering model.  If we're using
1931          * kernel memory buffers, then we can allocate them here.  If we're
1932          * using zero-copy, then the user process must have registered
1933          * buffers by the time we get here.  If not, return an error.
1934          */
1935         switch (d->bd_bufmode) {
1936         case BPF_BUFMODE_BUFFER:
1937         case BPF_BUFMODE_ZBUF:
1938                 if (d->bd_sbuf == NULL)
1939                         return (EINVAL);
1940                 break;
1941
1942         default:
1943                 panic("bpf_setif: bufmode %d", d->bd_bufmode);
1944         }
1945         if (bp != d->bd_bif)
1946                 bpf_attachd(d, bp);
1947         BPFD_LOCK(d);
1948         reset_d(d);
1949         BPFD_UNLOCK(d);
1950         return (0);
1951 }
1952
1953 /*
1954  * Support for select() and poll() system calls
1955  *
1956  * Return true iff the specific operation will not block indefinitely.
1957  * Otherwise, return false but make a note that a selwakeup() must be done.
1958  */
1959 static int
1960 bpfpoll(struct cdev *dev, int events, struct thread *td)
1961 {
1962         struct bpf_d *d;
1963         int revents;
1964
1965         if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
1966                 return (events &
1967                     (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1968
1969         /*
1970          * Refresh PID associated with this descriptor.
1971          */
1972         revents = events & (POLLOUT | POLLWRNORM);
1973         BPFD_LOCK(d);
1974         BPF_PID_REFRESH(d, td);
1975         if (events & (POLLIN | POLLRDNORM)) {
1976                 if (bpf_ready(d))
1977                         revents |= events & (POLLIN | POLLRDNORM);
1978                 else {
1979                         selrecord(td, &d->bd_sel);
1980                         /* Start the read timeout if necessary. */
1981                         if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1982                                 callout_reset(&d->bd_callout, d->bd_rtout,
1983                                     bpf_timed_out, d);
1984                                 d->bd_state = BPF_WAITING;
1985                         }
1986                 }
1987         }
1988         BPFD_UNLOCK(d);
1989         return (revents);
1990 }
1991
1992 /*
1993  * Support for kevent() system call.  Register EVFILT_READ filters and
1994  * reject all others.
1995  */
1996 int
1997 bpfkqfilter(struct cdev *dev, struct knote *kn)
1998 {
1999         struct bpf_d *d;
2000
2001         if (devfs_get_cdevpriv((void **)&d) != 0 ||
2002             kn->kn_filter != EVFILT_READ)
2003                 return (1);
2004
2005         /*
2006          * Refresh PID associated with this descriptor.
2007          */
2008         BPFD_LOCK(d);
2009         BPF_PID_REFRESH_CUR(d);
2010         kn->kn_fop = &bpfread_filtops;
2011         kn->kn_hook = d;
2012         knlist_add(&d->bd_sel.si_note, kn, 1);
2013         BPFD_UNLOCK(d);
2014
2015         return (0);
2016 }
2017
2018 static void
2019 filt_bpfdetach(struct knote *kn)
2020 {
2021         struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2022
2023         knlist_remove(&d->bd_sel.si_note, kn, 0);
2024 }
2025
2026 static int
2027 filt_bpfread(struct knote *kn, long hint)
2028 {
2029         struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2030         int ready;
2031
2032         BPFD_LOCK_ASSERT(d);
2033         ready = bpf_ready(d);
2034         if (ready) {
2035                 kn->kn_data = d->bd_slen;
2036                 while (d->bd_hbuf_in_use)
2037                         mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2038                             PRINET, "bd_hbuf", 0);
2039                 if (d->bd_hbuf)
2040                         kn->kn_data += d->bd_hlen;
2041         } else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2042                 callout_reset(&d->bd_callout, d->bd_rtout,
2043                     bpf_timed_out, d);
2044                 d->bd_state = BPF_WAITING;
2045         }
2046
2047         return (ready);
2048 }
2049
2050 #define BPF_TSTAMP_NONE         0
2051 #define BPF_TSTAMP_FAST         1
2052 #define BPF_TSTAMP_NORMAL       2
2053 #define BPF_TSTAMP_EXTERN       3
2054
2055 static int
2056 bpf_ts_quality(int tstype)
2057 {
2058
2059         if (tstype == BPF_T_NONE)
2060                 return (BPF_TSTAMP_NONE);
2061         if ((tstype & BPF_T_FAST) != 0)
2062                 return (BPF_TSTAMP_FAST);
2063
2064         return (BPF_TSTAMP_NORMAL);
2065 }
2066
2067 static int
2068 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
2069 {
2070         struct m_tag *tag;
2071         int quality;
2072
2073         quality = bpf_ts_quality(tstype);
2074         if (quality == BPF_TSTAMP_NONE)
2075                 return (quality);
2076
2077         if (m != NULL) {
2078                 tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2079                 if (tag != NULL) {
2080                         *bt = *(struct bintime *)(tag + 1);
2081                         return (BPF_TSTAMP_EXTERN);
2082                 }
2083         }
2084         if (quality == BPF_TSTAMP_NORMAL)
2085                 binuptime(bt);
2086         else
2087                 getbinuptime(bt);
2088
2089         return (quality);
2090 }
2091
2092 /*
2093  * Incoming linkage from device drivers.  Process the packet pkt, of length
2094  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
2095  * by each process' filter, and if accepted, stashed into the corresponding
2096  * buffer.
2097  */
2098 void
2099 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2100 {
2101         struct bintime bt;
2102         struct bpf_d *d;
2103 #ifdef BPF_JITTER
2104         bpf_jit_filter *bf;
2105 #endif
2106         u_int slen;
2107         int gottime;
2108
2109         gottime = BPF_TSTAMP_NONE;
2110
2111         BPFIF_RLOCK(bp);
2112
2113         LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2114                 /*
2115                  * We are not using any locks for d here because:
2116                  * 1) any filter change is protected by interface
2117                  * write lock
2118                  * 2) destroying/detaching d is protected by interface
2119                  * write lock, too
2120                  */
2121
2122                 /* XXX: Do not protect counter for the sake of performance. */
2123                 ++d->bd_rcount;
2124                 /*
2125                  * NB: We dont call BPF_CHECK_DIRECTION() here since there is no
2126                  * way for the caller to indiciate to us whether this packet
2127                  * is inbound or outbound.  In the bpf_mtap() routines, we use
2128                  * the interface pointers on the mbuf to figure it out.
2129                  */
2130 #ifdef BPF_JITTER
2131                 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2132                 if (bf != NULL)
2133                         slen = (*(bf->func))(pkt, pktlen, pktlen);
2134                 else
2135 #endif
2136                 slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2137                 if (slen != 0) {
2138                         /*
2139                          * Filter matches. Let's to acquire write lock.
2140                          */
2141                         BPFD_LOCK(d);
2142
2143                         d->bd_fcount++;
2144                         if (gottime < bpf_ts_quality(d->bd_tstamp))
2145                                 gottime = bpf_gettime(&bt, d->bd_tstamp, NULL);
2146 #ifdef MAC
2147                         if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2148 #endif
2149                                 catchpacket(d, pkt, pktlen, slen,
2150                                     bpf_append_bytes, &bt);
2151                         BPFD_UNLOCK(d);
2152                 }
2153         }
2154         BPFIF_RUNLOCK(bp);
2155 }
2156
2157 #define BPF_CHECK_DIRECTION(d, r, i)                            \
2158             (((d)->bd_direction == BPF_D_IN && (r) != (i)) ||   \
2159             ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2160
2161 /*
2162  * Incoming linkage from device drivers, when packet is in an mbuf chain.
2163  * Locking model is explained in bpf_tap().
2164  */
2165 void
2166 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2167 {
2168         struct bintime bt;
2169         struct bpf_d *d;
2170 #ifdef BPF_JITTER
2171         bpf_jit_filter *bf;
2172 #endif
2173         u_int pktlen, slen;
2174         int gottime;
2175
2176         /* Skip outgoing duplicate packets. */
2177         if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2178                 m->m_flags &= ~M_PROMISC;
2179                 return;
2180         }
2181
2182         pktlen = m_length(m, NULL);
2183         gottime = BPF_TSTAMP_NONE;
2184
2185         BPFIF_RLOCK(bp);
2186
2187         LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2188                 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2189                         continue;
2190                 ++d->bd_rcount;
2191 #ifdef BPF_JITTER
2192                 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2193                 /* XXX We cannot handle multiple mbufs. */
2194                 if (bf != NULL && m->m_next == NULL)
2195                         slen = (*(bf->func))(mtod(m, u_char *), pktlen, pktlen);
2196                 else
2197 #endif
2198                 slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2199                 if (slen != 0) {
2200                         BPFD_LOCK(d);
2201
2202                         d->bd_fcount++;
2203                         if (gottime < bpf_ts_quality(d->bd_tstamp))
2204                                 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2205 #ifdef MAC
2206                         if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2207 #endif
2208                                 catchpacket(d, (u_char *)m, pktlen, slen,
2209                                     bpf_append_mbuf, &bt);
2210                         BPFD_UNLOCK(d);
2211                 }
2212         }
2213         BPFIF_RUNLOCK(bp);
2214 }
2215
2216 /*
2217  * Incoming linkage from device drivers, when packet is in
2218  * an mbuf chain and to be prepended by a contiguous header.
2219  */
2220 void
2221 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2222 {
2223         struct bintime bt;
2224         struct mbuf mb;
2225         struct bpf_d *d;
2226         u_int pktlen, slen;
2227         int gottime;
2228
2229         /* Skip outgoing duplicate packets. */
2230         if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2231                 m->m_flags &= ~M_PROMISC;
2232                 return;
2233         }
2234
2235         pktlen = m_length(m, NULL);
2236         /*
2237          * Craft on-stack mbuf suitable for passing to bpf_filter.
2238          * Note that we cut corners here; we only setup what's
2239          * absolutely needed--this mbuf should never go anywhere else.
2240          */
2241         mb.m_next = m;
2242         mb.m_data = data;
2243         mb.m_len = dlen;
2244         pktlen += dlen;
2245
2246         gottime = BPF_TSTAMP_NONE;
2247
2248         BPFIF_RLOCK(bp);
2249
2250         LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2251                 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2252                         continue;
2253                 ++d->bd_rcount;
2254                 slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2255                 if (slen != 0) {
2256                         BPFD_LOCK(d);
2257
2258                         d->bd_fcount++;
2259                         if (gottime < bpf_ts_quality(d->bd_tstamp))
2260                                 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2261 #ifdef MAC
2262                         if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2263 #endif
2264                                 catchpacket(d, (u_char *)&mb, pktlen, slen,
2265                                     bpf_append_mbuf, &bt);
2266                         BPFD_UNLOCK(d);
2267                 }
2268         }
2269         BPFIF_RUNLOCK(bp);
2270 }
2271
2272 #undef  BPF_CHECK_DIRECTION
2273
2274 #undef  BPF_TSTAMP_NONE
2275 #undef  BPF_TSTAMP_FAST
2276 #undef  BPF_TSTAMP_NORMAL
2277 #undef  BPF_TSTAMP_EXTERN
2278
2279 static int
2280 bpf_hdrlen(struct bpf_d *d)
2281 {
2282         int hdrlen;
2283
2284         hdrlen = d->bd_bif->bif_hdrlen;
2285 #ifndef BURN_BRIDGES
2286         if (d->bd_tstamp == BPF_T_NONE ||
2287             BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2288 #ifdef COMPAT_FREEBSD32
2289                 if (d->bd_compat32)
2290                         hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2291                 else
2292 #endif
2293                         hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2294         else
2295 #endif
2296                 hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2297 #ifdef COMPAT_FREEBSD32
2298         if (d->bd_compat32)
2299                 hdrlen = BPF_WORDALIGN32(hdrlen);
2300         else
2301 #endif
2302                 hdrlen = BPF_WORDALIGN(hdrlen);
2303
2304         return (hdrlen - d->bd_bif->bif_hdrlen);
2305 }
2306
2307 static void
2308 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2309 {
2310         struct bintime bt2;
2311         struct timeval tsm;
2312         struct timespec tsn;
2313
2314         if ((tstype & BPF_T_MONOTONIC) == 0) {
2315                 bt2 = *bt;
2316                 bintime_add(&bt2, &boottimebin);
2317                 bt = &bt2;
2318         }
2319         switch (BPF_T_FORMAT(tstype)) {
2320         case BPF_T_MICROTIME:
2321                 bintime2timeval(bt, &tsm);
2322                 ts->bt_sec = tsm.tv_sec;
2323                 ts->bt_frac = tsm.tv_usec;
2324                 break;
2325         case BPF_T_NANOTIME:
2326                 bintime2timespec(bt, &tsn);
2327                 ts->bt_sec = tsn.tv_sec;
2328                 ts->bt_frac = tsn.tv_nsec;
2329                 break;
2330         case BPF_T_BINTIME:
2331                 ts->bt_sec = bt->sec;
2332                 ts->bt_frac = bt->frac;
2333                 break;
2334         }
2335 }
2336
2337 /*
2338  * Move the packet data from interface memory (pkt) into the
2339  * store buffer.  "cpfn" is the routine called to do the actual data
2340  * transfer.  bcopy is passed in to copy contiguous chunks, while
2341  * bpf_append_mbuf is passed in to copy mbuf chains.  In the latter case,
2342  * pkt is really an mbuf.
2343  */
2344 static void
2345 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2346     void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2347     struct bintime *bt)
2348 {
2349         struct bpf_xhdr hdr;
2350 #ifndef BURN_BRIDGES
2351         struct bpf_hdr hdr_old;
2352 #ifdef COMPAT_FREEBSD32
2353         struct bpf_hdr32 hdr32_old;
2354 #endif
2355 #endif
2356         int caplen, curlen, hdrlen, totlen;
2357         int do_wakeup = 0;
2358         int do_timestamp;
2359         int tstype;
2360
2361         BPFD_LOCK_ASSERT(d);
2362
2363         /*
2364          * Detect whether user space has released a buffer back to us, and if
2365          * so, move it from being a hold buffer to a free buffer.  This may
2366          * not be the best place to do it (for example, we might only want to
2367          * run this check if we need the space), but for now it's a reliable
2368          * spot to do it.
2369          */
2370         if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2371                 while (d->bd_hbuf_in_use)
2372                         mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2373                             PRINET, "bd_hbuf", 0);
2374                 d->bd_fbuf = d->bd_hbuf;
2375                 d->bd_hbuf = NULL;
2376                 d->bd_hlen = 0;
2377                 bpf_buf_reclaimed(d);
2378         }
2379
2380         /*
2381          * Figure out how many bytes to move.  If the packet is
2382          * greater or equal to the snapshot length, transfer that
2383          * much.  Otherwise, transfer the whole packet (unless
2384          * we hit the buffer size limit).
2385          */
2386         hdrlen = bpf_hdrlen(d);
2387         totlen = hdrlen + min(snaplen, pktlen);
2388         if (totlen > d->bd_bufsize)
2389                 totlen = d->bd_bufsize;
2390
2391         /*
2392          * Round up the end of the previous packet to the next longword.
2393          *
2394          * Drop the packet if there's no room and no hope of room
2395          * If the packet would overflow the storage buffer or the storage
2396          * buffer is considered immutable by the buffer model, try to rotate
2397          * the buffer and wakeup pending processes.
2398          */
2399 #ifdef COMPAT_FREEBSD32
2400         if (d->bd_compat32)
2401                 curlen = BPF_WORDALIGN32(d->bd_slen);
2402         else
2403 #endif
2404                 curlen = BPF_WORDALIGN(d->bd_slen);
2405         if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2406                 if (d->bd_fbuf == NULL) {
2407                         /*
2408                          * There's no room in the store buffer, and no
2409                          * prospect of room, so drop the packet.  Notify the
2410                          * buffer model.
2411                          */
2412                         bpf_buffull(d);
2413                         ++d->bd_dcount;
2414                         return;
2415                 }
2416                 while (d->bd_hbuf_in_use)
2417                         mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2418                             PRINET, "bd_hbuf", 0);
2419                 ROTATE_BUFFERS(d);
2420                 do_wakeup = 1;
2421                 curlen = 0;
2422         } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2423                 /*
2424                  * Immediate mode is set, or the read timeout has already
2425                  * expired during a select call.  A packet arrived, so the
2426                  * reader should be woken up.
2427                  */
2428                 do_wakeup = 1;
2429         caplen = totlen - hdrlen;
2430         tstype = d->bd_tstamp;
2431         do_timestamp = tstype != BPF_T_NONE;
2432 #ifndef BURN_BRIDGES
2433         if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2434                 struct bpf_ts ts;
2435                 if (do_timestamp)
2436                         bpf_bintime2ts(bt, &ts, tstype);
2437 #ifdef COMPAT_FREEBSD32
2438                 if (d->bd_compat32) {
2439                         bzero(&hdr32_old, sizeof(hdr32_old));
2440                         if (do_timestamp) {
2441                                 hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2442                                 hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2443                         }
2444                         hdr32_old.bh_datalen = pktlen;
2445                         hdr32_old.bh_hdrlen = hdrlen;
2446                         hdr32_old.bh_caplen = caplen;
2447                         bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2448                             sizeof(hdr32_old));
2449                         goto copy;
2450                 }
2451 #endif
2452                 bzero(&hdr_old, sizeof(hdr_old));
2453                 if (do_timestamp) {
2454                         hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2455                         hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2456                 }
2457                 hdr_old.bh_datalen = pktlen;
2458                 hdr_old.bh_hdrlen = hdrlen;
2459                 hdr_old.bh_caplen = caplen;
2460                 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2461                     sizeof(hdr_old));
2462                 goto copy;
2463         }
2464 #endif
2465
2466         /*
2467          * Append the bpf header.  Note we append the actual header size, but
2468          * move forward the length of the header plus padding.
2469          */
2470         bzero(&hdr, sizeof(hdr));
2471         if (do_timestamp)
2472                 bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2473         hdr.bh_datalen = pktlen;
2474         hdr.bh_hdrlen = hdrlen;
2475         hdr.bh_caplen = caplen;
2476         bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2477
2478         /*
2479          * Copy the packet data into the store buffer and update its length.
2480          */
2481 #ifndef BURN_BRIDGES
2482 copy:
2483 #endif
2484         (*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2485         d->bd_slen = curlen + totlen;
2486
2487         if (do_wakeup)
2488                 bpf_wakeup(d);
2489 }
2490
2491 /*
2492  * Free buffers currently in use by a descriptor.
2493  * Called on close.
2494  */
2495 static void
2496 bpf_freed(struct bpf_d *d)
2497 {
2498
2499         /*
2500          * We don't need to lock out interrupts since this descriptor has
2501          * been detached from its interface and it yet hasn't been marked
2502          * free.
2503          */
2504         bpf_free(d);
2505         if (d->bd_rfilter != NULL) {
2506                 free((caddr_t)d->bd_rfilter, M_BPF);
2507 #ifdef BPF_JITTER
2508                 if (d->bd_bfilter != NULL)
2509                         bpf_destroy_jit_filter(d->bd_bfilter);
2510 #endif
2511         }
2512         if (d->bd_wfilter != NULL)
2513                 free((caddr_t)d->bd_wfilter, M_BPF);
2514         mtx_destroy(&d->bd_lock);
2515 }
2516
2517 /*
2518  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
2519  * fixed size of the link header (variable length headers not yet supported).
2520  */
2521 void
2522 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2523 {
2524
2525         bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2526 }
2527
2528 /*
2529  * Attach an interface to bpf.  ifp is a pointer to the structure
2530  * defining the interface to be attached, dlt is the link layer type,
2531  * and hdrlen is the fixed size of the link header (variable length
2532  * headers are not yet supporrted).
2533  */
2534 void
2535 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2536 {
2537         struct bpf_if *bp;
2538
2539         bp = malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
2540         if (bp == NULL)
2541                 panic("bpfattach");
2542
2543         LIST_INIT(&bp->bif_dlist);
2544         LIST_INIT(&bp->bif_wlist);
2545         bp->bif_ifp = ifp;
2546         bp->bif_dlt = dlt;
2547         rw_init(&bp->bif_lock, "bpf interface lock");
2548         KASSERT(*driverp == NULL, ("bpfattach2: driverp already initialized"));
2549         *driverp = bp;
2550
2551         BPF_LOCK();
2552         LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2553         BPF_UNLOCK();
2554
2555         bp->bif_hdrlen = hdrlen;
2556
2557         if (bootverbose)
2558                 if_printf(ifp, "bpf attached\n");
2559 }
2560
2561 /*
2562  * Detach bpf from an interface. This involves detaching each descriptor
2563  * associated with the interface. Notify each descriptor as it's detached
2564  * so that any sleepers wake up and get ENXIO.
2565  */
2566 void
2567 bpfdetach(struct ifnet *ifp)
2568 {
2569         struct bpf_if   *bp;
2570         struct bpf_d    *d;
2571 #ifdef INVARIANTS
2572         int ndetached;
2573
2574         ndetached = 0;
2575 #endif
2576
2577         BPF_LOCK();
2578         /* Find all bpf_if struct's which reference ifp and detach them. */
2579         do {
2580                 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2581                         if (ifp == bp->bif_ifp)
2582                                 break;
2583                 }
2584                 if (bp != NULL)
2585                         LIST_REMOVE(bp, bif_next);
2586
2587                 if (bp != NULL) {
2588 #ifdef INVARIANTS
2589                         ndetached++;
2590 #endif
2591                         while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
2592                                 bpf_detachd_locked(d);
2593                                 BPFD_LOCK(d);
2594                                 bpf_wakeup(d);
2595                                 BPFD_UNLOCK(d);
2596                         }
2597                         /* Free writer-only descriptors */
2598                         while ((d = LIST_FIRST(&bp->bif_wlist)) != NULL) {
2599                                 bpf_detachd_locked(d);
2600                                 BPFD_LOCK(d);
2601                                 bpf_wakeup(d);
2602                                 BPFD_UNLOCK(d);
2603                         }
2604
2605                         /*
2606                          * Delay freing bp till interface is detached
2607                          * and all routes through this interface are removed.
2608                          * Mark bp as detached to restrict new consumers.
2609                          */
2610                         BPFIF_WLOCK(bp);
2611                         bp->flags |= BPFIF_FLAG_DYING;
2612                         BPFIF_WUNLOCK(bp);
2613                 }
2614         } while (bp != NULL);
2615         BPF_UNLOCK();
2616
2617 #ifdef INVARIANTS
2618         if (ndetached == 0)
2619                 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
2620 #endif
2621 }
2622
2623 /*
2624  * Interface departure handler.
2625  * Note departure event does not guarantee interface is going down.
2626  */
2627 static void
2628 bpf_ifdetach(void *arg __unused, struct ifnet *ifp)
2629 {
2630         struct bpf_if *bp;
2631
2632         BPF_LOCK();
2633         if ((bp = ifp->if_bpf) == NULL) {
2634                 BPF_UNLOCK();
2635                 return;
2636         }
2637
2638         /* Check if bpfdetach() was called previously */
2639         if ((bp->flags & BPFIF_FLAG_DYING) == 0) {
2640                 BPF_UNLOCK();
2641                 return;
2642         }
2643
2644         CTR3(KTR_NET, "%s: freing BPF instance %p for interface %p",
2645             __func__, bp, ifp);
2646
2647         ifp->if_bpf = NULL;
2648         BPF_UNLOCK();
2649
2650         rw_destroy(&bp->bif_lock);
2651         free(bp, M_BPF);
2652 }
2653
2654 /*
2655  * Get a list of available data link type of the interface.
2656  */
2657 static int
2658 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2659 {
2660         int n, error;
2661         struct ifnet *ifp;
2662         struct bpf_if *bp;
2663
2664         BPF_LOCK_ASSERT();
2665
2666         ifp = d->bd_bif->bif_ifp;
2667         n = 0;
2668         error = 0;
2669         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2670                 if (bp->bif_ifp != ifp)
2671                         continue;
2672                 if (bfl->bfl_list != NULL) {
2673                         if (n >= bfl->bfl_len)
2674                                 return (ENOMEM);
2675                         error = copyout(&bp->bif_dlt,
2676                             bfl->bfl_list + n, sizeof(u_int));
2677                 }
2678                 n++;
2679         }
2680         bfl->bfl_len = n;
2681         return (error);
2682 }
2683
2684 /*
2685  * Set the data link type of a BPF instance.
2686  */
2687 static int
2688 bpf_setdlt(struct bpf_d *d, u_int dlt)
2689 {
2690         int error, opromisc;
2691         struct ifnet *ifp;
2692         struct bpf_if *bp;
2693
2694         BPF_LOCK_ASSERT();
2695
2696         if (d->bd_bif->bif_dlt == dlt)
2697                 return (0);
2698         ifp = d->bd_bif->bif_ifp;
2699
2700         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2701                 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2702                         break;
2703         }
2704
2705         if (bp != NULL) {
2706                 opromisc = d->bd_promisc;
2707                 bpf_attachd(d, bp);
2708                 BPFD_LOCK(d);
2709                 reset_d(d);
2710                 BPFD_UNLOCK(d);
2711                 if (opromisc) {
2712                         error = ifpromisc(bp->bif_ifp, 1);
2713                         if (error)
2714                                 if_printf(bp->bif_ifp,
2715                                         "bpf_setdlt: ifpromisc failed (%d)\n",
2716                                         error);
2717                         else
2718                                 d->bd_promisc = 1;
2719                 }
2720         }
2721         return (bp == NULL ? EINVAL : 0);
2722 }
2723
2724 static void
2725 bpf_drvinit(void *unused)
2726 {
2727         struct cdev *dev;
2728
2729         mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
2730         LIST_INIT(&bpf_iflist);
2731
2732         dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2733         /* For compatibility */
2734         make_dev_alias(dev, "bpf0");
2735
2736         /* Register interface departure handler */
2737         bpf_ifdetach_cookie = EVENTHANDLER_REGISTER(
2738                     ifnet_departure_event, bpf_ifdetach, NULL,
2739                     EVENTHANDLER_PRI_ANY);
2740 }
2741
2742 /*
2743  * Zero out the various packet counters associated with all of the bpf
2744  * descriptors.  At some point, we will probably want to get a bit more
2745  * granular and allow the user to specify descriptors to be zeroed.
2746  */
2747 static void
2748 bpf_zero_counters(void)
2749 {
2750         struct bpf_if *bp;
2751         struct bpf_d *bd;
2752
2753         BPF_LOCK();
2754         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2755                 BPFIF_RLOCK(bp);
2756                 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2757                         BPFD_LOCK(bd);
2758                         bd->bd_rcount = 0;
2759                         bd->bd_dcount = 0;
2760                         bd->bd_fcount = 0;
2761                         bd->bd_wcount = 0;
2762                         bd->bd_wfcount = 0;
2763                         bd->bd_zcopy = 0;
2764                         BPFD_UNLOCK(bd);
2765                 }
2766                 BPFIF_RUNLOCK(bp);
2767         }
2768         BPF_UNLOCK();
2769 }
2770
2771 /*
2772  * Fill filter statistics
2773  */
2774 static void
2775 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2776 {
2777
2778         bzero(d, sizeof(*d));
2779         BPFD_LOCK_ASSERT(bd);
2780         d->bd_structsize = sizeof(*d);
2781         /* XXX: reading should be protected by global lock */
2782         d->bd_immediate = bd->bd_immediate;
2783         d->bd_promisc = bd->bd_promisc;
2784         d->bd_hdrcmplt = bd->bd_hdrcmplt;
2785         d->bd_direction = bd->bd_direction;
2786         d->bd_feedback = bd->bd_feedback;
2787         d->bd_async = bd->bd_async;
2788         d->bd_rcount = bd->bd_rcount;
2789         d->bd_dcount = bd->bd_dcount;
2790         d->bd_fcount = bd->bd_fcount;
2791         d->bd_sig = bd->bd_sig;
2792         d->bd_slen = bd->bd_slen;
2793         d->bd_hlen = bd->bd_hlen;
2794         d->bd_bufsize = bd->bd_bufsize;
2795         d->bd_pid = bd->bd_pid;
2796         strlcpy(d->bd_ifname,
2797             bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2798         d->bd_locked = bd->bd_locked;
2799         d->bd_wcount = bd->bd_wcount;
2800         d->bd_wdcount = bd->bd_wdcount;
2801         d->bd_wfcount = bd->bd_wfcount;
2802         d->bd_zcopy = bd->bd_zcopy;
2803         d->bd_bufmode = bd->bd_bufmode;
2804 }
2805
2806 /*
2807  * Handle `netstat -B' stats request
2808  */
2809 static int
2810 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2811 {
2812         static const struct xbpf_d zerostats;
2813         struct xbpf_d *xbdbuf, *xbd, tempstats;
2814         int index, error;
2815         struct bpf_if *bp;
2816         struct bpf_d *bd;
2817
2818         /*
2819          * XXX This is not technically correct. It is possible for non
2820          * privileged users to open bpf devices. It would make sense
2821          * if the users who opened the devices were able to retrieve
2822          * the statistics for them, too.
2823          */
2824         error = priv_check(req->td, PRIV_NET_BPF);
2825         if (error)
2826                 return (error);
2827         /*
2828          * Check to see if the user is requesting that the counters be
2829          * zeroed out.  Explicitly check that the supplied data is zeroed,
2830          * as we aren't allowing the user to set the counters currently.
2831          */
2832         if (req->newptr != NULL) {
2833                 if (req->newlen != sizeof(tempstats))
2834                         return (EINVAL);
2835                 memset(&tempstats, 0, sizeof(tempstats));
2836                 error = SYSCTL_IN(req, &tempstats, sizeof(tempstats));
2837                 if (error)
2838                         return (error);
2839                 if (bcmp(&tempstats, &zerostats, sizeof(tempstats)) != 0)
2840                         return (EINVAL);
2841                 bpf_zero_counters();
2842                 return (0);
2843         }
2844         if (req->oldptr == NULL)
2845                 return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
2846         if (bpf_bpfd_cnt == 0)
2847                 return (SYSCTL_OUT(req, 0, 0));
2848         xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
2849         BPF_LOCK();
2850         if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
2851                 BPF_UNLOCK();
2852                 free(xbdbuf, M_BPF);
2853                 return (ENOMEM);
2854         }
2855         index = 0;
2856         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2857                 BPFIF_RLOCK(bp);
2858                 /* Send writers-only first */
2859                 LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
2860                         xbd = &xbdbuf[index++];
2861                         BPFD_LOCK(bd);
2862                         bpfstats_fill_xbpf(xbd, bd);
2863                         BPFD_UNLOCK(bd);
2864                 }
2865                 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2866                         xbd = &xbdbuf[index++];
2867                         BPFD_LOCK(bd);
2868                         bpfstats_fill_xbpf(xbd, bd);
2869                         BPFD_UNLOCK(bd);
2870                 }
2871                 BPFIF_RUNLOCK(bp);
2872         }
2873         BPF_UNLOCK();
2874         error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
2875         free(xbdbuf, M_BPF);
2876         return (error);
2877 }
2878
2879 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
2880
2881 #else /* !DEV_BPF && !NETGRAPH_BPF */
2882 /*
2883  * NOP stubs to allow bpf-using drivers to load and function.
2884  *
2885  * A 'better' implementation would allow the core bpf functionality
2886  * to be loaded at runtime.
2887  */
2888 static struct bpf_if bp_null;
2889
2890 void
2891 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2892 {
2893 }
2894
2895 void
2896 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2897 {
2898 }
2899
2900 void
2901 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
2902 {
2903 }
2904
2905 void
2906 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2907 {
2908
2909         bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2910 }
2911
2912 void
2913 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2914 {
2915
2916         *driverp = &bp_null;
2917 }
2918
2919 void
2920 bpfdetach(struct ifnet *ifp)
2921 {
2922 }
2923
2924 u_int
2925 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
2926 {
2927         return -1;      /* "no filter" behaviour */
2928 }
2929
2930 int
2931 bpf_validate(const struct bpf_insn *f, int len)
2932 {
2933         return 0;               /* false */
2934 }
2935
2936 #endif /* !DEV_BPF && !NETGRAPH_BPF */