Skip to content

Commit ac42b7a

Browse files
committed
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]>
1 parent 42faedf commit ac42b7a

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
@@ -1084,6 +1084,18 @@ const struct bpf_func_proto bpf_snprintf_proto = {
10841084
.arg5_type = ARG_CONST_SIZE_OR_ZERO,
10851085
};
10861086

1087+
static void *map_key_from_value(struct bpf_map *map, void *value, u32 *arr_idx)
1088+
{
1089+
if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1090+
struct bpf_array *array =
1091+
container_of(map, struct bpf_array, map);
1092+
1093+
*arr_idx = ((char *)value - array->value) / array->elem_size;
1094+
return arr_idx;
1095+
}
1096+
return (void *)value - round_up(map->key_size, 8);
1097+
}
1098+
10871099
struct bpf_async_cb {
10881100
struct bpf_map *map;
10891101
struct bpf_prog *prog;
@@ -1166,15 +1178,8 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer)
11661178
* bpf_map_delete_elem() on the same timer.
11671179
*/
11681180
this_cpu_write(hrtimer_running, t);
1169-
if (map->map_type == BPF_MAP_TYPE_ARRAY) {
1170-
struct bpf_array *array = container_of(map, struct bpf_array, map);
11711181

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

11791184
callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
11801185
/* The verifier checked that return value is zero. */
@@ -1200,15 +1205,7 @@ static void bpf_wq_work(struct work_struct *work)
12001205
if (!callback_fn)
12011206
return;
12021207

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

12131210
rcu_read_lock_trace();
12141211
migrate_disable();

0 commit comments

Comments
 (0)