Merge branch 'for-linus' into for-next
[linux-2.6-block.git] / samples / bpf / trace_event_kern.c
CommitLineData
1c47910e
AS
1/* Copyright (c) 2016 Facebook
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
6 */
7#include <linux/ptrace.h>
8#include <linux/version.h>
9#include <uapi/linux/bpf.h>
10#include <uapi/linux/bpf_perf_event.h>
11#include <uapi/linux/perf_event.h>
12#include "bpf_helpers.h"
13
14struct key_t {
15 char comm[TASK_COMM_LEN];
16 u32 kernstack;
17 u32 userstack;
18};
19
20struct bpf_map_def SEC("maps") counts = {
21 .type = BPF_MAP_TYPE_HASH,
22 .key_size = sizeof(struct key_t),
23 .value_size = sizeof(u64),
24 .max_entries = 10000,
25};
26
27struct bpf_map_def SEC("maps") stackmap = {
28 .type = BPF_MAP_TYPE_STACK_TRACE,
29 .key_size = sizeof(u32),
30 .value_size = PERF_MAX_STACK_DEPTH * sizeof(u64),
31 .max_entries = 10000,
32};
33
34#define KERN_STACKID_FLAGS (0 | BPF_F_FAST_STACK_CMP)
35#define USER_STACKID_FLAGS (0 | BPF_F_FAST_STACK_CMP | BPF_F_USER_STACK)
36
37SEC("perf_event")
38int bpf_prog1(struct bpf_perf_event_data *ctx)
39{
81b9cf80
YS
40 char time_fmt1[] = "Time Enabled: %llu, Time Running: %llu";
41 char time_fmt2[] = "Get Time Failed, ErrCode: %d";
12fe1225 42 char addr_fmt[] = "Address recorded on event: %llx";
1c47910e
AS
43 char fmt[] = "CPU-%d period %lld ip %llx";
44 u32 cpu = bpf_get_smp_processor_id();
81b9cf80 45 struct bpf_perf_event_value value_buf;
1c47910e
AS
46 struct key_t key;
47 u64 *val, one = 1;
81b9cf80 48 int ret;
1c47910e
AS
49
50 if (ctx->sample_period < 10000)
51 /* ignore warmup */
52 return 0;
53 bpf_get_current_comm(&key.comm, sizeof(key.comm));
54 key.kernstack = bpf_get_stackid(ctx, &stackmap, KERN_STACKID_FLAGS);
55 key.userstack = bpf_get_stackid(ctx, &stackmap, USER_STACKID_FLAGS);
56 if ((int)key.kernstack < 0 && (int)key.userstack < 0) {
57 bpf_trace_printk(fmt, sizeof(fmt), cpu, ctx->sample_period,
2dbb4c05 58 PT_REGS_IP(&ctx->regs));
1c47910e
AS
59 return 0;
60 }
61
81b9cf80
YS
62 ret = bpf_perf_prog_read_value(ctx, (void *)&value_buf, sizeof(struct bpf_perf_event_value));
63 if (!ret)
64 bpf_trace_printk(time_fmt1, sizeof(time_fmt1), value_buf.enabled, value_buf.running);
65 else
66 bpf_trace_printk(time_fmt2, sizeof(time_fmt2), ret);
67
12fe1225
TQ
68 if (ctx->addr != 0)
69 bpf_trace_printk(addr_fmt, sizeof(addr_fmt), ctx->addr);
70
1c47910e
AS
71 val = bpf_map_lookup_elem(&counts, &key);
72 if (val)
73 (*val)++;
74 else
75 bpf_map_update_elem(&counts, &key, &one, BPF_NOEXIST);
76 return 0;
77}
78
79char _license[] SEC("license") = "GPL";