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