1 // SPDX-License-Identifier: GPL-2.0
4 #include <linux/if_ether.h>
7 #include <linux/pkt_cls.h>
9 #include "bpf_helpers.h"
10 #include "bpf_endian.h"
12 /* the maximum delay we are willing to add (drop packets beyond that) */
13 #define TIME_HORIZON_NS (2000 * 1000 * 1000)
14 #define NS_PER_SEC 1000000000
15 #define ECN_HORIZON_NS 5000000
16 #define THROTTLE_RATE_BPS (5 * 1000 * 1000)
18 /* flow_key => last_tstamp timestamp used */
19 struct bpf_map_def
SEC("maps") flow_map
= {
20 .type
= BPF_MAP_TYPE_HASH
,
21 .key_size
= sizeof(uint32_t),
22 .value_size
= sizeof(uint64_t),
26 static inline int throttle_flow(struct __sk_buff
*skb
)
29 uint64_t *last_tstamp
= bpf_map_lookup_elem(&flow_map
, &key
);
30 uint64_t delay_ns
= ((uint64_t)skb
->len
) * NS_PER_SEC
/
32 uint64_t now
= bpf_ktime_get_ns();
33 uint64_t tstamp
, next_tstamp
= 0;
36 next_tstamp
= *last_tstamp
+ delay_ns
;
42 /* should we throttle? */
43 if (next_tstamp
<= tstamp
) {
44 if (bpf_map_update_elem(&flow_map
, &key
, &tstamp
, BPF_ANY
))
49 /* do not queue past the time horizon */
50 if (next_tstamp
- now
>= TIME_HORIZON_NS
)
53 /* set ecn bit, if needed */
54 if (next_tstamp
- now
>= ECN_HORIZON_NS
)
55 bpf_skb_ecn_set_ce(skb
);
57 if (bpf_map_update_elem(&flow_map
, &key
, &next_tstamp
, BPF_EXIST
))
59 skb
->tstamp
= next_tstamp
;
64 static inline int handle_tcp(struct __sk_buff
*skb
, struct tcphdr
*tcp
)
66 void *data_end
= (void *)(long)skb
->data_end
;
68 /* drop malformed packets */
69 if ((void *)(tcp
+ 1) > data_end
)
72 if (tcp
->dest
== bpf_htons(9000))
73 return throttle_flow(skb
);
78 static inline int handle_ipv4(struct __sk_buff
*skb
)
80 void *data_end
= (void *)(long)skb
->data_end
;
81 void *data
= (void *)(long)skb
->data
;
85 /* drop malformed packets */
86 if (data
+ sizeof(struct ethhdr
) > data_end
)
88 iph
= (struct iphdr
*)(data
+ sizeof(struct ethhdr
));
89 if ((void *)(iph
+ 1) > data_end
)
92 if (((void *)iph
) + ihl
> data_end
)
95 if (iph
->protocol
== IPPROTO_TCP
)
96 return handle_tcp(skb
, (struct tcphdr
*)(((void *)iph
) + ihl
));
101 SEC("cls_test") int tc_prog(struct __sk_buff
*skb
)
103 if (skb
->protocol
== bpf_htons(ETH_P_IP
))
104 return handle_ipv4(skb
);
109 char __license
[] SEC("license") = "GPL";