Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
0002 
0003 #include "util/bpf_map.h"
0004 #include <bpf/bpf.h>
0005 #include <bpf/libbpf.h>
0006 #include <linux/err.h>
0007 #include <linux/kernel.h>
0008 #include <stdbool.h>
0009 #include <stdlib.h>
0010 #include <unistd.h>
0011 
0012 static bool bpf_map__is_per_cpu(enum bpf_map_type type)
0013 {
0014     return type == BPF_MAP_TYPE_PERCPU_HASH ||
0015            type == BPF_MAP_TYPE_PERCPU_ARRAY ||
0016            type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
0017            type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE;
0018 }
0019 
0020 static void *bpf_map__alloc_value(const struct bpf_map *map)
0021 {
0022     if (bpf_map__is_per_cpu(bpf_map__type(map)))
0023         return malloc(round_up(bpf_map__value_size(map), 8) *
0024                   sysconf(_SC_NPROCESSORS_CONF));
0025 
0026     return malloc(bpf_map__value_size(map));
0027 }
0028 
0029 int bpf_map__fprintf(struct bpf_map *map, FILE *fp)
0030 {
0031     void *prev_key = NULL, *key, *value;
0032     int fd = bpf_map__fd(map), err;
0033     int printed = 0;
0034 
0035     if (fd < 0)
0036         return fd;
0037 
0038     if (!map)
0039         return PTR_ERR(map);
0040 
0041     err = -ENOMEM;
0042     key = malloc(bpf_map__key_size(map));
0043     if (key == NULL)
0044         goto out;
0045 
0046     value = bpf_map__alloc_value(map);
0047     if (value == NULL)
0048         goto out_free_key;
0049 
0050     while ((err = bpf_map_get_next_key(fd, prev_key, key) == 0)) {
0051         int intkey = *(int *)key;
0052 
0053         if (!bpf_map_lookup_elem(fd, key, value)) {
0054             bool boolval = *(bool *)value;
0055             if (boolval)
0056                 printed += fprintf(fp, "[%d] = %d,\n", intkey, boolval);
0057         } else {
0058             printed += fprintf(fp, "[%d] = ERROR,\n", intkey);
0059         }
0060 
0061         prev_key = key;
0062     }
0063 
0064     if (err == ENOENT)
0065         err = printed;
0066 
0067     free(value);
0068 out_free_key:
0069     free(key);
0070 out:
0071     return err;
0072 }