xref: /freebsd/share/man/man4/bpf.4 (revision fcb560670601b2a4d87bb31d7531c8dcc37ee71b)
1.\" Copyright (c) 2007 Seccuris Inc.
2.\" All rights reserved.
3.\"
4.\" This software was developed by Robert N. M. Watson under contract to
5.\" Seccuris Inc.
6.\"
7.\" Redistribution and use in source and binary forms, with or without
8.\" modification, are permitted provided that the following conditions
9.\" are met:
10.\" 1. Redistributions of source code must retain the above copyright
11.\"    notice, this list of conditions and the following disclaimer.
12.\" 2. Redistributions in binary form must reproduce the above copyright
13.\"    notice, this list of conditions and the following disclaimer in the
14.\"    documentation and/or other materials provided with the distribution.
15.\"
16.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26.\" SUCH DAMAGE.
27.\"
28.\" Copyright (c) 1990 The Regents of the University of California.
29.\" All rights reserved.
30.\"
31.\" Redistribution and use in source and binary forms, with or without
32.\" modification, are permitted provided that: (1) source code distributions
33.\" retain the above copyright notice and this paragraph in its entirety, (2)
34.\" distributions including binary code include the above copyright notice and
35.\" this paragraph in its entirety in the documentation or other materials
36.\" provided with the distribution, and (3) all advertising materials mentioning
37.\" features or use of this software display the following acknowledgement:
38.\" ``This product includes software developed by the University of California,
39.\" Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
40.\" the University nor the names of its contributors may be used to endorse
41.\" or promote products derived from this software without specific prior
42.\" written permission.
43.\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
44.\" WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
45.\" MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
46.\"
47.\" This document is derived in part from the enet man page (enet.4)
48.\" distributed with 4.3BSD Unix.
49.\"
50.\" $FreeBSD$
51.\"
52.Dd June 15, 2010
53.Dt BPF 4
54.Os
55.Sh NAME
56.Nm bpf
57.Nd Berkeley Packet Filter
58.Sh SYNOPSIS
59.Cd device bpf
60.Sh DESCRIPTION
61The Berkeley Packet Filter
62provides a raw interface to data link layers in a protocol
63independent fashion.
64All packets on the network, even those destined for other hosts,
65are accessible through this mechanism.
66.Pp
67The packet filter appears as a character special device,
68.Pa /dev/bpf .
69After opening the device, the file descriptor must be bound to a
70specific network interface with the
71.Dv BIOCSETIF
72ioctl.
73A given interface can be shared by multiple listeners, and the filter
74underlying each descriptor will see an identical packet stream.
75.Pp
76A separate device file is required for each minor device.
77If a file is in use, the open will fail and
78.Va errno
79will be set to
80.Er EBUSY .
81.Pp
82Associated with each open instance of a
83.Nm
84file is a user-settable packet filter.
85Whenever a packet is received by an interface,
86all file descriptors listening on that interface apply their filter.
87Each descriptor that accepts the packet receives its own copy.
88.Pp
89The packet filter will support any link level protocol that has fixed length
90headers.
91Currently, only Ethernet,
92.Tn SLIP ,
93and
94.Tn PPP
95drivers have been modified to interact with
96.Nm .
97.Pp
98Since packet data is in network byte order, applications should use the
99.Xr byteorder 3
100macros to extract multi-byte values.
101.Pp
102A packet can be sent out on the network by writing to a
103.Nm
104file descriptor.
105The writes are unbuffered, meaning only one packet can be processed per write.
106Currently, only writes to Ethernets and
107.Tn SLIP
108links are supported.
109.Sh BUFFER MODES
110.Nm
111devices deliver packet data to the application via memory buffers provided by
112the application.
113The buffer mode is set using the
114.Dv BIOCSETBUFMODE
115ioctl, and read using the
116.Dv BIOCGETBUFMODE
117ioctl.
118.Ss Buffered read mode
119By default,
120.Nm
121devices operate in the
122.Dv BPF_BUFMODE_BUFFER
123mode, in which packet data is copied explicitly from kernel to user memory
124using the
125.Xr read 2
126system call.
127The user process will declare a fixed buffer size that will be used both for
128sizing internal buffers and for all
129.Xr read 2
130operations on the file.
131This size is queried using the
132.Dv BIOCGBLEN
133ioctl, and is set using the
134.Dv BIOCSBLEN
135ioctl.
136Note that an individual packet larger than the buffer size is necessarily
137truncated.
138.Ss Zero-copy buffer mode
139.Nm
140devices may also operate in the
141.Dv BPF_BUFMODE_ZEROCOPY
142mode, in which packet data is written directly into two user memory buffers
143by the kernel, avoiding both system call and copying overhead.
144Buffers are of fixed (and equal) size, page-aligned, and an even multiple of
145the page size.
146The maximum zero-copy buffer size is returned by the
147.Dv BIOCGETZMAX
148ioctl.
149Note that an individual packet larger than the buffer size is necessarily
150truncated.
151.Pp
152The user process registers two memory buffers using the
153.Dv BIOCSETZBUF
154ioctl, which accepts a
155.Vt struct bpf_zbuf
156pointer as an argument:
157.Bd -literal
158struct bpf_zbuf {
159	void *bz_bufa;
160	void *bz_bufb;
161	size_t bz_buflen;
162};
163.Ed
164.Pp
165.Vt bz_bufa
166is a pointer to the userspace address of the first buffer that will be
167filled, and
168.Vt bz_bufb
169is a pointer to the second buffer.
170.Nm
171will then cycle between the two buffers as they fill and are acknowledged.
172.Pp
173Each buffer begins with a fixed-length header to hold synchronization and
174data length information for the buffer:
175.Bd -literal
176struct bpf_zbuf_header {
177	volatile u_int  bzh_kernel_gen;	/* Kernel generation number. */
178	volatile u_int  bzh_kernel_len;	/* Length of data in the buffer. */
179	volatile u_int  bzh_user_gen;	/* User generation number. */
180	/* ...padding for future use... */
181};
182.Ed
183.Pp
184The header structure of each buffer, including all padding, should be zeroed
185before it is configured using
186.Dv BIOCSETZBUF .
187Remaining space in the buffer will be used by the kernel to store packet
188data, laid out in the same format as with buffered read mode.
189.Pp
190The kernel and the user process follow a simple acknowledgement protocol via
191the buffer header to synchronize access to the buffer: when the header
192generation numbers,
193.Vt bzh_kernel_gen
194and
195.Vt bzh_user_gen ,
196hold the same value, the kernel owns the buffer, and when they differ,
197userspace owns the buffer.
198.Pp
199While the kernel owns the buffer, the contents are unstable and may change
200asynchronously; while the user process owns the buffer, its contents are
201stable and will not be changed until the buffer has been acknowledged.
202.Pp
203Initializing the buffer headers to all 0's before registering the buffer has
204the effect of assigning initial ownership of both buffers to the kernel.
205The kernel signals that a buffer has been assigned to userspace by modifying
206.Vt bzh_kernel_gen ,
207and userspace acknowledges the buffer and returns it to the kernel by setting
208the value of
209.Vt bzh_user_gen
210to the value of
211.Vt bzh_kernel_gen .
212.Pp
213In order to avoid caching and memory re-ordering effects, the user process
214must use atomic operations and memory barriers when checking for and
215acknowledging buffers:
216.Bd -literal
217#include <machine/atomic.h>
218
219/*
220 * Return ownership of a buffer to the kernel for reuse.
221 */
222static void
223buffer_acknowledge(struct bpf_zbuf_header *bzh)
224{
225
226	atomic_store_rel_int(&bzh->bzh_user_gen, bzh->bzh_kernel_gen);
227}
228
229/*
230 * Check whether a buffer has been assigned to userspace by the kernel.
231 * Return true if userspace owns the buffer, and false otherwise.
232 */
233static int
234buffer_check(struct bpf_zbuf_header *bzh)
235{
236
237	return (bzh->bzh_user_gen !=
238	    atomic_load_acq_int(&bzh->bzh_kernel_gen));
239}
240.Ed
241.Pp
242The user process may force the assignment of the next buffer, if any data
243is pending, to userspace using the
244.Dv BIOCROTZBUF
245ioctl.
246This allows the user process to retrieve data in a partially filled buffer
247before the buffer is full, such as following a timeout; the process must
248recheck for buffer ownership using the header generation numbers, as the
249buffer will not be assigned to userspace if no data was present.
250.Pp
251As in the buffered read mode,
252.Xr kqueue 2 ,
253.Xr poll 2 ,
254and
255.Xr select 2
256may be used to sleep awaiting the availability of a completed buffer.
257They will return a readable file descriptor when ownership of the next buffer
258is assigned to user space.
259.Pp
260In the current implementation, the kernel may assign zero, one, or both
261buffers to the user process; however, an earlier implementation maintained
262the invariant that at most one buffer could be assigned to the user process
263at a time.
264In order to both ensure progress and high performance, user processes should
265acknowledge a completely processed buffer as quickly as possible, returning
266it for reuse, and not block waiting on a second buffer while holding another
267buffer.
268.Sh IOCTLS
269The
270.Xr ioctl 2
271command codes below are defined in
272.In net/bpf.h .
273All commands require
274these includes:
275.Bd -literal
276	#include <sys/types.h>
277	#include <sys/time.h>
278	#include <sys/ioctl.h>
279	#include <net/bpf.h>
280.Ed
281.Pp
282Additionally,
283.Dv BIOCGETIF
284and
285.Dv BIOCSETIF
286require
287.In sys/socket.h
288and
289.In net/if.h .
290.Pp
291In addition to
292.Dv FIONREAD
293the following commands may be applied to any open
294.Nm
295file.
296The (third) argument to
297.Xr ioctl 2
298should be a pointer to the type indicated.
299.Bl -tag -width BIOCGETBUFMODE
300.It Dv BIOCGBLEN
301.Pq Li u_int
302Returns the required buffer length for reads on
303.Nm
304files.
305.It Dv BIOCSBLEN
306.Pq Li u_int
307Sets the buffer length for reads on
308.Nm
309files.
310The buffer must be set before the file is attached to an interface
311with
312.Dv BIOCSETIF .
313If the requested buffer size cannot be accommodated, the closest
314allowable size will be set and returned in the argument.
315A read call will result in
316.Er EIO
317if it is passed a buffer that is not this size.
318.It Dv BIOCGDLT
319.Pq Li u_int
320Returns the type of the data link layer underlying the attached interface.
321.Er EINVAL
322is returned if no interface has been specified.
323The device types, prefixed with
324.Dq Li DLT_ ,
325are defined in
326.In net/bpf.h .
327.It Dv BIOCPROMISC
328Forces the interface into promiscuous mode.
329All packets, not just those destined for the local host, are processed.
330Since more than one file can be listening on a given interface,
331a listener that opened its interface non-promiscuously may receive
332packets promiscuously.
333This problem can be remedied with an appropriate filter.
334.It Dv BIOCFLUSH
335Flushes the buffer of incoming packets,
336and resets the statistics that are returned by BIOCGSTATS.
337.It Dv BIOCGETIF
338.Pq Li "struct ifreq"
339Returns the name of the hardware interface that the file is listening on.
340The name is returned in the ifr_name field of
341the
342.Li ifreq
343structure.
344All other fields are undefined.
345.It Dv BIOCSETIF
346.Pq Li "struct ifreq"
347Sets the hardware interface associate with the file.
348This
349command must be performed before any packets can be read.
350The device is indicated by name using the
351.Li ifr_name
352field of the
353.Li ifreq
354structure.
355Additionally, performs the actions of
356.Dv BIOCFLUSH .
357.It Dv BIOCSRTIMEOUT
358.It Dv BIOCGRTIMEOUT
359.Pq Li "struct timeval"
360Set or get the read timeout parameter.
361The argument
362specifies the length of time to wait before timing
363out on a read request.
364This parameter is initialized to zero by
365.Xr open 2 ,
366indicating no timeout.
367.It Dv BIOCGSTATS
368.Pq Li "struct bpf_stat"
369Returns the following structure of packet statistics:
370.Bd -literal
371struct bpf_stat {
372	u_int bs_recv;    /* number of packets received */
373	u_int bs_drop;    /* number of packets dropped */
374};
375.Ed
376.Pp
377The fields are:
378.Bl -hang -offset indent
379.It Li bs_recv
380the number of packets received by the descriptor since opened or reset
381(including any buffered since the last read call);
382and
383.It Li bs_drop
384the number of packets which were accepted by the filter but dropped by the
385kernel because of buffer overflows
386(i.e., the application's reads are not keeping up with the packet traffic).
387.El
388.It Dv BIOCIMMEDIATE
389.Pq Li u_int
390Enable or disable
391.Dq immediate mode ,
392based on the truth value of the argument.
393When immediate mode is enabled, reads return immediately upon packet
394reception.
395Otherwise, a read will block until either the kernel buffer
396becomes full or a timeout occurs.
397This is useful for programs like
398.Xr rarpd 8
399which must respond to messages in real time.
400The default for a new file is off.
401.It Dv BIOCSETF
402.It Dv BIOCSETFNR
403.Pq Li "struct bpf_program"
404Sets the read filter program used by the kernel to discard uninteresting
405packets.
406An array of instructions and its length is passed in using
407the following structure:
408.Bd -literal
409struct bpf_program {
410	int bf_len;
411	struct bpf_insn *bf_insns;
412};
413.Ed
414.Pp
415The filter program is pointed to by the
416.Li bf_insns
417field while its length in units of
418.Sq Li struct bpf_insn
419is given by the
420.Li bf_len
421field.
422See section
423.Sx "FILTER MACHINE"
424for an explanation of the filter language.
425The only difference between
426.Dv BIOCSETF
427and
428.Dv BIOCSETFNR
429is
430.Dv BIOCSETF
431performs the actions of
432.Dv BIOCFLUSH
433while
434.Dv BIOCSETFNR
435does not.
436.It Dv BIOCSETWF
437.Pq Li "struct bpf_program"
438Sets the write filter program used by the kernel to control what type of
439packets can be written to the interface.
440See the
441.Dv BIOCSETF
442command for more
443information on the
444.Nm
445filter program.
446.It Dv BIOCVERSION
447.Pq Li "struct bpf_version"
448Returns the major and minor version numbers of the filter language currently
449recognized by the kernel.
450Before installing a filter, applications must check
451that the current version is compatible with the running kernel.
452Version numbers are compatible if the major numbers match and the application minor
453is less than or equal to the kernel minor.
454The kernel version number is returned in the following structure:
455.Bd -literal
456struct bpf_version {
457        u_short bv_major;
458        u_short bv_minor;
459};
460.Ed
461.Pp
462The current version numbers are given by
463.Dv BPF_MAJOR_VERSION
464and
465.Dv BPF_MINOR_VERSION
466from
467.In net/bpf.h .
468An incompatible filter
469may result in undefined behavior (most likely, an error returned by
470.Fn ioctl
471or haphazard packet matching).
472.It Dv BIOCSHDRCMPLT
473.It Dv BIOCGHDRCMPLT
474.Pq Li u_int
475Set or get the status of the
476.Dq header complete
477flag.
478Set to zero if the link level source address should be filled in automatically
479by the interface output routine.
480Set to one if the link level source
481address will be written, as provided, to the wire.
482This flag is initialized to zero by default.
483.It Dv BIOCSSEESENT
484.It Dv BIOCGSEESENT
485.Pq Li u_int
486These commands are obsolete but left for compatibility.
487Use
488.Dv BIOCSDIRECTION
489and
490.Dv BIOCGDIRECTION
491instead.
492Set or get the flag determining whether locally generated packets on the
493interface should be returned by BPF.
494Set to zero to see only incoming packets on the interface.
495Set to one to see packets originating locally and remotely on the interface.
496This flag is initialized to one by default.
497.It Dv BIOCSDIRECTION
498.It Dv BIOCGDIRECTION
499.Pq Li u_int
500Set or get the setting determining whether incoming, outgoing, or all packets
501on the interface should be returned by BPF.
502Set to
503.Dv BPF_D_IN
504to see only incoming packets on the interface.
505Set to
506.Dv BPF_D_INOUT
507to see packets originating locally and remotely on the interface.
508Set to
509.Dv BPF_D_OUT
510to see only outgoing packets on the interface.
511This setting is initialized to
512.Dv BPF_D_INOUT
513by default.
514.It Dv BIOCSTSTAMP
515.It Dv BIOCGTSTAMP
516.Pq Li u_int
517Set or get format and resolution of the time stamps returned by BPF.
518Set to
519.Dv BPF_T_MICROTIME ,
520.Dv BPF_T_MICROTIME_FAST ,
521.Dv BPF_T_MICROTIME_MONOTONIC ,
522or
523.Dv BPF_T_MICROTIME_MONOTONIC_FAST
524to get time stamps in 64-bit
525.Vt struct timeval
526format.
527Set to
528.Dv BPF_T_NANOTIME ,
529.Dv BPF_T_NANOTIME_FAST ,
530.Dv BPF_T_NANOTIME_MONOTONIC ,
531or
532.Dv BPF_T_NANOTIME_MONOTONIC_FAST
533to get time stamps in 64-bit
534.Vt struct timespec
535format.
536Set to
537.Dv BPF_T_BINTIME ,
538.Dv BPF_T_BINTIME_FAST ,
539.Dv BPF_T_NANOTIME_MONOTONIC ,
540or
541.Dv BPF_T_BINTIME_MONOTONIC_FAST
542to get time stamps in 64-bit
543.Vt struct bintime
544format.
545Set to
546.Dv BPF_T_NONE
547to ignore time stamp.
548All 64-bit time stamp formats are wrapped in
549.Vt struct bpf_ts .
550The
551.Dv BPF_T_MICROTIME_FAST ,
552.Dv BPF_T_NANOTIME_FAST ,
553.Dv BPF_T_BINTIME_FAST ,
554.Dv BPF_T_MICROTIME_MONOTONIC_FAST ,
555.Dv BPF_T_NANOTIME_MONOTONIC_FAST ,
556and
557.Dv BPF_T_BINTIME_MONOTONIC_FAST
558are analogs of corresponding formats without _FAST suffix but do not perform
559a full time counter query, so their accuracy is one timer tick.
560The
561.Dv BPF_T_MICROTIME_MONOTONIC ,
562.Dv BPF_T_NANOTIME_MONOTONIC ,
563.Dv BPF_T_BINTIME_MONOTONIC ,
564.Dv BPF_T_MICROTIME_MONOTONIC_FAST ,
565.Dv BPF_T_NANOTIME_MONOTONIC_FAST ,
566and
567.Dv BPF_T_BINTIME_MONOTONIC_FAST
568store the time elapsed since kernel boot.
569This setting is initialized to
570.Dv BPF_T_MICROTIME
571by default.
572.It Dv BIOCFEEDBACK
573.Pq Li u_int
574Set packet feedback mode.
575This allows injected packets to be fed back as input to the interface when
576output via the interface is successful.
577When
578.Dv BPF_D_INOUT
579direction is set, injected outgoing packet is not returned by BPF to avoid
580duplication. This flag is initialized to zero by default.
581.It Dv BIOCLOCK
582Set the locked flag on the
583.Nm
584descriptor.
585This prevents the execution of
586ioctl commands which could change the underlying operating parameters of
587the device.
588.It Dv BIOCGETBUFMODE
589.It Dv BIOCSETBUFMODE
590.Pq Li u_int
591Get or set the current
592.Nm
593buffering mode; possible values are
594.Dv BPF_BUFMODE_BUFFER ,
595buffered read mode, and
596.Dv BPF_BUFMODE_ZBUF ,
597zero-copy buffer mode.
598.It Dv BIOCSETZBUF
599.Pq Li struct bpf_zbuf
600Set the current zero-copy buffer locations; buffer locations may be
601set only once zero-copy buffer mode has been selected, and prior to attaching
602to an interface.
603Buffers must be of identical size, page-aligned, and an integer multiple of
604pages in size.
605The three fields
606.Vt bz_bufa ,
607.Vt bz_bufb ,
608and
609.Vt bz_buflen
610must be filled out.
611If buffers have already been set for this device, the ioctl will fail.
612.It Dv BIOCGETZMAX
613.Pq Li size_t
614Get the largest individual zero-copy buffer size allowed.
615As two buffers are used in zero-copy buffer mode, the limit (in practice) is
616twice the returned size.
617As zero-copy buffers consume kernel address space, conservative selection of
618buffer size is suggested, especially when there are multiple
619.Nm
620descriptors in use on 32-bit systems.
621.It Dv BIOCROTZBUF
622Force ownership of the next buffer to be assigned to userspace, if any data
623present in the buffer.
624If no data is present, the buffer will remain owned by the kernel.
625This allows consumers of zero-copy buffering to implement timeouts and
626retrieve partially filled buffers.
627In order to handle the case where no data is present in the buffer and
628therefore ownership is not assigned, the user process must check
629.Vt bzh_kernel_gen
630against
631.Vt bzh_user_gen .
632.El
633.Sh BPF HEADER
634One of the following structures is prepended to each packet returned by
635.Xr read 2
636or via a zero-copy buffer:
637.Bd -literal
638struct bpf_xhdr {
639	struct bpf_ts	bh_tstamp;     /* time stamp */
640	uint32_t	bh_caplen;     /* length of captured portion */
641	uint32_t	bh_datalen;    /* original length of packet */
642	u_short		bh_hdrlen;     /* length of bpf header (this struct
643					  plus alignment padding) */
644};
645
646struct bpf_hdr {
647	struct timeval	bh_tstamp;     /* time stamp */
648	uint32_t	bh_caplen;     /* length of captured portion */
649	uint32_t	bh_datalen;    /* original length of packet */
650	u_short		bh_hdrlen;     /* length of bpf header (this struct
651					  plus alignment padding) */
652};
653.Ed
654.Pp
655The fields, whose values are stored in host order, and are:
656.Pp
657.Bl -tag -compact -width bh_datalen
658.It Li bh_tstamp
659The time at which the packet was processed by the packet filter.
660.It Li bh_caplen
661The length of the captured portion of the packet.
662This is the minimum of
663the truncation amount specified by the filter and the length of the packet.
664.It Li bh_datalen
665The length of the packet off the wire.
666This value is independent of the truncation amount specified by the filter.
667.It Li bh_hdrlen
668The length of the
669.Nm
670header, which may not be equal to
671.\" XXX - not really a function call
672.Fn sizeof "struct bpf_xhdr"
673or
674.Fn sizeof "struct bpf_hdr" .
675.El
676.Pp
677The
678.Li bh_hdrlen
679field exists to account for
680padding between the header and the link level protocol.
681The purpose here is to guarantee proper alignment of the packet
682data structures, which is required on alignment sensitive
683architectures and improves performance on many other architectures.
684The packet filter ensures that the
685.Vt bpf_xhdr ,
686.Vt bpf_hdr
687and the network layer
688header will be word aligned.
689Currently,
690.Vt bpf_hdr
691is used when the time stamp is set to
692.Dv BPF_T_MICROTIME ,
693.Dv BPF_T_MICROTIME_FAST ,
694.Dv BPF_T_MICROTIME_MONOTONIC ,
695.Dv BPF_T_MICROTIME_MONOTONIC_FAST ,
696or
697.Dv BPF_T_NONE
698for backward compatibility reasons.
699Otherwise,
700.Vt bpf_xhdr
701is used.
702However,
703.Vt bpf_hdr
704may be deprecated in the near future.
705Suitable precautions
706must be taken when accessing the link layer protocol fields on alignment
707restricted machines.
708(This is not a problem on an Ethernet, since
709the type field is a short falling on an even offset,
710and the addresses are probably accessed in a bytewise fashion).
711.Pp
712Additionally, individual packets are padded so that each starts
713on a word boundary.
714This requires that an application
715has some knowledge of how to get from packet to packet.
716The macro
717.Dv BPF_WORDALIGN
718is defined in
719.In net/bpf.h
720to facilitate
721this process.
722It rounds up its argument to the nearest word aligned value (where a word is
723.Dv BPF_ALIGNMENT
724bytes wide).
725.Pp
726For example, if
727.Sq Li p
728points to the start of a packet, this expression
729will advance it to the next packet:
730.Dl p = (char *)p + BPF_WORDALIGN(p->bh_hdrlen + p->bh_caplen)
731.Pp
732For the alignment mechanisms to work properly, the
733buffer passed to
734.Xr read 2
735must itself be word aligned.
736The
737.Xr malloc 3
738function
739will always return an aligned buffer.
740.Sh FILTER MACHINE
741A filter program is an array of instructions, with all branches forwardly
742directed, terminated by a
743.Em return
744instruction.
745Each instruction performs some action on the pseudo-machine state,
746which consists of an accumulator, index register, scratch memory store,
747and implicit program counter.
748.Pp
749The following structure defines the instruction format:
750.Bd -literal
751struct bpf_insn {
752	u_short	code;
753	u_char 	jt;
754	u_char 	jf;
755	u_long k;
756};
757.Ed
758.Pp
759The
760.Li k
761field is used in different ways by different instructions,
762and the
763.Li jt
764and
765.Li jf
766fields are used as offsets
767by the branch instructions.
768The opcodes are encoded in a semi-hierarchical fashion.
769There are eight classes of instructions:
770.Dv BPF_LD ,
771.Dv BPF_LDX ,
772.Dv BPF_ST ,
773.Dv BPF_STX ,
774.Dv BPF_ALU ,
775.Dv BPF_JMP ,
776.Dv BPF_RET ,
777and
778.Dv BPF_MISC .
779Various other mode and
780operator bits are or'd into the class to give the actual instructions.
781The classes and modes are defined in
782.In net/bpf.h .
783.Pp
784Below are the semantics for each defined
785.Nm
786instruction.
787We use the convention that A is the accumulator, X is the index register,
788P[] packet data, and M[] scratch memory store.
789P[i:n] gives the data at byte offset
790.Dq i
791in the packet,
792interpreted as a word (n=4),
793unsigned halfword (n=2), or unsigned byte (n=1).
794M[i] gives the i'th word in the scratch memory store, which is only
795addressed in word units.
796The memory store is indexed from 0 to
797.Dv BPF_MEMWORDS
798- 1.
799.Li k ,
800.Li jt ,
801and
802.Li jf
803are the corresponding fields in the
804instruction definition.
805.Dq len
806refers to the length of the packet.
807.Bl -tag -width BPF_STXx
808.It Dv BPF_LD
809These instructions copy a value into the accumulator.
810The type of the source operand is specified by an
811.Dq addressing mode
812and can be a constant
813.Pq Dv BPF_IMM ,
814packet data at a fixed offset
815.Pq Dv BPF_ABS ,
816packet data at a variable offset
817.Pq Dv BPF_IND ,
818the packet length
819.Pq Dv BPF_LEN ,
820or a word in the scratch memory store
821.Pq Dv BPF_MEM .
822For
823.Dv BPF_IND
824and
825.Dv BPF_ABS ,
826the data size must be specified as a word
827.Pq Dv BPF_W ,
828halfword
829.Pq Dv BPF_H ,
830or byte
831.Pq Dv BPF_B .
832The semantics of all the recognized
833.Dv BPF_LD
834instructions follow.
835.Bd -literal
836BPF_LD+BPF_W+BPF_ABS	A <- P[k:4]
837BPF_LD+BPF_H+BPF_ABS	A <- P[k:2]
838BPF_LD+BPF_B+BPF_ABS	A <- P[k:1]
839BPF_LD+BPF_W+BPF_IND	A <- P[X+k:4]
840BPF_LD+BPF_H+BPF_IND	A <- P[X+k:2]
841BPF_LD+BPF_B+BPF_IND	A <- P[X+k:1]
842BPF_LD+BPF_W+BPF_LEN	A <- len
843BPF_LD+BPF_IMM		A <- k
844BPF_LD+BPF_MEM		A <- M[k]
845.Ed
846.It Dv BPF_LDX
847These instructions load a value into the index register.
848Note that
849the addressing modes are more restrictive than those of the accumulator loads,
850but they include
851.Dv BPF_MSH ,
852a hack for efficiently loading the IP header length.
853.Bd -literal
854BPF_LDX+BPF_W+BPF_IMM	X <- k
855BPF_LDX+BPF_W+BPF_MEM	X <- M[k]
856BPF_LDX+BPF_W+BPF_LEN	X <- len
857BPF_LDX+BPF_B+BPF_MSH	X <- 4*(P[k:1]&0xf)
858.Ed
859.It Dv BPF_ST
860This instruction stores the accumulator into the scratch memory.
861We do not need an addressing mode since there is only one possibility
862for the destination.
863.Bd -literal
864BPF_ST			M[k] <- A
865.Ed
866.It Dv BPF_STX
867This instruction stores the index register in the scratch memory store.
868.Bd -literal
869BPF_STX			M[k] <- X
870.Ed
871.It Dv BPF_ALU
872The alu instructions perform operations between the accumulator and
873index register or constant, and store the result back in the accumulator.
874For binary operations, a source mode is required
875.Dv ( BPF_K
876or
877.Dv BPF_X ) .
878.Bd -literal
879BPF_ALU+BPF_ADD+BPF_K	A <- A + k
880BPF_ALU+BPF_SUB+BPF_K	A <- A - k
881BPF_ALU+BPF_MUL+BPF_K	A <- A * k
882BPF_ALU+BPF_DIV+BPF_K	A <- A / k
883BPF_ALU+BPF_AND+BPF_K	A <- A & k
884BPF_ALU+BPF_OR+BPF_K	A <- A | k
885BPF_ALU+BPF_LSH+BPF_K	A <- A << k
886BPF_ALU+BPF_RSH+BPF_K	A <- A >> k
887BPF_ALU+BPF_ADD+BPF_X	A <- A + X
888BPF_ALU+BPF_SUB+BPF_X	A <- A - X
889BPF_ALU+BPF_MUL+BPF_X	A <- A * X
890BPF_ALU+BPF_DIV+BPF_X	A <- A / X
891BPF_ALU+BPF_AND+BPF_X	A <- A & X
892BPF_ALU+BPF_OR+BPF_X	A <- A | X
893BPF_ALU+BPF_LSH+BPF_X	A <- A << X
894BPF_ALU+BPF_RSH+BPF_X	A <- A >> X
895BPF_ALU+BPF_NEG		A <- -A
896.Ed
897.It Dv BPF_JMP
898The jump instructions alter flow of control.
899Conditional jumps
900compare the accumulator against a constant
901.Pq Dv BPF_K
902or the index register
903.Pq Dv BPF_X .
904If the result is true (or non-zero),
905the true branch is taken, otherwise the false branch is taken.
906Jump offsets are encoded in 8 bits so the longest jump is 256 instructions.
907However, the jump always
908.Pq Dv BPF_JA
909opcode uses the 32 bit
910.Li k
911field as the offset, allowing arbitrarily distant destinations.
912All conditionals use unsigned comparison conventions.
913.Bd -literal
914BPF_JMP+BPF_JA		pc += k
915BPF_JMP+BPF_JGT+BPF_K	pc += (A > k) ? jt : jf
916BPF_JMP+BPF_JGE+BPF_K	pc += (A >= k) ? jt : jf
917BPF_JMP+BPF_JEQ+BPF_K	pc += (A == k) ? jt : jf
918BPF_JMP+BPF_JSET+BPF_K	pc += (A & k) ? jt : jf
919BPF_JMP+BPF_JGT+BPF_X	pc += (A > X) ? jt : jf
920BPF_JMP+BPF_JGE+BPF_X	pc += (A >= X) ? jt : jf
921BPF_JMP+BPF_JEQ+BPF_X	pc += (A == X) ? jt : jf
922BPF_JMP+BPF_JSET+BPF_X	pc += (A & X) ? jt : jf
923.Ed
924.It Dv BPF_RET
925The return instructions terminate the filter program and specify the amount
926of packet to accept (i.e., they return the truncation amount).
927A return value of zero indicates that the packet should be ignored.
928The return value is either a constant
929.Pq Dv BPF_K
930or the accumulator
931.Pq Dv BPF_A .
932.Bd -literal
933BPF_RET+BPF_A		accept A bytes
934BPF_RET+BPF_K		accept k bytes
935.Ed
936.It Dv BPF_MISC
937The miscellaneous category was created for anything that does not
938fit into the above classes, and for any new instructions that might need to
939be added.
940Currently, these are the register transfer instructions
941that copy the index register to the accumulator or vice versa.
942.Bd -literal
943BPF_MISC+BPF_TAX	X <- A
944BPF_MISC+BPF_TXA	A <- X
945.Ed
946.El
947.Pp
948The
949.Nm
950interface provides the following macros to facilitate
951array initializers:
952.Fn BPF_STMT opcode operand
953and
954.Fn BPF_JUMP opcode operand true_offset false_offset .
955.Sh SYSCTL VARIABLES
956A set of
957.Xr sysctl 8
958variables controls the behaviour of the
959.Nm
960subsystem
961.Bl -tag -width indent
962.It Va net.bpf.optimize_writers: No 0
963Various programs use BPF to send (but not receive) raw packets
964(cdpd, lldpd, dhcpd, dhcp relays, etc. are good examples of such programs).
965They do not need incoming packets to be send to them.
966Turning this option on
967makes new BPF users to be attached to write-only interface list until program
968explicitly specifies read filter via
969.Fn pcap_set_filter .
970This removes any performance degradation for high-speed interfaces.
971.It Va net.bpf.stats:
972Binary interface for retrieving general statistics.
973.It Va net.bpf.zerocopy_enable: No 0
974Permits zero-copy to be used with net BPF readers.
975Use with caution.
976.It Va net.bpf.maxinsns: No 512
977Maximum number of instructions that BPF program can contain.
978Use
979.Xr tcpdump 1
980.Fl d
981option to determine approximate number of instruction for any filter.
982.It Va net.bpf.maxbufsize: No 524288
983Maximum buffer size to allocate for packets buffer.
984.It Va net.bpf.bufsize: No 4096
985Default buffer size to allocate for packets buffer.
986.El
987.Sh EXAMPLES
988The following filter is taken from the Reverse ARP Daemon.
989It accepts only Reverse ARP requests.
990.Bd -literal
991struct bpf_insn insns[] = {
992	BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12),
993	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ETHERTYPE_REVARP, 0, 3),
994	BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 20),
995	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, REVARP_REQUEST, 0, 1),
996	BPF_STMT(BPF_RET+BPF_K, sizeof(struct ether_arp) +
997		 sizeof(struct ether_header)),
998	BPF_STMT(BPF_RET+BPF_K, 0),
999};
1000.Ed
1001.Pp
1002This filter accepts only IP packets between host 128.3.112.15 and
1003128.3.112.35.
1004.Bd -literal
1005struct bpf_insn insns[] = {
1006	BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12),
1007	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ETHERTYPE_IP, 0, 8),
1008	BPF_STMT(BPF_LD+BPF_W+BPF_ABS, 26),
1009	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0x8003700f, 0, 2),
1010	BPF_STMT(BPF_LD+BPF_W+BPF_ABS, 30),
1011	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0x80037023, 3, 4),
1012	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0x80037023, 0, 3),
1013	BPF_STMT(BPF_LD+BPF_W+BPF_ABS, 30),
1014	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0x8003700f, 0, 1),
1015	BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
1016	BPF_STMT(BPF_RET+BPF_K, 0),
1017};
1018.Ed
1019.Pp
1020Finally, this filter returns only TCP finger packets.
1021We must parse the IP header to reach the TCP header.
1022The
1023.Dv BPF_JSET
1024instruction
1025checks that the IP fragment offset is 0 so we are sure
1026that we have a TCP header.
1027.Bd -literal
1028struct bpf_insn insns[] = {
1029	BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12),
1030	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, ETHERTYPE_IP, 0, 10),
1031	BPF_STMT(BPF_LD+BPF_B+BPF_ABS, 23),
1032	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, IPPROTO_TCP, 0, 8),
1033	BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 20),
1034	BPF_JUMP(BPF_JMP+BPF_JSET+BPF_K, 0x1fff, 6, 0),
1035	BPF_STMT(BPF_LDX+BPF_B+BPF_MSH, 14),
1036	BPF_STMT(BPF_LD+BPF_H+BPF_IND, 14),
1037	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 79, 2, 0),
1038	BPF_STMT(BPF_LD+BPF_H+BPF_IND, 16),
1039	BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 79, 0, 1),
1040	BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
1041	BPF_STMT(BPF_RET+BPF_K, 0),
1042};
1043.Ed
1044.Sh SEE ALSO
1045.Xr tcpdump 1 ,
1046.Xr ioctl 2 ,
1047.Xr kqueue 2 ,
1048.Xr poll 2 ,
1049.Xr select 2 ,
1050.Xr byteorder 3 ,
1051.Xr ng_bpf 4 ,
1052.Xr bpf 9
1053.Rs
1054.%A McCanne, S.
1055.%A Jacobson V.
1056.%T "An efficient, extensible, and portable network monitor"
1057.Re
1058.Sh HISTORY
1059The Enet packet filter was created in 1980 by Mike Accetta and
1060Rick Rashid at Carnegie-Mellon University.
1061Jeffrey Mogul, at
1062Stanford, ported the code to
1063.Bx
1064and continued its development from
10651983 on.
1066Since then, it has evolved into the Ultrix Packet Filter at
1067.Tn DEC ,
1068a
1069.Tn STREAMS
1070.Tn NIT
1071module under
1072.Tn SunOS 4.1 ,
1073and
1074.Tn BPF .
1075.Sh AUTHORS
1076.An -nosplit
1077.An Steven McCanne ,
1078of Lawrence Berkeley Laboratory, implemented BPF in
1079Summer 1990.
1080Much of the design is due to
1081.An Van Jacobson .
1082.Pp
1083Support for zero-copy buffers was added by
1084.An Robert N. M. Watson
1085under contract to Seccuris Inc.
1086.Sh BUGS
1087The read buffer must be of a fixed size (returned by the
1088.Dv BIOCGBLEN
1089ioctl).
1090.Pp
1091A file that does not request promiscuous mode may receive promiscuously
1092received packets as a side effect of another file requesting this
1093mode on the same hardware interface.
1094This could be fixed in the kernel with additional processing overhead.
1095However, we favor the model where
1096all files must assume that the interface is promiscuous, and if
1097so desired, must utilize a filter to reject foreign packets.
1098.Pp
1099Data link protocols with variable length headers are not currently supported.
1100.Pp
1101The
1102.Dv SEESENT ,
1103.Dv DIRECTION ,
1104and
1105.Dv FEEDBACK
1106settings have been observed to work incorrectly on some interface
1107types, including those with hardware loopback rather than software loopback,
1108and point-to-point interfaces.
1109They appear to function correctly on a
1110broad range of Ethernet-style interfaces.
1111