1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2020 Facebook */
3 #include "bpf_iter.h"
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_tracing.h>
6 
7 char _license[] SEC("license") = "GPL";
8 
9 struct key_t {
10 	int a;
11 	int b;
12 	int c;
13 };
14 
15 struct {
16 	__uint(type, BPF_MAP_TYPE_HASH);
17 	__uint(max_entries, 3);
18 	__type(key, struct key_t);
19 	__type(value, __u64);
20 } hashmap1 SEC(".maps");
21 
22 struct {
23 	__uint(type, BPF_MAP_TYPE_HASH);
24 	__uint(max_entries, 3);
25 	__type(key, __u64);
26 	__type(value, __u64);
27 } hashmap2 SEC(".maps");
28 
29 struct {
30 	__uint(type, BPF_MAP_TYPE_HASH);
31 	__uint(max_entries, 3);
32 	__type(key, struct key_t);
33 	__type(value, __u32);
34 } hashmap3 SEC(".maps");
35 
36 /* will set before prog run */
37 bool in_test_mode = 0;
38 
39 /* will collect results during prog run */
40 __u32 key_sum_a = 0, key_sum_b = 0, key_sum_c = 0;
41 __u64 val_sum = 0;
42 
43 SEC("iter/bpf_map_elem")
44 int dump_bpf_hash_map(struct bpf_iter__bpf_map_elem *ctx)
45 {
46 	struct seq_file *seq = ctx->meta->seq;
47 	__u32 seq_num = ctx->meta->seq_num;
48 	struct bpf_map *map = ctx->map;
49 	struct key_t *key = ctx->key;
50 	__u64 *val = ctx->value;
51 
52 	if (in_test_mode) {
53 		/* test mode is used by selftests to
54 		 * test functionality of bpf_hash_map iter.
55 		 *
56 		 * the above hashmap1 will have correct size
57 		 * and will be accepted, hashmap2 and hashmap3
58 		 * should be rejected due to smaller key/value
59 		 * size.
60 		 */
61 		if (key == (void *)0 || val == (void *)0)
62 			return 0;
63 
64 		key_sum_a += key->a;
65 		key_sum_b += key->b;
66 		key_sum_c += key->c;
67 		val_sum += *val;
68 		return 0;
69 	}
70 
71 	/* non-test mode, the map is prepared with the
72 	 * below bpftool command sequence:
73 	 *   bpftool map create /sys/fs/bpf/m1 type hash \
74 	 *   	key 12 value 8 entries 3 name map1
75 	 *   bpftool map update id 77 key 0 0 0 1 0 0 0 0 0 0 0 1 \
76 	 *   	value 0 0 0 1 0 0 0 1
77 	 *   bpftool map update id 77 key 0 0 0 1 0 0 0 0 0 0 0 2 \
78 	 *   	value 0 0 0 1 0 0 0 2
79 	 * The bpftool iter command line:
80 	 *   bpftool iter pin ./bpf_iter_bpf_hash_map.o /sys/fs/bpf/p1 \
81 	 *   	map id 77
82 	 * The below output will be:
83 	 *   map dump starts
84 	 *   77: (1000000 0 2000000) (200000001000000)
85 	 *   77: (1000000 0 1000000) (100000001000000)
86 	 *   map dump ends
87 	 */
88 	if (seq_num == 0)
89 		BPF_SEQ_PRINTF(seq, "map dump starts\n");
90 
91 	if (key == (void *)0 || val == (void *)0) {
92 		BPF_SEQ_PRINTF(seq, "map dump ends\n");
93 		return 0;
94 	}
95 
96 	BPF_SEQ_PRINTF(seq, "%d: (%x %d %x) (%llx)\n", map->id,
97 		       key->a, key->b, key->c, *val);
98 
99 	return 0;
100 }
101