xref: /openbmc/linux/samples/bpf/tracex4.bpf.c (revision 4a0ee788)
1*4a0ee788SDaniel T. Lee /* Copyright (c) 2015 PLUMgrid, http://plumgrid.com
2*4a0ee788SDaniel T. Lee  *
3*4a0ee788SDaniel T. Lee  * This program is free software; you can redistribute it and/or
4*4a0ee788SDaniel T. Lee  * modify it under the terms of version 2 of the GNU General Public
5*4a0ee788SDaniel T. Lee  * License as published by the Free Software Foundation.
6*4a0ee788SDaniel T. Lee  */
7*4a0ee788SDaniel T. Lee #include "vmlinux.h"
8*4a0ee788SDaniel T. Lee #include <linux/version.h>
9*4a0ee788SDaniel T. Lee #include <bpf/bpf_helpers.h>
10*4a0ee788SDaniel T. Lee #include <bpf/bpf_tracing.h>
11*4a0ee788SDaniel T. Lee 
12*4a0ee788SDaniel T. Lee struct pair {
13*4a0ee788SDaniel T. Lee 	u64 val;
14*4a0ee788SDaniel T. Lee 	u64 ip;
15*4a0ee788SDaniel T. Lee };
16*4a0ee788SDaniel T. Lee 
17*4a0ee788SDaniel T. Lee struct {
18*4a0ee788SDaniel T. Lee 	__uint(type, BPF_MAP_TYPE_HASH);
19*4a0ee788SDaniel T. Lee 	__type(key, long);
20*4a0ee788SDaniel T. Lee 	__type(value, struct pair);
21*4a0ee788SDaniel T. Lee 	__uint(max_entries, 1000000);
22*4a0ee788SDaniel T. Lee } my_map SEC(".maps");
23*4a0ee788SDaniel T. Lee 
24*4a0ee788SDaniel T. Lee /* kprobe is NOT a stable ABI. If kernel internals change this bpf+kprobe
25*4a0ee788SDaniel T. Lee  * example will no longer be meaningful
26*4a0ee788SDaniel T. Lee  */
27*4a0ee788SDaniel T. Lee SEC("kprobe/kmem_cache_free")
bpf_prog1(struct pt_regs * ctx)28*4a0ee788SDaniel T. Lee int bpf_prog1(struct pt_regs *ctx)
29*4a0ee788SDaniel T. Lee {
30*4a0ee788SDaniel T. Lee 	long ptr = PT_REGS_PARM2(ctx);
31*4a0ee788SDaniel T. Lee 
32*4a0ee788SDaniel T. Lee 	bpf_map_delete_elem(&my_map, &ptr);
33*4a0ee788SDaniel T. Lee 	return 0;
34*4a0ee788SDaniel T. Lee }
35*4a0ee788SDaniel T. Lee 
36*4a0ee788SDaniel T. Lee SEC("kretprobe/kmem_cache_alloc_node")
bpf_prog2(struct pt_regs * ctx)37*4a0ee788SDaniel T. Lee int bpf_prog2(struct pt_regs *ctx)
38*4a0ee788SDaniel T. Lee {
39*4a0ee788SDaniel T. Lee 	long ptr = PT_REGS_RC(ctx);
40*4a0ee788SDaniel T. Lee 	long ip = 0;
41*4a0ee788SDaniel T. Lee 
42*4a0ee788SDaniel T. Lee 	/* get ip address of kmem_cache_alloc_node() caller */
43*4a0ee788SDaniel T. Lee 	BPF_KRETPROBE_READ_RET_IP(ip, ctx);
44*4a0ee788SDaniel T. Lee 
45*4a0ee788SDaniel T. Lee 	struct pair v = {
46*4a0ee788SDaniel T. Lee 		.val = bpf_ktime_get_ns(),
47*4a0ee788SDaniel T. Lee 		.ip = ip,
48*4a0ee788SDaniel T. Lee 	};
49*4a0ee788SDaniel T. Lee 
50*4a0ee788SDaniel T. Lee 	bpf_map_update_elem(&my_map, &ptr, &v, BPF_ANY);
51*4a0ee788SDaniel T. Lee 	return 0;
52*4a0ee788SDaniel T. Lee }
53*4a0ee788SDaniel T. Lee char _license[] SEC("license") = "GPL";
54*4a0ee788SDaniel T. Lee u32 _version SEC("version") = LINUX_VERSION_CODE;
55