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