summaryrefslogtreecommitdiff
path: root/tools/testing/selftests/bpf/prog_tests/htab_reuse.c
blob: a742dd994d6001de339ff6e8b9aacdd672008578 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// SPDX-License-Identifier: GPL-2.0
/* Copyright (C) 2023. Huawei Technologies Co., Ltd */
#define _GNU_SOURCE
#include <sched.h>
#include <stdbool.h>
#include <test_progs.h>
#include "htab_reuse.skel.h"

struct htab_op_ctx {
	int fd;
	int loop;
	bool stop;
};

struct htab_val {
	unsigned int lock;
	unsigned int data;
};

static void *htab_lookup_fn(void *arg)
{
	struct htab_op_ctx *ctx = arg;
	int i = 0;

	while (i++ < ctx->loop && !ctx->stop) {
		struct htab_val value;
		unsigned int key;

		/* Use BPF_F_LOCK to use spin-lock in map value. */
		key = 7;
		bpf_map_lookup_elem_flags(ctx->fd, &key, &value, BPF_F_LOCK);
	}

	return NULL;
}

static void *htab_update_fn(void *arg)
{
	struct htab_op_ctx *ctx = arg;
	int i = 0;

	while (i++ < ctx->loop && !ctx->stop) {
		struct htab_val value;
		unsigned int key;

		key = 7;
		value.lock = 0;
		value.data = key;
		bpf_map_update_elem(ctx->fd, &key, &value, BPF_F_LOCK);
		bpf_map_delete_elem(ctx->fd, &key);

		key = 24;
		value.lock = 0;
		value.data = key;
		bpf_map_update_elem(ctx->fd, &key, &value, BPF_F_LOCK);
		bpf_map_delete_elem(ctx->fd, &key);
	}

	return NULL;
}

void test_htab_reuse(void)
{
	unsigned int i, wr_nr = 1, rd_nr = 4;
	pthread_t tids[wr_nr + rd_nr];
	struct htab_reuse *skel;
	struct htab_op_ctx ctx;
	int err;

	skel = htab_reuse__open_and_load();
	if (!ASSERT_OK_PTR(skel, "htab_reuse__open_and_load"))
		return;

	ctx.fd = bpf_map__fd(skel->maps.htab);
	ctx.loop = 500;
	ctx.stop = false;

	memset(tids, 0, sizeof(tids));
	for (i = 0; i < wr_nr; i++) {
		err = pthread_create(&tids[i], NULL, htab_update_fn, &ctx);
		if (!ASSERT_OK(err, "pthread_create")) {
			ctx.stop = true;
			goto reap;
		}
	}
	for (i = 0; i < rd_nr; i++) {
		err = pthread_create(&tids[i + wr_nr], NULL, htab_lookup_fn, &ctx);
		if (!ASSERT_OK(err, "pthread_create")) {
			ctx.stop = true;
			goto reap;
		}
	}

reap:
	for (i = 0; i < wr_nr + rd_nr; i++) {
		if (!tids[i])
			continue;
		pthread_join(tids[i], NULL);
	}
	htab_reuse__destroy(skel);
}