]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/net/bpf.c
MFC r363988:
[FreeBSD/stable/9.git] / sys / net / bpf.c
1 /*-
2  * Copyright (c) 1990, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from the Stanford/CMU enet packet filter,
6  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
7  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
8  * Berkeley Laboratory.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)bpf.c       8.4 (Berkeley) 1/9/95
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_bpf.h"
41 #include "opt_compat.h"
42 #include "opt_netgraph.h"
43
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/lock.h>
47 #include <sys/rwlock.h>
48 #include <sys/systm.h>
49 #include <sys/conf.h>
50 #include <sys/fcntl.h>
51 #include <sys/jail.h>
52 #include <sys/malloc.h>
53 #include <sys/mbuf.h>
54 #include <sys/time.h>
55 #include <sys/priv.h>
56 #include <sys/proc.h>
57 #include <sys/signalvar.h>
58 #include <sys/filio.h>
59 #include <sys/sockio.h>
60 #include <sys/ttycom.h>
61 #include <sys/uio.h>
62
63 #include <sys/event.h>
64 #include <sys/file.h>
65 #include <sys/poll.h>
66 #include <sys/proc.h>
67
68 #include <sys/socket.h>
69
70 #include <net/if.h>
71 #define BPF_INTERNAL
72 #include <net/bpf.h>
73 #include <net/bpf_buffer.h>
74 #ifdef BPF_JITTER
75 #include <net/bpf_jitter.h>
76 #endif
77 #include <net/bpf_zerocopy.h>
78 #include <net/bpfdesc.h>
79 #include <net/vnet.h>
80
81 #include <netinet/in.h>
82 #include <netinet/if_ether.h>
83 #include <sys/kernel.h>
84 #include <sys/sysctl.h>
85
86 #include <net80211/ieee80211_freebsd.h>
87
88 #include <security/mac/mac_framework.h>
89
90 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
91
92 #if defined(DEV_BPF) || defined(NETGRAPH_BPF)
93
94 #define PRINET  26                      /* interruptible */
95
96 #define SIZEOF_BPF_HDR(type)    \
97     (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
98
99 #ifdef COMPAT_FREEBSD32
100 #include <sys/mount.h>
101 #include <compat/freebsd32/freebsd32.h>
102 #define BPF_ALIGNMENT32 sizeof(int32_t)
103 #define BPF_WORDALIGN32(x) (((x)+(BPF_ALIGNMENT32-1))&~(BPF_ALIGNMENT32-1))
104
105 #ifndef BURN_BRIDGES
106 /*
107  * 32-bit version of structure prepended to each packet.  We use this header
108  * instead of the standard one for 32-bit streams.  We mark the a stream as
109  * 32-bit the first time we see a 32-bit compat ioctl request.
110  */
111 struct bpf_hdr32 {
112         struct timeval32 bh_tstamp;     /* time stamp */
113         uint32_t        bh_caplen;      /* length of captured portion */
114         uint32_t        bh_datalen;     /* original length of packet */
115         uint16_t        bh_hdrlen;      /* length of bpf header (this struct
116                                            plus alignment padding) */
117 };
118 #endif
119
120 struct bpf_program32 {
121         u_int bf_len;
122         uint32_t bf_insns;
123 };
124
125 struct bpf_dltlist32 {
126         u_int   bfl_len;
127         u_int   bfl_list;
128 };
129
130 #define BIOCSETF32      _IOW('B', 103, struct bpf_program32)
131 #define BIOCSRTIMEOUT32 _IOW('B', 109, struct timeval32)
132 #define BIOCGRTIMEOUT32 _IOR('B', 110, struct timeval32)
133 #define BIOCGDLTLIST32  _IOWR('B', 121, struct bpf_dltlist32)
134 #define BIOCSETWF32     _IOW('B', 123, struct bpf_program32)
135 #define BIOCSETFNR32    _IOW('B', 130, struct bpf_program32)
136 #endif
137
138 /*
139  * bpf_iflist is a list of BPF interface structures, each corresponding to a
140  * specific DLT.  The same network interface might have several BPF interface
141  * structures registered by different layers in the stack (i.e., 802.11
142  * frames, ethernet frames, etc).
143  */
144 static LIST_HEAD(, bpf_if)      bpf_iflist;
145 static struct mtx       bpf_mtx;                /* bpf global lock */
146 static int              bpf_bpfd_cnt;
147
148 static void     bpf_attachd(struct bpf_d *, struct bpf_if *);
149 static void     bpf_detachd(struct bpf_d *);
150 static void     bpf_detachd_locked(struct bpf_d *);
151 static void     bpf_freed(struct bpf_d *);
152 static int      bpf_movein(struct uio *, int, struct ifnet *, struct mbuf **,
153                     struct sockaddr *, int *, struct bpf_insn *);
154 static int      bpf_setif(struct bpf_d *, struct ifreq *);
155 static void     bpf_timed_out(void *);
156 static __inline void
157                 bpf_wakeup(struct bpf_d *);
158 static void     catchpacket(struct bpf_d *, u_char *, u_int, u_int,
159                     void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
160                     struct bintime *);
161 static void     reset_d(struct bpf_d *);
162 static int      bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
163 static int      bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
164 static int      bpf_setdlt(struct bpf_d *, u_int);
165 static void     filt_bpfdetach(struct knote *);
166 static int      filt_bpfread(struct knote *, long);
167 static void     bpf_drvinit(void *);
168 static int      bpf_stats_sysctl(SYSCTL_HANDLER_ARGS);
169
170 SYSCTL_NODE(_net, OID_AUTO, bpf, CTLFLAG_RW, 0, "bpf sysctl");
171 int bpf_maxinsns = BPF_MAXINSNS;
172 SYSCTL_INT(_net_bpf, OID_AUTO, maxinsns, CTLFLAG_RW,
173     &bpf_maxinsns, 0, "Maximum bpf program instructions");
174 static int bpf_zerocopy_enable = 0;
175 SYSCTL_INT(_net_bpf, OID_AUTO, zerocopy_enable, CTLFLAG_RW,
176     &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
177 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
178     bpf_stats_sysctl, "bpf statistics portal");
179
180 static VNET_DEFINE(int, bpf_optimize_writers) = 0;
181 #define V_bpf_optimize_writers VNET(bpf_optimize_writers)
182 SYSCTL_VNET_INT(_net_bpf, OID_AUTO, optimize_writers,
183     CTLFLAG_RW, &VNET_NAME(bpf_optimize_writers), 0,
184     "Do not send packets until BPF program is set");
185
186 static  d_open_t        bpfopen;
187 static  d_read_t        bpfread;
188 static  d_write_t       bpfwrite;
189 static  d_ioctl_t       bpfioctl;
190 static  d_poll_t        bpfpoll;
191 static  d_kqfilter_t    bpfkqfilter;
192
193 static struct cdevsw bpf_cdevsw = {
194         .d_version =    D_VERSION,
195         .d_open =       bpfopen,
196         .d_read =       bpfread,
197         .d_write =      bpfwrite,
198         .d_ioctl =      bpfioctl,
199         .d_poll =       bpfpoll,
200         .d_name =       "bpf",
201         .d_kqfilter =   bpfkqfilter,
202 };
203
204 static struct filterops bpfread_filtops = {
205         .f_isfd = 1,
206         .f_detach = filt_bpfdetach,
207         .f_event = filt_bpfread,
208 };
209
210 eventhandler_tag        bpf_ifdetach_cookie = NULL;
211
212 /*
213  * LOCKING MODEL USED BY BPF:
214  * Locks:
215  * 1) global lock (BPF_LOCK). Mutex, used to protect interface addition/removal,
216  * some global counters and every bpf_if reference.
217  * 2) Interface lock. Rwlock, used to protect list of BPF descriptors and their filters.
218  * 3) Descriptor lock. Mutex, used to protect BPF buffers and various structure fields
219  *   used by bpf_mtap code.
220  *
221  * Lock order:
222  *
223  * Global lock, interface lock, descriptor lock
224  *
225  * We have to acquire interface lock before descriptor main lock due to BPF_MTAP[2]
226  * working model. In many places (like bpf_detachd) we start with BPF descriptor
227  * (and we need to at least rlock it to get reliable interface pointer). This
228  * gives us potential LOR. As a result, we use global lock to protect from bpf_if
229  * change in every such place.
230  *
231  * Changing d->bd_bif is protected by 1) global lock, 2) interface lock and
232  * 3) descriptor main wlock.
233  * Reading bd_bif can be protected by any of these locks, typically global lock.
234  *
235  * Changing read/write BPF filter is protected by the same three locks,
236  * the same applies for reading.
237  *
238  * Sleeping in global lock is not allowed due to bpfdetach() using it.
239  */
240
241 /*
242  * Wrapper functions for various buffering methods.  If the set of buffer
243  * modes expands, we will probably want to introduce a switch data structure
244  * similar to protosw, et.
245  */
246 static void
247 bpf_append_bytes(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
248     u_int len)
249 {
250
251         BPFD_LOCK_ASSERT(d);
252
253         switch (d->bd_bufmode) {
254         case BPF_BUFMODE_BUFFER:
255                 return (bpf_buffer_append_bytes(d, buf, offset, src, len));
256
257         case BPF_BUFMODE_ZBUF:
258                 d->bd_zcopy++;
259                 return (bpf_zerocopy_append_bytes(d, buf, offset, src, len));
260
261         default:
262                 panic("bpf_buf_append_bytes");
263         }
264 }
265
266 static void
267 bpf_append_mbuf(struct bpf_d *d, caddr_t buf, u_int offset, void *src,
268     u_int len)
269 {
270
271         BPFD_LOCK_ASSERT(d);
272
273         switch (d->bd_bufmode) {
274         case BPF_BUFMODE_BUFFER:
275                 return (bpf_buffer_append_mbuf(d, buf, offset, src, len));
276
277         case BPF_BUFMODE_ZBUF:
278                 d->bd_zcopy++;
279                 return (bpf_zerocopy_append_mbuf(d, buf, offset, src, len));
280
281         default:
282                 panic("bpf_buf_append_mbuf");
283         }
284 }
285
286 /*
287  * This function gets called when the free buffer is re-assigned.
288  */
289 static void
290 bpf_buf_reclaimed(struct bpf_d *d)
291 {
292
293         BPFD_LOCK_ASSERT(d);
294
295         switch (d->bd_bufmode) {
296         case BPF_BUFMODE_BUFFER:
297                 return;
298
299         case BPF_BUFMODE_ZBUF:
300                 bpf_zerocopy_buf_reclaimed(d);
301                 return;
302
303         default:
304                 panic("bpf_buf_reclaimed");
305         }
306 }
307
308 /*
309  * If the buffer mechanism has a way to decide that a held buffer can be made
310  * free, then it is exposed via the bpf_canfreebuf() interface.  (1) is
311  * returned if the buffer can be discarded, (0) is returned if it cannot.
312  */
313 static int
314 bpf_canfreebuf(struct bpf_d *d)
315 {
316
317         BPFD_LOCK_ASSERT(d);
318
319         switch (d->bd_bufmode) {
320         case BPF_BUFMODE_ZBUF:
321                 return (bpf_zerocopy_canfreebuf(d));
322         }
323         return (0);
324 }
325
326 /*
327  * Allow the buffer model to indicate that the current store buffer is
328  * immutable, regardless of the appearance of space.  Return (1) if the
329  * buffer is writable, and (0) if not.
330  */
331 static int
332 bpf_canwritebuf(struct bpf_d *d)
333 {
334         BPFD_LOCK_ASSERT(d);
335
336         switch (d->bd_bufmode) {
337         case BPF_BUFMODE_ZBUF:
338                 return (bpf_zerocopy_canwritebuf(d));
339         }
340         return (1);
341 }
342
343 /*
344  * Notify buffer model that an attempt to write to the store buffer has
345  * resulted in a dropped packet, in which case the buffer may be considered
346  * full.
347  */
348 static void
349 bpf_buffull(struct bpf_d *d)
350 {
351
352         BPFD_LOCK_ASSERT(d);
353
354         switch (d->bd_bufmode) {
355         case BPF_BUFMODE_ZBUF:
356                 bpf_zerocopy_buffull(d);
357                 break;
358         }
359 }
360
361 /*
362  * Notify the buffer model that a buffer has moved into the hold position.
363  */
364 void
365 bpf_bufheld(struct bpf_d *d)
366 {
367
368         BPFD_LOCK_ASSERT(d);
369
370         switch (d->bd_bufmode) {
371         case BPF_BUFMODE_ZBUF:
372                 bpf_zerocopy_bufheld(d);
373                 break;
374         }
375 }
376
377 static void
378 bpf_free(struct bpf_d *d)
379 {
380
381         switch (d->bd_bufmode) {
382         case BPF_BUFMODE_BUFFER:
383                 return (bpf_buffer_free(d));
384
385         case BPF_BUFMODE_ZBUF:
386                 return (bpf_zerocopy_free(d));
387
388         default:
389                 panic("bpf_buf_free");
390         }
391 }
392
393 static int
394 bpf_uiomove(struct bpf_d *d, caddr_t buf, u_int len, struct uio *uio)
395 {
396
397         if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
398                 return (EOPNOTSUPP);
399         return (bpf_buffer_uiomove(d, buf, len, uio));
400 }
401
402 static int
403 bpf_ioctl_sblen(struct bpf_d *d, u_int *i)
404 {
405
406         if (d->bd_bufmode != BPF_BUFMODE_BUFFER)
407                 return (EOPNOTSUPP);
408         return (bpf_buffer_ioctl_sblen(d, i));
409 }
410
411 static int
412 bpf_ioctl_getzmax(struct thread *td, struct bpf_d *d, size_t *i)
413 {
414
415         if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
416                 return (EOPNOTSUPP);
417         return (bpf_zerocopy_ioctl_getzmax(td, d, i));
418 }
419
420 static int
421 bpf_ioctl_rotzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
422 {
423
424         if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
425                 return (EOPNOTSUPP);
426         return (bpf_zerocopy_ioctl_rotzbuf(td, d, bz));
427 }
428
429 static int
430 bpf_ioctl_setzbuf(struct thread *td, struct bpf_d *d, struct bpf_zbuf *bz)
431 {
432
433         if (d->bd_bufmode != BPF_BUFMODE_ZBUF)
434                 return (EOPNOTSUPP);
435         return (bpf_zerocopy_ioctl_setzbuf(td, d, bz));
436 }
437
438 /*
439  * General BPF functions.
440  */
441 static int
442 bpf_movein(struct uio *uio, int linktype, struct ifnet *ifp, struct mbuf **mp,
443     struct sockaddr *sockp, int *hdrlen, struct bpf_insn *wfilter)
444 {
445         const struct ieee80211_bpf_params *p;
446         struct ether_header *eh;
447         struct mbuf *m;
448         int error;
449         int len;
450         int hlen;
451         int slen;
452
453         /*
454          * Build a sockaddr based on the data link layer type.
455          * We do this at this level because the ethernet header
456          * is copied directly into the data field of the sockaddr.
457          * In the case of SLIP, there is no header and the packet
458          * is forwarded as is.
459          * Also, we are careful to leave room at the front of the mbuf
460          * for the link level header.
461          */
462         switch (linktype) {
463
464         case DLT_SLIP:
465                 sockp->sa_family = AF_INET;
466                 hlen = 0;
467                 break;
468
469         case DLT_EN10MB:
470                 sockp->sa_family = AF_UNSPEC;
471                 /* XXX Would MAXLINKHDR be better? */
472                 hlen = ETHER_HDR_LEN;
473                 break;
474
475         case DLT_FDDI:
476                 sockp->sa_family = AF_IMPLINK;
477                 hlen = 0;
478                 break;
479
480         case DLT_RAW:
481                 sockp->sa_family = AF_UNSPEC;
482                 hlen = 0;
483                 break;
484
485         case DLT_NULL:
486                 /*
487                  * null interface types require a 4 byte pseudo header which
488                  * corresponds to the address family of the packet.
489                  */
490                 sockp->sa_family = AF_UNSPEC;
491                 hlen = 4;
492                 break;
493
494         case DLT_ATM_RFC1483:
495                 /*
496                  * en atm driver requires 4-byte atm pseudo header.
497                  * though it isn't standard, vpi:vci needs to be
498                  * specified anyway.
499                  */
500                 sockp->sa_family = AF_UNSPEC;
501                 hlen = 12;      /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
502                 break;
503
504         case DLT_PPP:
505                 sockp->sa_family = AF_UNSPEC;
506                 hlen = 4;       /* This should match PPP_HDRLEN */
507                 break;
508
509         case DLT_IEEE802_11:            /* IEEE 802.11 wireless */
510                 sockp->sa_family = AF_IEEE80211;
511                 hlen = 0;
512                 break;
513
514         case DLT_IEEE802_11_RADIO:      /* IEEE 802.11 wireless w/ phy params */
515                 sockp->sa_family = AF_IEEE80211;
516                 sockp->sa_len = 12;     /* XXX != 0 */
517                 hlen = sizeof(struct ieee80211_bpf_params);
518                 break;
519
520         default:
521                 return (EIO);
522         }
523
524         len = uio->uio_resid;
525
526         if (len - hlen > ifp->if_mtu)
527                 return (EMSGSIZE);
528
529         if ((unsigned)len > MJUM16BYTES)
530                 return (EIO);
531
532         if (len <= MHLEN)
533                 MGETHDR(m, M_WAIT, MT_DATA);
534         else if (len <= MCLBYTES)
535                 m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
536         else
537                 m = m_getjcl(M_WAIT, MT_DATA, M_PKTHDR,
538 #if (MJUMPAGESIZE > MCLBYTES)
539                     len <= MJUMPAGESIZE ? MJUMPAGESIZE :
540 #endif
541                     (len <= MJUM9BYTES ? MJUM9BYTES : MJUM16BYTES));
542         m->m_pkthdr.len = m->m_len = len;
543         m->m_pkthdr.rcvif = NULL;
544         *mp = m;
545
546         if (m->m_len < hlen) {
547                 error = EPERM;
548                 goto bad;
549         }
550
551         error = uiomove(mtod(m, u_char *), len, uio);
552         if (error)
553                 goto bad;
554
555         slen = bpf_filter(wfilter, mtod(m, u_char *), len, len);
556         if (slen == 0) {
557                 error = EPERM;
558                 goto bad;
559         }
560
561         /* Check for multicast destination */
562         switch (linktype) {
563         case DLT_EN10MB:
564                 eh = mtod(m, struct ether_header *);
565                 if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
566                         if (bcmp(ifp->if_broadcastaddr, eh->ether_dhost,
567                             ETHER_ADDR_LEN) == 0)
568                                 m->m_flags |= M_BCAST;
569                         else
570                                 m->m_flags |= M_MCAST;
571                 }
572                 break;
573         }
574
575         /*
576          * Make room for link header, and copy it to sockaddr
577          */
578         if (hlen != 0) {
579                 if (sockp->sa_family == AF_IEEE80211) {
580                         /*
581                          * Collect true length from the parameter header
582                          * NB: sockp is known to be zero'd so if we do a
583                          *     short copy unspecified parameters will be
584                          *     zero.
585                          * NB: packet may not be aligned after stripping
586                          *     bpf params
587                          * XXX check ibp_vers
588                          */
589                         p = mtod(m, const struct ieee80211_bpf_params *);
590                         hlen = p->ibp_len;
591                         if (hlen > sizeof(sockp->sa_data)) {
592                                 error = EINVAL;
593                                 goto bad;
594                         }
595                 }
596                 bcopy(m->m_data, sockp->sa_data, hlen);
597         }
598         *hdrlen = hlen;
599
600         return (0);
601 bad:
602         m_freem(m);
603         return (error);
604 }
605
606 /*
607  * Attach file to the bpf interface, i.e. make d listen on bp.
608  */
609 static void
610 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
611 {
612         int op_w;
613
614         BPF_LOCK_ASSERT();
615
616         /*
617          * Save sysctl value to protect from sysctl change
618          * between reads
619          */
620         op_w = V_bpf_optimize_writers || d->bd_writer;
621
622         if (d->bd_bif != NULL)
623                 bpf_detachd_locked(d);
624         /*
625          * Point d at bp, and add d to the interface's list.
626          * Since there are many applicaiotns using BPF for
627          * sending raw packets only (dhcpd, cdpd are good examples)
628          * we can delay adding d to the list of active listeners until
629          * some filter is configured.
630          */
631
632         BPFIF_WLOCK(bp);
633         BPFD_LOCK(d);
634
635         d->bd_bif = bp;
636
637         if (op_w != 0) {
638                 /* Add to writers-only list */
639                 LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
640                 /*
641                  * We decrement bd_writer on every filter set operation.
642                  * First BIOCSETF is done by pcap_open_live() to set up
643                  * snap length. After that appliation usually sets its own filter
644                  */
645                 d->bd_writer = 2;
646         } else
647                 LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
648
649         BPFD_UNLOCK(d);
650         BPFIF_WUNLOCK(bp);
651
652         bpf_bpfd_cnt++;
653
654         CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
655             __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
656
657         if (op_w == 0)
658                 EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
659 }
660
661 /*
662  * Check if we need to upgrade our descriptor @d from write-only mode.
663  */
664 static int
665 bpf_check_upgrade(u_long cmd, struct bpf_d *d, struct bpf_insn *fcode, int flen)
666 {
667         int is_snap, need_upgrade;
668
669         /*
670          * Check if we've already upgraded or new filter is empty.
671          */
672         if (d->bd_writer == 0 || fcode == NULL)
673                 return (0);
674
675         need_upgrade = 0;
676
677         /*
678          * Check if cmd looks like snaplen setting from
679          * pcap_bpf.c:pcap_open_live().
680          * Note we're not checking .k value here:
681          * while pcap_open_live() definitely sets to to non-zero value,
682          * we'd prefer to treat k=0 (deny ALL) case the same way: e.g.
683          * do not consider upgrading immediately
684          */
685         if (cmd == BIOCSETF && flen == 1 && fcode[0].code == (BPF_RET | BPF_K))
686                 is_snap = 1;
687         else
688                 is_snap = 0;
689
690         if (is_snap == 0) {
691                 /*
692                  * We're setting first filter and it doesn't look like
693                  * setting snaplen.  We're probably using bpf directly.
694                  * Upgrade immediately.
695                  */
696                 need_upgrade = 1;
697         } else {
698                 /*
699                  * Do not require upgrade by first BIOCSETF
700                  * (used to set snaplen) by pcap_open_live().
701                  */
702
703                 if (--d->bd_writer == 0) {
704                         /*
705                          * First snaplen filter has already
706                          * been set. This is probably catch-all
707                          * filter
708                          */
709                         need_upgrade = 1;
710                 }
711         }
712
713         CTR5(KTR_NET,
714             "%s: filter function set by pid %d, "
715             "bd_writer counter %d, snap %d upgrade %d",
716             __func__, d->bd_pid, d->bd_writer,
717             is_snap, need_upgrade);
718
719         return (need_upgrade);
720 }
721
722 /*
723  * Add d to the list of active bp filters.
724  * Reuqires bpf_attachd() to be called before
725  */
726 static void
727 bpf_upgraded(struct bpf_d *d)
728 {
729         struct bpf_if *bp;
730
731         BPF_LOCK_ASSERT();
732
733         bp = d->bd_bif;
734
735         /*
736          * Filter can be set several times without specifying interface.
737          * Mark d as reader and exit.
738          */
739         if (bp == NULL) {
740                 BPFD_LOCK(d);
741                 d->bd_writer = 0;
742                 BPFD_UNLOCK(d);
743                 return;
744         }
745
746         BPFIF_WLOCK(bp);
747         BPFD_LOCK(d);
748
749         /* Remove from writers-only list */
750         LIST_REMOVE(d, bd_next);
751         LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
752         /* Mark d as reader */
753         d->bd_writer = 0;
754
755         BPFD_UNLOCK(d);
756         BPFIF_WUNLOCK(bp);
757
758         CTR2(KTR_NET, "%s: upgrade required by pid %d", __func__, d->bd_pid);
759
760         EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
761 }
762
763 /*
764  * Detach a file from its interface.
765  */
766 static void
767 bpf_detachd(struct bpf_d *d)
768 {
769         BPF_LOCK();
770         bpf_detachd_locked(d);
771         BPF_UNLOCK();
772 }
773
774 static void
775 bpf_detachd_locked(struct bpf_d *d)
776 {
777         int error;
778         struct bpf_if *bp;
779         struct ifnet *ifp;
780
781         CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
782
783         BPF_LOCK_ASSERT();
784
785         /* Check if descriptor is attached */
786         if ((bp = d->bd_bif) == NULL)
787                 return;
788
789         BPFIF_WLOCK(bp);
790         BPFD_LOCK(d);
791
792         /* Save bd_writer value */
793         error = d->bd_writer;
794
795         /*
796          * Remove d from the interface's descriptor list.
797          */
798         LIST_REMOVE(d, bd_next);
799
800         ifp = bp->bif_ifp;
801         d->bd_bif = NULL;
802         BPFD_UNLOCK(d);
803         BPFIF_WUNLOCK(bp);
804
805         bpf_bpfd_cnt--;
806
807         /* Call event handler iff d is attached */
808         if (error == 0)
809                 EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
810
811         /*
812          * Check if this descriptor had requested promiscuous mode.
813          * If so, turn it off.
814          */
815         if (d->bd_promisc) {
816                 d->bd_promisc = 0;
817                 CURVNET_SET(ifp->if_vnet);
818                 error = ifpromisc(ifp, 0);
819                 CURVNET_RESTORE();
820                 if (error != 0 && error != ENXIO) {
821                         /*
822                          * ENXIO can happen if a pccard is unplugged
823                          * Something is really wrong if we were able to put
824                          * the driver into promiscuous mode, but can't
825                          * take it out.
826                          */
827                         if_printf(bp->bif_ifp,
828                                 "bpf_detach: ifpromisc failed (%d)\n", error);
829                 }
830         }
831 }
832
833 /*
834  * Close the descriptor by detaching it from its interface,
835  * deallocating its buffers, and marking it free.
836  */
837 static void
838 bpf_dtor(void *data)
839 {
840         struct bpf_d *d = data;
841
842         BPFD_LOCK(d);
843         if (d->bd_state == BPF_WAITING)
844                 callout_stop(&d->bd_callout);
845         d->bd_state = BPF_IDLE;
846         BPFD_UNLOCK(d);
847         funsetown(&d->bd_sigio);
848         bpf_detachd(d);
849 #ifdef MAC
850         mac_bpfdesc_destroy(d);
851 #endif /* MAC */
852         seldrain(&d->bd_sel);
853         knlist_destroy(&d->bd_sel.si_note);
854         callout_drain(&d->bd_callout);
855         bpf_freed(d);
856         free(d, M_BPF);
857 }
858
859 /*
860  * Open ethernet device.  Returns ENXIO for illegal minor device number,
861  * EBUSY if file is open by another process.
862  */
863 /* ARGSUSED */
864 static  int
865 bpfopen(struct cdev *dev, int flags, int fmt, struct thread *td)
866 {
867         struct bpf_d *d;
868         int error, size;
869
870         d = malloc(sizeof(*d), M_BPF, M_WAITOK | M_ZERO);
871         error = devfs_set_cdevpriv(d, bpf_dtor);
872         if (error != 0) {
873                 free(d, M_BPF);
874                 return (error);
875         }
876
877         /*
878          * For historical reasons, perform a one-time initialization call to
879          * the buffer routines, even though we're not yet committed to a
880          * particular buffer method.
881          */
882         bpf_buffer_init(d);
883         if ((flags & FREAD) == 0)
884                 d->bd_writer = 2;
885         d->bd_hbuf_in_use = 0;
886         d->bd_bufmode = BPF_BUFMODE_BUFFER;
887         d->bd_sig = SIGIO;
888         d->bd_direction = BPF_D_INOUT;
889         BPF_PID_REFRESH(d, td);
890 #ifdef MAC
891         mac_bpfdesc_init(d);
892         mac_bpfdesc_create(td->td_ucred, d);
893 #endif
894         mtx_init(&d->bd_lock, devtoname(dev), "bpf cdev lock", MTX_DEF);
895         callout_init_mtx(&d->bd_callout, &d->bd_lock, 0);
896         knlist_init_mtx(&d->bd_sel.si_note, &d->bd_lock);
897
898         /* Allocate default buffers */
899         size = d->bd_bufsize;
900         bpf_buffer_ioctl_sblen(d, &size);
901
902         return (0);
903 }
904
905 /*
906  *  bpfread - read next chunk of packets from buffers
907  */
908 static  int
909 bpfread(struct cdev *dev, struct uio *uio, int ioflag)
910 {
911         struct bpf_d *d;
912         int error;
913         int non_block;
914         int timed_out;
915
916         error = devfs_get_cdevpriv((void **)&d);
917         if (error != 0)
918                 return (error);
919
920         /*
921          * Restrict application to use a buffer the same size as
922          * as kernel buffers.
923          */
924         if (uio->uio_resid != d->bd_bufsize)
925                 return (EINVAL);
926
927         non_block = ((ioflag & O_NONBLOCK) != 0);
928
929         BPFD_LOCK(d);
930         BPF_PID_REFRESH_CUR(d);
931         if (d->bd_bufmode != BPF_BUFMODE_BUFFER) {
932                 BPFD_UNLOCK(d);
933                 return (EOPNOTSUPP);
934         }
935         if (d->bd_state == BPF_WAITING)
936                 callout_stop(&d->bd_callout);
937         timed_out = (d->bd_state == BPF_TIMED_OUT);
938         d->bd_state = BPF_IDLE;
939         while (d->bd_hbuf_in_use) {
940                 error = mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
941                     PRINET|PCATCH, "bd_hbuf", 0);
942                 if (error != 0) {
943                         BPFD_UNLOCK(d);
944                         return (error);
945                 }
946         }
947         /*
948          * If the hold buffer is empty, then do a timed sleep, which
949          * ends when the timeout expires or when enough packets
950          * have arrived to fill the store buffer.
951          */
952         while (d->bd_hbuf == NULL) {
953                 if (d->bd_slen != 0) {
954                         /*
955                          * A packet(s) either arrived since the previous
956                          * read or arrived while we were asleep.
957                          */
958                         if (d->bd_immediate || non_block || timed_out) {
959                                 /*
960                                  * Rotate the buffers and return what's here
961                                  * if we are in immediate mode, non-blocking
962                                  * flag is set, or this descriptor timed out.
963                                  */
964                                 ROTATE_BUFFERS(d);
965                                 break;
966                         }
967                 }
968
969                 /*
970                  * No data is available, check to see if the bpf device
971                  * is still pointed at a real interface.  If not, return
972                  * ENXIO so that the userland process knows to rebind
973                  * it before using it again.
974                  */
975                 if (d->bd_bif == NULL) {
976                         BPFD_UNLOCK(d);
977                         return (ENXIO);
978                 }
979
980                 if (non_block) {
981                         BPFD_UNLOCK(d);
982                         return (EWOULDBLOCK);
983                 }
984                 error = msleep(d, &d->bd_lock, PRINET|PCATCH,
985                      "bpf", d->bd_rtout);
986                 if (error == EINTR || error == ERESTART) {
987                         BPFD_UNLOCK(d);
988                         return (error);
989                 }
990                 if (error == EWOULDBLOCK) {
991                         /*
992                          * On a timeout, return what's in the buffer,
993                          * which may be nothing.  If there is something
994                          * in the store buffer, we can rotate the buffers.
995                          */
996                         if (d->bd_hbuf)
997                                 /*
998                                  * We filled up the buffer in between
999                                  * getting the timeout and arriving
1000                                  * here, so we don't need to rotate.
1001                                  */
1002                                 break;
1003
1004                         if (d->bd_slen == 0) {
1005                                 BPFD_UNLOCK(d);
1006                                 return (0);
1007                         }
1008                         ROTATE_BUFFERS(d);
1009                         break;
1010                 }
1011         }
1012         /*
1013          * At this point, we know we have something in the hold slot.
1014          */
1015         d->bd_hbuf_in_use = 1;
1016         BPFD_UNLOCK(d);
1017
1018         /*
1019          * Move data from hold buffer into user space.
1020          * We know the entire buffer is transferred since
1021          * we checked above that the read buffer is bpf_bufsize bytes.
1022          *
1023          * We do not have to worry about simultaneous reads because
1024          * we waited for sole access to the hold buffer above.
1025          */
1026         error = bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
1027
1028         BPFD_LOCK(d);
1029         KASSERT(d->bd_hbuf != NULL, ("bpfread: lost bd_hbuf"));
1030         d->bd_fbuf = d->bd_hbuf;
1031         d->bd_hbuf = NULL;
1032         d->bd_hlen = 0;
1033         bpf_buf_reclaimed(d);
1034         d->bd_hbuf_in_use = 0;
1035         wakeup(&d->bd_hbuf_in_use);
1036         BPFD_UNLOCK(d);
1037
1038         return (error);
1039 }
1040
1041 /*
1042  * If there are processes sleeping on this descriptor, wake them up.
1043  */
1044 static __inline void
1045 bpf_wakeup(struct bpf_d *d)
1046 {
1047
1048         BPFD_LOCK_ASSERT(d);
1049         if (d->bd_state == BPF_WAITING) {
1050                 callout_stop(&d->bd_callout);
1051                 d->bd_state = BPF_IDLE;
1052         }
1053         wakeup(d);
1054         if (d->bd_async && d->bd_sig && d->bd_sigio)
1055                 pgsigio(&d->bd_sigio, d->bd_sig, 0);
1056
1057         selwakeuppri(&d->bd_sel, PRINET);
1058         KNOTE_LOCKED(&d->bd_sel.si_note, 0);
1059 }
1060
1061 static void
1062 bpf_timed_out(void *arg)
1063 {
1064         struct bpf_d *d = (struct bpf_d *)arg;
1065
1066         BPFD_LOCK_ASSERT(d);
1067
1068         if (callout_pending(&d->bd_callout) || !callout_active(&d->bd_callout))
1069                 return;
1070         if (d->bd_state == BPF_WAITING) {
1071                 d->bd_state = BPF_TIMED_OUT;
1072                 if (d->bd_slen != 0)
1073                         bpf_wakeup(d);
1074         }
1075 }
1076
1077 static int
1078 bpf_ready(struct bpf_d *d)
1079 {
1080
1081         BPFD_LOCK_ASSERT(d);
1082
1083         if (!bpf_canfreebuf(d) && d->bd_hlen != 0)
1084                 return (1);
1085         if ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1086             d->bd_slen != 0)
1087                 return (1);
1088         return (0);
1089 }
1090
1091 static int
1092 bpfwrite(struct cdev *dev, struct uio *uio, int ioflag)
1093 {
1094         struct bpf_d *d;
1095         struct ifnet *ifp;
1096         struct mbuf *m, *mc;
1097         struct sockaddr dst;
1098         int error, hlen;
1099
1100         error = devfs_get_cdevpriv((void **)&d);
1101         if (error != 0)
1102                 return (error);
1103
1104         BPF_PID_REFRESH_CUR(d);
1105         d->bd_wcount++;
1106         /* XXX: locking required */
1107         if (d->bd_bif == NULL) {
1108                 d->bd_wdcount++;
1109                 return (ENXIO);
1110         }
1111
1112         ifp = d->bd_bif->bif_ifp;
1113
1114         if ((ifp->if_flags & IFF_UP) == 0) {
1115                 d->bd_wdcount++;
1116                 return (ENETDOWN);
1117         }
1118
1119         if (uio->uio_resid == 0) {
1120                 d->bd_wdcount++;
1121                 return (0);
1122         }
1123
1124         bzero(&dst, sizeof(dst));
1125         m = NULL;
1126         hlen = 0;
1127         /* XXX: bpf_movein() can sleep */
1128         error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp,
1129             &m, &dst, &hlen, d->bd_wfilter);
1130         if (error) {
1131                 d->bd_wdcount++;
1132                 return (error);
1133         }
1134         d->bd_wfcount++;
1135         if (d->bd_hdrcmplt)
1136                 dst.sa_family = pseudo_AF_HDRCMPLT;
1137
1138         if (d->bd_feedback) {
1139                 mc = m_dup(m, M_DONTWAIT);
1140                 if (mc != NULL)
1141                         mc->m_pkthdr.rcvif = ifp;
1142                 /* Set M_PROMISC for outgoing packets to be discarded. */
1143                 if (d->bd_direction == BPF_D_INOUT)
1144                         m->m_flags |= M_PROMISC;
1145         } else
1146                 mc = NULL;
1147
1148         m->m_pkthdr.len -= hlen;
1149         m->m_len -= hlen;
1150         m->m_data += hlen;      /* XXX */
1151
1152         CURVNET_SET(ifp->if_vnet);
1153 #ifdef MAC
1154         BPFD_LOCK(d);
1155         mac_bpfdesc_create_mbuf(d, m);
1156         if (mc != NULL)
1157                 mac_bpfdesc_create_mbuf(d, mc);
1158         BPFD_UNLOCK(d);
1159 #endif
1160
1161         error = (*ifp->if_output)(ifp, m, &dst, NULL);
1162         if (error)
1163                 d->bd_wdcount++;
1164
1165         if (mc != NULL) {
1166                 if (error == 0)
1167                         (*ifp->if_input)(ifp, mc);
1168                 else
1169                         m_freem(mc);
1170         }
1171         CURVNET_RESTORE();
1172
1173         return (error);
1174 }
1175
1176 /*
1177  * Reset a descriptor by flushing its packet buffer and clearing the receive
1178  * and drop counts.  This is doable for kernel-only buffers, but with
1179  * zero-copy buffers, we can't write to (or rotate) buffers that are
1180  * currently owned by userspace.  It would be nice if we could encapsulate
1181  * this logic in the buffer code rather than here.
1182  */
1183 static void
1184 reset_d(struct bpf_d *d)
1185 {
1186
1187         BPFD_LOCK_ASSERT(d);
1188
1189         while (d->bd_hbuf_in_use)
1190                 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock, PRINET,
1191                     "bd_hbuf", 0);
1192         if ((d->bd_hbuf != NULL) &&
1193             (d->bd_bufmode != BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
1194                 /* Free the hold buffer. */
1195                 d->bd_fbuf = d->bd_hbuf;
1196                 d->bd_hbuf = NULL;
1197                 d->bd_hlen = 0;
1198                 bpf_buf_reclaimed(d);
1199         }
1200         if (bpf_canwritebuf(d))
1201                 d->bd_slen = 0;
1202         d->bd_rcount = 0;
1203         d->bd_dcount = 0;
1204         d->bd_fcount = 0;
1205         d->bd_wcount = 0;
1206         d->bd_wfcount = 0;
1207         d->bd_wdcount = 0;
1208         d->bd_zcopy = 0;
1209 }
1210
1211 /*
1212  *  FIONREAD            Check for read packet available.
1213  *  SIOCGIFADDR         Get interface address - convenient hook to driver.
1214  *  BIOCGBLEN           Get buffer len [for read()].
1215  *  BIOCSETF            Set read filter.
1216  *  BIOCSETFNR          Set read filter without resetting descriptor.
1217  *  BIOCSETWF           Set write filter.
1218  *  BIOCFLUSH           Flush read packet buffer.
1219  *  BIOCPROMISC         Put interface into promiscuous mode.
1220  *  BIOCGDLT            Get link layer type.
1221  *  BIOCGETIF           Get interface name.
1222  *  BIOCSETIF           Set interface.
1223  *  BIOCSRTIMEOUT       Set read timeout.
1224  *  BIOCGRTIMEOUT       Get read timeout.
1225  *  BIOCGSTATS          Get packet stats.
1226  *  BIOCIMMEDIATE       Set immediate mode.
1227  *  BIOCVERSION         Get filter language version.
1228  *  BIOCGHDRCMPLT       Get "header already complete" flag
1229  *  BIOCSHDRCMPLT       Set "header already complete" flag
1230  *  BIOCGDIRECTION      Get packet direction flag
1231  *  BIOCSDIRECTION      Set packet direction flag
1232  *  BIOCGTSTAMP         Get time stamp format and resolution.
1233  *  BIOCSTSTAMP         Set time stamp format and resolution.
1234  *  BIOCLOCK            Set "locked" flag
1235  *  BIOCFEEDBACK        Set packet feedback mode.
1236  *  BIOCSETZBUF         Set current zero-copy buffer locations.
1237  *  BIOCGETZMAX         Get maximum zero-copy buffer size.
1238  *  BIOCROTZBUF         Force rotation of zero-copy buffer
1239  *  BIOCSETBUFMODE      Set buffer mode.
1240  *  BIOCGETBUFMODE      Get current buffer mode.
1241  */
1242 /* ARGSUSED */
1243 static  int
1244 bpfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1245     struct thread *td)
1246 {
1247         struct bpf_d *d;
1248         int error;
1249
1250         error = devfs_get_cdevpriv((void **)&d);
1251         if (error != 0)
1252                 return (error);
1253
1254         /*
1255          * Refresh PID associated with this descriptor.
1256          */
1257         BPFD_LOCK(d);
1258         BPF_PID_REFRESH(d, td);
1259         if (d->bd_state == BPF_WAITING)
1260                 callout_stop(&d->bd_callout);
1261         d->bd_state = BPF_IDLE;
1262         BPFD_UNLOCK(d);
1263
1264         if (d->bd_locked == 1) {
1265                 switch (cmd) {
1266                 case BIOCGBLEN:
1267                 case BIOCFLUSH:
1268                 case BIOCGDLT:
1269                 case BIOCGDLTLIST:
1270 #ifdef COMPAT_FREEBSD32
1271                 case BIOCGDLTLIST32:
1272 #endif
1273                 case BIOCGETIF:
1274                 case BIOCGRTIMEOUT:
1275 #ifdef COMPAT_FREEBSD32
1276                 case BIOCGRTIMEOUT32:
1277 #endif
1278                 case BIOCGSTATS:
1279                 case BIOCVERSION:
1280                 case BIOCGRSIG:
1281                 case BIOCGHDRCMPLT:
1282                 case BIOCSTSTAMP:
1283                 case BIOCFEEDBACK:
1284                 case FIONREAD:
1285                 case BIOCLOCK:
1286                 case BIOCSRTIMEOUT:
1287 #ifdef COMPAT_FREEBSD32
1288                 case BIOCSRTIMEOUT32:
1289 #endif
1290                 case BIOCIMMEDIATE:
1291                 case TIOCGPGRP:
1292                 case BIOCROTZBUF:
1293                         break;
1294                 default:
1295                         return (EPERM);
1296                 }
1297         }
1298 #ifdef COMPAT_FREEBSD32
1299         /*
1300          * If we see a 32-bit compat ioctl, mark the stream as 32-bit so
1301          * that it will get 32-bit packet headers.
1302          */
1303         switch (cmd) {
1304         case BIOCSETF32:
1305         case BIOCSETFNR32:
1306         case BIOCSETWF32:
1307         case BIOCGDLTLIST32:
1308         case BIOCGRTIMEOUT32:
1309         case BIOCSRTIMEOUT32:
1310                 BPFD_LOCK(d);
1311                 d->bd_compat32 = 1;
1312                 BPFD_UNLOCK(d);
1313         }
1314 #endif
1315
1316         CURVNET_SET(TD_TO_VNET(td));
1317         switch (cmd) {
1318
1319         default:
1320                 error = EINVAL;
1321                 break;
1322
1323         /*
1324          * Check for read packet available.
1325          */
1326         case FIONREAD:
1327                 {
1328                         int n;
1329
1330                         BPFD_LOCK(d);
1331                         n = d->bd_slen;
1332                         while (d->bd_hbuf_in_use)
1333                                 mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
1334                                     PRINET, "bd_hbuf", 0);
1335                         if (d->bd_hbuf)
1336                                 n += d->bd_hlen;
1337                         BPFD_UNLOCK(d);
1338
1339                         *(int *)addr = n;
1340                         break;
1341                 }
1342
1343         case SIOCGIFADDR:
1344                 {
1345                         struct ifnet *ifp;
1346
1347                         if (d->bd_bif == NULL)
1348                                 error = EINVAL;
1349                         else {
1350                                 ifp = d->bd_bif->bif_ifp;
1351                                 error = (*ifp->if_ioctl)(ifp, cmd, addr);
1352                         }
1353                         break;
1354                 }
1355
1356         /*
1357          * Get buffer len [for read()].
1358          */
1359         case BIOCGBLEN:
1360                 BPFD_LOCK(d);
1361                 *(u_int *)addr = d->bd_bufsize;
1362                 BPFD_UNLOCK(d);
1363                 break;
1364
1365         /*
1366          * Set buffer length.
1367          */
1368         case BIOCSBLEN:
1369                 error = bpf_ioctl_sblen(d, (u_int *)addr);
1370                 break;
1371
1372         /*
1373          * Set link layer read filter.
1374          */
1375         case BIOCSETF:
1376         case BIOCSETFNR:
1377         case BIOCSETWF:
1378 #ifdef COMPAT_FREEBSD32
1379         case BIOCSETF32:
1380         case BIOCSETFNR32:
1381         case BIOCSETWF32:
1382 #endif
1383                 error = bpf_setf(d, (struct bpf_program *)addr, cmd);
1384                 break;
1385
1386         /*
1387          * Flush read packet buffer.
1388          */
1389         case BIOCFLUSH:
1390                 BPFD_LOCK(d);
1391                 reset_d(d);
1392                 BPFD_UNLOCK(d);
1393                 break;
1394
1395         /*
1396          * Put interface into promiscuous mode.
1397          */
1398         case BIOCPROMISC:
1399                 if (d->bd_bif == NULL) {
1400                         /*
1401                          * No interface attached yet.
1402                          */
1403                         error = EINVAL;
1404                         break;
1405                 }
1406                 if (d->bd_promisc == 0) {
1407                         error = ifpromisc(d->bd_bif->bif_ifp, 1);
1408                         if (error == 0)
1409                                 d->bd_promisc = 1;
1410                 }
1411                 break;
1412
1413         /*
1414          * Get current data link type.
1415          */
1416         case BIOCGDLT:
1417                 BPF_LOCK();
1418                 if (d->bd_bif == NULL)
1419                         error = EINVAL;
1420                 else
1421                         *(u_int *)addr = d->bd_bif->bif_dlt;
1422                 BPF_UNLOCK();
1423                 break;
1424
1425         /*
1426          * Get a list of supported data link types.
1427          */
1428 #ifdef COMPAT_FREEBSD32
1429         case BIOCGDLTLIST32:
1430                 {
1431                         struct bpf_dltlist32 *list32;
1432                         struct bpf_dltlist dltlist;
1433
1434                         list32 = (struct bpf_dltlist32 *)addr;
1435                         dltlist.bfl_len = list32->bfl_len;
1436                         dltlist.bfl_list = PTRIN(list32->bfl_list);
1437                         BPF_LOCK();
1438                         if (d->bd_bif == NULL)
1439                                 error = EINVAL;
1440                         else {
1441                                 error = bpf_getdltlist(d, &dltlist);
1442                                 if (error == 0)
1443                                         list32->bfl_len = dltlist.bfl_len;
1444                         }
1445                         BPF_UNLOCK();
1446                         break;
1447                 }
1448 #endif
1449
1450         case BIOCGDLTLIST:
1451                 BPF_LOCK();
1452                 if (d->bd_bif == NULL)
1453                         error = EINVAL;
1454                 else
1455                         error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
1456                 BPF_UNLOCK();
1457                 break;
1458
1459         /*
1460          * Set data link type.
1461          */
1462         case BIOCSDLT:
1463                 BPF_LOCK();
1464                 if (d->bd_bif == NULL)
1465                         error = EINVAL;
1466                 else
1467                         error = bpf_setdlt(d, *(u_int *)addr);
1468                 BPF_UNLOCK();
1469                 break;
1470
1471         /*
1472          * Get interface name.
1473          */
1474         case BIOCGETIF:
1475                 BPF_LOCK();
1476                 if (d->bd_bif == NULL)
1477                         error = EINVAL;
1478                 else {
1479                         struct ifnet *const ifp = d->bd_bif->bif_ifp;
1480                         struct ifreq *const ifr = (struct ifreq *)addr;
1481
1482                         strlcpy(ifr->ifr_name, ifp->if_xname,
1483                             sizeof(ifr->ifr_name));
1484                 }
1485                 BPF_UNLOCK();
1486                 break;
1487
1488         /*
1489          * Set interface.
1490          */
1491         case BIOCSETIF:
1492                 BPF_LOCK();
1493                 error = bpf_setif(d, (struct ifreq *)addr);
1494                 BPF_UNLOCK();
1495                 break;
1496
1497         /*
1498          * Set read timeout.
1499          */
1500         case BIOCSRTIMEOUT:
1501 #ifdef COMPAT_FREEBSD32
1502         case BIOCSRTIMEOUT32:
1503 #endif
1504                 {
1505                         struct timeval *tv = (struct timeval *)addr;
1506 #ifdef COMPAT_FREEBSD32
1507                         struct timeval32 *tv32;
1508                         struct timeval tv64;
1509
1510                         if (cmd == BIOCSRTIMEOUT32) {
1511                                 tv32 = (struct timeval32 *)addr;
1512                                 tv = &tv64;
1513                                 tv->tv_sec = tv32->tv_sec;
1514                                 tv->tv_usec = tv32->tv_usec;
1515                         } else
1516 #endif
1517                                 tv = (struct timeval *)addr;
1518
1519                         /*
1520                          * Subtract 1 tick from tvtohz() since this isn't
1521                          * a one-shot timer.
1522                          */
1523                         if ((error = itimerfix(tv)) == 0)
1524                                 d->bd_rtout = tvtohz(tv) - 1;
1525                         break;
1526                 }
1527
1528         /*
1529          * Get read timeout.
1530          */
1531         case BIOCGRTIMEOUT:
1532 #ifdef COMPAT_FREEBSD32
1533         case BIOCGRTIMEOUT32:
1534 #endif
1535                 {
1536                         struct timeval *tv;
1537 #ifdef COMPAT_FREEBSD32
1538                         struct timeval32 *tv32;
1539                         struct timeval tv64;
1540
1541                         if (cmd == BIOCGRTIMEOUT32)
1542                                 tv = &tv64;
1543                         else
1544 #endif
1545                                 tv = (struct timeval *)addr;
1546
1547                         tv->tv_sec = d->bd_rtout / hz;
1548                         tv->tv_usec = (d->bd_rtout % hz) * tick;
1549 #ifdef COMPAT_FREEBSD32
1550                         if (cmd == BIOCGRTIMEOUT32) {
1551                                 tv32 = (struct timeval32 *)addr;
1552                                 tv32->tv_sec = tv->tv_sec;
1553                                 tv32->tv_usec = tv->tv_usec;
1554                         }
1555 #endif
1556
1557                         break;
1558                 }
1559
1560         /*
1561          * Get packet stats.
1562          */
1563         case BIOCGSTATS:
1564                 {
1565                         struct bpf_stat *bs = (struct bpf_stat *)addr;
1566
1567                         /* XXXCSJP overflow */
1568                         bs->bs_recv = d->bd_rcount;
1569                         bs->bs_drop = d->bd_dcount;
1570                         break;
1571                 }
1572
1573         /*
1574          * Set immediate mode.
1575          */
1576         case BIOCIMMEDIATE:
1577                 BPFD_LOCK(d);
1578                 d->bd_immediate = *(u_int *)addr;
1579                 BPFD_UNLOCK(d);
1580                 break;
1581
1582         case BIOCVERSION:
1583                 {
1584                         struct bpf_version *bv = (struct bpf_version *)addr;
1585
1586                         bv->bv_major = BPF_MAJOR_VERSION;
1587                         bv->bv_minor = BPF_MINOR_VERSION;
1588                         break;
1589                 }
1590
1591         /*
1592          * Get "header already complete" flag
1593          */
1594         case BIOCGHDRCMPLT:
1595                 BPFD_LOCK(d);
1596                 *(u_int *)addr = d->bd_hdrcmplt;
1597                 BPFD_UNLOCK(d);
1598                 break;
1599
1600         /*
1601          * Set "header already complete" flag
1602          */
1603         case BIOCSHDRCMPLT:
1604                 BPFD_LOCK(d);
1605                 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
1606                 BPFD_UNLOCK(d);
1607                 break;
1608
1609         /*
1610          * Get packet direction flag
1611          */
1612         case BIOCGDIRECTION:
1613                 BPFD_LOCK(d);
1614                 *(u_int *)addr = d->bd_direction;
1615                 BPFD_UNLOCK(d);
1616                 break;
1617
1618         /*
1619          * Set packet direction flag
1620          */
1621         case BIOCSDIRECTION:
1622                 {
1623                         u_int   direction;
1624
1625                         direction = *(u_int *)addr;
1626                         switch (direction) {
1627                         case BPF_D_IN:
1628                         case BPF_D_INOUT:
1629                         case BPF_D_OUT:
1630                                 BPFD_LOCK(d);
1631                                 d->bd_direction = direction;
1632                                 BPFD_UNLOCK(d);
1633                                 break;
1634                         default:
1635                                 error = EINVAL;
1636                         }
1637                 }
1638                 break;
1639
1640         /*
1641          * Get packet timestamp format and resolution.
1642          */
1643         case BIOCGTSTAMP:
1644                 BPFD_LOCK(d);
1645                 *(u_int *)addr = d->bd_tstamp;
1646                 BPFD_UNLOCK(d);
1647                 break;
1648
1649         /*
1650          * Set packet timestamp format and resolution.
1651          */
1652         case BIOCSTSTAMP:
1653                 {
1654                         u_int   func;
1655
1656                         func = *(u_int *)addr;
1657                         if (BPF_T_VALID(func))
1658                                 d->bd_tstamp = func;
1659                         else
1660                                 error = EINVAL;
1661                 }
1662                 break;
1663
1664         case BIOCFEEDBACK:
1665                 BPFD_LOCK(d);
1666                 d->bd_feedback = *(u_int *)addr;
1667                 BPFD_UNLOCK(d);
1668                 break;
1669
1670         case BIOCLOCK:
1671                 BPFD_LOCK(d);
1672                 d->bd_locked = 1;
1673                 BPFD_UNLOCK(d);
1674                 break;
1675
1676         case FIONBIO:           /* Non-blocking I/O */
1677                 break;
1678
1679         case FIOASYNC:          /* Send signal on receive packets */
1680                 BPFD_LOCK(d);
1681                 d->bd_async = *(int *)addr;
1682                 BPFD_UNLOCK(d);
1683                 break;
1684
1685         case FIOSETOWN:
1686                 /*
1687                  * XXX: Add some sort of locking here?
1688                  * fsetown() can sleep.
1689                  */
1690                 error = fsetown(*(int *)addr, &d->bd_sigio);
1691                 break;
1692
1693         case FIOGETOWN:
1694                 BPFD_LOCK(d);
1695                 *(int *)addr = fgetown(&d->bd_sigio);
1696                 BPFD_UNLOCK(d);
1697                 break;
1698
1699         /* This is deprecated, FIOSETOWN should be used instead. */
1700         case TIOCSPGRP:
1701                 error = fsetown(-(*(int *)addr), &d->bd_sigio);
1702                 break;
1703
1704         /* This is deprecated, FIOGETOWN should be used instead. */
1705         case TIOCGPGRP:
1706                 *(int *)addr = -fgetown(&d->bd_sigio);
1707                 break;
1708
1709         case BIOCSRSIG:         /* Set receive signal */
1710                 {
1711                         u_int sig;
1712
1713                         sig = *(u_int *)addr;
1714
1715                         if (sig >= NSIG)
1716                                 error = EINVAL;
1717                         else {
1718                                 BPFD_LOCK(d);
1719                                 d->bd_sig = sig;
1720                                 BPFD_UNLOCK(d);
1721                         }
1722                         break;
1723                 }
1724         case BIOCGRSIG:
1725                 BPFD_LOCK(d);
1726                 *(u_int *)addr = d->bd_sig;
1727                 BPFD_UNLOCK(d);
1728                 break;
1729
1730         case BIOCGETBUFMODE:
1731                 BPFD_LOCK(d);
1732                 *(u_int *)addr = d->bd_bufmode;
1733                 BPFD_UNLOCK(d);
1734                 break;
1735
1736         case BIOCSETBUFMODE:
1737                 /*
1738                  * Allow the buffering mode to be changed as long as we
1739                  * haven't yet committed to a particular mode.  Our
1740                  * definition of commitment, for now, is whether or not a
1741                  * buffer has been allocated or an interface attached, since
1742                  * that's the point where things get tricky.
1743                  */
1744                 switch (*(u_int *)addr) {
1745                 case BPF_BUFMODE_BUFFER:
1746                         break;
1747
1748                 case BPF_BUFMODE_ZBUF:
1749                         if (bpf_zerocopy_enable)
1750                                 break;
1751                         /* FALLSTHROUGH */
1752
1753                 default:
1754                         CURVNET_RESTORE();
1755                         return (EINVAL);
1756                 }
1757
1758                 BPFD_LOCK(d);
1759                 if (d->bd_sbuf != NULL || d->bd_hbuf != NULL ||
1760                     d->bd_fbuf != NULL || d->bd_bif != NULL) {
1761                         BPFD_UNLOCK(d);
1762                         CURVNET_RESTORE();
1763                         return (EBUSY);
1764                 }
1765                 d->bd_bufmode = *(u_int *)addr;
1766                 BPFD_UNLOCK(d);
1767                 break;
1768
1769         case BIOCGETZMAX:
1770                 error = bpf_ioctl_getzmax(td, d, (size_t *)addr);
1771                 break;
1772
1773         case BIOCSETZBUF:
1774                 error = bpf_ioctl_setzbuf(td, d, (struct bpf_zbuf *)addr);
1775                 break;
1776
1777         case BIOCROTZBUF:
1778                 error = bpf_ioctl_rotzbuf(td, d, (struct bpf_zbuf *)addr);
1779                 break;
1780         }
1781         CURVNET_RESTORE();
1782         return (error);
1783 }
1784
1785 /*
1786  * Set d's packet filter program to fp.  If this file already has a filter,
1787  * free it and replace it.  Returns EINVAL for bogus requests.
1788  *
1789  * Note we need global lock here to serialize bpf_setf() and bpf_setif() calls
1790  * since reading d->bd_bif can't be protected by d or interface lock due to
1791  * lock order.
1792  *
1793  * Additionally, we have to acquire interface write lock due to bpf_mtap() uses
1794  * interface read lock to read all filers.
1795  *
1796  */
1797 static int
1798 bpf_setf(struct bpf_d *d, struct bpf_program *fp, u_long cmd)
1799 {
1800 #ifdef COMPAT_FREEBSD32
1801         struct bpf_program fp_swab;
1802         struct bpf_program32 *fp32;
1803 #endif
1804         struct bpf_insn *fcode, *old;
1805 #ifdef BPF_JITTER
1806         bpf_jit_filter *jfunc, *ofunc;
1807 #endif
1808         size_t size;
1809         u_int flen;
1810         int need_upgrade;
1811
1812 #ifdef COMPAT_FREEBSD32
1813         switch (cmd) {
1814         case BIOCSETF32:
1815         case BIOCSETWF32:
1816         case BIOCSETFNR32:
1817                 fp32 = (struct bpf_program32 *)fp;
1818                 fp_swab.bf_len = fp32->bf_len;
1819                 fp_swab.bf_insns = (struct bpf_insn *)(uintptr_t)fp32->bf_insns;
1820                 fp = &fp_swab;
1821                 switch (cmd) {
1822                 case BIOCSETF32:
1823                         cmd = BIOCSETF;
1824                         break;
1825                 case BIOCSETWF32:
1826                         cmd = BIOCSETWF;
1827                         break;
1828                 }
1829                 break;
1830         }
1831 #endif
1832
1833         fcode = NULL;
1834 #ifdef BPF_JITTER
1835         jfunc = ofunc = NULL;
1836 #endif
1837         need_upgrade = 0;
1838
1839         /*
1840          * Check new filter validness before acquiring any locks.
1841          * Allocate memory for new filter, if needed.
1842          */
1843         flen = fp->bf_len;
1844         if (flen > bpf_maxinsns || (fp->bf_insns == NULL && flen != 0))
1845                 return (EINVAL);
1846         size = flen * sizeof(*fp->bf_insns);
1847         if (size > 0) {
1848                 /* We're setting up new filter.  Copy and check actual data. */
1849                 fcode = malloc(size, M_BPF, M_WAITOK);
1850                 if (copyin(fp->bf_insns, fcode, size) != 0 ||
1851                     !bpf_validate(fcode, flen)) {
1852                         free(fcode, M_BPF);
1853                         return (EINVAL);
1854                 }
1855 #ifdef BPF_JITTER
1856                 /* Filter is copied inside fcode and is perfectly valid. */
1857                 jfunc = bpf_jitter(fcode, flen);
1858 #endif
1859         }
1860
1861         BPF_LOCK();
1862
1863         /*
1864          * Set up new filter.
1865          * Protect filter change by interface lock.
1866          * Additionally, we are protected by global lock here.
1867          */
1868         if (d->bd_bif != NULL)
1869                 BPFIF_WLOCK(d->bd_bif);
1870         BPFD_LOCK(d);
1871         if (cmd == BIOCSETWF) {
1872                 old = d->bd_wfilter;
1873                 d->bd_wfilter = fcode;
1874         } else {
1875                 old = d->bd_rfilter;
1876                 d->bd_rfilter = fcode;
1877 #ifdef BPF_JITTER
1878                 ofunc = d->bd_bfilter;
1879                 d->bd_bfilter = jfunc;
1880 #endif
1881                 if (cmd == BIOCSETF)
1882                         reset_d(d);
1883
1884                 need_upgrade = bpf_check_upgrade(cmd, d, fcode, flen);
1885         }
1886         BPFD_UNLOCK(d);
1887         if (d->bd_bif != NULL)
1888                 BPFIF_WUNLOCK(d->bd_bif);
1889         if (old != NULL)
1890                 free(old, M_BPF);
1891 #ifdef BPF_JITTER
1892         if (ofunc != NULL)
1893                 bpf_destroy_jit_filter(ofunc);
1894 #endif
1895
1896         /* Move d to active readers list. */
1897         if (need_upgrade != 0)
1898                 bpf_upgraded(d);
1899
1900         BPF_UNLOCK();
1901         return (0);
1902 }
1903
1904 /*
1905  * Detach a file from its current interface (if attached at all) and attach
1906  * to the interface indicated by the name stored in ifr.
1907  * Return an errno or 0.
1908  */
1909 static int
1910 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1911 {
1912         struct bpf_if *bp;
1913         struct ifnet *theywant;
1914
1915         BPF_LOCK_ASSERT();
1916
1917         theywant = ifunit(ifr->ifr_name);
1918         if (theywant == NULL || theywant->if_bpf == NULL)
1919                 return (ENXIO);
1920
1921         bp = theywant->if_bpf;
1922
1923         /* Check if interface is not being detached from BPF */
1924         BPFIF_RLOCK(bp);
1925         if (bp->flags & BPFIF_FLAG_DYING) {
1926                 BPFIF_RUNLOCK(bp);
1927                 return (ENXIO);
1928         }
1929         BPFIF_RUNLOCK(bp);
1930
1931         /*
1932          * Behavior here depends on the buffering model.  If we're using
1933          * kernel memory buffers, then we can allocate them here.  If we're
1934          * using zero-copy, then the user process must have registered
1935          * buffers by the time we get here.  If not, return an error.
1936          */
1937         switch (d->bd_bufmode) {
1938         case BPF_BUFMODE_BUFFER:
1939         case BPF_BUFMODE_ZBUF:
1940                 if (d->bd_sbuf == NULL)
1941                         return (EINVAL);
1942                 break;
1943
1944         default:
1945                 panic("bpf_setif: bufmode %d", d->bd_bufmode);
1946         }
1947         if (bp != d->bd_bif)
1948                 bpf_attachd(d, bp);
1949         BPFD_LOCK(d);
1950         reset_d(d);
1951         BPFD_UNLOCK(d);
1952         return (0);
1953 }
1954
1955 /*
1956  * Support for select() and poll() system calls
1957  *
1958  * Return true iff the specific operation will not block indefinitely.
1959  * Otherwise, return false but make a note that a selwakeup() must be done.
1960  */
1961 static int
1962 bpfpoll(struct cdev *dev, int events, struct thread *td)
1963 {
1964         struct bpf_d *d;
1965         int revents;
1966
1967         if (devfs_get_cdevpriv((void **)&d) != 0 || d->bd_bif == NULL)
1968                 return (events &
1969                     (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
1970
1971         /*
1972          * Refresh PID associated with this descriptor.
1973          */
1974         revents = events & (POLLOUT | POLLWRNORM);
1975         BPFD_LOCK(d);
1976         BPF_PID_REFRESH(d, td);
1977         if (events & (POLLIN | POLLRDNORM)) {
1978                 if (bpf_ready(d))
1979                         revents |= events & (POLLIN | POLLRDNORM);
1980                 else {
1981                         selrecord(td, &d->bd_sel);
1982                         /* Start the read timeout if necessary. */
1983                         if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1984                                 callout_reset(&d->bd_callout, d->bd_rtout,
1985                                     bpf_timed_out, d);
1986                                 d->bd_state = BPF_WAITING;
1987                         }
1988                 }
1989         }
1990         BPFD_UNLOCK(d);
1991         return (revents);
1992 }
1993
1994 /*
1995  * Support for kevent() system call.  Register EVFILT_READ filters and
1996  * reject all others.
1997  */
1998 int
1999 bpfkqfilter(struct cdev *dev, struct knote *kn)
2000 {
2001         struct bpf_d *d;
2002
2003         if (devfs_get_cdevpriv((void **)&d) != 0 ||
2004             kn->kn_filter != EVFILT_READ)
2005                 return (1);
2006
2007         /*
2008          * Refresh PID associated with this descriptor.
2009          */
2010         BPFD_LOCK(d);
2011         BPF_PID_REFRESH_CUR(d);
2012         kn->kn_fop = &bpfread_filtops;
2013         kn->kn_hook = d;
2014         knlist_add(&d->bd_sel.si_note, kn, 1);
2015         BPFD_UNLOCK(d);
2016
2017         return (0);
2018 }
2019
2020 static void
2021 filt_bpfdetach(struct knote *kn)
2022 {
2023         struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2024
2025         knlist_remove(&d->bd_sel.si_note, kn, 0);
2026 }
2027
2028 static int
2029 filt_bpfread(struct knote *kn, long hint)
2030 {
2031         struct bpf_d *d = (struct bpf_d *)kn->kn_hook;
2032         int ready;
2033
2034         BPFD_LOCK_ASSERT(d);
2035         ready = bpf_ready(d);
2036         if (ready) {
2037                 kn->kn_data = d->bd_slen;
2038                 while (d->bd_hbuf_in_use)
2039                         mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2040                             PRINET, "bd_hbuf", 0);
2041                 if (d->bd_hbuf)
2042                         kn->kn_data += d->bd_hlen;
2043         } else if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
2044                 callout_reset(&d->bd_callout, d->bd_rtout,
2045                     bpf_timed_out, d);
2046                 d->bd_state = BPF_WAITING;
2047         }
2048
2049         return (ready);
2050 }
2051
2052 #define BPF_TSTAMP_NONE         0
2053 #define BPF_TSTAMP_FAST         1
2054 #define BPF_TSTAMP_NORMAL       2
2055 #define BPF_TSTAMP_EXTERN       3
2056
2057 static int
2058 bpf_ts_quality(int tstype)
2059 {
2060
2061         if (tstype == BPF_T_NONE)
2062                 return (BPF_TSTAMP_NONE);
2063         if ((tstype & BPF_T_FAST) != 0)
2064                 return (BPF_TSTAMP_FAST);
2065
2066         return (BPF_TSTAMP_NORMAL);
2067 }
2068
2069 static int
2070 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
2071 {
2072         struct m_tag *tag;
2073         int quality;
2074
2075         quality = bpf_ts_quality(tstype);
2076         if (quality == BPF_TSTAMP_NONE)
2077                 return (quality);
2078
2079         if (m != NULL) {
2080                 tag = m_tag_locate(m, MTAG_BPF, MTAG_BPF_TIMESTAMP, NULL);
2081                 if (tag != NULL) {
2082                         *bt = *(struct bintime *)(tag + 1);
2083                         return (BPF_TSTAMP_EXTERN);
2084                 }
2085         }
2086         if (quality == BPF_TSTAMP_NORMAL)
2087                 binuptime(bt);
2088         else
2089                 getbinuptime(bt);
2090
2091         return (quality);
2092 }
2093
2094 /*
2095  * Incoming linkage from device drivers.  Process the packet pkt, of length
2096  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
2097  * by each process' filter, and if accepted, stashed into the corresponding
2098  * buffer.
2099  */
2100 void
2101 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2102 {
2103         struct bintime bt;
2104         struct bpf_d *d;
2105 #ifdef BPF_JITTER
2106         bpf_jit_filter *bf;
2107 #endif
2108         u_int slen;
2109         int gottime;
2110
2111         gottime = BPF_TSTAMP_NONE;
2112
2113         BPFIF_RLOCK(bp);
2114
2115         LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2116                 /*
2117                  * We are not using any locks for d here because:
2118                  * 1) any filter change is protected by interface
2119                  * write lock
2120                  * 2) destroying/detaching d is protected by interface
2121                  * write lock, too
2122                  */
2123
2124                 /* XXX: Do not protect counter for the sake of performance. */
2125                 ++d->bd_rcount;
2126                 /*
2127                  * NB: We dont call BPF_CHECK_DIRECTION() here since there is no
2128                  * way for the caller to indiciate to us whether this packet
2129                  * is inbound or outbound.  In the bpf_mtap() routines, we use
2130                  * the interface pointers on the mbuf to figure it out.
2131                  */
2132 #ifdef BPF_JITTER
2133                 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2134                 if (bf != NULL)
2135                         slen = (*(bf->func))(pkt, pktlen, pktlen);
2136                 else
2137 #endif
2138                 slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
2139                 if (slen != 0) {
2140                         /*
2141                          * Filter matches. Let's to acquire write lock.
2142                          */
2143                         BPFD_LOCK(d);
2144
2145                         d->bd_fcount++;
2146                         if (gottime < bpf_ts_quality(d->bd_tstamp))
2147                                 gottime = bpf_gettime(&bt, d->bd_tstamp, NULL);
2148 #ifdef MAC
2149                         if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2150 #endif
2151                                 catchpacket(d, pkt, pktlen, slen,
2152                                     bpf_append_bytes, &bt);
2153                         BPFD_UNLOCK(d);
2154                 }
2155         }
2156         BPFIF_RUNLOCK(bp);
2157 }
2158
2159 #define BPF_CHECK_DIRECTION(d, r, i)                            \
2160             (((d)->bd_direction == BPF_D_IN && (r) != (i)) ||   \
2161             ((d)->bd_direction == BPF_D_OUT && (r) == (i)))
2162
2163 /*
2164  * Incoming linkage from device drivers, when packet is in an mbuf chain.
2165  * Locking model is explained in bpf_tap().
2166  */
2167 void
2168 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2169 {
2170         struct bintime bt;
2171         struct bpf_d *d;
2172 #ifdef BPF_JITTER
2173         bpf_jit_filter *bf;
2174 #endif
2175         u_int pktlen, slen;
2176         int gottime;
2177
2178         /* Skip outgoing duplicate packets. */
2179         if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2180                 m->m_flags &= ~M_PROMISC;
2181                 return;
2182         }
2183
2184         pktlen = m_length(m, NULL);
2185         gottime = BPF_TSTAMP_NONE;
2186
2187         BPFIF_RLOCK(bp);
2188
2189         LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2190                 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2191                         continue;
2192                 ++d->bd_rcount;
2193 #ifdef BPF_JITTER
2194                 bf = bpf_jitter_enable != 0 ? d->bd_bfilter : NULL;
2195                 /* XXX We cannot handle multiple mbufs. */
2196                 if (bf != NULL && m->m_next == NULL)
2197                         slen = (*(bf->func))(mtod(m, u_char *), pktlen, pktlen);
2198                 else
2199 #endif
2200                 slen = bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
2201                 if (slen != 0) {
2202                         BPFD_LOCK(d);
2203
2204                         d->bd_fcount++;
2205                         if (gottime < bpf_ts_quality(d->bd_tstamp))
2206                                 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2207 #ifdef MAC
2208                         if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2209 #endif
2210                                 catchpacket(d, (u_char *)m, pktlen, slen,
2211                                     bpf_append_mbuf, &bt);
2212                         BPFD_UNLOCK(d);
2213                 }
2214         }
2215         BPFIF_RUNLOCK(bp);
2216 }
2217
2218 /*
2219  * Incoming linkage from device drivers, when packet is in
2220  * an mbuf chain and to be prepended by a contiguous header.
2221  */
2222 void
2223 bpf_mtap2(struct bpf_if *bp, void *data, u_int dlen, struct mbuf *m)
2224 {
2225         struct bintime bt;
2226         struct mbuf mb;
2227         struct bpf_d *d;
2228         u_int pktlen, slen;
2229         int gottime;
2230
2231         /* Skip outgoing duplicate packets. */
2232         if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
2233                 m->m_flags &= ~M_PROMISC;
2234                 return;
2235         }
2236
2237         pktlen = m_length(m, NULL);
2238         /*
2239          * Craft on-stack mbuf suitable for passing to bpf_filter.
2240          * Note that we cut corners here; we only setup what's
2241          * absolutely needed--this mbuf should never go anywhere else.
2242          */
2243         mb.m_next = m;
2244         mb.m_data = data;
2245         mb.m_len = dlen;
2246         pktlen += dlen;
2247
2248         gottime = BPF_TSTAMP_NONE;
2249
2250         BPFIF_RLOCK(bp);
2251
2252         LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
2253                 if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
2254                         continue;
2255                 ++d->bd_rcount;
2256                 slen = bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
2257                 if (slen != 0) {
2258                         BPFD_LOCK(d);
2259
2260                         d->bd_fcount++;
2261                         if (gottime < bpf_ts_quality(d->bd_tstamp))
2262                                 gottime = bpf_gettime(&bt, d->bd_tstamp, m);
2263 #ifdef MAC
2264                         if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
2265 #endif
2266                                 catchpacket(d, (u_char *)&mb, pktlen, slen,
2267                                     bpf_append_mbuf, &bt);
2268                         BPFD_UNLOCK(d);
2269                 }
2270         }
2271         BPFIF_RUNLOCK(bp);
2272 }
2273
2274 #undef  BPF_CHECK_DIRECTION
2275
2276 #undef  BPF_TSTAMP_NONE
2277 #undef  BPF_TSTAMP_FAST
2278 #undef  BPF_TSTAMP_NORMAL
2279 #undef  BPF_TSTAMP_EXTERN
2280
2281 static int
2282 bpf_hdrlen(struct bpf_d *d)
2283 {
2284         int hdrlen;
2285
2286         hdrlen = d->bd_bif->bif_hdrlen;
2287 #ifndef BURN_BRIDGES
2288         if (d->bd_tstamp == BPF_T_NONE ||
2289             BPF_T_FORMAT(d->bd_tstamp) == BPF_T_MICROTIME)
2290 #ifdef COMPAT_FREEBSD32
2291                 if (d->bd_compat32)
2292                         hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr32);
2293                 else
2294 #endif
2295                         hdrlen += SIZEOF_BPF_HDR(struct bpf_hdr);
2296         else
2297 #endif
2298                 hdrlen += SIZEOF_BPF_HDR(struct bpf_xhdr);
2299 #ifdef COMPAT_FREEBSD32
2300         if (d->bd_compat32)
2301                 hdrlen = BPF_WORDALIGN32(hdrlen);
2302         else
2303 #endif
2304                 hdrlen = BPF_WORDALIGN(hdrlen);
2305
2306         return (hdrlen - d->bd_bif->bif_hdrlen);
2307 }
2308
2309 static void
2310 bpf_bintime2ts(struct bintime *bt, struct bpf_ts *ts, int tstype)
2311 {
2312         struct bintime bt2;
2313         struct timeval tsm;
2314         struct timespec tsn;
2315
2316         if ((tstype & BPF_T_MONOTONIC) == 0) {
2317                 bt2 = *bt;
2318                 bintime_add(&bt2, &boottimebin);
2319                 bt = &bt2;
2320         }
2321         switch (BPF_T_FORMAT(tstype)) {
2322         case BPF_T_MICROTIME:
2323                 bintime2timeval(bt, &tsm);
2324                 ts->bt_sec = tsm.tv_sec;
2325                 ts->bt_frac = tsm.tv_usec;
2326                 break;
2327         case BPF_T_NANOTIME:
2328                 bintime2timespec(bt, &tsn);
2329                 ts->bt_sec = tsn.tv_sec;
2330                 ts->bt_frac = tsn.tv_nsec;
2331                 break;
2332         case BPF_T_BINTIME:
2333                 ts->bt_sec = bt->sec;
2334                 ts->bt_frac = bt->frac;
2335                 break;
2336         }
2337 }
2338
2339 /*
2340  * Move the packet data from interface memory (pkt) into the
2341  * store buffer.  "cpfn" is the routine called to do the actual data
2342  * transfer.  bcopy is passed in to copy contiguous chunks, while
2343  * bpf_append_mbuf is passed in to copy mbuf chains.  In the latter case,
2344  * pkt is really an mbuf.
2345  */
2346 static void
2347 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
2348     void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
2349     struct bintime *bt)
2350 {
2351         struct bpf_xhdr hdr;
2352 #ifndef BURN_BRIDGES
2353         struct bpf_hdr hdr_old;
2354 #ifdef COMPAT_FREEBSD32
2355         struct bpf_hdr32 hdr32_old;
2356 #endif
2357 #endif
2358         int caplen, curlen, hdrlen, totlen;
2359         int do_wakeup = 0;
2360         int do_timestamp;
2361         int tstype;
2362
2363         BPFD_LOCK_ASSERT(d);
2364
2365         /*
2366          * Detect whether user space has released a buffer back to us, and if
2367          * so, move it from being a hold buffer to a free buffer.  This may
2368          * not be the best place to do it (for example, we might only want to
2369          * run this check if we need the space), but for now it's a reliable
2370          * spot to do it.
2371          */
2372         if (d->bd_fbuf == NULL && bpf_canfreebuf(d)) {
2373                 while (d->bd_hbuf_in_use)
2374                         mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2375                             PRINET, "bd_hbuf", 0);
2376                 d->bd_fbuf = d->bd_hbuf;
2377                 d->bd_hbuf = NULL;
2378                 d->bd_hlen = 0;
2379                 bpf_buf_reclaimed(d);
2380         }
2381
2382         /*
2383          * Figure out how many bytes to move.  If the packet is
2384          * greater or equal to the snapshot length, transfer that
2385          * much.  Otherwise, transfer the whole packet (unless
2386          * we hit the buffer size limit).
2387          */
2388         hdrlen = bpf_hdrlen(d);
2389         totlen = hdrlen + min(snaplen, pktlen);
2390         if (totlen > d->bd_bufsize)
2391                 totlen = d->bd_bufsize;
2392
2393         /*
2394          * Round up the end of the previous packet to the next longword.
2395          *
2396          * Drop the packet if there's no room and no hope of room
2397          * If the packet would overflow the storage buffer or the storage
2398          * buffer is considered immutable by the buffer model, try to rotate
2399          * the buffer and wakeup pending processes.
2400          */
2401 #ifdef COMPAT_FREEBSD32
2402         if (d->bd_compat32)
2403                 curlen = BPF_WORDALIGN32(d->bd_slen);
2404         else
2405 #endif
2406                 curlen = BPF_WORDALIGN(d->bd_slen);
2407         if (curlen + totlen > d->bd_bufsize || !bpf_canwritebuf(d)) {
2408                 if (d->bd_fbuf == NULL) {
2409                         /*
2410                          * There's no room in the store buffer, and no
2411                          * prospect of room, so drop the packet.  Notify the
2412                          * buffer model.
2413                          */
2414                         bpf_buffull(d);
2415                         ++d->bd_dcount;
2416                         return;
2417                 }
2418                 while (d->bd_hbuf_in_use)
2419                         mtx_sleep(&d->bd_hbuf_in_use, &d->bd_lock,
2420                             PRINET, "bd_hbuf", 0);
2421                 ROTATE_BUFFERS(d);
2422                 do_wakeup = 1;
2423                 curlen = 0;
2424         } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
2425                 /*
2426                  * Immediate mode is set, or the read timeout has already
2427                  * expired during a select call.  A packet arrived, so the
2428                  * reader should be woken up.
2429                  */
2430                 do_wakeup = 1;
2431         caplen = totlen - hdrlen;
2432         tstype = d->bd_tstamp;
2433         do_timestamp = tstype != BPF_T_NONE;
2434 #ifndef BURN_BRIDGES
2435         if (tstype == BPF_T_NONE || BPF_T_FORMAT(tstype) == BPF_T_MICROTIME) {
2436                 struct bpf_ts ts;
2437                 if (do_timestamp)
2438                         bpf_bintime2ts(bt, &ts, tstype);
2439 #ifdef COMPAT_FREEBSD32
2440                 if (d->bd_compat32) {
2441                         bzero(&hdr32_old, sizeof(hdr32_old));
2442                         if (do_timestamp) {
2443                                 hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
2444                                 hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
2445                         }
2446                         hdr32_old.bh_datalen = pktlen;
2447                         hdr32_old.bh_hdrlen = hdrlen;
2448                         hdr32_old.bh_caplen = caplen;
2449                         bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr32_old,
2450                             sizeof(hdr32_old));
2451                         goto copy;
2452                 }
2453 #endif
2454                 bzero(&hdr_old, sizeof(hdr_old));
2455                 if (do_timestamp) {
2456                         hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
2457                         hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
2458                 }
2459                 hdr_old.bh_datalen = pktlen;
2460                 hdr_old.bh_hdrlen = hdrlen;
2461                 hdr_old.bh_caplen = caplen;
2462                 bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr_old,
2463                     sizeof(hdr_old));
2464                 goto copy;
2465         }
2466 #endif
2467
2468         /*
2469          * Append the bpf header.  Note we append the actual header size, but
2470          * move forward the length of the header plus padding.
2471          */
2472         bzero(&hdr, sizeof(hdr));
2473         if (do_timestamp)
2474                 bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
2475         hdr.bh_datalen = pktlen;
2476         hdr.bh_hdrlen = hdrlen;
2477         hdr.bh_caplen = caplen;
2478         bpf_append_bytes(d, d->bd_sbuf, curlen, &hdr, sizeof(hdr));
2479
2480         /*
2481          * Copy the packet data into the store buffer and update its length.
2482          */
2483 #ifndef BURN_BRIDGES
2484 copy:
2485 #endif
2486         (*cpfn)(d, d->bd_sbuf, curlen + hdrlen, pkt, caplen);
2487         d->bd_slen = curlen + totlen;
2488
2489         if (do_wakeup)
2490                 bpf_wakeup(d);
2491 }
2492
2493 /*
2494  * Free buffers currently in use by a descriptor.
2495  * Called on close.
2496  */
2497 static void
2498 bpf_freed(struct bpf_d *d)
2499 {
2500
2501         /*
2502          * We don't need to lock out interrupts since this descriptor has
2503          * been detached from its interface and it yet hasn't been marked
2504          * free.
2505          */
2506         bpf_free(d);
2507         if (d->bd_rfilter != NULL) {
2508                 free((caddr_t)d->bd_rfilter, M_BPF);
2509 #ifdef BPF_JITTER
2510                 if (d->bd_bfilter != NULL)
2511                         bpf_destroy_jit_filter(d->bd_bfilter);
2512 #endif
2513         }
2514         if (d->bd_wfilter != NULL)
2515                 free((caddr_t)d->bd_wfilter, M_BPF);
2516         mtx_destroy(&d->bd_lock);
2517 }
2518
2519 /*
2520  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
2521  * fixed size of the link header (variable length headers not yet supported).
2522  */
2523 void
2524 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2525 {
2526
2527         bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2528 }
2529
2530 /*
2531  * Attach an interface to bpf.  ifp is a pointer to the structure
2532  * defining the interface to be attached, dlt is the link layer type,
2533  * and hdrlen is the fixed size of the link header (variable length
2534  * headers are not yet supporrted).
2535  */
2536 void
2537 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2538 {
2539         struct bpf_if *bp;
2540
2541         bp = malloc(sizeof(*bp), M_BPF, M_NOWAIT | M_ZERO);
2542         if (bp == NULL)
2543                 panic("bpfattach");
2544
2545         LIST_INIT(&bp->bif_dlist);
2546         LIST_INIT(&bp->bif_wlist);
2547         bp->bif_ifp = ifp;
2548         bp->bif_dlt = dlt;
2549         rw_init(&bp->bif_lock, "bpf interface lock");
2550         KASSERT(*driverp == NULL, ("bpfattach2: driverp already initialized"));
2551         *driverp = bp;
2552
2553         BPF_LOCK();
2554         LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
2555         BPF_UNLOCK();
2556
2557         bp->bif_hdrlen = hdrlen;
2558
2559         if (bootverbose)
2560                 if_printf(ifp, "bpf attached\n");
2561 }
2562
2563 /*
2564  * Detach bpf from an interface. This involves detaching each descriptor
2565  * associated with the interface. Notify each descriptor as it's detached
2566  * so that any sleepers wake up and get ENXIO.
2567  */
2568 void
2569 bpfdetach(struct ifnet *ifp)
2570 {
2571         struct bpf_if   *bp;
2572         struct bpf_d    *d;
2573 #ifdef INVARIANTS
2574         int ndetached;
2575
2576         ndetached = 0;
2577 #endif
2578
2579         BPF_LOCK();
2580         /* Find all bpf_if struct's which reference ifp and detach them. */
2581         do {
2582                 LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2583                         if (ifp == bp->bif_ifp)
2584                                 break;
2585                 }
2586                 if (bp != NULL)
2587                         LIST_REMOVE(bp, bif_next);
2588
2589                 if (bp != NULL) {
2590 #ifdef INVARIANTS
2591                         ndetached++;
2592 #endif
2593                         while ((d = LIST_FIRST(&bp->bif_dlist)) != NULL) {
2594                                 bpf_detachd_locked(d);
2595                                 BPFD_LOCK(d);
2596                                 bpf_wakeup(d);
2597                                 BPFD_UNLOCK(d);
2598                         }
2599                         /* Free writer-only descriptors */
2600                         while ((d = LIST_FIRST(&bp->bif_wlist)) != NULL) {
2601                                 bpf_detachd_locked(d);
2602                                 BPFD_LOCK(d);
2603                                 bpf_wakeup(d);
2604                                 BPFD_UNLOCK(d);
2605                         }
2606
2607                         /*
2608                          * Delay freing bp till interface is detached
2609                          * and all routes through this interface are removed.
2610                          * Mark bp as detached to restrict new consumers.
2611                          */
2612                         BPFIF_WLOCK(bp);
2613                         bp->flags |= BPFIF_FLAG_DYING;
2614                         BPFIF_WUNLOCK(bp);
2615                 }
2616         } while (bp != NULL);
2617         BPF_UNLOCK();
2618
2619 #ifdef INVARIANTS
2620         if (ndetached == 0)
2621                 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
2622 #endif
2623 }
2624
2625 /*
2626  * Interface departure handler.
2627  * Note departure event does not guarantee interface is going down.
2628  */
2629 static void
2630 bpf_ifdetach(void *arg __unused, struct ifnet *ifp)
2631 {
2632         struct bpf_if *bp;
2633
2634         BPF_LOCK();
2635         if ((bp = ifp->if_bpf) == NULL) {
2636                 BPF_UNLOCK();
2637                 return;
2638         }
2639
2640         /* Check if bpfdetach() was called previously */
2641         if ((bp->flags & BPFIF_FLAG_DYING) == 0) {
2642                 BPF_UNLOCK();
2643                 return;
2644         }
2645
2646         CTR3(KTR_NET, "%s: freing BPF instance %p for interface %p",
2647             __func__, bp, ifp);
2648
2649         ifp->if_bpf = NULL;
2650         BPF_UNLOCK();
2651
2652         rw_destroy(&bp->bif_lock);
2653         free(bp, M_BPF);
2654 }
2655
2656 /*
2657  * Get a list of available data link type of the interface.
2658  */
2659 static int
2660 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
2661 {
2662         int n, error;
2663         struct ifnet *ifp;
2664         struct bpf_if *bp;
2665
2666         BPF_LOCK_ASSERT();
2667
2668         ifp = d->bd_bif->bif_ifp;
2669         n = 0;
2670         error = 0;
2671         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2672                 if (bp->bif_ifp != ifp)
2673                         continue;
2674                 if (bfl->bfl_list != NULL) {
2675                         if (n >= bfl->bfl_len)
2676                                 return (ENOMEM);
2677                         error = copyout(&bp->bif_dlt,
2678                             bfl->bfl_list + n, sizeof(u_int));
2679                 }
2680                 n++;
2681         }
2682         bfl->bfl_len = n;
2683         return (error);
2684 }
2685
2686 /*
2687  * Set the data link type of a BPF instance.
2688  */
2689 static int
2690 bpf_setdlt(struct bpf_d *d, u_int dlt)
2691 {
2692         int error, opromisc;
2693         struct ifnet *ifp;
2694         struct bpf_if *bp;
2695
2696         BPF_LOCK_ASSERT();
2697
2698         if (d->bd_bif->bif_dlt == dlt)
2699                 return (0);
2700         ifp = d->bd_bif->bif_ifp;
2701
2702         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2703                 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
2704                         break;
2705         }
2706
2707         if (bp != NULL) {
2708                 opromisc = d->bd_promisc;
2709                 bpf_attachd(d, bp);
2710                 BPFD_LOCK(d);
2711                 reset_d(d);
2712                 BPFD_UNLOCK(d);
2713                 if (opromisc) {
2714                         error = ifpromisc(bp->bif_ifp, 1);
2715                         if (error)
2716                                 if_printf(bp->bif_ifp,
2717                                         "bpf_setdlt: ifpromisc failed (%d)\n",
2718                                         error);
2719                         else
2720                                 d->bd_promisc = 1;
2721                 }
2722         }
2723         return (bp == NULL ? EINVAL : 0);
2724 }
2725
2726 static void
2727 bpf_drvinit(void *unused)
2728 {
2729         struct cdev *dev;
2730
2731         mtx_init(&bpf_mtx, "bpf global lock", NULL, MTX_DEF);
2732         LIST_INIT(&bpf_iflist);
2733
2734         dev = make_dev(&bpf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "bpf");
2735         /* For compatibility */
2736         make_dev_alias(dev, "bpf0");
2737
2738         /* Register interface departure handler */
2739         bpf_ifdetach_cookie = EVENTHANDLER_REGISTER(
2740                     ifnet_departure_event, bpf_ifdetach, NULL,
2741                     EVENTHANDLER_PRI_ANY);
2742 }
2743
2744 /*
2745  * Zero out the various packet counters associated with all of the bpf
2746  * descriptors.  At some point, we will probably want to get a bit more
2747  * granular and allow the user to specify descriptors to be zeroed.
2748  */
2749 static void
2750 bpf_zero_counters(void)
2751 {
2752         struct bpf_if *bp;
2753         struct bpf_d *bd;
2754
2755         BPF_LOCK();
2756         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2757                 BPFIF_RLOCK(bp);
2758                 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2759                         BPFD_LOCK(bd);
2760                         bd->bd_rcount = 0;
2761                         bd->bd_dcount = 0;
2762                         bd->bd_fcount = 0;
2763                         bd->bd_wcount = 0;
2764                         bd->bd_wfcount = 0;
2765                         bd->bd_zcopy = 0;
2766                         BPFD_UNLOCK(bd);
2767                 }
2768                 BPFIF_RUNLOCK(bp);
2769         }
2770         BPF_UNLOCK();
2771 }
2772
2773 /*
2774  * Fill filter statistics
2775  */
2776 static void
2777 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
2778 {
2779
2780         bzero(d, sizeof(*d));
2781         BPFD_LOCK_ASSERT(bd);
2782         d->bd_structsize = sizeof(*d);
2783         /* XXX: reading should be protected by global lock */
2784         d->bd_immediate = bd->bd_immediate;
2785         d->bd_promisc = bd->bd_promisc;
2786         d->bd_hdrcmplt = bd->bd_hdrcmplt;
2787         d->bd_direction = bd->bd_direction;
2788         d->bd_feedback = bd->bd_feedback;
2789         d->bd_async = bd->bd_async;
2790         d->bd_rcount = bd->bd_rcount;
2791         d->bd_dcount = bd->bd_dcount;
2792         d->bd_fcount = bd->bd_fcount;
2793         d->bd_sig = bd->bd_sig;
2794         d->bd_slen = bd->bd_slen;
2795         d->bd_hlen = bd->bd_hlen;
2796         d->bd_bufsize = bd->bd_bufsize;
2797         d->bd_pid = bd->bd_pid;
2798         strlcpy(d->bd_ifname,
2799             bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
2800         d->bd_locked = bd->bd_locked;
2801         d->bd_wcount = bd->bd_wcount;
2802         d->bd_wdcount = bd->bd_wdcount;
2803         d->bd_wfcount = bd->bd_wfcount;
2804         d->bd_zcopy = bd->bd_zcopy;
2805         d->bd_bufmode = bd->bd_bufmode;
2806 }
2807
2808 /*
2809  * Handle `netstat -B' stats request
2810  */
2811 static int
2812 bpf_stats_sysctl(SYSCTL_HANDLER_ARGS)
2813 {
2814         static const struct xbpf_d zerostats;
2815         struct xbpf_d *xbdbuf, *xbd, tempstats;
2816         int index, error;
2817         struct bpf_if *bp;
2818         struct bpf_d *bd;
2819
2820         /*
2821          * XXX This is not technically correct. It is possible for non
2822          * privileged users to open bpf devices. It would make sense
2823          * if the users who opened the devices were able to retrieve
2824          * the statistics for them, too.
2825          */
2826         error = priv_check(req->td, PRIV_NET_BPF);
2827         if (error)
2828                 return (error);
2829         /*
2830          * Check to see if the user is requesting that the counters be
2831          * zeroed out.  Explicitly check that the supplied data is zeroed,
2832          * as we aren't allowing the user to set the counters currently.
2833          */
2834         if (req->newptr != NULL) {
2835                 if (req->newlen != sizeof(tempstats))
2836                         return (EINVAL);
2837                 memset(&tempstats, 0, sizeof(tempstats));
2838                 error = SYSCTL_IN(req, &tempstats, sizeof(tempstats));
2839                 if (error)
2840                         return (error);
2841                 if (bcmp(&tempstats, &zerostats, sizeof(tempstats)) != 0)
2842                         return (EINVAL);
2843                 bpf_zero_counters();
2844                 return (0);
2845         }
2846         if (req->oldptr == NULL)
2847                 return (SYSCTL_OUT(req, 0, bpf_bpfd_cnt * sizeof(*xbd)));
2848         if (bpf_bpfd_cnt == 0)
2849                 return (SYSCTL_OUT(req, 0, 0));
2850         xbdbuf = malloc(req->oldlen, M_BPF, M_WAITOK);
2851         BPF_LOCK();
2852         if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
2853                 BPF_UNLOCK();
2854                 free(xbdbuf, M_BPF);
2855                 return (ENOMEM);
2856         }
2857         index = 0;
2858         LIST_FOREACH(bp, &bpf_iflist, bif_next) {
2859                 BPFIF_RLOCK(bp);
2860                 /* Send writers-only first */
2861                 LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
2862                         xbd = &xbdbuf[index++];
2863                         BPFD_LOCK(bd);
2864                         bpfstats_fill_xbpf(xbd, bd);
2865                         BPFD_UNLOCK(bd);
2866                 }
2867                 LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
2868                         xbd = &xbdbuf[index++];
2869                         BPFD_LOCK(bd);
2870                         bpfstats_fill_xbpf(xbd, bd);
2871                         BPFD_UNLOCK(bd);
2872                 }
2873                 BPFIF_RUNLOCK(bp);
2874         }
2875         BPF_UNLOCK();
2876         error = SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
2877         free(xbdbuf, M_BPF);
2878         return (error);
2879 }
2880
2881 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,bpf_drvinit,NULL);
2882
2883 #else /* !DEV_BPF && !NETGRAPH_BPF */
2884 /*
2885  * NOP stubs to allow bpf-using drivers to load and function.
2886  *
2887  * A 'better' implementation would allow the core bpf functionality
2888  * to be loaded at runtime.
2889  */
2890 static struct bpf_if bp_null;
2891
2892 void
2893 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
2894 {
2895 }
2896
2897 void
2898 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
2899 {
2900 }
2901
2902 void
2903 bpf_mtap2(struct bpf_if *bp, void *d, u_int l, struct mbuf *m)
2904 {
2905 }
2906
2907 void
2908 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
2909 {
2910
2911         bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
2912 }
2913
2914 void
2915 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
2916 {
2917
2918         *driverp = &bp_null;
2919 }
2920
2921 void
2922 bpfdetach(struct ifnet *ifp)
2923 {
2924 }
2925
2926 u_int
2927 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
2928 {
2929         return -1;      /* "no filter" behaviour */
2930 }
2931
2932 int
2933 bpf_validate(const struct bpf_insn *f, int len)
2934 {
2935         return 0;               /* false */
2936 }
2937
2938 #endif /* !DEV_BPF && !NETGRAPH_BPF */