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