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