xref: /openbmc/linux/kernel/bpf/map_in_map.c (revision 309600c1)
1 /* Copyright (c) 2017 Facebook
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of version 2 of the GNU General Public
5  * License as published by the Free Software Foundation.
6  */
7 #include <linux/slab.h>
8 #include <linux/bpf.h>
9 
10 #include "map_in_map.h"
11 
12 struct bpf_map *bpf_map_meta_alloc(int inner_map_ufd)
13 {
14 	struct bpf_map *inner_map, *inner_map_meta;
15 	struct fd f;
16 
17 	f = fdget(inner_map_ufd);
18 	inner_map = __bpf_map_get(f);
19 	if (IS_ERR(inner_map))
20 		return inner_map;
21 
22 	/* prog_array->owner_prog_type and owner_jited
23 	 * is a runtime binding.  Doing static check alone
24 	 * in the verifier is not enough.
25 	 */
26 	if (inner_map->map_type == BPF_MAP_TYPE_PROG_ARRAY ||
27 	    inner_map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE) {
28 		fdput(f);
29 		return ERR_PTR(-ENOTSUPP);
30 	}
31 
32 	/* Does not support >1 level map-in-map */
33 	if (inner_map->inner_map_meta) {
34 		fdput(f);
35 		return ERR_PTR(-EINVAL);
36 	}
37 
38 	inner_map_meta = kzalloc(sizeof(*inner_map_meta), GFP_USER);
39 	if (!inner_map_meta) {
40 		fdput(f);
41 		return ERR_PTR(-ENOMEM);
42 	}
43 
44 	inner_map_meta->map_type = inner_map->map_type;
45 	inner_map_meta->key_size = inner_map->key_size;
46 	inner_map_meta->value_size = inner_map->value_size;
47 	inner_map_meta->map_flags = inner_map->map_flags;
48 	inner_map_meta->ops = inner_map->ops;
49 	inner_map_meta->max_entries = inner_map->max_entries;
50 
51 	fdput(f);
52 	return inner_map_meta;
53 }
54 
55 void bpf_map_meta_free(struct bpf_map *map_meta)
56 {
57 	kfree(map_meta);
58 }
59 
60 bool bpf_map_meta_equal(const struct bpf_map *meta0,
61 			const struct bpf_map *meta1)
62 {
63 	/* No need to compare ops because it is covered by map_type */
64 	return meta0->map_type == meta1->map_type &&
65 		meta0->key_size == meta1->key_size &&
66 		meta0->value_size == meta1->value_size &&
67 		meta0->map_flags == meta1->map_flags &&
68 		meta0->max_entries == meta1->max_entries;
69 }
70 
71 void *bpf_map_fd_get_ptr(struct bpf_map *map,
72 			 struct file *map_file /* not used */,
73 			 int ufd)
74 {
75 	struct bpf_map *inner_map;
76 	struct fd f;
77 
78 	f = fdget(ufd);
79 	inner_map = __bpf_map_get(f);
80 	if (IS_ERR(inner_map))
81 		return inner_map;
82 
83 	if (bpf_map_meta_equal(map->inner_map_meta, inner_map))
84 		inner_map = bpf_map_inc(inner_map, false);
85 	else
86 		inner_map = ERR_PTR(-EINVAL);
87 
88 	fdput(f);
89 	return inner_map;
90 }
91 
92 void bpf_map_fd_put_ptr(void *ptr)
93 {
94 	/* ptr->ops->map_free() has to go through one
95 	 * rcu grace period by itself.
96 	 */
97 	bpf_map_put(ptr);
98 }
99 
100 u32 bpf_map_fd_sys_lookup_elem(void *ptr)
101 {
102 	return ((struct bpf_map *)ptr)->id;
103 }
104