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