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