Skip to content

Commit 5e8134f

Browse files
mykyta5Alexei Starovoitov
authored andcommitted
bpf: extract map key pointer calculation
Calculation of the BPF map key, given the pointer to a value is duplicated in a couple of places in helpers already, in the next patch another use case is introduced as well. This patch extracts that functionality into a separate function. Signed-off-by: Mykyta Yatsenko <[email protected]> Acked-by: Kumar Kartikeya Dwivedi <[email protected]> Acked-by: Andrii Nakryiko <[email protected]> Acked-by: Eduard Zingerman <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Alexei Starovoitov <[email protected]>
1 parent 5c8fd7e commit 5e8134f

File tree

1 file changed

+13
-17
lines changed

1 file changed

+13
-17
lines changed

kernel/bpf/helpers.c

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,6 +1082,17 @@ const struct bpf_func_proto bpf_snprintf_proto = {
10821082
.arg5_type = ARG_CONST_SIZE_OR_ZERO,
10831083
};
10841084

1085+
static void *map_key_from_value(struct bpf_map *map, void *value, u32 *arr_idx)
1086+
{
1087+
if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1088+
struct bpf_array *array = container_of(map, struct bpf_array, map);
1089+
1090+
*arr_idx = ((char *)value - array->value) / array->elem_size;
1091+
return arr_idx;
1092+
}
1093+
return (void *)value - round_up(map->key_size, 8);
1094+
}
1095+
10851096
struct bpf_async_cb {
10861097
struct bpf_map *map;
10871098
struct bpf_prog *prog;
@@ -1164,15 +1175,8 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
11641175
* bpf_map_delete_elem() on the same timer.
11651176
*/
11661177
this_cpu_write(hrtimer_running, t);
1167-
if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1168-
struct bpf_array *array = container_of(map, struct bpf_array, map);
11691178

1170-
/* compute the key */
1171-
idx = ((char *)value - array->value) / array->elem_size;
1172-
key = &idx;
1173-
} else { /* hash or lru */
1174-
key = value - round_up(map->key_size, 8);
1175-
}
1179+
key = map_key_from_value(map, value, &idx);
11761180

11771181
callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
11781182
/* The verifier checked that return value is zero. */
@@ -1198,15 +1202,7 @@ static void bpf_wq_work(struct work_struct *work)
11981202
if (!callback_fn)
11991203
return;
12001204

1201-
if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1202-
struct bpf_array *array = container_of(map, struct bpf_array, map);
1203-
1204-
/* compute the key */
1205-
idx = ((char *)value - array->value) / array->elem_size;
1206-
key = &idx;
1207-
} else { /* hash or lru */
1208-
key = value - round_up(map->key_size, 8);
1209-
}
1205+
key = map_key_from_value(map, value, &idx);
12101206

12111207
rcu_read_lock_trace();
12121208
migrate_disable();

0 commit comments

Comments
 (0)