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