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