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 #include "bpf_net_helpers.h"
22 
23 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)24 DEFINE_BPF_MAP(test_stats_map_A, HASH, uint64_t, stats_value, NUM_SOCKETS)
25 DEFINE_BPF_MAP(test_stats_map_B, HASH, uint64_t, stats_value, NUM_SOCKETS)
26 
27 #define DEFINE_UPDATE_INGRESS_STATS(the_map)                               \
28   static inline void update_ingress_##the_map(struct __sk_buff* skb) {     \
29     uint64_t sock_cookie = bpf_get_socket_cookie(skb);                     \
30     stats_value* value = bpf_##the_map##_lookup_elem(&sock_cookie);        \
31     if (!value) {                                                          \
32       stats_value newValue = {};                                           \
33       bpf_##the_map##_update_elem(&sock_cookie, &newValue, BPF_NOEXIST);   \
34       value = bpf_##the_map##_lookup_elem(&sock_cookie);                   \
35     }                                                                      \
36     if (value) {                                                           \
37       __sync_fetch_and_add(&value->rxPackets, 1);                          \
38       __sync_fetch_and_add(&value->rxBytes, skb->len);                     \
39     }                                                                      \
40   }
41 
42 DEFINE_UPDATE_INGRESS_STATS(test_stats_map_A)
43 DEFINE_UPDATE_INGRESS_STATS(test_stats_map_B)
44 
45 SEC("skfilter/test")
46 int ingress_prog(struct __sk_buff* skb) {
47   uint32_t key = 1;
48   uint32_t* config = bpf_test_configuration_map_lookup_elem(&key);
49   if (config) {
50     if (*config) {
51       update_ingress_test_stats_map_A(skb);
52     } else {
53       update_ingress_test_stats_map_B(skb);
54     }
55   }
56   return skb->len;
57 }
58 
59 LICENSE("Apache 2.0");
60 CRITICAL("bpf_native_test");
61