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