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