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