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