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