bpf.c revision 1.213 1 /* $NetBSD: bpf.c,v 1.213 2017/02/09 09:30:26 ozaki-r Exp $ */
2
3 /*
4 * Copyright (c) 1990, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from the Stanford/CMU enet packet filter,
8 * (net/enet.c) distributed as part of 4.3BSD, and code contributed
9 * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
10 * Berkeley Laboratory.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * @(#)bpf.c 8.4 (Berkeley) 1/9/95
37 * static char rcsid[] =
38 * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
39 */
40
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.213 2017/02/09 09:30:26 ozaki-r 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_INSEART_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 .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
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 * Must be called at splnet.
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_INSEART_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. Should be called at splnet.
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
1390 bpf_attachd(d, bp);
1391 }
1392 reset_d(d);
1393 mutex_exit(d->bd_mtx);
1394 return (0);
1395 }
1396 /* Not found. */
1397 return (ENXIO);
1398 }
1399
1400 /*
1401 * Copy the interface name to the ifreq.
1402 */
1403 static void
1404 bpf_ifname(struct ifnet *ifp, struct ifreq *ifr)
1405 {
1406 memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
1407 }
1408
1409 static int
1410 bpf_stat(struct file *fp, struct stat *st)
1411 {
1412 struct bpf_d *d = fp->f_bpf;
1413
1414 (void)memset(st, 0, sizeof(*st));
1415 mutex_enter(d->bd_mtx);
1416 st->st_dev = makedev(cdevsw_lookup_major(&bpf_cdevsw), d->bd_pid);
1417 st->st_atimespec = d->bd_atime;
1418 st->st_mtimespec = d->bd_mtime;
1419 st->st_ctimespec = st->st_birthtimespec = d->bd_btime;
1420 st->st_uid = kauth_cred_geteuid(fp->f_cred);
1421 st->st_gid = kauth_cred_getegid(fp->f_cred);
1422 st->st_mode = S_IFCHR;
1423 mutex_exit(d->bd_mtx);
1424 return 0;
1425 }
1426
1427 /*
1428 * Support for poll() system call
1429 *
1430 * Return true iff the specific operation will not block indefinitely - with
1431 * the assumption that it is safe to positively acknowledge a request for the
1432 * ability to write to the BPF device.
1433 * Otherwise, return false but make a note that a selnotify() must be done.
1434 */
1435 static int
1436 bpf_poll(struct file *fp, int events)
1437 {
1438 struct bpf_d *d = fp->f_bpf;
1439 int revents;
1440
1441 /*
1442 * Refresh the PID associated with this bpf file.
1443 */
1444 mutex_enter(&bpf_mtx);
1445 d->bd_pid = curproc->p_pid;
1446
1447 revents = events & (POLLOUT | POLLWRNORM);
1448 if (events & (POLLIN | POLLRDNORM)) {
1449 /*
1450 * An imitation of the FIONREAD ioctl code.
1451 */
1452 mutex_enter(d->bd_mtx);
1453 if (d->bd_hlen != 0 ||
1454 ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1455 d->bd_slen != 0)) {
1456 revents |= events & (POLLIN | POLLRDNORM);
1457 } else {
1458 selrecord(curlwp, &d->bd_sel);
1459 /* Start the read timeout if necessary */
1460 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1461 callout_reset(&d->bd_callout, d->bd_rtout,
1462 bpf_timed_out, d);
1463 d->bd_state = BPF_WAITING;
1464 }
1465 }
1466 mutex_exit(d->bd_mtx);
1467 }
1468
1469 mutex_exit(&bpf_mtx);
1470 return (revents);
1471 }
1472
1473 static void
1474 filt_bpfrdetach(struct knote *kn)
1475 {
1476 struct bpf_d *d = kn->kn_hook;
1477
1478 mutex_enter(d->bd_buf_mtx);
1479 SLIST_REMOVE(&d->bd_sel.sel_klist, kn, knote, kn_selnext);
1480 mutex_exit(d->bd_buf_mtx);
1481 }
1482
1483 static int
1484 filt_bpfread(struct knote *kn, long hint)
1485 {
1486 struct bpf_d *d = kn->kn_hook;
1487 int rv;
1488
1489 mutex_enter(d->bd_buf_mtx);
1490 kn->kn_data = d->bd_hlen;
1491 if (d->bd_immediate)
1492 kn->kn_data += d->bd_slen;
1493 rv = (kn->kn_data > 0);
1494 mutex_exit(d->bd_buf_mtx);
1495 return rv;
1496 }
1497
1498 static const struct filterops bpfread_filtops =
1499 { 1, NULL, filt_bpfrdetach, filt_bpfread };
1500
1501 static int
1502 bpf_kqfilter(struct file *fp, struct knote *kn)
1503 {
1504 struct bpf_d *d = fp->f_bpf;
1505 struct klist *klist;
1506
1507 mutex_enter(d->bd_buf_mtx);
1508 switch (kn->kn_filter) {
1509 case EVFILT_READ:
1510 klist = &d->bd_sel.sel_klist;
1511 kn->kn_fop = &bpfread_filtops;
1512 break;
1513
1514 default:
1515 mutex_exit(d->bd_buf_mtx);
1516 return (EINVAL);
1517 }
1518
1519 kn->kn_hook = d;
1520
1521 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1522 mutex_exit(d->bd_buf_mtx);
1523
1524 return (0);
1525 }
1526
1527 /*
1528 * Copy data from an mbuf chain into a buffer. This code is derived
1529 * from m_copydata in sys/uipc_mbuf.c.
1530 */
1531 static void *
1532 bpf_mcpy(void *dst_arg, const void *src_arg, size_t len)
1533 {
1534 const struct mbuf *m;
1535 u_int count;
1536 u_char *dst;
1537
1538 m = src_arg;
1539 dst = dst_arg;
1540 while (len > 0) {
1541 if (m == NULL)
1542 panic("bpf_mcpy");
1543 count = min(m->m_len, len);
1544 memcpy(dst, mtod(m, const void *), count);
1545 m = m->m_next;
1546 dst += count;
1547 len -= count;
1548 }
1549 return dst_arg;
1550 }
1551
1552 /*
1553 * Dispatch a packet to all the listeners on interface bp.
1554 *
1555 * pkt pointer to the packet, either a data buffer or an mbuf chain
1556 * buflen buffer length, if pkt is a data buffer
1557 * cpfn a function that can copy pkt into the listener's buffer
1558 * pktlen length of the packet
1559 * rcv true if packet came in
1560 */
1561 static inline void
1562 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
1563 void *pkt, u_int pktlen, u_int buflen, const bool rcv)
1564 {
1565 uint32_t mem[BPF_MEMWORDS];
1566 bpf_args_t args = {
1567 .pkt = (const uint8_t *)pkt,
1568 .wirelen = pktlen,
1569 .buflen = buflen,
1570 .mem = mem,
1571 .arg = NULL
1572 };
1573 bool gottime = false;
1574 struct timespec ts;
1575 struct bpf_d *d;
1576 int s;
1577
1578 KASSERT(!cpu_intr_p());
1579
1580 /*
1581 * Note that the IPL does not have to be raised at this point.
1582 * The only problem that could arise here is that if two different
1583 * interfaces shared any data. This is not the case.
1584 */
1585 s = pserialize_read_enter();
1586 BPFIF_DLIST_READER_FOREACH(d, bp) {
1587 u_int slen = 0;
1588 struct bpf_filter *filter;
1589
1590 if (!d->bd_seesent && !rcv) {
1591 continue;
1592 }
1593 atomic_inc_ulong(&d->bd_rcount);
1594 BPF_STATINC(recv);
1595
1596 filter = d->bd_filter;
1597 membar_datadep_consumer();
1598 if (filter != NULL) {
1599 if (filter->bf_jitcode != NULL)
1600 slen = filter->bf_jitcode(NULL, &args);
1601 else
1602 slen = bpf_filter_ext(NULL, filter->bf_insn,
1603 &args);
1604 }
1605
1606 if (!slen) {
1607 continue;
1608 }
1609 if (!gottime) {
1610 gottime = true;
1611 nanotime(&ts);
1612 }
1613 /* Assume catchpacket doesn't sleep */
1614 catchpacket(d, pkt, pktlen, slen, cpfn, &ts);
1615 }
1616 pserialize_read_exit(s);
1617 }
1618
1619 /*
1620 * Incoming linkage from device drivers. Process the packet pkt, of length
1621 * pktlen, which is stored in a contiguous buffer. The packet is parsed
1622 * by each process' filter, and if accepted, stashed into the corresponding
1623 * buffer.
1624 */
1625 static void
1626 _bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
1627 {
1628
1629 bpf_deliver(bp, memcpy, pkt, pktlen, pktlen, true);
1630 }
1631
1632 /*
1633 * Incoming linkage from device drivers, when the head of the packet is in
1634 * a buffer, and the tail is in an mbuf chain.
1635 */
1636 static void
1637 _bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
1638 {
1639 u_int pktlen;
1640 struct mbuf mb;
1641
1642 /* Skip outgoing duplicate packets. */
1643 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif_index == 0) {
1644 m->m_flags &= ~M_PROMISC;
1645 return;
1646 }
1647
1648 pktlen = m_length(m) + dlen;
1649
1650 /*
1651 * Craft on-stack mbuf suitable for passing to bpf_filter.
1652 * Note that we cut corners here; we only setup what's
1653 * absolutely needed--this mbuf should never go anywhere else.
1654 */
1655 (void)memset(&mb, 0, sizeof(mb));
1656 mb.m_next = m;
1657 mb.m_data = data;
1658 mb.m_len = dlen;
1659
1660 bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, m->m_pkthdr.rcvif_index != 0);
1661 }
1662
1663 /*
1664 * Incoming linkage from device drivers, when packet is in an mbuf chain.
1665 */
1666 static void
1667 _bpf_mtap(struct bpf_if *bp, struct mbuf *m)
1668 {
1669 void *(*cpfn)(void *, const void *, size_t);
1670 u_int pktlen, buflen;
1671 void *marg;
1672
1673 /* Skip outgoing duplicate packets. */
1674 if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif_index == 0) {
1675 m->m_flags &= ~M_PROMISC;
1676 return;
1677 }
1678
1679 pktlen = m_length(m);
1680
1681 if (pktlen == m->m_len) {
1682 cpfn = (void *)memcpy;
1683 marg = mtod(m, void *);
1684 buflen = pktlen;
1685 } else {
1686 cpfn = bpf_mcpy;
1687 marg = m;
1688 buflen = 0;
1689 }
1690
1691 bpf_deliver(bp, cpfn, marg, pktlen, buflen, m->m_pkthdr.rcvif_index != 0);
1692 }
1693
1694 /*
1695 * We need to prepend the address family as
1696 * a four byte field. Cons up a dummy header
1697 * to pacify bpf. This is safe because bpf
1698 * will only read from the mbuf (i.e., it won't
1699 * try to free it or keep a pointer a to it).
1700 */
1701 static void
1702 _bpf_mtap_af(struct bpf_if *bp, uint32_t af, struct mbuf *m)
1703 {
1704 struct mbuf m0;
1705
1706 m0.m_flags = 0;
1707 m0.m_next = m;
1708 m0.m_len = 4;
1709 m0.m_data = (char *)⁡
1710
1711 _bpf_mtap(bp, &m0);
1712 }
1713
1714 /*
1715 * Put the SLIP pseudo-"link header" in place.
1716 * Note this M_PREPEND() should never fail,
1717 * swince we know we always have enough space
1718 * in the input buffer.
1719 */
1720 static void
1721 _bpf_mtap_sl_in(struct bpf_if *bp, u_char *chdr, struct mbuf **m)
1722 {
1723 u_char *hp;
1724
1725 M_PREPEND(*m, SLIP_HDRLEN, M_DONTWAIT);
1726 if (*m == NULL)
1727 return;
1728
1729 hp = mtod(*m, u_char *);
1730 hp[SLX_DIR] = SLIPDIR_IN;
1731 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1732
1733 _bpf_mtap(bp, *m);
1734
1735 m_adj(*m, SLIP_HDRLEN);
1736 }
1737
1738 /*
1739 * Put the SLIP pseudo-"link header" in
1740 * place. The compressed header is now
1741 * at the beginning of the mbuf.
1742 */
1743 static void
1744 _bpf_mtap_sl_out(struct bpf_if *bp, u_char *chdr, struct mbuf *m)
1745 {
1746 struct mbuf m0;
1747 u_char *hp;
1748
1749 m0.m_flags = 0;
1750 m0.m_next = m;
1751 m0.m_data = m0.m_dat;
1752 m0.m_len = SLIP_HDRLEN;
1753
1754 hp = mtod(&m0, u_char *);
1755
1756 hp[SLX_DIR] = SLIPDIR_OUT;
1757 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1758
1759 _bpf_mtap(bp, &m0);
1760 m_freem(m);
1761 }
1762
1763 static struct mbuf *
1764 bpf_mbuf_enqueue(struct bpf_if *bp, struct mbuf *m)
1765 {
1766 struct mbuf *dup;
1767
1768 dup = m_dup(m, 0, M_COPYALL, M_NOWAIT);
1769 if (dup == NULL)
1770 return NULL;
1771
1772 if (bp->bif_mbuf_tail != NULL) {
1773 bp->bif_mbuf_tail->m_nextpkt = dup;
1774 } else {
1775 bp->bif_mbuf_head = dup;
1776 }
1777 bp->bif_mbuf_tail = dup;
1778 #ifdef BPF_MTAP_SOFTINT_DEBUG
1779 log(LOG_DEBUG, "%s: enqueued mbuf=%p to %s\n",
1780 __func__, dup, bp->bif_ifp->if_xname);
1781 #endif
1782
1783 return dup;
1784 }
1785
1786 static struct mbuf *
1787 bpf_mbuf_dequeue(struct bpf_if *bp)
1788 {
1789 struct mbuf *m;
1790 int s;
1791
1792 /* XXX NOMPSAFE: assumed running on one CPU */
1793 s = splnet();
1794 m = bp->bif_mbuf_head;
1795 if (m != NULL) {
1796 bp->bif_mbuf_head = m->m_nextpkt;
1797 m->m_nextpkt = NULL;
1798
1799 if (bp->bif_mbuf_head == NULL)
1800 bp->bif_mbuf_tail = NULL;
1801 #ifdef BPF_MTAP_SOFTINT_DEBUG
1802 log(LOG_DEBUG, "%s: dequeued mbuf=%p from %s\n",
1803 __func__, m, bp->bif_ifp->if_xname);
1804 #endif
1805 }
1806 splx(s);
1807
1808 return m;
1809 }
1810
1811 static void
1812 bpf_mtap_si(void *arg)
1813 {
1814 struct bpf_if *bp = arg;
1815 struct mbuf *m;
1816
1817 while ((m = bpf_mbuf_dequeue(bp)) != NULL) {
1818 #ifdef BPF_MTAP_SOFTINT_DEBUG
1819 log(LOG_DEBUG, "%s: tapping mbuf=%p on %s\n",
1820 __func__, m, bp->bif_ifp->if_xname);
1821 #endif
1822 bpf_ops->bpf_mtap(bp, m);
1823 m_freem(m);
1824 }
1825 }
1826
1827 static void
1828 _bpf_mtap_softint(struct ifnet *ifp, struct mbuf *m)
1829 {
1830 struct bpf_if *bp = ifp->if_bpf;
1831 struct mbuf *dup;
1832
1833 KASSERT(cpu_intr_p());
1834
1835 /* To avoid extra invocations of the softint */
1836 if (BPFIF_DLIST_READER_EMPTY(bp))
1837 return;
1838 KASSERT(bp->bif_si != NULL);
1839
1840 dup = bpf_mbuf_enqueue(bp, m);
1841 if (dup != NULL)
1842 softint_schedule(bp->bif_si);
1843 }
1844
1845 static int
1846 bpf_hdrlen(struct bpf_d *d)
1847 {
1848 int hdrlen = d->bd_bif->bif_hdrlen;
1849 /*
1850 * Compute the length of the bpf header. This is not necessarily
1851 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1852 * that the network layer header begins on a longword boundary (for
1853 * performance reasons and to alleviate alignment restrictions).
1854 */
1855 #ifdef _LP64
1856 if (d->bd_compat32)
1857 return (BPF_WORDALIGN32(hdrlen + SIZEOF_BPF_HDR32) - hdrlen);
1858 else
1859 #endif
1860 return (BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen);
1861 }
1862
1863 /*
1864 * Move the packet data from interface memory (pkt) into the
1865 * store buffer. Call the wakeup functions if it's time to wakeup
1866 * a listener (buffer full), "cpfn" is the routine called to do the
1867 * actual data transfer. memcpy is passed in to copy contiguous chunks,
1868 * while bpf_mcpy is passed in to copy mbuf chains. In the latter case,
1869 * pkt is really an mbuf.
1870 */
1871 static void
1872 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
1873 void *(*cpfn)(void *, const void *, size_t), struct timespec *ts)
1874 {
1875 char *h;
1876 int totlen, curlen, caplen;
1877 int hdrlen = bpf_hdrlen(d);
1878 int do_wakeup = 0;
1879
1880 atomic_inc_ulong(&d->bd_ccount);
1881 BPF_STATINC(capt);
1882 /*
1883 * Figure out how many bytes to move. If the packet is
1884 * greater or equal to the snapshot length, transfer that
1885 * much. Otherwise, transfer the whole packet (unless
1886 * we hit the buffer size limit).
1887 */
1888 totlen = hdrlen + min(snaplen, pktlen);
1889 if (totlen > d->bd_bufsize)
1890 totlen = d->bd_bufsize;
1891 /*
1892 * If we adjusted totlen to fit the bufsize, it could be that
1893 * totlen is smaller than hdrlen because of the link layer header.
1894 */
1895 caplen = totlen - hdrlen;
1896 if (caplen < 0)
1897 caplen = 0;
1898
1899 mutex_enter(d->bd_buf_mtx);
1900 /*
1901 * Round up the end of the previous packet to the next longword.
1902 */
1903 #ifdef _LP64
1904 if (d->bd_compat32)
1905 curlen = BPF_WORDALIGN32(d->bd_slen);
1906 else
1907 #endif
1908 curlen = BPF_WORDALIGN(d->bd_slen);
1909 if (curlen + totlen > d->bd_bufsize) {
1910 /*
1911 * This packet will overflow the storage buffer.
1912 * Rotate the buffers if we can, then wakeup any
1913 * pending reads.
1914 */
1915 if (d->bd_fbuf == NULL) {
1916 mutex_exit(d->bd_buf_mtx);
1917 /*
1918 * We haven't completed the previous read yet,
1919 * so drop the packet.
1920 */
1921 atomic_inc_ulong(&d->bd_dcount);
1922 BPF_STATINC(drop);
1923 return;
1924 }
1925 ROTATE_BUFFERS(d);
1926 do_wakeup = 1;
1927 curlen = 0;
1928 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT) {
1929 /*
1930 * Immediate mode is set, or the read timeout has
1931 * already expired during a select call. A packet
1932 * arrived, so the reader should be woken up.
1933 */
1934 do_wakeup = 1;
1935 }
1936
1937 /*
1938 * Append the bpf header.
1939 */
1940 h = (char *)d->bd_sbuf + curlen;
1941 #ifdef _LP64
1942 if (d->bd_compat32) {
1943 struct bpf_hdr32 *hp32;
1944
1945 hp32 = (struct bpf_hdr32 *)h;
1946 hp32->bh_tstamp.tv_sec = ts->tv_sec;
1947 hp32->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
1948 hp32->bh_datalen = pktlen;
1949 hp32->bh_hdrlen = hdrlen;
1950 hp32->bh_caplen = caplen;
1951 } else
1952 #endif
1953 {
1954 struct bpf_hdr *hp;
1955
1956 hp = (struct bpf_hdr *)h;
1957 hp->bh_tstamp.tv_sec = ts->tv_sec;
1958 hp->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
1959 hp->bh_datalen = pktlen;
1960 hp->bh_hdrlen = hdrlen;
1961 hp->bh_caplen = caplen;
1962 }
1963
1964 /*
1965 * Copy the packet data into the store buffer and update its length.
1966 */
1967 (*cpfn)(h + hdrlen, pkt, caplen);
1968 d->bd_slen = curlen + totlen;
1969 mutex_exit(d->bd_buf_mtx);
1970
1971 /*
1972 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
1973 * will cause filt_bpfread() to be called with it adjusted.
1974 */
1975 if (do_wakeup)
1976 bpf_wakeup(d);
1977 }
1978
1979 /*
1980 * Initialize all nonzero fields of a descriptor.
1981 */
1982 static int
1983 bpf_allocbufs(struct bpf_d *d)
1984 {
1985
1986 d->bd_fbuf = kmem_alloc(d->bd_bufsize, KM_NOSLEEP);
1987 if (!d->bd_fbuf)
1988 return (ENOBUFS);
1989 d->bd_sbuf = kmem_alloc(d->bd_bufsize, KM_NOSLEEP);
1990 if (!d->bd_sbuf) {
1991 kmem_free(d->bd_fbuf, d->bd_bufsize);
1992 return (ENOBUFS);
1993 }
1994 d->bd_slen = 0;
1995 d->bd_hlen = 0;
1996 return (0);
1997 }
1998
1999 static void
2000 bpf_free_filter(struct bpf_filter *filter)
2001 {
2002
2003 KASSERT(filter != NULL);
2004 KASSERT(filter->bf_insn != NULL);
2005
2006 kmem_free(filter->bf_insn, filter->bf_size);
2007 if (filter->bf_jitcode != NULL)
2008 bpf_jit_freecode(filter->bf_jitcode);
2009 kmem_free(filter, sizeof(*filter));
2010 }
2011
2012 /*
2013 * Free buffers currently in use by a descriptor.
2014 * Called on close.
2015 */
2016 static void
2017 bpf_freed(struct bpf_d *d)
2018 {
2019 /*
2020 * We don't need to lock out interrupts since this descriptor has
2021 * been detached from its interface and it yet hasn't been marked
2022 * free.
2023 */
2024 if (d->bd_sbuf != NULL) {
2025 kmem_free(d->bd_sbuf, d->bd_bufsize);
2026 if (d->bd_hbuf != NULL)
2027 kmem_free(d->bd_hbuf, d->bd_bufsize);
2028 if (d->bd_fbuf != NULL)
2029 kmem_free(d->bd_fbuf, d->bd_bufsize);
2030 }
2031 if (d->bd_filter != NULL) {
2032 bpf_free_filter(d->bd_filter);
2033 d->bd_filter = NULL;
2034 }
2035 d->bd_jitcode = NULL;
2036 }
2037
2038 /*
2039 * Attach an interface to bpf. dlt is the link layer type;
2040 * hdrlen is the fixed size of the link header for the specified dlt
2041 * (variable length headers not yet supported).
2042 */
2043 static void
2044 _bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2045 {
2046 struct bpf_if *bp;
2047 bp = kmem_alloc(sizeof(*bp), KM_NOSLEEP);
2048 if (bp == NULL)
2049 panic("bpfattach");
2050
2051 mutex_enter(&bpf_mtx);
2052 bp->bif_driverp = driverp;
2053 bp->bif_ifp = ifp;
2054 bp->bif_dlt = dlt;
2055 bp->bif_si = NULL;
2056 BPF_IFLIST_ENTRY_INIT(bp);
2057 PSLIST_INIT(&bp->bif_dlist_head);
2058 psref_target_init(&bp->bif_psref, bpf_psref_class);
2059
2060 BPF_IFLIST_WRITER_INSERT_HEAD(bp);
2061
2062 *bp->bif_driverp = NULL;
2063
2064 bp->bif_hdrlen = hdrlen;
2065 mutex_exit(&bpf_mtx);
2066 #if 0
2067 printf("bpf: %s attached\n", ifp->if_xname);
2068 #endif
2069 }
2070
2071 static void
2072 _bpf_mtap_softint_init(struct ifnet *ifp)
2073 {
2074 struct bpf_if *bp;
2075
2076 mutex_enter(&bpf_mtx);
2077 BPF_IFLIST_WRITER_FOREACH(bp) {
2078 if (bp->bif_ifp != ifp)
2079 continue;
2080
2081 bp->bif_mbuf_head = NULL;
2082 bp->bif_mbuf_tail = NULL;
2083 bp->bif_si = softint_establish(SOFTINT_NET, bpf_mtap_si, bp);
2084 if (bp->bif_si == NULL)
2085 panic("%s: softint_establish() failed", __func__);
2086 break;
2087 }
2088 mutex_exit(&bpf_mtx);
2089
2090 if (bp == NULL)
2091 panic("%s: no bpf_if found for %s", __func__, ifp->if_xname);
2092 }
2093
2094 /*
2095 * Remove an interface from bpf.
2096 */
2097 static void
2098 _bpfdetach(struct ifnet *ifp)
2099 {
2100 struct bpf_if *bp;
2101 struct bpf_d *d;
2102 int s;
2103
2104 mutex_enter(&bpf_mtx);
2105 /* Nuke the vnodes for any open instances */
2106 again_d:
2107 BPF_DLIST_WRITER_FOREACH(d) {
2108 mutex_enter(d->bd_mtx);
2109 if (d->bd_bif != NULL && d->bd_bif->bif_ifp == ifp) {
2110 /*
2111 * Detach the descriptor from an interface now.
2112 * It will be free'ed later by close routine.
2113 */
2114 d->bd_promisc = 0; /* we can't touch device. */
2115 bpf_detachd(d);
2116 mutex_exit(d->bd_mtx);
2117 goto again_d;
2118 }
2119 mutex_exit(d->bd_mtx);
2120 }
2121
2122 again:
2123 BPF_IFLIST_WRITER_FOREACH(bp) {
2124 if (bp->bif_ifp == ifp) {
2125 BPF_IFLIST_WRITER_REMOVE(bp);
2126
2127 pserialize_perform(bpf_psz);
2128 psref_target_destroy(&bp->bif_psref, bpf_psref_class);
2129
2130 BPF_IFLIST_ENTRY_DESTROY(bp);
2131 if (bp->bif_si != NULL) {
2132 /* XXX NOMPSAFE: assumed running on one CPU */
2133 s = splnet();
2134 while (bp->bif_mbuf_head != NULL) {
2135 struct mbuf *m = bp->bif_mbuf_head;
2136 bp->bif_mbuf_head = m->m_nextpkt;
2137 m_freem(m);
2138 }
2139 splx(s);
2140 softint_disestablish(bp->bif_si);
2141 }
2142 kmem_free(bp, sizeof(*bp));
2143 goto again;
2144 }
2145 }
2146 mutex_exit(&bpf_mtx);
2147 }
2148
2149 /*
2150 * Change the data link type of a interface.
2151 */
2152 static void
2153 _bpf_change_type(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2154 {
2155 struct bpf_if *bp;
2156
2157 mutex_enter(&bpf_mtx);
2158 BPF_IFLIST_WRITER_FOREACH(bp) {
2159 if (bp->bif_driverp == &ifp->if_bpf)
2160 break;
2161 }
2162 if (bp == NULL)
2163 panic("bpf_change_type");
2164
2165 bp->bif_dlt = dlt;
2166
2167 bp->bif_hdrlen = hdrlen;
2168 mutex_exit(&bpf_mtx);
2169 }
2170
2171 /*
2172 * Get a list of available data link type of the interface.
2173 */
2174 static int
2175 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2176 {
2177 int n, error;
2178 struct ifnet *ifp;
2179 struct bpf_if *bp;
2180 int s, bound;
2181
2182 KASSERT(mutex_owned(d->bd_mtx));
2183
2184 ifp = d->bd_bif->bif_ifp;
2185 n = 0;
2186 error = 0;
2187
2188 bound = curlwp_bind();
2189 s = pserialize_read_enter();
2190 BPF_IFLIST_READER_FOREACH(bp) {
2191 if (bp->bif_ifp != ifp)
2192 continue;
2193 if (bfl->bfl_list != NULL) {
2194 struct psref psref;
2195
2196 if (n >= bfl->bfl_len) {
2197 pserialize_read_exit(s);
2198 return ENOMEM;
2199 }
2200
2201 bpf_if_acquire(bp, &psref);
2202 pserialize_read_exit(s);
2203
2204 error = copyout(&bp->bif_dlt,
2205 bfl->bfl_list + n, sizeof(u_int));
2206
2207 s = pserialize_read_enter();
2208 bpf_if_release(bp, &psref);
2209 }
2210 n++;
2211 }
2212 pserialize_read_exit(s);
2213 curlwp_bindx(bound);
2214
2215 bfl->bfl_len = n;
2216 return error;
2217 }
2218
2219 /*
2220 * Set the data link type of a BPF instance.
2221 */
2222 static int
2223 bpf_setdlt(struct bpf_d *d, u_int dlt)
2224 {
2225 int error, opromisc;
2226 struct ifnet *ifp;
2227 struct bpf_if *bp;
2228
2229 KASSERT(mutex_owned(&bpf_mtx));
2230 KASSERT(mutex_owned(d->bd_mtx));
2231
2232 if (d->bd_bif->bif_dlt == dlt)
2233 return 0;
2234 ifp = d->bd_bif->bif_ifp;
2235 BPF_IFLIST_WRITER_FOREACH(bp) {
2236 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2237 break;
2238 }
2239 if (bp == NULL)
2240 return EINVAL;
2241 opromisc = d->bd_promisc;
2242 bpf_detachd(d);
2243 bpf_attachd(d, bp);
2244 reset_d(d);
2245 if (opromisc) {
2246 #ifndef NET_MPSAFE
2247 KERNEL_LOCK(1, NULL);
2248 #endif
2249 error = ifpromisc(bp->bif_ifp, 1);
2250 #ifndef NET_MPSAFE
2251 KERNEL_UNLOCK_ONE(NULL);
2252 #endif
2253 if (error)
2254 printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
2255 bp->bif_ifp->if_xname, error);
2256 else
2257 d->bd_promisc = 1;
2258 }
2259 return 0;
2260 }
2261
2262 static int
2263 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
2264 {
2265 int newsize, error;
2266 struct sysctlnode node;
2267
2268 node = *rnode;
2269 node.sysctl_data = &newsize;
2270 newsize = bpf_maxbufsize;
2271 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2272 if (error || newp == NULL)
2273 return (error);
2274
2275 if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
2276 return (EINVAL);
2277
2278 bpf_maxbufsize = newsize;
2279
2280 return (0);
2281 }
2282
2283 #if defined(MODULAR) || defined(BPFJIT)
2284 static int
2285 sysctl_net_bpf_jit(SYSCTLFN_ARGS)
2286 {
2287 bool newval;
2288 int error;
2289 struct sysctlnode node;
2290
2291 node = *rnode;
2292 node.sysctl_data = &newval;
2293 newval = bpf_jit;
2294 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2295 if (error != 0 || newp == NULL)
2296 return error;
2297
2298 bpf_jit = newval;
2299
2300 /*
2301 * Do a full sync to publish new bpf_jit value and
2302 * update bpfjit_module_ops.bj_generate_code variable.
2303 */
2304 membar_sync();
2305
2306 if (newval && bpfjit_module_ops.bj_generate_code == NULL) {
2307 printf("JIT compilation is postponed "
2308 "until after bpfjit module is loaded\n");
2309 }
2310
2311 return 0;
2312 }
2313 #endif
2314
2315 static int
2316 sysctl_net_bpf_peers(SYSCTLFN_ARGS)
2317 {
2318 int error, elem_count;
2319 struct bpf_d *dp;
2320 struct bpf_d_ext dpe;
2321 size_t len, needed, elem_size, out_size;
2322 char *sp;
2323
2324 if (namelen == 1 && name[0] == CTL_QUERY)
2325 return (sysctl_query(SYSCTLFN_CALL(rnode)));
2326
2327 if (namelen != 2)
2328 return (EINVAL);
2329
2330 /* BPF peers is privileged information. */
2331 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
2332 KAUTH_REQ_NETWORK_INTERFACE_GETPRIV, NULL, NULL, NULL);
2333 if (error)
2334 return (EPERM);
2335
2336 len = (oldp != NULL) ? *oldlenp : 0;
2337 sp = oldp;
2338 elem_size = name[0];
2339 elem_count = name[1];
2340 out_size = MIN(sizeof(dpe), elem_size);
2341 needed = 0;
2342
2343 if (elem_size < 1 || elem_count < 0)
2344 return (EINVAL);
2345
2346 mutex_enter(&bpf_mtx);
2347 BPF_DLIST_WRITER_FOREACH(dp) {
2348 if (len >= elem_size && elem_count > 0) {
2349 #define BPF_EXT(field) dpe.bde_ ## field = dp->bd_ ## field
2350 BPF_EXT(bufsize);
2351 BPF_EXT(promisc);
2352 BPF_EXT(state);
2353 BPF_EXT(immediate);
2354 BPF_EXT(hdrcmplt);
2355 BPF_EXT(seesent);
2356 BPF_EXT(pid);
2357 BPF_EXT(rcount);
2358 BPF_EXT(dcount);
2359 BPF_EXT(ccount);
2360 #undef BPF_EXT
2361 mutex_enter(dp->bd_mtx);
2362 if (dp->bd_bif)
2363 (void)strlcpy(dpe.bde_ifname,
2364 dp->bd_bif->bif_ifp->if_xname,
2365 IFNAMSIZ - 1);
2366 else
2367 dpe.bde_ifname[0] = '\0';
2368 mutex_exit(dp->bd_mtx);
2369
2370 error = copyout(&dpe, sp, out_size);
2371 if (error)
2372 break;
2373 sp += elem_size;
2374 len -= elem_size;
2375 }
2376 needed += elem_size;
2377 if (elem_count > 0 && elem_count != INT_MAX)
2378 elem_count--;
2379 }
2380 mutex_exit(&bpf_mtx);
2381
2382 *oldlenp = needed;
2383
2384 return (error);
2385 }
2386
2387 static void
2388 bpf_stats(void *p, void *arg, struct cpu_info *ci __unused)
2389 {
2390 struct bpf_stat *const stats = p;
2391 struct bpf_stat *sum = arg;
2392
2393 sum->bs_recv += stats->bs_recv;
2394 sum->bs_drop += stats->bs_drop;
2395 sum->bs_capt += stats->bs_capt;
2396 }
2397
2398 static int
2399 bpf_sysctl_gstats_handler(SYSCTLFN_ARGS)
2400 {
2401 struct sysctlnode node;
2402 int error;
2403 struct bpf_stat sum;
2404
2405 memset(&sum, 0, sizeof(sum));
2406 node = *rnode;
2407
2408 percpu_foreach(bpf_gstats_percpu, bpf_stats, &sum);
2409
2410 node.sysctl_data = ∑
2411 node.sysctl_size = sizeof(sum);
2412 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2413 if (error != 0 || newp == NULL)
2414 return error;
2415
2416 return 0;
2417 }
2418
2419 static struct sysctllog *bpf_sysctllog;
2420 static void
2421 sysctl_net_bpf_setup(void)
2422 {
2423 const struct sysctlnode *node;
2424
2425 node = NULL;
2426 sysctl_createv(&bpf_sysctllog, 0, NULL, &node,
2427 CTLFLAG_PERMANENT,
2428 CTLTYPE_NODE, "bpf",
2429 SYSCTL_DESCR("BPF options"),
2430 NULL, 0, NULL, 0,
2431 CTL_NET, CTL_CREATE, CTL_EOL);
2432 if (node != NULL) {
2433 #if defined(MODULAR) || defined(BPFJIT)
2434 sysctl_createv(&bpf_sysctllog, 0, NULL, NULL,
2435 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2436 CTLTYPE_BOOL, "jit",
2437 SYSCTL_DESCR("Toggle Just-In-Time compilation"),
2438 sysctl_net_bpf_jit, 0, &bpf_jit, 0,
2439 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2440 #endif
2441 sysctl_createv(&bpf_sysctllog, 0, NULL, NULL,
2442 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2443 CTLTYPE_INT, "maxbufsize",
2444 SYSCTL_DESCR("Maximum size for data capture buffer"),
2445 sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
2446 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2447 sysctl_createv(&bpf_sysctllog, 0, NULL, NULL,
2448 CTLFLAG_PERMANENT,
2449 CTLTYPE_STRUCT, "stats",
2450 SYSCTL_DESCR("BPF stats"),
2451 bpf_sysctl_gstats_handler, 0, NULL, 0,
2452 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2453 sysctl_createv(&bpf_sysctllog, 0, NULL, NULL,
2454 CTLFLAG_PERMANENT,
2455 CTLTYPE_STRUCT, "peers",
2456 SYSCTL_DESCR("BPF peers"),
2457 sysctl_net_bpf_peers, 0, NULL, 0,
2458 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
2459 }
2460
2461 }
2462
2463 struct bpf_ops bpf_ops_kernel = {
2464 .bpf_attach = _bpfattach,
2465 .bpf_detach = _bpfdetach,
2466 .bpf_change_type = _bpf_change_type,
2467
2468 .bpf_tap = _bpf_tap,
2469 .bpf_mtap = _bpf_mtap,
2470 .bpf_mtap2 = _bpf_mtap2,
2471 .bpf_mtap_af = _bpf_mtap_af,
2472 .bpf_mtap_sl_in = _bpf_mtap_sl_in,
2473 .bpf_mtap_sl_out = _bpf_mtap_sl_out,
2474
2475 .bpf_mtap_softint = _bpf_mtap_softint,
2476 .bpf_mtap_softint_init = _bpf_mtap_softint_init,
2477 };
2478
2479 MODULE(MODULE_CLASS_DRIVER, bpf, "bpf_filter");
2480
2481 static int
2482 bpf_modcmd(modcmd_t cmd, void *arg)
2483 {
2484 #ifdef _MODULE
2485 devmajor_t bmajor, cmajor;
2486 #endif
2487 int error = 0;
2488
2489 switch (cmd) {
2490 case MODULE_CMD_INIT:
2491 bpf_init();
2492 #ifdef _MODULE
2493 bmajor = cmajor = NODEVMAJOR;
2494 error = devsw_attach("bpf", NULL, &bmajor,
2495 &bpf_cdevsw, &cmajor);
2496 if (error)
2497 break;
2498 #endif
2499
2500 bpf_ops_handover_enter(&bpf_ops_kernel);
2501 atomic_swap_ptr(&bpf_ops, &bpf_ops_kernel);
2502 bpf_ops_handover_exit();
2503 sysctl_net_bpf_setup();
2504 break;
2505
2506 case MODULE_CMD_FINI:
2507 /*
2508 * While there is no reference counting for bpf callers,
2509 * unload could at least in theory be done similarly to
2510 * system call disestablishment. This should even be
2511 * a little simpler:
2512 *
2513 * 1) replace op vector with stubs
2514 * 2) post update to all cpus with xc
2515 * 3) check that nobody is in bpf anymore
2516 * (it's doubtful we'd want something like l_sysent,
2517 * but we could do something like *signed* percpu
2518 * counters. if the sum is 0, we're good).
2519 * 4) if fail, unroll changes
2520 *
2521 * NOTE: change won't be atomic to the outside. some
2522 * packets may be not captured even if unload is
2523 * not succesful. I think packet capture not working
2524 * is a perfectly logical consequence of trying to
2525 * disable packet capture.
2526 */
2527 error = EOPNOTSUPP;
2528 /* insert sysctl teardown */
2529 break;
2530
2531 default:
2532 error = ENOTTY;
2533 break;
2534 }
2535
2536 return error;
2537 }
2538