ringbuf.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. ===============
  2. BPF ring buffer
  3. ===============
  4. This document describes BPF ring buffer design, API, and implementation details.
  5. .. contents::
  6. :local:
  7. :depth: 2
  8. Motivation
  9. ----------
  10. There are two distinctive motivators for this work, which are not satisfied by
  11. existing perf buffer, which prompted creation of a new ring buffer
  12. implementation.
  13. - more efficient memory utilization by sharing ring buffer across CPUs;
  14. - preserving ordering of events that happen sequentially in time, even across
  15. multiple CPUs (e.g., fork/exec/exit events for a task).
  16. These two problems are independent, but perf buffer fails to satisfy both.
  17. Both are a result of a choice to have per-CPU perf ring buffer. Both can be
  18. also solved by having an MPSC implementation of ring buffer. The ordering
  19. problem could technically be solved for perf buffer with some in-kernel
  20. counting, but given the first one requires an MPSC buffer, the same solution
  21. would solve the second problem automatically.
  22. Semantics and APIs
  23. ------------------
  24. Single ring buffer is presented to BPF programs as an instance of BPF map of
  25. type ``BPF_MAP_TYPE_RINGBUF``. Two other alternatives considered, but
  26. ultimately rejected.
  27. One way would be to, similar to ``BPF_MAP_TYPE_PERF_EVENT_ARRAY``, make
  28. ``BPF_MAP_TYPE_RINGBUF`` could represent an array of ring buffers, but not
  29. enforce "same CPU only" rule. This would be more familiar interface compatible
  30. with existing perf buffer use in BPF, but would fail if application needed more
  31. advanced logic to lookup ring buffer by arbitrary key.
  32. ``BPF_MAP_TYPE_HASH_OF_MAPS`` addresses this with current approach.
  33. Additionally, given the performance of BPF ringbuf, many use cases would just
  34. opt into a simple single ring buffer shared among all CPUs, for which current
  35. approach would be an overkill.
  36. Another approach could introduce a new concept, alongside BPF map, to represent
  37. generic "container" object, which doesn't necessarily have key/value interface
  38. with lookup/update/delete operations. This approach would add a lot of extra
  39. infrastructure that has to be built for observability and verifier support. It
  40. would also add another concept that BPF developers would have to familiarize
  41. themselves with, new syntax in libbpf, etc. But then would really provide no
  42. additional benefits over the approach of using a map. ``BPF_MAP_TYPE_RINGBUF``
  43. doesn't support lookup/update/delete operations, but so doesn't few other map
  44. types (e.g., queue and stack; array doesn't support delete, etc).
  45. The approach chosen has an advantage of re-using existing BPF map
  46. infrastructure (introspection APIs in kernel, libbpf support, etc), being
  47. familiar concept (no need to teach users a new type of object in BPF program),
  48. and utilizing existing tooling (bpftool). For common scenario of using a single
  49. ring buffer for all CPUs, it's as simple and straightforward, as would be with
  50. a dedicated "container" object. On the other hand, by being a map, it can be
  51. combined with ``ARRAY_OF_MAPS`` and ``HASH_OF_MAPS`` map-in-maps to implement
  52. a wide variety of topologies, from one ring buffer for each CPU (e.g., as
  53. a replacement for perf buffer use cases), to a complicated application
  54. hashing/sharding of ring buffers (e.g., having a small pool of ring buffers
  55. with hashed task's tgid being a look up key to preserve order, but reduce
  56. contention).
  57. Key and value sizes are enforced to be zero. ``max_entries`` is used to specify
  58. the size of ring buffer and has to be a power of 2 value.
  59. There are a bunch of similarities between perf buffer
  60. (``BPF_MAP_TYPE_PERF_EVENT_ARRAY``) and new BPF ring buffer semantics:
  61. - variable-length records;
  62. - if there is no more space left in ring buffer, reservation fails, no
  63. blocking;
  64. - memory-mappable data area for user-space applications for ease of
  65. consumption and high performance;
  66. - epoll notifications for new incoming data;
  67. - but still the ability to do busy polling for new data to achieve the
  68. lowest latency, if necessary.
  69. BPF ringbuf provides two sets of APIs to BPF programs:
  70. - ``bpf_ringbuf_output()`` allows to *copy* data from one place to a ring
  71. buffer, similarly to ``bpf_perf_event_output()``;
  72. - ``bpf_ringbuf_reserve()``/``bpf_ringbuf_commit()``/``bpf_ringbuf_discard()``
  73. APIs split the whole process into two steps. First, a fixed amount of space
  74. is reserved. If successful, a pointer to a data inside ring buffer data
  75. area is returned, which BPF programs can use similarly to a data inside
  76. array/hash maps. Once ready, this piece of memory is either committed or
  77. discarded. Discard is similar to commit, but makes consumer ignore the
  78. record.
  79. ``bpf_ringbuf_output()`` has disadvantage of incurring extra memory copy,
  80. because record has to be prepared in some other place first. But it allows to
  81. submit records of the length that's not known to verifier beforehand. It also
  82. closely matches ``bpf_perf_event_output()``, so will simplify migration
  83. significantly.
  84. ``bpf_ringbuf_reserve()`` avoids the extra copy of memory by providing a memory
  85. pointer directly to ring buffer memory. In a lot of cases records are larger
  86. than BPF stack space allows, so many programs have use extra per-CPU array as
  87. a temporary heap for preparing sample. bpf_ringbuf_reserve() avoid this needs
  88. completely. But in exchange, it only allows a known constant size of memory to
  89. be reserved, such that verifier can verify that BPF program can't access memory
  90. outside its reserved record space. bpf_ringbuf_output(), while slightly slower
  91. due to extra memory copy, covers some use cases that are not suitable for
  92. ``bpf_ringbuf_reserve()``.
  93. The difference between commit and discard is very small. Discard just marks
  94. a record as discarded, and such records are supposed to be ignored by consumer
  95. code. Discard is useful for some advanced use-cases, such as ensuring
  96. all-or-nothing multi-record submission, or emulating temporary
  97. ``malloc()``/``free()`` within single BPF program invocation.
  98. Each reserved record is tracked by verifier through existing
  99. reference-tracking logic, similar to socket ref-tracking. It is thus
  100. impossible to reserve a record, but forget to submit (or discard) it.
  101. ``bpf_ringbuf_query()`` helper allows to query various properties of ring
  102. buffer. Currently 4 are supported:
  103. - ``BPF_RB_AVAIL_DATA`` returns amount of unconsumed data in ring buffer;
  104. - ``BPF_RB_RING_SIZE`` returns the size of ring buffer;
  105. - ``BPF_RB_CONS_POS``/``BPF_RB_PROD_POS`` returns current logical possition
  106. of consumer/producer, respectively.
  107. Returned values are momentarily snapshots of ring buffer state and could be
  108. off by the time helper returns, so this should be used only for
  109. debugging/reporting reasons or for implementing various heuristics, that take
  110. into account highly-changeable nature of some of those characteristics.
  111. One such heuristic might involve more fine-grained control over poll/epoll
  112. notifications about new data availability in ring buffer. Together with
  113. ``BPF_RB_NO_WAKEUP``/``BPF_RB_FORCE_WAKEUP`` flags for output/commit/discard
  114. helpers, it allows BPF program a high degree of control and, e.g., more
  115. efficient batched notifications. Default self-balancing strategy, though,
  116. should be adequate for most applications and will work reliable and efficiently
  117. already.
  118. Design and Implementation
  119. -------------------------
  120. This reserve/commit schema allows a natural way for multiple producers, either
  121. on different CPUs or even on the same CPU/in the same BPF program, to reserve
  122. independent records and work with them without blocking other producers. This
  123. means that if BPF program was interruped by another BPF program sharing the
  124. same ring buffer, they will both get a record reserved (provided there is
  125. enough space left) and can work with it and submit it independently. This
  126. applies to NMI context as well, except that due to using a spinlock during
  127. reservation, in NMI context, ``bpf_ringbuf_reserve()`` might fail to get
  128. a lock, in which case reservation will fail even if ring buffer is not full.
  129. The ring buffer itself internally is implemented as a power-of-2 sized
  130. circular buffer, with two logical and ever-increasing counters (which might
  131. wrap around on 32-bit architectures, that's not a problem):
  132. - consumer counter shows up to which logical position consumer consumed the
  133. data;
  134. - producer counter denotes amount of data reserved by all producers.
  135. Each time a record is reserved, producer that "owns" the record will
  136. successfully advance producer counter. At that point, data is still not yet
  137. ready to be consumed, though. Each record has 8 byte header, which contains the
  138. length of reserved record, as well as two extra bits: busy bit to denote that
  139. record is still being worked on, and discard bit, which might be set at commit
  140. time if record is discarded. In the latter case, consumer is supposed to skip
  141. the record and move on to the next one. Record header also encodes record's
  142. relative offset from the beginning of ring buffer data area (in pages). This
  143. allows ``bpf_ringbuf_commit()``/``bpf_ringbuf_discard()`` to accept only the
  144. pointer to the record itself, without requiring also the pointer to ring buffer
  145. itself. Ring buffer memory location will be restored from record metadata
  146. header. This significantly simplifies verifier, as well as improving API
  147. usability.
  148. Producer counter increments are serialized under spinlock, so there is
  149. a strict ordering between reservations. Commits, on the other hand, are
  150. completely lockless and independent. All records become available to consumer
  151. in the order of reservations, but only after all previous records where
  152. already committed. It is thus possible for slow producers to temporarily hold
  153. off submitted records, that were reserved later.
  154. One interesting implementation bit, that significantly simplifies (and thus
  155. speeds up as well) implementation of both producers and consumers is how data
  156. area is mapped twice contiguously back-to-back in the virtual memory. This
  157. allows to not take any special measures for samples that have to wrap around
  158. at the end of the circular buffer data area, because the next page after the
  159. last data page would be first data page again, and thus the sample will still
  160. appear completely contiguous in virtual memory. See comment and a simple ASCII
  161. diagram showing this visually in ``bpf_ringbuf_area_alloc()``.
  162. Another feature that distinguishes BPF ringbuf from perf ring buffer is
  163. a self-pacing notifications of new data being availability.
  164. ``bpf_ringbuf_commit()`` implementation will send a notification of new record
  165. being available after commit only if consumer has already caught up right up to
  166. the record being committed. If not, consumer still has to catch up and thus
  167. will see new data anyways without needing an extra poll notification.
  168. Benchmarks (see tools/testing/selftests/bpf/benchs/bench_ringbufs.c) show that
  169. this allows to achieve a very high throughput without having to resort to
  170. tricks like "notify only every Nth sample", which are necessary with perf
  171. buffer. For extreme cases, when BPF program wants more manual control of
  172. notifications, commit/discard/output helpers accept ``BPF_RB_NO_WAKEUP`` and
  173. ``BPF_RB_FORCE_WAKEUP`` flags, which give full control over notifications of
  174. data availability, but require extra caution and diligence in using this API.