1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "kern.h"
18 #include <linux/bpf.h>
19 #include <stdint.h>
20 #include "bpf_helpers.h"
21
22 DEFINE_BPF_MAP(test_configuration_map, HASH, uint32_t, uint32_t, 1)
DEFINE_BPF_MAP(test_stats_map_A,HASH,uint64_t,stats_value,NUM_SOCKETS)23 DEFINE_BPF_MAP(test_stats_map_A, HASH, uint64_t, stats_value, NUM_SOCKETS)
24 DEFINE_BPF_MAP(test_stats_map_B, HASH, uint64_t, stats_value, NUM_SOCKETS)
25
26 #define DEFINE_UPDATE_INGRESS_STATS(the_map) \
27 static inline void update_ingress_##the_map(struct __sk_buff* skb) { \
28 uint64_t sock_cookie = bpf_get_socket_cookie(skb); \
29 stats_value* value = bpf_##the_map##_lookup_elem(&sock_cookie); \
30 if (!value) { \
31 stats_value newValue = {}; \
32 bpf_##the_map##_update_elem(&sock_cookie, &newValue, BPF_NOEXIST); \
33 value = bpf_##the_map##_lookup_elem(&sock_cookie); \
34 } \
35 if (value) { \
36 __sync_fetch_and_add(&value->rxPackets, 1); \
37 __sync_fetch_and_add(&value->rxBytes, skb->len); \
38 } \
39 }
40
41 DEFINE_UPDATE_INGRESS_STATS(test_stats_map_A)
42 DEFINE_UPDATE_INGRESS_STATS(test_stats_map_B)
43
44 SEC("skfilter/test")
45 int ingress_prog(struct __sk_buff* skb) {
46 uint32_t key = 1;
47 uint32_t* config = bpf_test_configuration_map_lookup_elem(&key);
48 if (config) {
49 if (*config) {
50 update_ingress_test_stats_map_A(skb);
51 } else {
52 update_ingress_test_stats_map_B(skb);
53 }
54 }
55 return skb->len;
56 }
57
58 char _license[] SEC("license") = "Apache 2.0";
59