Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 // Copyright (c) 2018 Facebook
0003 
0004 #include <linux/bpf.h>
0005 #include <bpf/bpf_helpers.h>
0006 
0007 #ifndef PERF_MAX_STACK_DEPTH
0008 #define PERF_MAX_STACK_DEPTH         127
0009 #endif
0010 
0011 struct {
0012     __uint(type, BPF_MAP_TYPE_ARRAY);
0013     __uint(max_entries, 1);
0014     __type(key, __u32);
0015     __type(value, __u32);
0016 } control_map SEC(".maps");
0017 
0018 struct {
0019     __uint(type, BPF_MAP_TYPE_HASH);
0020     __uint(max_entries, 16384);
0021     __type(key, __u32);
0022     __type(value, __u32);
0023 } stackid_hmap SEC(".maps");
0024 
0025 typedef struct bpf_stack_build_id stack_trace_t[PERF_MAX_STACK_DEPTH];
0026 
0027 struct {
0028     __uint(type, BPF_MAP_TYPE_STACK_TRACE);
0029     __uint(max_entries, 128);
0030     __uint(map_flags, BPF_F_STACK_BUILD_ID);
0031     __type(key, __u32);
0032     __type(value, stack_trace_t);
0033 } stackmap SEC(".maps");
0034 
0035 struct {
0036     __uint(type, BPF_MAP_TYPE_ARRAY);
0037     __uint(max_entries, 128);
0038     __type(key, __u32);
0039     __type(value, stack_trace_t);
0040 } stack_amap SEC(".maps");
0041 
0042 SEC("kprobe/urandom_read_iter")
0043 int oncpu(struct pt_regs *args)
0044 {
0045     __u32 max_len = sizeof(struct bpf_stack_build_id)
0046             * PERF_MAX_STACK_DEPTH;
0047     __u32 key = 0, val = 0, *value_p;
0048     void *stack_p;
0049 
0050     value_p = bpf_map_lookup_elem(&control_map, &key);
0051     if (value_p && *value_p)
0052         return 0; /* skip if non-zero *value_p */
0053 
0054     /* The size of stackmap and stackid_hmap should be the same */
0055     key = bpf_get_stackid(args, &stackmap, BPF_F_USER_STACK);
0056     if ((int)key >= 0) {
0057         bpf_map_update_elem(&stackid_hmap, &key, &val, 0);
0058         stack_p = bpf_map_lookup_elem(&stack_amap, &key);
0059         if (stack_p)
0060             bpf_get_stack(args, stack_p, max_len,
0061                       BPF_F_USER_STACK | BPF_F_USER_BUILD_ID);
0062     }
0063 
0064     return 0;
0065 }
0066 
0067 char _license[] SEC("license") = "GPL";