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