bpf.c revision 1.248 1 /* $NetBSD: bpf.c,v 1.248 2022/11/19 08:53:06 yamt Exp $ */
2
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 * static char rcsid[] =
38 * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
39 */
40
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.248 2022/11/19 08:53:06 yamt Exp $");
43
44 #if defined(_KERNEL_OPT)
45 #include "opt_bpf.h"
46 #include "sl.h"
47 #include "opt_net_mpsafe.h"
48 #endif
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/mbuf.h>
53 #include <sys/buf.h>
54 #include <sys/time.h>
55 #include <sys/proc.h>
56 #include <sys/ioctl.h>
57 #include <sys/conf.h>
58 #include <sys/vnode.h>
59 #include <sys/queue.h>
60 #include <sys/stat.h>
61 #include <sys/module.h>
62 #include <sys/atomic.h>
63 #include <sys/cpu.h>
64
65 #include <sys/file.h>
66 #include <sys/filedesc.h>
67 #include <sys/tty.h>
68 #include <sys/uio.h>
69
70 #include <sys/protosw.h>
71 #include <sys/socket.h>
72 #include <sys/errno.h>
73 #include <sys/kernel.h>
74 #include <sys/poll.h>
75 #include <sys/sysctl.h>
76 #include <sys/kauth.h>
77 #include <sys/syslog.h>
78 #include <sys/percpu.h>
79 #include <sys/pserialize.h>
80 #include <sys/lwp.h>
81 #include <sys/xcall.h>
82
83 #include <net/if.h>
84 #include <net/slip.h>
85
86 #include <net/bpf.h>
87 #include <net/bpfdesc.h>
88 #include <net/bpfjit.h>
89
90 #include <net/if_arc.h>
91 #include <net/if_ether.h>
92
93 #include <netinet/in.h>
94 #include <netinet/if_inarp.h>
95
96
97 #include <compat/sys/sockio.h>
98
99 #ifndef BPF_BUFSIZE
100 /*
101 * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
102 * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
103 */
104 # define BPF_BUFSIZE 32768
105 #endif
106
107 #define PRINET 26 /* interruptible */
108
109 /*
110 * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
111 * XXX the default values should be computed dynamically based
112 * on available memory size and available mbuf clusters.
113 */
114 static int bpf_bufsize = BPF_BUFSIZE;
115 static int bpf_maxbufsize = BPF_DFLTBUFSIZE; /* XXX set dynamically, see above */
116 static bool bpf_jit = false;
117
118 struct bpfjit_ops bpfjit_module_ops = {
119 .bj_generate_code = NULL,
120 .bj_free_code = NULL
121 };
122
123 /*
124 * Global BPF statistics returned by net.bpf.stats sysctl.
125 */
126 static struct percpu *bpf_gstats_percpu; /* struct bpf_stat */
127
128 #define BPF_STATINC(id) \
129 { \
130 struct bpf_stat *__stats = \
131 percpu_getref(bpf_gstats_percpu); \
132 __stats->bs_##id++; \
133 percpu_putref(bpf_gstats_percpu); \
134 }
135
136 /*
137 * Locking notes:
138 * - bpf_mtx (adaptive mutex) protects:
139 * - Gobal lists: bpf_iflist and bpf_dlist
140 * - struct bpf_if
141 * - bpf_close
142 * - bpf_psz (pserialize)
143 * - struct bpf_d has two mutexes:
144 * - bd_buf_mtx (spin mutex) protects the buffers that can be accessed
145 * on packet tapping
146 * - bd_mtx (adaptive mutex) protects member variables other than the buffers
147 * - Locking order: bpf_mtx => bpf_d#bd_mtx => bpf_d#bd_buf_mtx
148 * - struct bpf_d obtained via fp->f_bpf in bpf_read and bpf_write is
149 * never freed because struct bpf_d is only freed in bpf_close and
150 * bpf_close never be called while executing bpf_read and bpf_write
151 * - A filter that is assigned to bpf_d can be replaced with another filter
152 * while tapping packets, so it needs to be done atomically
153 * - struct bpf_d is iterated on bpf_dlist with psz
154 * - struct bpf_if is iterated on bpf_iflist with psz or psref
155 */
156 /*
157 * Use a mutex to avoid a race condition between gathering the stats/peers
158 * and opening/closing the device.
159 */
160 static kmutex_t bpf_mtx;
161
162 static struct psref_class *bpf_psref_class __read_mostly;
163 static pserialize_t bpf_psz;
164
165 static inline void
166 bpf_if_acquire(struct bpf_if *bp, struct psref *psref)
167 {
168
169 psref_acquire(psref, &bp->bif_psref, bpf_psref_class);
170 }
171
172 static inline void
173 bpf_if_release(struct bpf_if *bp, struct psref *psref)
174 {
175
176 psref_release(psref, &bp->bif_psref, bpf_psref_class);
177 }
178
179 /*
180 * bpf_iflist is the list of interfaces; each corresponds to an ifnet
181 * bpf_dtab holds the descriptors, indexed by minor device #
182 */
183 static struct pslist_head bpf_iflist;
184 static struct pslist_head bpf_dlist;
185
186 /* Macros for bpf_d on bpf_dlist */
187 #define BPF_DLIST_WRITER_INSERT_HEAD(__d) \
188 PSLIST_WRITER_INSERT_HEAD(&bpf_dlist, (__d), bd_bpf_dlist_entry)
189 #define BPF_DLIST_READER_FOREACH(__d) \
190 PSLIST_READER_FOREACH((__d), &bpf_dlist, struct bpf_d, \
191 bd_bpf_dlist_entry)
192 #define BPF_DLIST_WRITER_FOREACH(__d) \
193 PSLIST_WRITER_FOREACH((__d), &bpf_dlist, struct bpf_d, \
194 bd_bpf_dlist_entry)
195 #define BPF_DLIST_ENTRY_INIT(__d) \
196 PSLIST_ENTRY_INIT((__d), bd_bpf_dlist_entry)
197 #define BPF_DLIST_WRITER_REMOVE(__d) \
198 PSLIST_WRITER_REMOVE((__d), bd_bpf_dlist_entry)
199 #define BPF_DLIST_ENTRY_DESTROY(__d) \
200 PSLIST_ENTRY_DESTROY((__d), bd_bpf_dlist_entry)
201
202 /* Macros for bpf_if on bpf_iflist */
203 #define BPF_IFLIST_WRITER_INSERT_HEAD(__bp) \
204 PSLIST_WRITER_INSERT_HEAD(&bpf_iflist, (__bp), bif_iflist_entry)
205 #define BPF_IFLIST_READER_FOREACH(__bp) \
206 PSLIST_READER_FOREACH((__bp), &bpf_iflist, struct bpf_if, \
207 bif_iflist_entry)
208 #define BPF_IFLIST_WRITER_FOREACH(__bp) \
209 PSLIST_WRITER_FOREACH((__bp), &bpf_iflist, struct bpf_if, \
210 bif_iflist_entry)
211 #define BPF_IFLIST_WRITER_REMOVE(__bp) \
212 PSLIST_WRITER_REMOVE((__bp), bif_iflist_entry)
213 #define BPF_IFLIST_ENTRY_INIT(__bp) \
214 PSLIST_ENTRY_INIT((__bp), bif_iflist_entry)
215 #define BPF_IFLIST_ENTRY_DESTROY(__bp) \
216 PSLIST_ENTRY_DESTROY((__bp), bif_iflist_entry)
217
218 /* Macros for bpf_d on bpf_if#bif_dlist_pslist */
219 #define BPFIF_DLIST_READER_FOREACH(__d, __bp) \
220 PSLIST_READER_FOREACH((__d), &(__bp)->bif_dlist_head, struct bpf_d, \
221 bd_bif_dlist_entry)
222 #define BPFIF_DLIST_WRITER_INSERT_HEAD(__bp, __d) \
223 PSLIST_WRITER_INSERT_HEAD(&(__bp)->bif_dlist_head, (__d), \
224 bd_bif_dlist_entry)
225 #define BPFIF_DLIST_WRITER_REMOVE(__d) \
226 PSLIST_WRITER_REMOVE((__d), bd_bif_dlist_entry)
227 #define BPFIF_DLIST_ENTRY_INIT(__d) \
228 PSLIST_ENTRY_INIT((__d), bd_bif_dlist_entry)
229 #define BPFIF_DLIST_READER_EMPTY(__bp) \
230 (PSLIST_READER_FIRST(&(__bp)->bif_dlist_head, struct bpf_d, \
231 bd_bif_dlist_entry) == NULL)
232 #define BPFIF_DLIST_WRITER_EMPTY(__bp) \
233 (PSLIST_WRITER_FIRST(&(__bp)->bif_dlist_head, struct bpf_d, \
234 bd_bif_dlist_entry) == NULL)
235 #define BPFIF_DLIST_ENTRY_DESTROY(__d) \
236 PSLIST_ENTRY_DESTROY((__d), bd_bif_dlist_entry)
237
238 static int bpf_allocbufs(struct bpf_d *);
239 static u_int bpf_xfilter(struct bpf_filter **, void *, u_int, u_int);
240 static void bpf_deliver(struct bpf_if *,
241 void *(*cpfn)(void *, const void *, size_t),
242 void *, u_int, u_int, const u_int);
243 static void bpf_freed(struct bpf_d *);
244 static void bpf_free_filter(struct bpf_filter *);
245 static void bpf_ifname(struct ifnet *, struct ifreq *);
246 static void *bpf_mcpy(void *, const void *, size_t);
247 static int bpf_movein(struct uio *, int, uint64_t,
248 struct mbuf **, struct sockaddr *,
249 struct bpf_filter **);
250 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
251 static void bpf_detachd(struct bpf_d *);
252 static int bpf_setif(struct bpf_d *, struct ifreq *);
253 static int bpf_setf(struct bpf_d *, struct bpf_program *, u_long);
254 static void bpf_timed_out(void *);
255 static inline void
256 bpf_wakeup(struct bpf_d *);
257 static int bpf_hdrlen(struct bpf_d *);
258 static void catchpacket(struct bpf_d *, u_char *, u_int, u_int,
259 void *(*)(void *, const void *, size_t), struct timespec *);
260 static void reset_d(struct bpf_d *);
261 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
262 static int bpf_setdlt(struct bpf_d *, u_int);
263
264 static int bpf_read(struct file *, off_t *, struct uio *, kauth_cred_t,
265 int);
266 static int bpf_write(struct file *, off_t *, struct uio *, kauth_cred_t,
267 int);
268 static int bpf_ioctl(struct file *, u_long, void *);
269 static int bpf_poll(struct file *, int);
270 static int bpf_stat(struct file *, struct stat *);
271 static int bpf_close(struct file *);
272 static int bpf_kqfilter(struct file *, struct knote *);
273
274 static const struct fileops bpf_fileops = {
275 .fo_name = "bpf",
276 .fo_read = bpf_read,
277 .fo_write = bpf_write,
278 .fo_ioctl = bpf_ioctl,
279 .fo_fcntl = fnullop_fcntl,
280 .fo_poll = bpf_poll,
281 .fo_stat = bpf_stat,
282 .fo_close = bpf_close,
283 .fo_kqfilter = bpf_kqfilter,
284 .fo_restart = fnullop_restart,
285 };
286
287 dev_type_open(bpfopen);
288
289 const struct cdevsw bpf_cdevsw = {
290 .d_open = bpfopen,
291 .d_close = noclose,
292 .d_read = noread,
293 .d_write = nowrite,
294 .d_ioctl = noioctl,
295 .d_stop = nostop,
296 .d_tty = notty,
297 .d_poll = nopoll,
298 .d_mmap = nommap,
299 .d_kqfilter = nokqfilter,
300 .d_discard = nodiscard,
301 .d_flag = D_OTHER | D_MPSAFE
302 };
303
304 bpfjit_func_t
305 bpf_jit_generate(bpf_ctx_t *bc, void *code, size_t size)
306 {
307 struct bpfjit_ops *ops = &bpfjit_module_ops;
308 bpfjit_func_t (*generate_code)(const bpf_ctx_t *,
309 const struct bpf_insn *, size_t);
310
311 generate_code = atomic_load_acquire(&ops->bj_generate_code);
312 if (generate_code != NULL) {
313 return generate_code(bc, code, size);
314 }
315 return NULL;
316 }
317
318 void
319 bpf_jit_freecode(bpfjit_func_t jcode)
320 {
321 KASSERT(bpfjit_module_ops.bj_free_code != NULL);
322 bpfjit_module_ops.bj_free_code(jcode);
323 }
324
325 static int
326 bpf_movein(struct uio *uio, int linktype, uint64_t mtu, struct mbuf **mp,
327 struct sockaddr *sockp, struct bpf_filter **wfilter)
328 {
329 struct mbuf *m, *m0, *n;
330 int error;
331 size_t len;
332 size_t hlen;
333 size_t align;
334 u_int slen;
335
336 /*
337 * Build a sockaddr based on the data link layer type.
338 * We do this at this level because the ethernet header
339 * is copied directly into the data field of the sockaddr.
340 * In the case of SLIP, there is no header and the packet
341 * is forwarded as is.
342 * Also, we are careful to leave room at the front of the mbuf
343 * for the link level header.
344 */
345 switch (linktype) {
346
347 case DLT_SLIP:
348 sockp->sa_family = AF_INET;
349 hlen = 0;
350 align = 0;
351 break;
352
353 case DLT_PPP:
354 sockp->sa_family = AF_UNSPEC;
355 hlen = 0;
356 align = 0;
357 break;
358
359 case DLT_EN10MB:
360 sockp->sa_family = AF_UNSPEC;
361 /* XXX Would MAXLINKHDR be better? */
362 /* 6(dst)+6(src)+2(type) */
363 hlen = sizeof(struct ether_header);
364 align = 2;
365 break;
366
367 case DLT_ARCNET:
368 sockp->sa_family = AF_UNSPEC;
369 hlen = ARC_HDRLEN;
370 align = 5;
371 break;
372
373 case DLT_FDDI:
374 sockp->sa_family = AF_LINK;
375 /* XXX 4(FORMAC)+6(dst)+6(src) */
376 hlen = 16;
377 align = 0;
378 break;
379
380 case DLT_ECONET:
381 sockp->sa_family = AF_UNSPEC;
382 hlen = 6;
383 align = 2;
384 break;
385
386 case DLT_NULL:
387 sockp->sa_family = AF_UNSPEC;
388 hlen = 0;
389 align = 0;
390 break;
391
392 default:
393 return (EIO);
394 }
395
396 len = uio->uio_resid;
397 /*
398 * If there aren't enough bytes for a link level header or the
399 * packet length exceeds the interface mtu, return an error.
400 */
401 if (len - hlen > mtu)
402 return (EMSGSIZE);
403
404 m0 = m = m_gethdr(M_WAIT, MT_DATA);
405 m_reset_rcvif(m);
406 m->m_pkthdr.len = (int)(len - hlen);
407 if (len + align > MHLEN) {
408 m_clget(m, M_WAIT);
409 if ((m->m_flags & M_EXT) == 0) {
410 error = ENOBUFS;
411 goto bad;
412 }
413 }
414
415 /* Insure the data is properly aligned */
416 if (align > 0)
417 m->m_data += align;
418
419 for (;;) {
420 len = M_TRAILINGSPACE(m);
421 if (len > uio->uio_resid)
422 len = uio->uio_resid;
423 error = uiomove(mtod(m, void *), len, uio);
424 if (error)
425 goto bad;
426 m->m_len = len;
427
428 if (uio->uio_resid == 0)
429 break;
430
431 n = m_get(M_WAIT, MT_DATA);
432 m_clget(n, M_WAIT); /* if fails, there is no problem */
433 m->m_next = n;
434 m = n;
435 }
436
437 slen = bpf_xfilter(wfilter, mtod(m, u_char *), len, len);
438 if (slen == 0) {
439 error = EPERM;
440 goto bad;
441 }
442
443 if (hlen != 0) {
444 /* move link level header in the top of mbuf to sa_data */
445 memcpy(sockp->sa_data, mtod(m0, void *), hlen);
446 m0->m_data += hlen;
447 m0->m_len -= hlen;
448 }
449
450 *mp = m0;
451 return (0);
452
453 bad:
454 m_freem(m0);
455 return (error);
456 }
457
458 /*
459 * Attach file to the bpf interface, i.e. make d listen on bp.
460 */
461 static void
462 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
463 {
464 struct bpf_event_tracker *t;
465
466 KASSERT(mutex_owned(&bpf_mtx));
467 KASSERT(mutex_owned(d->bd_mtx));
468 /*
469 * Point d at bp, and add d to the interface's list of listeners.
470 * Finally, point the driver's bpf cookie at the interface so
471 * it will divert packets to bpf.
472 */
473 d->bd_bif = bp;
474 BPFIF_DLIST_WRITER_INSERT_HEAD(bp, d);
475
476 *bp->bif_driverp = bp;
477
478 SLIST_FOREACH(t, &bp->bif_trackers, bet_entries) {
479 t->bet_notify(bp, bp->bif_ifp, bp->bif_dlt,
480 BPF_TRACK_EVENT_ATTACH);
481 }
482 }
483
484 /*
485 * Detach a file from its interface.
486 */
487 static void
488 bpf_detachd(struct bpf_d *d)
489 {
490 struct bpf_if *bp;
491 struct bpf_event_tracker *t;
492
493 KASSERT(mutex_owned(&bpf_mtx));
494 KASSERT(mutex_owned(d->bd_mtx));
495
496 bp = d->bd_bif;
497 /*
498 * Check if this descriptor had requested promiscuous mode.
499 * If so, turn it off.
500 */
501 if (d->bd_promisc) {
502 int error __diagused;
503
504 d->bd_promisc = 0;
505 /*
506 * Take device out of promiscuous mode. Since we were
507 * able to enter promiscuous mode, we should be able
508 * to turn it off. But we can get an error if
509 * the interface was configured down, so only panic
510 * if we don't get an unexpected error.
511 */
512 KERNEL_LOCK_UNLESS_NET_MPSAFE();
513 error = ifpromisc(bp->bif_ifp, 0);
514 KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
515 #ifdef DIAGNOSTIC
516 if (error)
517 printf("%s: ifpromisc failed: %d", __func__, error);
518 #endif
519 }
520
521 /* Remove d from the interface's descriptor list. */
522 BPFIF_DLIST_WRITER_REMOVE(d);
523
524 pserialize_perform(bpf_psz);
525
526 if (BPFIF_DLIST_WRITER_EMPTY(bp)) {
527 /*
528 * Let the driver know that there are no more listeners.
529 */
530 *d->bd_bif->bif_driverp = NULL;
531 }
532
533 d->bd_bif = NULL;
534
535 SLIST_FOREACH(t, &bp->bif_trackers, bet_entries) {
536 t->bet_notify(bp, bp->bif_ifp, bp->bif_dlt,
537 BPF_TRACK_EVENT_DETACH);
538 }
539 }
540
541 static void
542 bpf_init(void)
543 {
544
545 mutex_init(&bpf_mtx, MUTEX_DEFAULT, IPL_NONE);
546 bpf_psz = pserialize_create();
547 bpf_psref_class = psref_class_create("bpf", IPL_SOFTNET);
548
549 PSLIST_INIT(&bpf_iflist);
550 PSLIST_INIT(&bpf_dlist);
551
552 bpf_gstats_percpu = percpu_alloc(sizeof(struct bpf_stat));
553
554 return;
555 }
556
557 /*
558 * bpfilterattach() is called at boot time. We don't need to do anything
559 * here, since any initialization will happen as part of module init code.
560 */
561 /* ARGSUSED */
562 void
563 bpfilterattach(int n)
564 {
565
566 }
567
568 /*
569 * Open ethernet device. Clones.
570 */
571 /* ARGSUSED */
572 int
573 bpfopen(dev_t dev, int flag, int mode, struct lwp *l)
574 {
575 struct bpf_d *d;
576 struct file *fp;
577 int error, fd;
578
579 /* falloc() will fill in the descriptor for us. */
580 if ((error = fd_allocfile(&fp, &fd)) != 0)
581 return error;
582
583 d = kmem_zalloc(sizeof(*d), KM_SLEEP);
584 d->bd_bufsize = bpf_bufsize;
585 d->bd_direction = BPF_D_INOUT;
586 d->bd_feedback = 0;
587 d->bd_pid = l->l_proc->p_pid;
588 #ifdef _LP64
589 if (curproc->p_flag & PK_32)
590 d->bd_compat32 = 1;
591 #endif
592 getnanotime(&d->bd_btime);
593 d->bd_atime = d->bd_mtime = d->bd_btime;
594 callout_init(&d->bd_callout, CALLOUT_MPSAFE);
595 selinit(&d->bd_sel);
596 d->bd_jitcode = NULL;
597 d->bd_rfilter = NULL;
598 d->bd_wfilter = NULL;
599 d->bd_locked = 0;
600 BPF_DLIST_ENTRY_INIT(d);
601 BPFIF_DLIST_ENTRY_INIT(d);
602 d->bd_mtx = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
603 d->bd_buf_mtx = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NET);
604 cv_init(&d->bd_cv, "bpf");
605
606 mutex_enter(&bpf_mtx);
607 BPF_DLIST_WRITER_INSERT_HEAD(d);
608 mutex_exit(&bpf_mtx);
609
610 return fd_clone(fp, fd, flag, &bpf_fileops, d);
611 }
612
613 /*
614 * Close the descriptor by detaching it from its interface,
615 * deallocating its buffers, and marking it free.
616 */
617 /* ARGSUSED */
618 static int
619 bpf_close(struct file *fp)
620 {
621 struct bpf_d *d;
622
623 mutex_enter(&bpf_mtx);
624
625 if ((d = fp->f_bpf) == NULL) {
626 mutex_exit(&bpf_mtx);
627 return 0;
628 }
629
630 /*
631 * Refresh the PID associated with this bpf file.
632 */
633 d->bd_pid = curproc->p_pid;
634
635 mutex_enter(d->bd_mtx);
636 if (d->bd_state == BPF_WAITING)
637 callout_halt(&d->bd_callout, d->bd_mtx);
638 d->bd_state = BPF_IDLE;
639 if (d->bd_bif)
640 bpf_detachd(d);
641 mutex_exit(d->bd_mtx);
642
643 BPF_DLIST_WRITER_REMOVE(d);
644
645 pserialize_perform(bpf_psz);
646 mutex_exit(&bpf_mtx);
647
648 BPFIF_DLIST_ENTRY_DESTROY(d);
649 BPF_DLIST_ENTRY_DESTROY(d);
650 fp->f_bpf = NULL;
651 bpf_freed(d);
652 callout_destroy(&d->bd_callout);
653 seldestroy(&d->bd_sel);
654 mutex_obj_free(d->bd_mtx);
655 mutex_obj_free(d->bd_buf_mtx);
656 cv_destroy(&d->bd_cv);
657
658 kmem_free(d, sizeof(*d));
659
660 return (0);
661 }
662
663 /*
664 * Rotate the packet buffers in descriptor d. Move the store buffer
665 * into the hold slot, and the free buffer into the store slot.
666 * Zero the length of the new store buffer.
667 */
668 #define ROTATE_BUFFERS(d) \
669 (d)->bd_hbuf = (d)->bd_sbuf; \
670 (d)->bd_hlen = (d)->bd_slen; \
671 (d)->bd_sbuf = (d)->bd_fbuf; \
672 (d)->bd_slen = 0; \
673 (d)->bd_fbuf = NULL;
674 /*
675 * bpfread - read next chunk of packets from buffers
676 */
677 static int
678 bpf_read(struct file *fp, off_t *offp, struct uio *uio,
679 kauth_cred_t cred, int flags)
680 {
681 struct bpf_d *d = fp->f_bpf;
682 int timed_out;
683 int error;
684
685 /*
686 * Refresh the PID associated with this bpf file.
687 */
688 d->bd_pid = curproc->p_pid;
689
690 getnanotime(&d->bd_atime);
691 /*
692 * Restrict application to use a buffer the same size as
693 * the kernel buffers.
694 */
695 if (uio->uio_resid != d->bd_bufsize)
696 return (EINVAL);
697
698 mutex_enter(d->bd_mtx);
699 if (d->bd_state == BPF_WAITING)
700 callout_halt(&d->bd_callout, d->bd_mtx);
701 timed_out = (d->bd_state == BPF_TIMED_OUT);
702 d->bd_state = BPF_IDLE;
703 mutex_exit(d->bd_mtx);
704 /*
705 * If the hold buffer is empty, then do a timed sleep, which
706 * ends when the timeout expires or when enough packets
707 * have arrived to fill the store buffer.
708 */
709 mutex_enter(d->bd_buf_mtx);
710 while (d->bd_hbuf == NULL) {
711 if (fp->f_flag & FNONBLOCK) {
712 if (d->bd_slen == 0) {
713 error = EWOULDBLOCK;
714 goto out;
715 }
716 ROTATE_BUFFERS(d);
717 break;
718 }
719
720 if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
721 /*
722 * A packet(s) either arrived since the previous
723 * read or arrived while we were asleep.
724 * Rotate the buffers and return what's here.
725 */
726 ROTATE_BUFFERS(d);
727 break;
728 }
729
730 error = cv_timedwait_sig(&d->bd_cv, d->bd_buf_mtx, d->bd_rtout);
731
732 if (error == EINTR || error == ERESTART)
733 goto out;
734
735 if (error == EWOULDBLOCK) {
736 /*
737 * On a timeout, return what's in the buffer,
738 * which may be nothing. If there is something
739 * in the store buffer, we can rotate the buffers.
740 */
741 if (d->bd_hbuf)
742 /*
743 * We filled up the buffer in between
744 * getting the timeout and arriving
745 * here, so we don't need to rotate.
746 */
747 break;
748
749 if (d->bd_slen == 0) {
750 error = 0;
751 goto out;
752 }
753 ROTATE_BUFFERS(d);
754 break;
755 }
756 if (error != 0)
757 goto out;
758 }
759 /*
760 * At this point, we know we have something in the hold slot.
761 */
762 mutex_exit(d->bd_buf_mtx);
763
764 /*
765 * Move data from hold buffer into user space.
766 * We know the entire buffer is transferred since
767 * we checked above that the read buffer is bpf_bufsize bytes.
768 */
769 error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
770
771 mutex_enter(d->bd_buf_mtx);
772 d->bd_fbuf = d->bd_hbuf;
773 d->bd_hbuf = NULL;
774 d->bd_hlen = 0;
775 out:
776 mutex_exit(d->bd_buf_mtx);
777 return (error);
778 }
779
780
781 /*
782 * If there are processes sleeping on this descriptor, wake them up.
783 */
784 static inline void
785 bpf_wakeup(struct bpf_d *d)
786 {
787
788 mutex_enter(d->bd_buf_mtx);
789 cv_broadcast(&d->bd_cv);
790 mutex_exit(d->bd_buf_mtx);
791
792 if (d->bd_async)
793 fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
794 selnotify(&d->bd_sel, 0, 0);
795 }
796
797 static void
798 bpf_timed_out(void *arg)
799 {
800 struct bpf_d *d = arg;
801
802 mutex_enter(d->bd_mtx);
803 if (d->bd_state == BPF_WAITING) {
804 d->bd_state = BPF_TIMED_OUT;
805 if (d->bd_slen != 0)
806 bpf_wakeup(d);
807 }
808 mutex_exit(d->bd_mtx);
809 }
810
811
812 static int
813 bpf_write(struct file *fp, off_t *offp, struct uio *uio,
814 kauth_cred_t cred, int flags)
815 {
816 struct bpf_d *d = fp->f_bpf;
817 struct bpf_if *bp;
818 struct ifnet *ifp;
819 struct mbuf *m, *mc;
820 int error;
821 static struct sockaddr_storage dst;
822 struct psref psref;
823 int bound;
824
825 /*
826 * Refresh the PID associated with this bpf file.
827 */
828 d->bd_pid = curproc->p_pid;
829
830 m = NULL; /* XXX gcc */
831
832 bound = curlwp_bind();
833 mutex_enter(d->bd_mtx);
834 bp = d->bd_bif;
835 if (bp == NULL) {
836 mutex_exit(d->bd_mtx);
837 error = ENXIO;
838 goto out_bindx;
839 }
840 bpf_if_acquire(bp, &psref);
841 mutex_exit(d->bd_mtx);
842
843 getnanotime(&d->bd_mtime);
844
845 ifp = bp->bif_ifp;
846 if (if_is_deactivated(ifp)) {
847 error = ENXIO;
848 goto out;
849 }
850
851 if (uio->uio_resid == 0) {
852 error = 0;
853 goto out;
854 }
855
856 error = bpf_movein(uio, (int)bp->bif_dlt, ifp->if_mtu, &m,
857 (struct sockaddr *) &dst, &d->bd_wfilter);
858 if (error)
859 goto out;
860
861 if (m->m_pkthdr.len > ifp->if_mtu) {
862 m_freem(m);
863 error = EMSGSIZE;
864 goto out;
865 }
866
867 if (d->bd_hdrcmplt)
868 dst.ss_family = pseudo_AF_HDRCMPLT;
869
870 if (d->bd_feedback) {
871 mc = m_dup(m, 0, M_COPYALL, M_NOWAIT);
872 if (mc != NULL)
873 m_set_rcvif(mc, ifp);
874 /* Set M_PROMISC for outgoing packets to be discarded. */
875 if (1 /*d->bd_direction == BPF_D_INOUT*/)
876 m->m_flags |= M_PROMISC;
877 } else
878 mc = NULL;
879
880 error = if_output_lock(ifp, ifp, m, (struct sockaddr *) &dst, NULL);
881
882 if (mc != NULL) {
883 if (error == 0) {
884 int s = splsoftnet();
885 KERNEL_LOCK_UNLESS_IFP_MPSAFE(ifp);
886 ifp->_if_input(ifp, mc);
887 KERNEL_UNLOCK_UNLESS_IFP_MPSAFE(ifp);
888 splx(s);
889 } else
890 m_freem(mc);
891 }
892 /*
893 * The driver frees the mbuf.
894 */
895 out:
896 bpf_if_release(bp, &psref);
897 out_bindx:
898 curlwp_bindx(bound);
899 return error;
900 }
901
902 /*
903 * Reset a descriptor by flushing its packet buffer and clearing the
904 * receive and drop counts.
905 */
906 static void
907 reset_d(struct bpf_d *d)
908 {
909
910 KASSERT(mutex_owned(d->bd_mtx));
911
912 mutex_enter(d->bd_buf_mtx);
913 if (d->bd_hbuf) {
914 /* Free the hold buffer. */
915 d->bd_fbuf = d->bd_hbuf;
916 d->bd_hbuf = NULL;
917 }
918 d->bd_slen = 0;
919 d->bd_hlen = 0;
920 d->bd_rcount = 0;
921 d->bd_dcount = 0;
922 d->bd_ccount = 0;
923 mutex_exit(d->bd_buf_mtx);
924 }
925
926 /*
927 * FIONREAD Check for read packet available.
928 * BIOCGBLEN Get buffer len [for read()].
929 * BIOCSETF Set ethernet read filter.
930 * BIOCFLUSH Flush read packet buffer.
931 * BIOCPROMISC Put interface into promiscuous mode.
932 * BIOCGDLT Get link layer type.
933 * BIOCGETIF Get interface name.
934 * BIOCSETIF Set interface.
935 * BIOCSRTIMEOUT Set read timeout.
936 * BIOCGRTIMEOUT Get read timeout.
937 * BIOCGSTATS Get packet stats.
938 * BIOCIMMEDIATE Set immediate mode.
939 * BIOCVERSION Get filter language version.
940 * BIOCGHDRCMPLT Get "header already complete" flag.
941 * BIOCSHDRCMPLT Set "header already complete" flag.
942 * BIOCSFEEDBACK Set packet feedback mode.
943 * BIOCGFEEDBACK Get packet feedback mode.
944 * BIOCGDIRECTION Get packet direction flag
945 * BIOCSDIRECTION Set packet direction flag
946 */
947 /* ARGSUSED */
948 static int
949 bpf_ioctl(struct file *fp, u_long cmd, void *addr)
950 {
951 struct bpf_d *d = fp->f_bpf;
952 int error = 0;
953
954 /*
955 * Refresh the PID associated with this bpf file.
956 */
957 d->bd_pid = curproc->p_pid;
958 #ifdef _LP64
959 if (curproc->p_flag & PK_32)
960 d->bd_compat32 = 1;
961 else
962 d->bd_compat32 = 0;
963 #endif
964
965 mutex_enter(d->bd_mtx);
966 if (d->bd_state == BPF_WAITING)
967 callout_halt(&d->bd_callout, d->bd_mtx);
968 d->bd_state = BPF_IDLE;
969 mutex_exit(d->bd_mtx);
970
971 if (d->bd_locked) {
972 switch (cmd) {
973 case BIOCGBLEN: /* FALLTHROUGH */
974 case BIOCFLUSH: /* FALLTHROUGH */
975 case BIOCGDLT: /* FALLTHROUGH */
976 case BIOCGDLTLIST: /* FALLTHROUGH */
977 case BIOCGETIF: /* FALLTHROUGH */
978 case BIOCGRTIMEOUT: /* FALLTHROUGH */
979 case BIOCGSTATS: /* FALLTHROUGH */
980 case BIOCVERSION: /* FALLTHROUGH */
981 case BIOCGHDRCMPLT: /* FALLTHROUGH */
982 case FIONREAD: /* FALLTHROUGH */
983 case BIOCLOCK: /* FALLTHROUGH */
984 case BIOCSRTIMEOUT: /* FALLTHROUGH */
985 case BIOCIMMEDIATE: /* FALLTHROUGH */
986 case TIOCGPGRP:
987 break;
988 default:
989 return EPERM;
990 }
991 }
992
993 switch (cmd) {
994
995 default:
996 error = EINVAL;
997 break;
998
999 /*
1000 * Check for read packet available.
1001 */
1002 case FIONREAD:
1003 {
1004 int n;
1005
1006 mutex_enter(d->bd_buf_mtx);
1007 n = d->bd_slen;
1008 if (d->bd_hbuf)
1009 n += d->bd_hlen;
1010 mutex_exit(d->bd_buf_mtx);
1011
1012 *(int *)addr = n;
1013 break;
1014 }
1015
1016 /*
1017 * Get buffer len [for read()].
1018 */
1019 case BIOCGBLEN:
1020 *(u_int *)addr = d->bd_bufsize;
1021 break;
1022
1023 /*
1024 * Set buffer length.
1025 */
1026 case BIOCSBLEN:
1027 /*
1028 * Forbid to change the buffer length if buffers are already
1029 * allocated.
1030 */
1031 mutex_enter(d->bd_mtx);
1032 mutex_enter(d->bd_buf_mtx);
1033 if (d->bd_bif != NULL || d->bd_sbuf != NULL)
1034 error = EINVAL;
1035 else {
1036 u_int size = *(u_int *)addr;
1037
1038 if (size > bpf_maxbufsize)
1039 *(u_int *)addr = size = bpf_maxbufsize;
1040 else if (size < BPF_MINBUFSIZE)
1041 *(u_int *)addr = size = BPF_MINBUFSIZE;
1042 d->bd_bufsize = size;
1043 }
1044 mutex_exit(d->bd_buf_mtx);
1045 mutex_exit(d->bd_mtx);
1046 break;
1047
1048 /*
1049 * Set link layer read filter.
1050 */
1051 case BIOCSETF: /* FALLTHROUGH */
1052 case BIOCSETWF:
1053 error = bpf_setf(d, addr, cmd);
1054 break;
1055
1056 case BIOCLOCK:
1057 d->bd_locked = 1;
1058 break;
1059
1060 /*
1061 * Flush read packet buffer.
1062 */
1063 case BIOCFLUSH:
1064 mutex_enter(d->bd_mtx);
1065 reset_d(d);
1066 mutex_exit(d->bd_mtx);
1067 break;
1068
1069 /*
1070 * Put interface into promiscuous mode.
1071 */
1072 case BIOCPROMISC:
1073 mutex_enter(d->bd_mtx);
1074 if (d->bd_bif == NULL) {
1075 mutex_exit(d->bd_mtx);
1076 /*
1077 * No interface attached yet.
1078 */
1079 error = EINVAL;
1080 break;
1081 }
1082 if (d->bd_promisc == 0) {
1083 KERNEL_LOCK_UNLESS_NET_MPSAFE();
1084 error = ifpromisc(d->bd_bif->bif_ifp, 1);
1085 KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
1086 if (error == 0)
1087 d->bd_promisc = 1;
1088 }
1089 mutex_exit(d->bd_mtx);
1090 break;
1091
1092 /*
1093 * Get device parameters.
1094 */
1095 case BIOCGDLT:
1096 mutex_enter(d->bd_mtx);
1097 if (d->bd_bif == NULL)
1098 error = EINVAL;
1099 else
1100 *(u_int *)addr = d->bd_bif->bif_dlt;
1101 mutex_exit(d->bd_mtx);
1102 break;
1103
1104 /*
1105 * Get a list of supported device parameters.
1106 */
1107 case BIOCGDLTLIST:
1108 mutex_enter(d->bd_mtx);
1109 if (d->bd_bif == NULL)
1110 error = EINVAL;
1111 else
1112 error = bpf_getdltlist(d, addr);
1113 mutex_exit(d->bd_mtx);
1114 break;
1115
1116 /*
1117 * Set device parameters.
1118 */
1119 case BIOCSDLT:
1120 mutex_enter(&bpf_mtx);
1121 mutex_enter(d->bd_mtx);
1122 if (d->bd_bif == NULL)
1123 error = EINVAL;
1124 else
1125 error = bpf_setdlt(d, *(u_int *)addr);
1126 mutex_exit(d->bd_mtx);
1127 mutex_exit(&bpf_mtx);
1128 break;
1129
1130 /*
1131 * Set interface name.
1132 */
1133 #ifdef OBIOCGETIF
1134 case OBIOCGETIF:
1135 #endif
1136 case BIOCGETIF:
1137 mutex_enter(d->bd_mtx);
1138 if (d->bd_bif == NULL)
1139 error = EINVAL;
1140 else
1141 bpf_ifname(d->bd_bif->bif_ifp, addr);
1142 mutex_exit(d->bd_mtx);
1143 break;
1144
1145 /*
1146 * Set interface.
1147 */
1148 #ifdef OBIOCSETIF
1149 case OBIOCSETIF:
1150 #endif
1151 case BIOCSETIF:
1152 mutex_enter(&bpf_mtx);
1153 error = bpf_setif(d, addr);
1154 mutex_exit(&bpf_mtx);
1155 break;
1156
1157 /*
1158 * Set read timeout.
1159 */
1160 case BIOCSRTIMEOUT:
1161 {
1162 struct timeval *tv = addr;
1163
1164 /* Compute number of ticks. */
1165 if (tv->tv_sec < 0 ||
1166 tv->tv_usec < 0 || tv->tv_usec >= 1000000) {
1167 error = EINVAL;
1168 break;
1169 } else if (tv->tv_sec > INT_MAX/hz - 1) {
1170 d->bd_rtout = INT_MAX;
1171 } else {
1172 d->bd_rtout = tv->tv_sec * hz
1173 + tv->tv_usec / tick;
1174 }
1175 if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
1176 d->bd_rtout = 1;
1177 break;
1178 }
1179
1180 #ifdef BIOCGORTIMEOUT
1181 /*
1182 * Get read timeout.
1183 */
1184 case BIOCGORTIMEOUT:
1185 {
1186 struct timeval50 *tv = addr;
1187
1188 tv->tv_sec = d->bd_rtout / hz;
1189 tv->tv_usec = (d->bd_rtout % hz) * tick;
1190 break;
1191 }
1192 #endif
1193
1194 #ifdef BIOCSORTIMEOUT
1195 /*
1196 * Set read timeout.
1197 */
1198 case BIOCSORTIMEOUT:
1199 {
1200 struct timeval50 *tv = addr;
1201
1202 /* Compute number of ticks. */
1203 if (tv->tv_sec < 0 ||
1204 tv->tv_usec < 0 || tv->tv_usec >= 1000000) {
1205 error = EINVAL;
1206 break;
1207 } else if (tv->tv_sec > INT_MAX/hz - 1) {
1208 d->bd_rtout = INT_MAX;
1209 } else {
1210 d->bd_rtout = tv->tv_sec * hz
1211 + tv->tv_usec / tick;
1212 }
1213 if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
1214 d->bd_rtout = 1;
1215 break;
1216 }
1217 #endif
1218
1219 /*
1220 * Get read timeout.
1221 */
1222 case BIOCGRTIMEOUT:
1223 {
1224 struct timeval *tv = addr;
1225
1226 tv->tv_sec = d->bd_rtout / hz;
1227 tv->tv_usec = (d->bd_rtout % hz) * tick;
1228 break;
1229 }
1230 /*
1231 * Get packet stats.
1232 */
1233 case BIOCGSTATS:
1234 {
1235 struct bpf_stat *bs = addr;
1236
1237 bs->bs_recv = d->bd_rcount;
1238 bs->bs_drop = d->bd_dcount;
1239 bs->bs_capt = d->bd_ccount;
1240 break;
1241 }
1242
1243 case BIOCGSTATSOLD:
1244 {
1245 struct bpf_stat_old *bs = addr;
1246
1247 bs->bs_recv = d->bd_rcount;
1248 bs->bs_drop = d->bd_dcount;
1249 break;
1250 }
1251
1252 /*
1253 * Set immediate mode.
1254 */
1255 case BIOCIMMEDIATE:
1256 d->bd_immediate = *(u_int *)addr;
1257 break;
1258
1259 case BIOCVERSION:
1260 {
1261 struct bpf_version *bv = addr;
1262
1263 bv->bv_major = BPF_MAJOR_VERSION;
1264 bv->bv_minor = BPF_MINOR_VERSION;
1265 break;
1266 }
1267
1268 case BIOCGHDRCMPLT: /* get "header already complete" flag */
1269 *(u_int *)addr = d->bd_hdrcmplt;
1270 break;
1271
1272 case BIOCSHDRCMPLT: /* set "header already complete" flag */
1273 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1274 break;
1275
1276 /*
1277 * Get packet direction flag
1278 */
1279 case BIOCGDIRECTION:
1280 *(u_int *)addr = d->bd_direction;
1281 break;
1282
1283 /*
1284 * Set packet direction flag
1285 */
1286 case BIOCSDIRECTION:
1287 {
1288 u_int direction;
1289
1290 direction = *(u_int *)addr;
1291 switch (direction) {
1292 case BPF_D_IN:
1293 case BPF_D_INOUT:
1294 case BPF_D_OUT:
1295 d->bd_direction = direction;
1296 break;
1297 default:
1298 error = EINVAL;
1299 }
1300 }
1301 break;
1302
1303 /*
1304 * Set "feed packets from bpf back to input" mode
1305 */
1306 case BIOCSFEEDBACK:
1307 d->bd_feedback = *(u_int *)addr;
1308 break;
1309
1310 /*
1311 * Get "feed packets from bpf back to input" mode
1312 */
1313 case BIOCGFEEDBACK:
1314 *(u_int *)addr = d->bd_feedback;
1315 break;
1316
1317 case FIONBIO: /* Non-blocking I/O */
1318 /*
1319 * No need to do anything special as we use IO_NDELAY in
1320 * bpfread() as an indication of whether or not to block
1321 * the read.
1322 */
1323 break;
1324
1325 case FIOASYNC: /* Send signal on receive packets */
1326 mutex_enter(d->bd_mtx);
1327 d->bd_async = *(int *)addr;
1328 mutex_exit(d->bd_mtx);
1329 break;
1330
1331 case TIOCSPGRP: /* Process or group to send signals to */
1332 case FIOSETOWN:
1333 error = fsetown(&d->bd_pgid, cmd, addr);
1334 break;
1335
1336 case TIOCGPGRP:
1337 case FIOGETOWN:
1338 error = fgetown(d->bd_pgid, cmd, addr);
1339 break;
1340 }
1341 return (error);
1342 }
1343
1344 /*
1345 * Set d's packet filter program to fp. If this file already has a filter,
1346 * free it and replace it. Returns EINVAL for bogus requests.
1347 */
1348 static int
1349 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1350 {
1351 struct bpf_insn *fcode;
1352 bpfjit_func_t jcode;
1353 size_t flen, size = 0;
1354 struct bpf_filter *oldf, *newf, **storef;
1355
1356 jcode = NULL;
1357 flen = fp->bf_len;
1358
1359 if ((fp->bf_insns == NULL && flen) || flen > BPF_MAXINSNS) {
1360 return EINVAL;
1361 }
1362
1363 if (flen) {
1364 /*
1365 * Allocate the buffer, copy the byte-code from
1366 * userspace and validate it.
1367 */
1368 size = flen * sizeof(*fp->bf_insns);
1369 fcode = kmem_alloc(size, KM_SLEEP);
1370 if (copyin(fp->bf_insns, fcode, size) != 0 ||
1371 !bpf_validate(fcode, (int)flen)) {
1372 kmem_free(fcode, size);
1373 return EINVAL;
1374 }
1375 if (bpf_jit)
1376 jcode = bpf_jit_generate(NULL, fcode, flen);
1377 } else {
1378 fcode = NULL;
1379 }
1380
1381 newf = kmem_alloc(sizeof(*newf), KM_SLEEP);
1382 newf->bf_insn = fcode;
1383 newf->bf_size = size;
1384 newf->bf_jitcode = jcode;
1385 if (cmd == BIOCSETF)
1386 d->bd_jitcode = jcode; /* XXX just for kvm(3) users */
1387
1388 /* Need to hold bpf_mtx for pserialize_perform */
1389 mutex_enter(&bpf_mtx);
1390 mutex_enter(d->bd_mtx);
1391 if (cmd == BIOCSETWF) {
1392 oldf = d->bd_wfilter;
1393 storef = &d->bd_wfilter;
1394 } else {
1395 oldf = d->bd_rfilter;
1396 storef = &d->bd_rfilter;
1397 }
1398 atomic_store_release(storef, newf);
1399 reset_d(d);
1400 pserialize_perform(bpf_psz);
1401 mutex_exit(d->bd_mtx);
1402 mutex_exit(&bpf_mtx);
1403
1404 if (oldf != NULL)
1405 bpf_free_filter(oldf);
1406
1407 return 0;
1408 }
1409
1410 /*
1411 * Detach a file from its current interface (if attached at all) and attach
1412 * to the interface indicated by the name stored in ifr.
1413 * Return an errno or 0.
1414 */
1415 static int
1416 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1417 {
1418 struct bpf_if *bp;
1419 char *cp;
1420 int unit_seen, i, error;
1421
1422 KASSERT(mutex_owned(&bpf_mtx));
1423 /*
1424 * Make sure the provided name has a unit number, and default
1425 * it to '0' if not specified.
1426 * XXX This is ugly ... do this differently?
1427 */
1428 unit_seen = 0;
1429 cp = ifr->ifr_name;
1430 cp[sizeof(ifr->ifr_name) - 1] = '\0'; /* sanity */
1431 while (*cp++)
1432 if (*cp >= '0' && *cp <= '9')
1433 unit_seen = 1;
1434 if (!unit_seen) {
1435 /* Make sure to leave room for the '\0'. */
1436 for (i = 0; i < (IFNAMSIZ - 1); ++i) {
1437 if ((ifr->ifr_name[i] >= 'a' &&
1438 ifr->ifr_name[i] <= 'z') ||
1439 (ifr->ifr_name[i] >= 'A' &&
1440 ifr->ifr_name[i] <= 'Z'))
1441 continue;
1442 ifr->ifr_name[i] = '0';
1443 }
1444 }
1445
1446 /*
1447 * Look through attached interfaces for the named one.
1448 */
1449 BPF_IFLIST_WRITER_FOREACH(bp) {
1450 struct ifnet *ifp = bp->bif_ifp;
1451
1452 if (ifp == NULL ||
1453 strcmp(ifp->if_xname, ifr->ifr_name) != 0)
1454 continue;
1455 /* skip additional entry */
1456 if (bp->bif_driverp != &ifp->if_bpf)
1457 continue;
1458 /*
1459 * We found the requested interface.
1460 * Allocate the packet buffers if we need to.
1461 * If we're already attached to requested interface,
1462 * just flush the buffer.
1463 */
1464 /*
1465 * bpf_allocbufs is called only here. bpf_mtx ensures that
1466 * no race condition happen on d->bd_sbuf.
1467 */
1468 if (d->bd_sbuf == NULL) {
1469 error = bpf_allocbufs(d);
1470 if (error != 0)
1471 return (error);
1472 }
1473 mutex_enter(d->bd_mtx);
1474 if (bp != d->bd_bif) {
1475 if (d->bd_bif) {
1476 /*
1477 * Detach if attached to something else.
1478 */
1479 bpf_detachd(d);
1480 BPFIF_DLIST_ENTRY_INIT(d);
1481 }
1482
1483 bpf_attachd(d, bp);
1484 }
1485 reset_d(d);
1486 mutex_exit(d->bd_mtx);
1487 return (0);
1488 }
1489 /* Not found. */
1490 return (ENXIO);
1491 }
1492
1493 /*
1494 * Copy the interface name to the ifreq.
1495 */
1496 static void
1497 bpf_ifname(struct ifnet *ifp, struct ifreq *ifr)
1498 {
1499 memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
1500 }
1501
1502 static int
1503 bpf_stat(struct file *fp, struct stat *st)
1504 {
1505 struct bpf_d *d = fp->f_bpf;
1506
1507 (void)memset(st, 0, sizeof(*st));
1508 mutex_enter(d->bd_mtx);
1509 st->st_dev = makedev(cdevsw_lookup_major(&bpf_cdevsw), d->bd_pid);
1510 st->st_atimespec = d->bd_atime;
1511 st->st_mtimespec = d->bd_mtime;
1512 st->st_ctimespec = st->st_birthtimespec = d->bd_btime;
1513 st->st_uid = kauth_cred_geteuid(fp->f_cred);
1514 st->st_gid = kauth_cred_getegid(fp->f_cred);
1515 st->st_mode = S_IFCHR;
1516 mutex_exit(d->bd_mtx);
1517 return 0;
1518 }
1519
1520 /*
1521 * Support for poll() system call
1522 *
1523 * Return true iff the specific operation will not block indefinitely - with
1524 * the assumption that it is safe to positively acknowledge a request for the
1525 * ability to write to the BPF device.
1526 * Otherwise, return false but make a note that a selnotify() must be done.
1527 */
1528 static int
1529 bpf_poll(struct file *fp, int events)
1530 {
1531 struct bpf_d *d = fp->f_bpf;
1532 int revents;
1533
1534 /*
1535 * Refresh the PID associated with this bpf file.
1536 */
1537 mutex_enter(&bpf_mtx);
1538 d->bd_pid = curproc->p_pid;
1539
1540 revents = events & (POLLOUT | POLLWRNORM);
1541 if (events & (POLLIN | POLLRDNORM)) {
1542 /*
1543 * An imitation of the FIONREAD ioctl code.
1544 */
1545 mutex_enter(d->bd_mtx);
1546 if (d->bd_hlen != 0 ||
1547 ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1548 d->bd_slen != 0)) {
1549 revents |= events & (POLLIN | POLLRDNORM);
1550 } else {
1551 selrecord(curlwp, &d->bd_sel);
1552 /* Start the read timeout if necessary */
1553 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1554 callout_reset(&d->bd_callout, d->bd_rtout,
1555 bpf_timed_out, d);
1556 d->bd_state = BPF_WAITING;
1557 }
1558 }
1559 mutex_exit(d->bd_mtx);
1560 }
1561
1562 mutex_exit(&bpf_mtx);
1563 return (revents);
1564 }
1565
1566 static void
1567 filt_bpfrdetach(struct knote *kn)
1568 {
1569 struct bpf_d *d = kn->kn_hook;
1570
1571 mutex_enter(d->bd_buf_mtx);
1572 selremove_knote(&d->bd_sel, kn);
1573 mutex_exit(d->bd_buf_mtx);
1574 }
1575
1576 static int
1577 filt_bpfread(struct knote *kn, long hint)
1578 {
1579 struct bpf_d *d = kn->kn_hook;
1580 int rv;
1581
1582 /*
1583 * Refresh the PID associated with this bpf file.
1584 */
1585 d->bd_pid = curproc->p_pid;
1586
1587 mutex_enter(d->bd_buf_mtx);
1588 kn->kn_data = d->bd_hlen;
1589 if (d->bd_immediate)
1590 kn->kn_data += d->bd_slen;
1591 rv = (kn->kn_data > 0);
1592 mutex_exit(d->bd_buf_mtx);
1593 return rv;
1594 }
1595
1596 static const struct filterops bpfread_filtops = {
1597 .f_flags = FILTEROP_ISFD,
1598 .f_attach = NULL,
1599 .f_detach = filt_bpfrdetach,
1600 .f_event = filt_bpfread,
1601 };
1602
1603 static int
1604 bpf_kqfilter(struct file *fp, struct knote *kn)
1605 {
1606 struct bpf_d *d = fp->f_bpf;
1607
1608 switch (kn->kn_filter) {
1609 case EVFILT_READ:
1610 kn->kn_fop = &bpfread_filtops;
1611 break;
1612
1613 default:
1614 return (EINVAL);
1615 }
1616
1617 kn->kn_hook = d;
1618
1619 mutex_enter(d->bd_buf_mtx);
1620 selrecord_knote(&d->bd_sel, kn);
1621 mutex_exit(d->bd_buf_mtx);
1622
1623 return (0);
1624 }
1625
1626 /*
1627 * Copy data from an mbuf chain into a buffer. This code is derived
1628 * from m_copydata in sys/uipc_mbuf.c.
1629 */
1630 static void *
1631 bpf_mcpy(void *dst_arg, const void *src_arg, size_t len)
1632 {
1633 const struct mbuf *m;
1634 u_int count;
1635 u_char *dst;
1636
1637 m = src_arg;
1638 dst = dst_arg;
1639 while (len > 0) {
1640 if (m == NULL)
1641 panic("bpf_mcpy");
1642 count = uimin(m->m_len, len);
1643 memcpy(dst, mtod(m, const void *), count);
1644 m = m->m_next;
1645 dst += count;
1646 len -= count;
1647 }
1648 return dst_arg;
1649 }
1650
1651 static inline u_int
1652 bpf_xfilter(struct bpf_filter **filter, void *pkt, u_int pktlen, u_int buflen)
1653 {
1654 struct bpf_filter *filt;
1655 uint32_t mem[BPF_MEMWORDS];
1656 bpf_args_t args = {
1657 .pkt = (const uint8_t *)pkt,
1658 .wirelen = pktlen,
1659 .buflen = buflen,
1660 .mem = mem,
1661 .arg = NULL
1662 };
1663 u_int slen;
1664
1665 filt = atomic_load_consume(filter);
1666 if (filt == NULL) /* No filter means accept all. */
1667 return (u_int)-1;
1668
1669 if (filt->bf_jitcode != NULL)
1670 slen = filt->bf_jitcode(NULL, &args);
1671 else
1672 slen = bpf_filter_ext(NULL, filt->bf_insn, &args);
1673 return slen;
1674 }
1675
1676 /*
1677 * Dispatch a packet to all the listeners on interface bp.
1678 *
1679 * pkt pointer to the packet, either a data buffer or an mbuf chain
1680 * buflen buffer length, if pkt is a data buffer
1681 * cpfn a function that can copy pkt into the listener's buffer
1682 * pktlen length of the packet
1683 * direction BPF_D_IN or BPF_D_OUT
1684 */
1685 static inline void
1686 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
1687 void *pkt, u_int pktlen, u_int buflen, const u_int direction)
1688 {
1689 bool gottime = false;
1690 struct timespec ts;
1691 struct bpf_d *d;
1692 int s;
1693 u_int slen;
1694
1695 KASSERT(!cpu_intr_p());
1696
1697 /*
1698 * Note that the IPL does not have to be raised at this point.
1699 * The only problem that could arise here is that if two different
1700 * interfaces shared any data. This is not the case.
1701 */
1702 s = pserialize_read_enter();
1703 BPFIF_DLIST_READER_FOREACH(d, bp) {
1704 if (direction == BPF_D_IN) {
1705 if (d->bd_direction == BPF_D_OUT)
1706 continue;
1707 } else { /* BPF_D_OUT */
1708 if (d->bd_direction == BPF_D_IN)
1709 continue;
1710 }
1711
1712 atomic_inc_ulong(&d->bd_rcount);
1713 BPF_STATINC(recv);
1714
1715 slen = bpf_xfilter(&d->bd_rfilter, pkt, pktlen, buflen);
1716 if (slen == 0)
1717 continue;
1718
1719 if (!gottime) {
1720 gottime = true;
1721 nanotime(&ts);
1722 }
1723 /* Assume catchpacket doesn't sleep */
1724 catchpacket(d, pkt, pktlen, slen, cpfn, &ts);
1725 }
1726 pserialize_read_exit(s);
1727 }
1728
1729 /*
1730 * Incoming linkage from device drivers, when the head of the packet is in
1731 * a buffer, and the tail is in an mbuf chain.
1732 */
1733 static void
1734 _bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m,
1735 u_int direction)
1736 {
1737 u_int pktlen;
1738 struct mbuf mb;
1739
1740 /* Skip outgoing duplicate packets. */
1741 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif_index == 0) {
1742 m->m_flags &= ~M_PROMISC;
1743 return;
1744 }
1745
1746 pktlen = m_length(m) + dlen;
1747
1748 /*
1749 * Craft on-stack mbuf suitable for passing to bpf_filter.
1750 * Note that we cut corners here; we only setup what's
1751 * absolutely needed--this mbuf should never go anywhere else.
1752 */
1753 (void)memset(&mb, 0, sizeof(mb));
1754 mb.m_type = MT_DATA;
1755 mb.m_next = m;
1756 mb.m_data = data;
1757 mb.m_len = dlen;
1758
1759 bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, direction);
1760 }
1761
1762 /*
1763 * Incoming linkage from device drivers, when packet is in an mbuf chain.
1764 */
1765 static void
1766 _bpf_mtap(struct bpf_if *bp, struct mbuf *m, u_int direction)
1767 {
1768 void *(*cpfn)(void *, const void *, size_t);
1769 u_int pktlen, buflen;
1770 void *marg;
1771
1772 /* Skip outgoing duplicate packets. */
1773 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif_index == 0) {
1774 m->m_flags &= ~M_PROMISC;
1775 return;
1776 }
1777
1778 pktlen = m_length(m);
1779
1780 /* Skip zero-sized packets. */
1781 if (__predict_false(pktlen == 0)) {
1782 return;
1783 }
1784
1785 if (pktlen == m->m_len) {
1786 cpfn = (void *)memcpy;
1787 marg = mtod(m, void *);
1788 buflen = pktlen;
1789 KASSERT(buflen != 0);
1790 } else {
1791 cpfn = bpf_mcpy;
1792 marg = m;
1793 buflen = 0;
1794 }
1795
1796 bpf_deliver(bp, cpfn, marg, pktlen, buflen, direction);
1797 }
1798
1799 /*
1800 * We need to prepend the address family as
1801 * a four byte field. Cons up a dummy header
1802 * to pacify bpf. This is safe because bpf
1803 * will only read from the mbuf (i.e., it won't
1804 * try to free it or keep a pointer a to it).
1805 */
1806 static void
1807 _bpf_mtap_af(struct bpf_if *bp, uint32_t af, struct mbuf *m, u_int direction)
1808 {
1809 struct mbuf m0;
1810
1811 m0.m_type = MT_DATA;
1812 m0.m_flags = 0;
1813 m0.m_next = m;
1814 m0.m_nextpkt = NULL;
1815 m0.m_owner = NULL;
1816 m0.m_len = 4;
1817 m0.m_data = (char *)⁡
1818
1819 _bpf_mtap(bp, &m0, direction);
1820 }
1821
1822 /*
1823 * Put the SLIP pseudo-"link header" in place.
1824 * Note this M_PREPEND() should never fail,
1825 * swince we know we always have enough space
1826 * in the input buffer.
1827 */
1828 static void
1829 _bpf_mtap_sl_in(struct bpf_if *bp, u_char *chdr, struct mbuf **m)
1830 {
1831 u_char *hp;
1832
1833 M_PREPEND(*m, SLIP_HDRLEN, M_DONTWAIT);
1834 if (*m == NULL)
1835 return;
1836
1837 hp = mtod(*m, u_char *);
1838 hp[SLX_DIR] = SLIPDIR_IN;
1839 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1840
1841 _bpf_mtap(bp, *m, BPF_D_IN);
1842
1843 m_adj(*m, SLIP_HDRLEN);
1844 }
1845
1846 /*
1847 * Put the SLIP pseudo-"link header" in
1848 * place. The compressed header is now
1849 * at the beginning of the mbuf.
1850 */
1851 static void
1852 _bpf_mtap_sl_out(struct bpf_if *bp, u_char *chdr, struct mbuf *m)
1853 {
1854 struct mbuf m0;
1855 u_char *hp;
1856
1857 m0.m_type = MT_DATA;
1858 m0.m_flags = 0;
1859 m0.m_next = m;
1860 m0.m_nextpkt = NULL;
1861 m0.m_owner = NULL;
1862 m0.m_data = m0.m_dat;
1863 m0.m_len = SLIP_HDRLEN;
1864
1865 hp = mtod(&m0, u_char *);
1866
1867 hp[SLX_DIR] = SLIPDIR_OUT;
1868 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1869
1870 _bpf_mtap(bp, &m0, BPF_D_OUT);
1871 m_freem(m);
1872 }
1873
1874 static struct mbuf *
1875 bpf_mbuf_enqueue(struct bpf_if *bp, struct mbuf *m)
1876 {
1877 struct mbuf *dup;
1878
1879 dup = m_dup(m, 0, M_COPYALL, M_NOWAIT);
1880 if (dup == NULL)
1881 return NULL;
1882
1883 if (bp->bif_mbuf_tail != NULL) {
1884 bp->bif_mbuf_tail->m_nextpkt = dup;
1885 } else {
1886 bp->bif_mbuf_head = dup;
1887 }
1888 bp->bif_mbuf_tail = dup;
1889 #ifdef BPF_MTAP_SOFTINT_DEBUG
1890 log(LOG_DEBUG, "%s: enqueued mbuf=%p to %s\n",
1891 __func__, dup, bp->bif_ifp->if_xname);
1892 #endif
1893
1894 return dup;
1895 }
1896
1897 static struct mbuf *
1898 bpf_mbuf_dequeue(struct bpf_if *bp)
1899 {
1900 struct mbuf *m;
1901 int s;
1902
1903 /* XXX NOMPSAFE: assumed running on one CPU */
1904 s = splnet();
1905 m = bp->bif_mbuf_head;
1906 if (m != NULL) {
1907 bp->bif_mbuf_head = m->m_nextpkt;
1908 m->m_nextpkt = NULL;
1909
1910 if (bp->bif_mbuf_head == NULL)
1911 bp->bif_mbuf_tail = NULL;
1912 #ifdef BPF_MTAP_SOFTINT_DEBUG
1913 log(LOG_DEBUG, "%s: dequeued mbuf=%p from %s\n",
1914 __func__, m, bp->bif_ifp->if_xname);
1915 #endif
1916 }
1917 splx(s);
1918
1919 return m;
1920 }
1921
1922 static void
1923 bpf_mtap_si(void *arg)
1924 {
1925 struct bpf_if *bp = arg;
1926 struct mbuf *m;
1927
1928 while ((m = bpf_mbuf_dequeue(bp)) != NULL) {
1929 #ifdef BPF_MTAP_SOFTINT_DEBUG
1930 log(LOG_DEBUG, "%s: tapping mbuf=%p on %s\n",
1931 __func__, m, bp->bif_ifp->if_xname);
1932 #endif
1933 bpf_ops->bpf_mtap(bp, m, BPF_D_IN);
1934 m_freem(m);
1935 }
1936 }
1937
1938 static void
1939 _bpf_mtap_softint(struct ifnet *ifp, struct mbuf *m)
1940 {
1941 struct bpf_if *bp = ifp->if_bpf;
1942 struct mbuf *dup;
1943
1944 KASSERT(cpu_intr_p());
1945
1946 /* To avoid extra invocations of the softint */
1947 if (BPFIF_DLIST_READER_EMPTY(bp))
1948 return;
1949 KASSERT(bp->bif_si != NULL);
1950
1951 dup = bpf_mbuf_enqueue(bp, m);
1952 if (dup != NULL)
1953 softint_schedule(bp->bif_si);
1954 }
1955
1956 static int
1957 bpf_hdrlen(struct bpf_d *d)
1958 {
1959 int hdrlen = d->bd_bif->bif_hdrlen;
1960 /*
1961 * Compute the length of the bpf header. This is not necessarily
1962 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1963 * that the network layer header begins on a longword boundary (for
1964 * performance reasons and to alleviate alignment restrictions).
1965 */
1966 #ifdef _LP64
1967 if (d->bd_compat32)
1968 return (BPF_WORDALIGN32(hdrlen + SIZEOF_BPF_HDR32) - hdrlen);
1969 else
1970 #endif
1971 return (BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen);
1972 }
1973
1974 /*
1975 * Move the packet data from interface memory (pkt) into the
1976 * store buffer. Call the wakeup functions if it's time to wakeup
1977 * a listener (buffer full), "cpfn" is the routine called to do the
1978 * actual data transfer. memcpy is passed in to copy contiguous chunks,
1979 * while bpf_mcpy is passed in to copy mbuf chains. In the latter case,
1980 * pkt is really an mbuf.
1981 */
1982 static void
1983 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
1984 void *(*cpfn)(void *, const void *, size_t), struct timespec *ts)
1985 {
1986 char *h;
1987 int totlen, curlen, caplen;
1988 int hdrlen = bpf_hdrlen(d);
1989 int do_wakeup = 0;
1990
1991 atomic_inc_ulong(&d->bd_ccount);
1992 BPF_STATINC(capt);
1993 /*
1994 * Figure out how many bytes to move. If the packet is
1995 * greater or equal to the snapshot length, transfer that
1996 * much. Otherwise, transfer the whole packet (unless
1997 * we hit the buffer size limit).
1998 */
1999 totlen = hdrlen + uimin(snaplen, pktlen);
2000 if (totlen > d->bd_bufsize)
2001 totlen = d->bd_bufsize;
2002 /*
2003 * If we adjusted totlen to fit the bufsize, it could be that
2004 * totlen is smaller than hdrlen because of the link layer header.
2005 */
2006 caplen = totlen - hdrlen;
2007 if (caplen < 0)
2008 caplen = 0;
2009
2010 mutex_enter(d->bd_buf_mtx);
2011 /*
2012 * Round up the end of the previous packet to the next longword.
2013 */
2014 #ifdef _LP64
2015 if (d->bd_compat32)
2016 curlen = BPF_WORDALIGN32(d->bd_slen);
2017 else
2018 #endif
2019 curlen = BPF_WORDALIGN(d->bd_slen);
2020 if (curlen + totlen > d->bd_bufsize) {
2021 /*
2022 * This packet will overflow the storage buffer.
2023 * Rotate the buffers if we can, then wakeup any
2024 * pending reads.
2025 */
2026 if (d->bd_fbuf == NULL) {
2027 mutex_exit(d->bd_buf_mtx);
2028 /*
2029 * We haven't completed the previous read yet,
2030 * so drop the packet.
2031 */
2032 atomic_inc_ulong(&d->bd_dcount);
2033 BPF_STATINC(drop);
2034 return;
2035 }
2036 ROTATE_BUFFERS(d);
2037 do_wakeup = 1;
2038 curlen = 0;
2039 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT) {
2040 /*
2041 * Immediate mode is set, or the read timeout has
2042 * already expired during a select call. A packet
2043 * arrived, so the reader should be woken up.
2044 */
2045 do_wakeup = 1;
2046 }
2047
2048 /*
2049 * Append the bpf header.
2050 */
2051 h = (char *)d->bd_sbuf + curlen;
2052 #ifdef _LP64
2053 if (d->bd_compat32) {
2054 struct bpf_hdr32 *hp32;
2055
2056 hp32 = (struct bpf_hdr32 *)h;
2057 hp32->bh_tstamp.tv_sec = ts->tv_sec;
2058 hp32->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
2059 hp32->bh_datalen = pktlen;
2060 hp32->bh_hdrlen = hdrlen;
2061 hp32->bh_caplen = caplen;
2062 } else
2063 #endif
2064 {
2065 struct bpf_hdr *hp;
2066
2067 hp = (struct bpf_hdr *)h;
2068 hp->bh_tstamp.tv_sec = ts->tv_sec;
2069 hp->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
2070 hp->bh_datalen = pktlen;
2071 hp->bh_hdrlen = hdrlen;
2072 hp->bh_caplen = caplen;
2073 }
2074
2075 /*
2076 * Copy the packet data into the store buffer and update its length.
2077 */
2078 (*cpfn)(h + hdrlen, pkt, caplen);
2079 d->bd_slen = curlen + totlen;
2080 mutex_exit(d->bd_buf_mtx);
2081
2082 /*
2083 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
2084 * will cause filt_bpfread() to be called with it adjusted.
2085 */
2086 if (do_wakeup)
2087 bpf_wakeup(d);
2088 }
2089
2090 /*
2091 * Initialize all nonzero fields of a descriptor.
2092 */
2093 static int
2094 bpf_allocbufs(struct bpf_d *d)
2095 {
2096
2097 d->bd_fbuf = kmem_zalloc(d->bd_bufsize, KM_NOSLEEP);
2098 if (!d->bd_fbuf)
2099 return (ENOBUFS);
2100 d->bd_sbuf = kmem_zalloc(d->bd_bufsize, KM_NOSLEEP);
2101 if (!d->bd_sbuf) {
2102 kmem_free(d->bd_fbuf, d->bd_bufsize);
2103 return (ENOBUFS);
2104 }
2105 d->bd_slen = 0;
2106 d->bd_hlen = 0;
2107 return (0);
2108 }
2109
2110 static void
2111 bpf_free_filter(struct bpf_filter *filter)
2112 {
2113
2114 KASSERT(filter != NULL);
2115
2116 if (filter->bf_insn != NULL)
2117 kmem_free(filter->bf_insn, filter->bf_size);
2118 if (filter->bf_jitcode != NULL)
2119 bpf_jit_freecode(filter->bf_jitcode);
2120 kmem_free(filter, sizeof(*filter));
2121 }
2122
2123 /*
2124 * Free buffers currently in use by a descriptor.
2125 * Called on close.
2126 */
2127 static void
2128 bpf_freed(struct bpf_d *d)
2129 {
2130 /*
2131 * We don't need to lock out interrupts since this descriptor has
2132 * been detached from its interface and it yet hasn't been marked
2133 * free.
2134 */
2135 if (d->bd_sbuf != NULL) {
2136 kmem_free(d->bd_sbuf, d->bd_bufsize);
2137 if (d->bd_hbuf != NULL)
2138 kmem_free(d->bd_hbuf, d->bd_bufsize);
2139 if (d->bd_fbuf != NULL)
2140 kmem_free(d->bd_fbuf, d->bd_bufsize);
2141 }
2142 if (d->bd_rfilter != NULL) {
2143 bpf_free_filter(d->bd_rfilter);
2144 d->bd_rfilter = NULL;
2145 }
2146 if (d->bd_wfilter != NULL) {
2147 bpf_free_filter(d->bd_wfilter);
2148 d->bd_wfilter = NULL;
2149 }
2150 d->bd_jitcode = NULL;
2151 }
2152
2153 /*
2154 * Attach an interface to bpf. dlt is the link layer type;
2155 * hdrlen is the fixed size of the link header for the specified dlt
2156 * (variable length headers not yet supported).
2157 */
2158 static void
2159 _bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2160 {
2161 struct bpf_if *bp;
2162
2163 bp = kmem_alloc(sizeof(*bp), KM_SLEEP);
2164
2165 mutex_enter(&bpf_mtx);
2166 bp->bif_driverp = driverp;
2167 bp->bif_ifp = ifp;
2168 bp->bif_dlt = dlt;
2169 bp->bif_si = NULL;
2170 BPF_IFLIST_ENTRY_INIT(bp);
2171 PSLIST_INIT(&bp->bif_dlist_head);
2172 psref_target_init(&bp->bif_psref, bpf_psref_class);
2173 SLIST_INIT(&bp->bif_trackers);
2174
2175 BPF_IFLIST_WRITER_INSERT_HEAD(bp);
2176
2177 *bp->bif_driverp = NULL;
2178
2179 bp->bif_hdrlen = hdrlen;
2180 mutex_exit(&bpf_mtx);
2181 #if 0
2182 printf("bpf: %s attached with dlt %x\n", ifp->if_xname, dlt);
2183 #endif
2184 }
2185
2186 static void
2187 _bpf_mtap_softint_init(struct ifnet *ifp)
2188 {
2189 struct bpf_if *bp;
2190
2191 mutex_enter(&bpf_mtx);
2192 BPF_IFLIST_WRITER_FOREACH(bp) {
2193 if (bp->bif_ifp != ifp)
2194 continue;
2195
2196 bp->bif_mbuf_head = NULL;
2197 bp->bif_mbuf_tail = NULL;
2198 bp->bif_si = softint_establish(SOFTINT_NET, bpf_mtap_si, bp);
2199 if (bp->bif_si == NULL)
2200 panic("%s: softint_establish() failed", __func__);
2201 break;
2202 }
2203 mutex_exit(&bpf_mtx);
2204
2205 if (bp == NULL)
2206 panic("%s: no bpf_if found for %s", __func__, ifp->if_xname);
2207 }
2208
2209 /*
2210 * Remove an interface from bpf.
2211 */
2212 static void
2213 _bpfdetach(struct ifnet *ifp)
2214 {
2215 struct bpf_if *bp;
2216 struct bpf_d *d;
2217 int s;
2218
2219 mutex_enter(&bpf_mtx);
2220 /* Nuke the vnodes for any open instances */
2221 again_d:
2222 BPF_DLIST_WRITER_FOREACH(d) {
2223 mutex_enter(d->bd_mtx);
2224 if (d->bd_bif != NULL && d->bd_bif->bif_ifp == ifp) {
2225 /*
2226 * Detach the descriptor from an interface now.
2227 * It will be free'ed later by close routine.
2228 */
2229 bpf_detachd(d);
2230 mutex_exit(d->bd_mtx);
2231 goto again_d;
2232 }
2233 mutex_exit(d->bd_mtx);
2234 }
2235
2236 again:
2237 BPF_IFLIST_WRITER_FOREACH(bp) {
2238 if (bp->bif_ifp == ifp) {
2239 BPF_IFLIST_WRITER_REMOVE(bp);
2240
2241 pserialize_perform(bpf_psz);
2242 psref_target_destroy(&bp->bif_psref, bpf_psref_class);
2243
2244 while (!SLIST_EMPTY(&bp->bif_trackers)) {
2245 struct bpf_event_tracker *t =
2246 SLIST_FIRST(&bp->bif_trackers);
2247 SLIST_REMOVE_HEAD(&bp->bif_trackers,
2248 bet_entries);
2249 kmem_free(t, sizeof(*t));
2250 }
2251
2252 BPF_IFLIST_ENTRY_DESTROY(bp);
2253 if (bp->bif_si != NULL) {
2254 /* XXX NOMPSAFE: assumed running on one CPU */
2255 s = splnet();
2256 while (bp->bif_mbuf_head != NULL) {
2257 struct mbuf *m = bp->bif_mbuf_head;
2258 bp->bif_mbuf_head = m->m_nextpkt;
2259 m_freem(m);
2260 }
2261 splx(s);
2262 softint_disestablish(bp->bif_si);
2263 }
2264 kmem_free(bp, sizeof(*bp));
2265 goto again;
2266 }
2267 }
2268 mutex_exit(&bpf_mtx);
2269 }
2270
2271 /*
2272 * Change the data link type of a interface.
2273 */
2274 static void
2275 _bpf_change_type(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2276 {
2277 struct bpf_if *bp;
2278
2279 mutex_enter(&bpf_mtx);
2280 BPF_IFLIST_WRITER_FOREACH(bp) {
2281 if (bp->bif_driverp == &ifp->if_bpf)
2282 break;
2283 }
2284 if (bp == NULL)
2285 panic("bpf_change_type");
2286
2287 bp->bif_dlt = dlt;
2288
2289 bp->bif_hdrlen = hdrlen;
2290 mutex_exit(&bpf_mtx);
2291 }
2292
2293 /*
2294 * Get a list of available data link type of the interface.
2295 */
2296 static int
2297 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2298 {
2299 int n, error;
2300 struct ifnet *ifp;
2301 struct bpf_if *bp;
2302 int s, bound;
2303
2304 KASSERT(mutex_owned(d->bd_mtx));
2305
2306 ifp = d->bd_bif->bif_ifp;
2307 n = 0;
2308 error = 0;
2309
2310 bound = curlwp_bind();
2311 s = pserialize_read_enter();
2312 BPF_IFLIST_READER_FOREACH(bp) {
2313 if (bp->bif_ifp != ifp)
2314 continue;
2315 if (bfl->bfl_list != NULL) {
2316 struct psref psref;
2317
2318 if (n >= bfl->bfl_len) {
2319 pserialize_read_exit(s);
2320 return ENOMEM;
2321 }
2322
2323 bpf_if_acquire(bp, &psref);
2324 pserialize_read_exit(s);
2325
2326 error = copyout(&bp->bif_dlt,
2327 bfl->bfl_list + n, sizeof(u_int));
2328
2329 s = pserialize_read_enter();
2330 bpf_if_release(bp, &psref);
2331 }
2332 n++;
2333 }
2334 pserialize_read_exit(s);
2335 curlwp_bindx(bound);
2336
2337 bfl->bfl_len = n;
2338 return error;
2339 }
2340
2341 /*
2342 * Set the data link type of a BPF instance.
2343 */
2344 static int
2345 bpf_setdlt(struct bpf_d *d, u_int dlt)
2346 {
2347 int error, opromisc;
2348 struct ifnet *ifp;
2349 struct bpf_if *bp;
2350
2351 KASSERT(mutex_owned(&bpf_mtx));
2352 KASSERT(mutex_owned(d->bd_mtx));
2353
2354 if (d->bd_bif->bif_dlt == dlt)
2355 return 0;
2356 ifp = d->bd_bif->bif_ifp;
2357 BPF_IFLIST_WRITER_FOREACH(bp) {
2358 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2359 break;
2360 }
2361 if (bp == NULL)
2362 return EINVAL;
2363 opromisc = d->bd_promisc;
2364 bpf_detachd(d);
2365 BPFIF_DLIST_ENTRY_INIT(d);
2366 bpf_attachd(d, bp);
2367 reset_d(d);
2368 if (opromisc) {
2369 KERNEL_LOCK_UNLESS_NET_MPSAFE();
2370 error = ifpromisc(bp->bif_ifp, 1);
2371 KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
2372 if (error)
2373 printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
2374 bp->bif_ifp->if_xname, error);
2375 else
2376 d->bd_promisc = 1;
2377 }
2378 return 0;
2379 }
2380
2381 static int
2382 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
2383 {
2384 int newsize, error;
2385 struct sysctlnode node;
2386
2387 node = *rnode;
2388 node.sysctl_data = &newsize;
2389 newsize = bpf_maxbufsize;
2390 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2391 if (error || newp == NULL)
2392 return (error);
2393
2394 if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
2395 return (EINVAL);
2396
2397 bpf_maxbufsize = newsize;
2398
2399 return (0);
2400 }
2401
2402 #if defined(MODULAR) || defined(BPFJIT)
2403 static int
2404 sysctl_net_bpf_jit(SYSCTLFN_ARGS)
2405 {
2406 bool newval;
2407 int error;
2408 struct sysctlnode node;
2409
2410 node = *rnode;
2411 node.sysctl_data = &newval;
2412 newval = bpf_jit;
2413 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2414 if (error != 0 || newp == NULL)
2415 return error;
2416
2417 bpf_jit = newval;
2418 if (newval && bpfjit_module_ops.bj_generate_code == NULL) {
2419 printf("JIT compilation is postponed "
2420 "until after bpfjit module is loaded\n");
2421 }
2422
2423 return 0;
2424 }
2425 #endif
2426
2427 static int
2428 sysctl_net_bpf_peers(SYSCTLFN_ARGS)
2429 {
2430 int error, elem_count;
2431 struct bpf_d *dp;
2432 struct bpf_d_ext dpe;
2433 size_t len, needed, elem_size, out_size;
2434 char *sp;
2435
2436 if (namelen == 1 && name[0] == CTL_QUERY)
2437 return (sysctl_query(SYSCTLFN_CALL(rnode)));
2438
2439 if (namelen != 2)
2440 return (EINVAL);
2441
2442 /* BPF peers is privileged information. */
2443 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
2444 KAUTH_REQ_NETWORK_INTERFACE_GETPRIV, NULL, NULL, NULL);
2445 if (error)
2446 return (EPERM);
2447
2448 len = (oldp != NULL) ? *oldlenp : 0;
2449 sp = oldp;
2450 elem_size = name[0];
2451 elem_count = name[1];
2452 out_size = MIN(sizeof(dpe), elem_size);
2453 needed = 0;
2454
2455 if (elem_size < 1 || elem_count < 0)
2456 return (EINVAL);
2457
2458 mutex_enter(&bpf_mtx);
2459 BPF_DLIST_WRITER_FOREACH(dp) {
2460 if (len >= elem_size && elem_count > 0) {
2461 #define BPF_EXT(field) dpe.bde_ ## field = dp->bd_ ## field
2462 BPF_EXT(bufsize);
2463 BPF_EXT(promisc);
2464 BPF_EXT(state);
2465 BPF_EXT(immediate);
2466 BPF_EXT(hdrcmplt);
2467 BPF_EXT(direction);
2468 BPF_EXT(pid);
2469 BPF_EXT(rcount);
2470 BPF_EXT(dcount);
2471 BPF_EXT(ccount);
2472 #undef BPF_EXT
2473 mutex_enter(dp->bd_mtx);
2474 if (dp->bd_bif)
2475 (void)strlcpy(dpe.bde_ifname,
2476 dp->bd_bif->bif_ifp->if_xname,
2477 IFNAMSIZ - 1);
2478 else
2479 dpe.bde_ifname[0] = '\0';
2480 dpe.bde_locked = dp->bd_locked;
2481 mutex_exit(dp->bd_mtx);
2482
2483 error = copyout(&dpe, sp, out_size);
2484 if (error)
2485 break;
2486 sp += elem_size;
2487 len -= elem_size;
2488 }
2489 needed += elem_size;
2490 if (elem_count > 0 && elem_count != INT_MAX)
2491 elem_count--;
2492 }
2493 mutex_exit(&bpf_mtx);
2494
2495 *oldlenp = needed;
2496
2497 return (error);
2498 }
2499
2500 static void
2501 bpf_stats(void *p, void *arg, struct cpu_info *ci __unused)
2502 {
2503 struct bpf_stat *const stats = p;
2504 struct bpf_stat *sum = arg;
2505
2506 int s = splnet();
2507
2508 sum->bs_recv += stats->bs_recv;
2509 sum->bs_drop += stats->bs_drop;
2510 sum->bs_capt += stats->bs_capt;
2511
2512 splx(s);
2513 }
2514
2515 static int
2516 bpf_sysctl_gstats_handler(SYSCTLFN_ARGS)
2517 {
2518 struct sysctlnode node;
2519 int error;
2520 struct bpf_stat sum;
2521
2522 memset(&sum, 0, sizeof(sum));
2523 node = *rnode;
2524
2525 percpu_foreach_xcall(bpf_gstats_percpu, XC_HIGHPRI_IPL(IPL_SOFTNET),
2526 bpf_stats, &sum);
2527
2528 node.sysctl_data = ∑
2529 node.sysctl_size = sizeof(sum);
2530 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2531 if (error != 0 || newp == NULL)
2532 return error;
2533
2534 return 0;
2535 }
2536
2537 SYSCTL_SETUP(sysctl_net_bpf_setup, "bpf sysctls")
2538 {
2539 const struct sysctlnode *node;
2540
2541 node = NULL;
2542 sysctl_createv(clog, 0, NULL, &node,
2543 CTLFLAG_PERMANENT,
2544 CTLTYPE_NODE, "bpf",
2545 SYSCTL_DESCR("BPF options"),
2546 NULL, 0, NULL, 0,
2547 CTL_NET, CTL_CREATE, CTL_EOL);
2548 if (node != NULL) {
2549 #if defined(MODULAR) || defined(BPFJIT)
2550 sysctl_createv(clog, 0, NULL, NULL,
2551 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2552 CTLTYPE_BOOL, "jit",
2553 SYSCTL_DESCR("Toggle Just-In-Time compilation"),
2554 sysctl_net_bpf_jit, 0, &bpf_jit, 0,
2555 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2556 #endif
2557 sysctl_createv(clog, 0, NULL, NULL,
2558 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2559 CTLTYPE_INT, "maxbufsize",
2560 SYSCTL_DESCR("Maximum size for data capture buffer"),
2561 sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
2562 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2563 sysctl_createv(clog, 0, NULL, NULL,
2564 CTLFLAG_PERMANENT,
2565 CTLTYPE_STRUCT, "stats",
2566 SYSCTL_DESCR("BPF stats"),
2567 bpf_sysctl_gstats_handler, 0, NULL, 0,
2568 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2569 sysctl_createv(clog, 0, NULL, NULL,
2570 CTLFLAG_PERMANENT,
2571 CTLTYPE_STRUCT, "peers",
2572 SYSCTL_DESCR("BPF peers"),
2573 sysctl_net_bpf_peers, 0, NULL, 0,
2574 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2575 }
2576
2577 }
2578
2579 static int
2580 _bpf_register_track_event(struct bpf_if **driverp,
2581 void (*_fun)(struct bpf_if *, struct ifnet *, int, int))
2582 {
2583 struct bpf_if *bp;
2584 struct bpf_event_tracker *t;
2585 int ret = ENOENT;
2586
2587 t = kmem_zalloc(sizeof(*t), KM_SLEEP);
2588 if (!t)
2589 return ENOMEM;
2590 t->bet_notify = _fun;
2591
2592 mutex_enter(&bpf_mtx);
2593 BPF_IFLIST_WRITER_FOREACH(bp) {
2594 if (bp->bif_driverp != driverp)
2595 continue;
2596 SLIST_INSERT_HEAD(&bp->bif_trackers, t, bet_entries);
2597 ret = 0;
2598 break;
2599 }
2600 mutex_exit(&bpf_mtx);
2601
2602 return ret;
2603 }
2604
2605 static int
2606 _bpf_deregister_track_event(struct bpf_if **driverp,
2607 void (*_fun)(struct bpf_if *, struct ifnet *, int, int))
2608 {
2609 struct bpf_if *bp;
2610 struct bpf_event_tracker *t = NULL;
2611 int ret = ENOENT;
2612
2613 mutex_enter(&bpf_mtx);
2614 BPF_IFLIST_WRITER_FOREACH(bp) {
2615 if (bp->bif_driverp != driverp)
2616 continue;
2617 SLIST_FOREACH(t, &bp->bif_trackers, bet_entries) {
2618 if (t->bet_notify == _fun) {
2619 ret = 0;
2620 break;
2621 }
2622 }
2623 if (ret == 0)
2624 break;
2625 }
2626 if (ret == 0 && t && t->bet_notify == _fun) {
2627 SLIST_REMOVE(&bp->bif_trackers, t, bpf_event_tracker,
2628 bet_entries);
2629 }
2630 mutex_exit(&bpf_mtx);
2631 if (ret == 0)
2632 kmem_free(t, sizeof(*t));
2633 return ret;
2634 }
2635
2636 struct bpf_ops bpf_ops_kernel = {
2637 .bpf_attach = _bpfattach,
2638 .bpf_detach = _bpfdetach,
2639 .bpf_change_type = _bpf_change_type,
2640 .bpf_register_track_event = _bpf_register_track_event,
2641 .bpf_deregister_track_event = _bpf_deregister_track_event,
2642
2643 .bpf_mtap = _bpf_mtap,
2644 .bpf_mtap2 = _bpf_mtap2,
2645 .bpf_mtap_af = _bpf_mtap_af,
2646 .bpf_mtap_sl_in = _bpf_mtap_sl_in,
2647 .bpf_mtap_sl_out = _bpf_mtap_sl_out,
2648
2649 .bpf_mtap_softint = _bpf_mtap_softint,
2650 .bpf_mtap_softint_init = _bpf_mtap_softint_init,
2651 };
2652
2653 MODULE(MODULE_CLASS_DRIVER, bpf, "bpf_filter");
2654
2655 static int
2656 bpf_modcmd(modcmd_t cmd, void *arg)
2657 {
2658 #ifdef _MODULE
2659 devmajor_t bmajor, cmajor;
2660 #endif
2661 int error = 0;
2662
2663 switch (cmd) {
2664 case MODULE_CMD_INIT:
2665 bpf_init();
2666 #ifdef _MODULE
2667 bmajor = cmajor = NODEVMAJOR;
2668 error = devsw_attach("bpf", NULL, &bmajor,
2669 &bpf_cdevsw, &cmajor);
2670 if (error)
2671 break;
2672 #endif
2673
2674 bpf_ops_handover_enter(&bpf_ops_kernel);
2675 atomic_swap_ptr(&bpf_ops, &bpf_ops_kernel);
2676 bpf_ops_handover_exit();
2677 break;
2678
2679 case MODULE_CMD_FINI:
2680 /*
2681 * While there is no reference counting for bpf callers,
2682 * unload could at least in theory be done similarly to
2683 * system call disestablishment. This should even be
2684 * a little simpler:
2685 *
2686 * 1) replace op vector with stubs
2687 * 2) post update to all cpus with xc
2688 * 3) check that nobody is in bpf anymore
2689 * (it's doubtful we'd want something like l_sysent,
2690 * but we could do something like *signed* percpu
2691 * counters. if the sum is 0, we're good).
2692 * 4) if fail, unroll changes
2693 *
2694 * NOTE: change won't be atomic to the outside. some
2695 * packets may be not captured even if unload is
2696 * not successful. I think packet capture not working
2697 * is a perfectly logical consequence of trying to
2698 * disable packet capture.
2699 */
2700 error = EOPNOTSUPP;
2701 break;
2702
2703 default:
2704 error = ENOTTY;
2705 break;
2706 }
2707
2708 return error;
2709 }
2710