samples: bpf: improve xdp1 example

Store only the total packet count for every protocol, instead of the
whole per-cpu array.
Use bpf_map_get_next_key() to iterate the map, instead of looking up
all the protocols.

Signed-off-by: Matteo Croce <mcroce@redhat.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
This commit is contained in:
Matteo Croce 2018-12-01 01:23:05 +01:00 committed by Alexei Starovoitov
parent 9ffd05d9b7
commit d606ee5c1d
1 changed files with 8 additions and 10 deletions

View File

@ -34,26 +34,24 @@ static void int_exit(int sig)
static void poll_stats(int map_fd, int interval) static void poll_stats(int map_fd, int interval)
{ {
unsigned int nr_cpus = bpf_num_possible_cpus(); unsigned int nr_cpus = bpf_num_possible_cpus();
const unsigned int nr_keys = 256; __u64 values[nr_cpus], prev[UINT8_MAX] = { 0 };
__u64 values[nr_cpus], prev[nr_keys][nr_cpus];
__u32 key;
int i; int i;
memset(prev, 0, sizeof(prev));
while (1) { while (1) {
__u32 key = UINT32_MAX;
sleep(interval); sleep(interval);
for (key = 0; key < nr_keys; key++) { while (bpf_map_get_next_key(map_fd, &key, &key) != -1) {
__u64 sum = 0; __u64 sum = 0;
assert(bpf_map_lookup_elem(map_fd, &key, values) == 0); assert(bpf_map_lookup_elem(map_fd, &key, values) == 0);
for (i = 0; i < nr_cpus; i++) for (i = 0; i < nr_cpus; i++)
sum += (values[i] - prev[key][i]); sum += values[i];
if (sum) if (sum > prev[key])
printf("proto %u: %10llu pkt/s\n", printf("proto %u: %10llu pkt/s\n",
key, sum / interval); key, (sum - prev[key]) / interval);
memcpy(prev[key], values, sizeof(values)); prev[key] = sum;
} }
} }
} }