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