Skip to contentSkip to conversation

Add bpf_read_branch_records() helper

PATCH RESEND Superseded Daniel Xu 2 participants 8 messages Feb 10, 2020 – Feb 14, 2020

Subsystems (6)
Kselftest BPF Tracing BPF selftests +2 more subsystems

v7 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

Daniel Xu

author
#0 lore raw

v7 cover Add bpf_read_branch_records() helper

Resend now that merge window is open again.

Branch records are a CPU feature that can be configured to record certain branches that are taken during code execution. This data is particularly interesting for profile guided optimizations. perf has had branch record support for a while but the data collection can be a bit coarse grained.

We (Facebook) have seen in experiments that associating metadata with branch records can improve results (after postprocessing). We generally use bpf_probe_read_*() to get metadata out of userspace. That's why bpf support for branch records is useful.

Aside from this particular use case, having branch data available to bpf progs can be useful to get stack traces out of userspace applications that omit frame pointers.

Changes in v7:
- Const-ify and static-ify local var
- Documentation formatting

Changes in v6:
- Move #ifdef a little to avoid unused variable warnings on !x86
- Test negative condition in selftest (-EINVAL on improperly configured perf event)
- Skip positive condition selftest on setups that don't support branch records

Changes in v5:
- Rename bpf_perf_prog_read_branches() -> bpf_read_branch_records()
- Rename BPF_F_GET_BR_SIZE -> BPF_F_GET_BRANCH_RECORDS_SIZE
- Squash tools/ bpf.h sync into selftest commit

Changes in v4:
- Add BPF_F_GET_BR_SIZE flag
- Return -ENOENT on unsupported architectures
- Only accept initialized memory in helper
- Check buffer size is multiple of sizeof(struct perf_branch_entry)
- Use bpf skeleton in selftest
- Add commit messages
- Spelling and formatting

Changes in v3:
- Document filling unused buffer with zero
- Formatting fixes
- Rebase

Changes in v2:
- Change to a bpf helper instead of context access
- Avoid mentioning Intel specific things

Daniel Xu (2):
bpf: Add bpf_read_branch_records() helper selftests/bpf: add bpf_read_branch_records() selftest

 include/uapi/linux/bpf.h                      |  25 ++-
 kernel/trace/bpf_trace.c                      |  41 ++++
 tools/include/uapi/linux/bpf.h                |  25 ++-
 .../selftests/bpf/prog_tests/perf_branches.c  | 182 ++++++++++++++++++
 .../selftests/bpf/progs/test_perf_branches.c  |  74 +++++++
 5 files changed, 345 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/perf_branches.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_perf_branches.c
Signature · 1 line
2.21.1
author
#1 lore raw

PATCH RESEND v7 1/2 bpf: Add bpf_read_branch_records() helper

Branch records are a CPU feature that can be configured to record certain branches that are taken during code execution. This data is particularly interesting for profile guided optimizations. perf has had branch record support for a while but the data collection can be a bit coarse grained.

We (Facebook) have seen in experiments that associating metadata with branch records can improve results (after postprocessing). We generally use bpf_probe_read_*() to get metadata out of userspace. That's why bpf support for branch records is useful.

Aside from this particular use case, having branch data available to bpf progs can be useful to get stack traces out of userspace applications that omit frame pointers.

---
 include/uapi/linux/bpf.h | 25 +++++++++++++++++++++++-
 kernel/trace/bpf_trace.c | 41 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 65 insertions(+), 1 deletion(-)
include/uapi/linux/bpf.h +24 -1
index f1d74a2bd234..3004470b7269 100644
@@ -2892,6 +2892,25 @@ union bpf_attr {
  *		Obtain the 64bit jiffies
  *	Return
  *		The 64 bit jiffies
+ *
+ * int bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, u32 size, u64 flags)
+ *	Description
+ *		For an eBPF program attached to a perf event, retrieve the
+ *		branch records (struct perf_branch_entry) associated to *ctx*
+ *		and store it in	the buffer pointed by *buf* up to size
+ *		*buf_size* bytes.
+ *	Return
+ *		On success, number of bytes written to *buf*. On error, a
+ *		negative value.
+ *
+ *		The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to
+ *		instead	return the number of bytes required to store all the
+ *		branch entries. If this flag is set, *buf* may be NULL.
+ *
+ *		**-EINVAL** if arguments invalid or **buf_size** not a multiple
+ *		of sizeof(struct perf_branch_entry).
+ *
+ *		**-ENOENT** if architecture does not support branch records.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -3012,7 +3031,8 @@ union bpf_attr {
 	FN(probe_read_kernel_str),	\
 	FN(tcp_send_ack),		\
 	FN(send_signal_thread),		\
-	FN(jiffies64),
+	FN(jiffies64),			\
+	FN(read_branch_records),
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
  * function eBPF program intends to call
@@ -3091,6 +3111,9 @@ enum bpf_func_id {
 /* BPF_FUNC_sk_storage_get flags */
 #define BPF_SK_STORAGE_GET_F_CREATE	(1ULL << 0)
 
+/* BPF_FUNC_read_branch_records flags. */
+#define BPF_F_GET_BRANCH_RECORDS_SIZE	(1ULL << 0)
+
 /* Mode for BPF_FUNC_skb_adjust_room helper. */
 enum bpf_adj_room_mode {
 	BPF_ADJ_ROOM_NET,
kernel/trace/bpf_trace.c +41 -0

53 lines not on this page · raw message

Signature · 1 line
2.21.1
Acked-by on v7 1/2
#2 lore raw

Re: [PATCH v7 bpf-next RESEND 1/2] bpf: Add bpf_read_branch_records() helper

Quoted 12 lines · Daniel Xu

Branch records are a CPU feature that can be configured to record certain branches that are taken during code execution. This data is particularly interesting for profile guided optimizations. perf has had branch record support for a while but the data collection can be a bit coarse grained.

We (Facebook) have seen in experiments that associating metadata with branch records can improve results (after postprocessing). We generally use bpf_probe_read_*() to get metadata out of userspace. That's why bpf support for branch records is useful.

Quoted 6 lines

Aside from this particular use case, having branch data available to bpf progs can be useful to get stack traces out of userspace applications that omit frame pointers.

---

LGTM, one typo in description of the helper. bpf-next is still closed, btw, but should hopefully open soon.

Quoted 18 lines
 include/uapi/linux/bpf.h | 25 +++++++++++++++++++++++-
 kernel/trace/bpf_trace.c | 41 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 65 insertions(+), 1 deletion(-)
include/uapi/linux/bpf.h +6 -0
index f1d74a2bd234..3004470b7269 100644
@@ -2892,6 +2892,25 @@ union bpf_attr {
  *             Obtain the 64bit jiffies
  *     Return
  *             The 64 bit jiffies
+ *
+ * int bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, u32 size, u64 flags)
+ *     Description
+ *             For an eBPF program attached to a perf event, retrieve the
+ *             branch records (struct perf_branch_entry) associated to *ctx*
+ *             and store it in the buffer pointed by *buf* up to size

include/uapi/linux/bpf.h union bpf_attr { · line 2910

Quoted 10 lines
include/uapi/linux/bpf.h +10 -0
+ *             *buf_size* bytes.
+ *     Return
+ *             On success, number of bytes written to *buf*. On error, a
+ *             negative value.
+ *
+ *             The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to
+ *             instead return the number of bytes required to store all the
+ *             branch entries. If this flag is set, *buf* may be NULL.
+ *
+ *             **-EINVAL** if arguments invalid or **buf_size** not a multiple

buf_size -> size

Quoted 4 lines
include/uapi/linux/bpf.h +3 -0
+ *             of sizeof(struct perf_branch_entry).
+ *
+ *             **-ENOENT** if architecture does not support branch records.
  */

[...]

author
#3 lore raw

Re: [PATCH v7 bpf-next RESEND 1/2] bpf: Add bpf_read_branch_records() helper

Quoted 1 line · Andrii Nakryiko

On Mon, Feb 10, 2020 at 12:09 PM Daniel Xu <[email protected]> wrote:

[...]

Quoted 17 lines
Quoted 10 lines

+ * int bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, u32 size, u64 flags)
+ * Description

+ *             For an eBPF program attached to a perf event, retrieve the
+ *             branch records (struct perf_branch_entry) associated to *ctx*
+ *             and store it in the buffer pointed by *buf* up to size
+ *             *buf_size* bytes.

+ * Return
+ * On success, number of bytes written to *buf*. On error, a
+ * negative value.
+ *

Quoted 5 lines
+ *             The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to
+ *             instead return the number of bytes required to store all the
+ *             branch entries. If this flag is set, *buf* may be NULL.

+ *
+ * **-EINVAL** if arguments invalid or **buf_size** not a multiple

Quoted 1 line

buf_size -> size

Whoops, thanks for catching.

[...]

author
#4 lore raw

PATCH RESEND v7 2/2 selftests/bpf: add bpf_read_branch_records() selftest

In reply to Daniel Xu

Add a selftest to test:

* default bpf_read_branch_records() behavior
* BPF_F_GET_BRANCH_RECORDS_SIZE flag behavior
* error path on non branch record perf events
* using helper to write to stack
* using helper to write to map

On host with hardware counter support:

    # ./test_progs -t perf_branches
    #27/1 perf_branches_hw:OK
    #27/2 perf_branches_no_hw:OK
    #27 perf_branches:OK
    Summary: 1/2 PASSED, 0 SKIPPED, 0 FAILED

On host without hardware counter support (VM):

    # ./test_progs -t perf_branches
    #27/1 perf_branches_hw:OK
    #27/2 perf_branches_no_hw:OK
    #27 perf_branches:OK
    Summary: 1/2 PASSED, 1 SKIPPED, 0 FAILED

Also sync tools/include/uapi/linux/bpf.h.

---
 tools/include/uapi/linux/bpf.h                |  25 ++-
 .../selftests/bpf/prog_tests/perf_branches.c  | 182 ++++++++++++++++++
 .../selftests/bpf/progs/test_perf_branches.c  |  74 +++++++
 3 files changed, 280 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/perf_branches.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_perf_branches.c
tools/include/uapi/linux/bpf.h +24 -1
index f1d74a2bd234..3004470b7269 100644
@@ -2892,6 +2892,25 @@ union bpf_attr {
  *		Obtain the 64bit jiffies
  *	Return
  *		The 64 bit jiffies
+ *
+ * int bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, u32 size, u64 flags)
+ *	Description
+ *		For an eBPF program attached to a perf event, retrieve the
+ *		branch records (struct perf_branch_entry) associated to *ctx*
+ *		and store it in	the buffer pointed by *buf* up to size
+ *		*buf_size* bytes.
+ *	Return
+ *		On success, number of bytes written to *buf*. On error, a
+ *		negative value.
+ *
+ *		The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to
+ *		instead	return the number of bytes required to store all the
+ *		branch entries. If this flag is set, *buf* may be NULL.
+ *
+ *		**-EINVAL** if arguments invalid or **buf_size** not a multiple
+ *		of sizeof(struct perf_branch_entry).
+ *
+ *		**-ENOENT** if architecture does not support branch records.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -3012,7 +3031,8 @@ union bpf_attr {
 	FN(probe_read_kernel_str),	\
 	FN(tcp_send_ack),		\
 	FN(send_signal_thread),		\
-	FN(jiffies64),
+	FN(jiffies64),			\
+	FN(read_branch_records),
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
  * function eBPF program intends to call
@@ -3091,6 +3111,9 @@ enum bpf_func_id {
 /* BPF_FUNC_sk_storage_get flags */
 #define BPF_SK_STORAGE_GET_F_CREATE	(1ULL << 0)
 
+/* BPF_FUNC_read_branch_records flags. */
+#define BPF_F_GET_BRANCH_RECORDS_SIZE	(1ULL << 0)
+
 /* Mode for BPF_FUNC_skb_adjust_room helper. */
 enum bpf_adj_room_mode {
 	BPF_ADJ_ROOM_NET,
tools/testing/selftests/bpf/prog_tests/perf_branches.c new file +182 -0

182 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_perf_branches.c new file +74 -0

74 lines not on this page · raw message

Signature · 1 line
2.21.1
#5 lore raw

Re: [PATCH v7 bpf-next RESEND 2/2] selftests/bpf: add bpf_read_branch_records() selftest

Quoted 36 lines · Daniel Xu

Add a selftest to test:

* default bpf_read_branch_records() behavior
* BPF_F_GET_BRANCH_RECORDS_SIZE flag behavior
* error path on non branch record perf events
* using helper to write to stack
* using helper to write to map

On host with hardware counter support:

    # ./test_progs -t perf_branches
    #27/1 perf_branches_hw:OK
    #27/2 perf_branches_no_hw:OK
    #27 perf_branches:OK
    Summary: 1/2 PASSED, 0 SKIPPED, 0 FAILED

On host without hardware counter support (VM):

    # ./test_progs -t perf_branches
    #27/1 perf_branches_hw:OK
    #27/2 perf_branches_no_hw:OK
    #27 perf_branches:OK
    Summary: 1/2 PASSED, 1 SKIPPED, 0 FAILED

Also sync tools/include/uapi/linux/bpf.h.

---
 tools/include/uapi/linux/bpf.h                |  25 ++-
 .../selftests/bpf/prog_tests/perf_branches.c  | 182 ++++++++++++++++++
 .../selftests/bpf/progs/test_perf_branches.c  |  74 +++++++
 3 files changed, 280 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/perf_branches.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_perf_branches.c

[...]

tools/testing/selftests/bpf/prog_tests/perf_branches.c line 98

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/perf_branches.c new file +10 -0
+       /* generate some branches on cpu 0 */
+       CPU_ZERO(&cpu_set);
+       CPU_SET(0, &cpu_set);
+       err = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set), &cpu_set);
+       if (CHECK(err, "set_affinity", "cpu #0, err %d\n", err))
+               goto out_free_pb;
+       /* spin the loop for a while (random high number) */
+       for (i = 0; i < 1000000; ++i)
+               ++j;
+

test_perf_branches__detach here?

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/perf_branches.c new file +8 -0
+       /* read perf buffer */
+       err = perf_buffer__poll(pb, 500);
+       if (CHECK(err < 0, "perf_buffer__poll", "err %d\n", err))
+               goto out_free_pb;
+
+       if (CHECK(!ok, "ok", "not ok\n"))
+               goto out_free_pb;
+

[...]

Quoted 31 lines
tools/testing/selftests/bpf/progs/test_perf_branches.c new file +25 -0
new file mode 100644
index 000000000000..60327d512400
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (c) 2019 Facebook
+
+#include <stddef.h>
+#include <linux/ptrace.h>
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_trace_helpers.h"
+
+struct fake_perf_branch_entry {
+       __u64 _a;
+       __u64 _b;
+       __u64 _c;
+};
+
+struct output {
+       int required_size;
+       int written_stack;
+       int written_map;
+};
+
+struct {
+       __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
+       __uint(key_size, sizeof(int));
+       __uint(value_size, sizeof(int));

tools/testing/selftests/bpf/progs/test_perf_branches.c line 35

Quoted 10 lines
tools/testing/selftests/bpf/progs/test_perf_branches.c new file +10 -0
+} perf_buf_map SEC(".maps");
+
+typedef struct fake_perf_branch_entry fpbe_t[30];
+
+struct {
+       __uint(type, BPF_MAP_TYPE_ARRAY);
+       __uint(max_entries, 1);
+       __type(key, __u32);
+       __type(value, fpbe_t);
+} scratch_map SEC(".maps");

Can you please use global variables instead of array and perf_event_array? Would make BPF side clearer and userspace simpler. struct output member will just become variables.

[...]

author
#6 lore raw

Re: [PATCH v7 bpf-next RESEND 2/2] selftests/bpf: add bpf_read_branch_records() selftest

Quoted 1 line · Andrii Nakryiko

On Mon, Feb 10, 2020 at 12:09 PM Daniel Xu <[email protected]> wrote:

[...]

Quoted 13 lines

tools/testing/selftests/bpf/prog_tests/perf_branches.c line 98

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/perf_branches.c new file +10 -0
+       /* generate some branches on cpu 0 */
+       CPU_ZERO(&cpu_set);
+       CPU_SET(0, &cpu_set);
+       err = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set), &cpu_set);
+       if (CHECK(err, "set_affinity", "cpu #0, err %d\n", err))
+               goto out_free_pb;
+       /* spin the loop for a while (random high number) */
+       for (i = 0; i < 1000000; ++i)
+               ++j;
+
Quoted 1 line

test_perf_branches__detach here?

Yeah, good idea.

[...]

Quoted 21 lines
Quoted 21 lines
tools/testing/selftests/bpf/progs/test_perf_branches.c new file +21 -0
+struct fake_perf_branch_entry {
+       __u64 _a;
+       __u64 _b;
+       __u64 _c;
+};
+
+struct output {
+       int required_size;
+       int written_stack;
+       int written_map;
+};
+
+struct {
+       __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
+       __uint(key_size, sizeof(int));
+       __uint(value_size, sizeof(int));
+} perf_buf_map SEC(".maps");
+
+typedef struct fake_perf_branch_entry fpbe_t[30];
+
+struct {
Quoted 8 lines

tools/testing/selftests/bpf/progs/test_perf_branches.c line 35

Quoted 5 lines
tools/testing/selftests/bpf/progs/test_perf_branches.c new file +5 -0
+       __uint(type, BPF_MAP_TYPE_ARRAY);
+       __uint(max_entries, 1);
+       __type(key, __u32);
+       __type(value, fpbe_t);
+} scratch_map SEC(".maps");

Can you please use global variables instead of array

If you mean scratch_map, sure.

Quoted 1 line

and perf_event_array?

Do you mean replace the perf ring buffer with global variables? I think that would limit the number of samples we validate in userspace to a fixed number. It might be better to validate as many as the system gives us.

Let me know what you think. I might be overthinking it.

Quoted 2 lines

Would make BPF side clearer and userspace simpler. struct output member will just become variables.

Thanks,
Daniel

#7 lore raw

Re: [PATCH v7 bpf-next RESEND 2/2] selftests/bpf: add bpf_read_branch_records() selftest

Quoted 56 lines · Daniel Xu
Quoted 1 line · Andrii Nakryiko

On Mon, Feb 10, 2020 at 12:09 PM Daniel Xu <[email protected]> wrote:

[...]

Quoted 13 lines

tools/testing/selftests/bpf/prog_tests/perf_branches.c line 98

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/perf_branches.c new file +10 -0
+       /* generate some branches on cpu 0 */
+       CPU_ZERO(&cpu_set);
+       CPU_SET(0, &cpu_set);
+       err = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set), &cpu_set);
+       if (CHECK(err, "set_affinity", "cpu #0, err %d\n", err))
+               goto out_free_pb;
+       /* spin the loop for a while (random high number) */
+       for (i = 0; i < 1000000; ++i)
+               ++j;
+
Quoted 1 line

test_perf_branches__detach here?

Yeah, good idea.

[...]

Quoted 21 lines
Quoted 21 lines
tools/testing/selftests/bpf/progs/test_perf_branches.c new file +21 -0
+struct fake_perf_branch_entry {
+       __u64 _a;
+       __u64 _b;
+       __u64 _c;
+};
+
+struct output {
+       int required_size;
+       int written_stack;
+       int written_map;
+};
+
+struct {
+       __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
+       __uint(key_size, sizeof(int));
+       __uint(value_size, sizeof(int));
+} perf_buf_map SEC(".maps");
+
+typedef struct fake_perf_branch_entry fpbe_t[30];
+
+struct {
Quoted 8 lines

tools/testing/selftests/bpf/progs/test_perf_branches.c line 35

Quoted 5 lines
tools/testing/selftests/bpf/progs/test_perf_branches.c new file +5 -0
+       __uint(type, BPF_MAP_TYPE_ARRAY);
+       __uint(max_entries, 1);
+       __type(key, __u32);
+       __type(value, fpbe_t);
+} scratch_map SEC(".maps");

Can you please use global variables instead of array

If you mean scratch_map, sure.

Quoted 7 lines
Quoted 1 line

and perf_event_array?

Do you mean replace the perf ring buffer with global variables? I think that would limit the number of samples we validate in userspace to a fixed number. It might be better to validate as many as the system gives us.

Let me know what you think. I might be overthinking it.

Yeah, I meant get rid of perf_buffer and just use global variables for outputting data.

re: validating multiple samples in perf_buffer. Given you don't really control how many samples you'll get and you check nothing specific about any single sample, I think it's fine to just validate any. They are not supposed to differ much, right? Checking that size is multiple of perf_branch_entry size is pretty much the only thing we can check, no?

Quoted 7 lines
Quoted 3 lines

Would make BPF side clearer and userspace simpler. struct output member will just become variables.

Thanks,
Daniel