Skip to content

Commit adf525d

Browse files
mykyta5Kernel Patches Daemon
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]>
1 parent f1eb8a5 commit adf525d

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

kernel/bpf/helpers.c

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

1084+
static void *map_key_from_value(struct bpf_map *map, void *value, u32 *arr_idx)
1085+
{
1086+
if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1087+
struct bpf_array *array = container_of(map, struct bpf_array, map);
1088+
1089+
*arr_idx = ((char *)value - array->value) / array->elem_size;
1090+
return arr_idx;
1091+
}
1092+
BUG_ON(map->map_type != BPF_MAP_TYPE_HASH && map->map_type != BPF_MAP_TYPE_LRU_HASH);
1093+
return (void *)value - round_up(map->key_size, 8);
1094+
}
1095+
10841096
struct bpf_async_cb {
10851097
struct bpf_map *map;
10861098
struct bpf_prog *prog;
@@ -1163,15 +1175,8 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
11631175
* bpf_map_delete_elem() on the same timer.
11641176
*/
11651177
this_cpu_write(hrtimer_running, t);
1166-
if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1167-
struct bpf_array *array = container_of(map, struct bpf_array, map);
11681178

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

11761181
callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
11771182
/* The verifier checked that return value is zero. */
@@ -1197,15 +1202,7 @@ static void bpf_wq_work(struct work_struct *work)
11971202
if (!callback_fn)
11981203
return;
11991204

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

12101207
rcu_read_lock_trace();
12111208
migrate_disable();

0 commit comments

Comments
 (0)