xref: /linux/tools/perf/bench/futex-requeue.c (revision b3570b00dc3062c5a5e8d9602b923618d679636a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2013  Davidlohr Bueso <davidlohr@hp.com>
4  *
5  * futex-requeue: Block a bunch of threads on futex1 and requeue them
6  *                on futex2, N at a time.
7  *
8  * This program is particularly useful to measure the latency of nthread
9  * requeues without waking up any tasks (in the non-pi case) -- thus
10  * mimicking a regular futex_wait.
11  */
12 
13 /* For the CLR_() macros */
14 #include <string.h>
15 #include <pthread.h>
16 
17 #include <signal.h>
18 #include "../util/mutex.h"
19 #include "../util/stat.h"
20 #include <subcmd/parse-options.h>
21 #include <linux/compiler.h>
22 #include <linux/kernel.h>
23 #include <linux/time64.h>
24 #include <errno.h>
25 #include <perf/cpumap.h>
26 #include "bench.h"
27 #include "futex.h"
28 
29 #include <err.h>
30 #include <stdlib.h>
31 #include <sys/time.h>
32 #include <sys/mman.h>
33 
34 static u_int32_t futex1 = 0, futex2 = 0;
35 
36 static pthread_t *worker;
37 static bool done = false;
38 static struct mutex thread_lock;
39 static struct cond thread_parent, thread_worker;
40 static struct stats requeuetime_stats, requeued_stats;
41 static unsigned int threads_starting;
42 static int futex_flag = 0;
43 
44 static struct bench_futex_parameters params = {
45 	.nbuckets = -1,
46 	/*
47 	 * How many tasks to requeue at a time.
48 	 * Default to 1 in order to make the kernel work more.
49 	 */
50 	.nrequeue = 1,
51 };
52 
53 static const struct option options[] = {
54 	OPT_INTEGER( 'b', "buckets", &params.nbuckets, "Specify amount of hash buckets"),
55 	OPT_BOOLEAN( 'I', "immutable", &params.buckets_immutable, "Make the hash buckets immutable"),
56 	OPT_UINTEGER('t', "threads",  &params.nthreads, "Specify amount of threads"),
57 	OPT_UINTEGER('q', "nrequeue", &params.nrequeue, "Specify amount of threads to requeue at once"),
58 	OPT_BOOLEAN( 's', "silent",   &params.silent, "Silent mode: do not display data/details"),
59 	OPT_BOOLEAN( 'S', "shared",   &params.fshared, "Use shared futexes instead of private ones"),
60 	OPT_BOOLEAN( 'm', "mlockall", &params.mlockall, "Lock all current and future memory"),
61 	OPT_BOOLEAN( 'B', "broadcast", &params.broadcast, "Requeue all threads at once"),
62 	OPT_BOOLEAN( 'p', "pi", &params.pi, "Use PI-aware variants of FUTEX_CMP_REQUEUE"),
63 
64 	OPT_END()
65 };
66 
67 static const char * const bench_futex_requeue_usage[] = {
68 	"perf bench futex requeue <options>",
69 	NULL
70 };
71 
72 static void print_summary(void)
73 {
74 	double requeuetime_avg = avg_stats(&requeuetime_stats);
75 	double requeuetime_stddev = stddev_stats(&requeuetime_stats);
76 	unsigned int requeued_avg = avg_stats(&requeued_stats);
77 
78 	printf("Requeued %d of %d threads in %.4f ms (+-%.2f%%)\n",
79 	       requeued_avg,
80 	       params.nthreads,
81 	       requeuetime_avg / USEC_PER_MSEC,
82 	       rel_stddev_stats(requeuetime_stddev, requeuetime_avg));
83 	futex_print_nbuckets(&params);
84 }
85 
86 static void *workerfn(void *arg __maybe_unused)
87 {
88 	int ret;
89 
90 	mutex_lock(&thread_lock);
91 	threads_starting--;
92 	if (!threads_starting)
93 		cond_signal(&thread_parent);
94 	cond_wait(&thread_worker, &thread_lock);
95 	mutex_unlock(&thread_lock);
96 
97 	while (1) {
98 		if (!params.pi) {
99 			ret = futex_wait(&futex1, 0, NULL, futex_flag);
100 			if (!ret)
101 				break;
102 
103 			if (ret && errno != EAGAIN) {
104 				if (!params.silent)
105 					warnx("futex_wait");
106 				break;
107 			}
108 		} else {
109 			ret = futex_wait_requeue_pi(&futex1, 0, &futex2,
110 						    NULL, futex_flag);
111 			if (!ret) {
112 				/* got the lock at futex2 */
113 				futex_unlock_pi(&futex2, futex_flag);
114 				break;
115 			}
116 
117 			if (ret && errno != EAGAIN) {
118 				if (!params.silent)
119 					warnx("futex_wait_requeue_pi");
120 				break;
121 			}
122 		}
123 	}
124 
125 	return NULL;
126 }
127 
128 static void block_threads(pthread_t *w, struct perf_cpu_map *cpu)
129 {
130 	cpu_set_t *cpuset;
131 	unsigned int i;
132 	int nrcpus = cpu__max_cpu().cpu;
133 	size_t size;
134 
135 	threads_starting = params.nthreads;
136 
137 	cpuset = CPU_ALLOC(nrcpus);
138 	BUG_ON(!cpuset);
139 	size = CPU_ALLOC_SIZE(nrcpus);
140 
141 	/* create and block all threads */
142 	for (i = 0; i < params.nthreads; i++) {
143 		pthread_attr_t thread_attr;
144 
145 		pthread_attr_init(&thread_attr);
146 		CPU_ZERO_S(size, cpuset);
147 		CPU_SET_S(perf_cpu_map__cpu(cpu, i % perf_cpu_map__nr(cpu)).cpu, size, cpuset);
148 
149 		if (pthread_attr_setaffinity_np(&thread_attr, size, cpuset)) {
150 			CPU_FREE(cpuset);
151 			err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
152 		}
153 
154 		if (pthread_create(&w[i], &thread_attr, workerfn, NULL)) {
155 			CPU_FREE(cpuset);
156 			err(EXIT_FAILURE, "pthread_create");
157 		}
158 		pthread_attr_destroy(&thread_attr);
159 	}
160 	CPU_FREE(cpuset);
161 }
162 
163 static void toggle_done(int sig __maybe_unused,
164 			siginfo_t *info __maybe_unused,
165 			void *uc __maybe_unused)
166 {
167 	done = true;
168 }
169 
170 int bench_futex_requeue(int argc, const char **argv)
171 {
172 	int ret = 0;
173 	unsigned int i, j;
174 	struct sigaction act;
175 	struct perf_cpu_map *cpu;
176 
177 	argc = parse_options(argc, argv, options, bench_futex_requeue_usage, 0);
178 	if (argc)
179 		goto err;
180 
181 	cpu = perf_cpu_map__new_online_cpus();
182 	if (!cpu)
183 		err(EXIT_FAILURE, "cpu_map__new");
184 
185 	memset(&act, 0, sizeof(act));
186 	sigfillset(&act.sa_mask);
187 	act.sa_sigaction = toggle_done;
188 	sigaction(SIGINT, &act, NULL);
189 
190 	if (params.mlockall) {
191 		if (mlockall(MCL_CURRENT | MCL_FUTURE))
192 			err(EXIT_FAILURE, "mlockall");
193 	}
194 
195 	if (!params.nthreads)
196 		params.nthreads = perf_cpu_map__nr(cpu);
197 
198 	worker = calloc(params.nthreads, sizeof(*worker));
199 	if (!worker)
200 		err(EXIT_FAILURE, "calloc");
201 
202 	if (!params.fshared)
203 		futex_flag = FUTEX_PRIVATE_FLAG;
204 
205 	if (params.nrequeue > params.nthreads)
206 		params.nrequeue = params.nthreads;
207 
208 	if (params.broadcast)
209 		params.nrequeue = params.nthreads;
210 
211 	futex_set_nbuckets_param(&params);
212 
213 	printf("Run summary [PID %d]: Requeuing %d threads (from [%s] %p to %s%p), "
214 	       "%d at a time.\n\n",  getpid(), params.nthreads,
215 	       params.fshared ? "shared":"private", &futex1,
216 	       params.pi ? "PI ": "", &futex2, params.nrequeue);
217 
218 	init_stats(&requeued_stats);
219 	init_stats(&requeuetime_stats);
220 	mutex_init(&thread_lock);
221 	cond_init(&thread_parent);
222 	cond_init(&thread_worker);
223 
224 	for (j = 0; j < bench_repeat && !done; j++) {
225 		unsigned int nrequeued = 0, wakeups = 0;
226 		struct timeval start, end, runtime;
227 
228 		/* create, launch & block all threads */
229 		block_threads(worker, cpu);
230 
231 		/* make sure all threads are already blocked */
232 		mutex_lock(&thread_lock);
233 		while (threads_starting)
234 			cond_wait(&thread_parent, &thread_lock);
235 		cond_broadcast(&thread_worker);
236 		mutex_unlock(&thread_lock);
237 
238 		usleep(100000);
239 
240 		/* Ok, all threads are patiently blocked, start requeueing */
241 		gettimeofday(&start, NULL);
242 		while (nrequeued < params.nthreads) {
243 			int r;
244 
245 			/*
246 			 * For the regular non-pi case, do not wakeup any tasks
247 			 * blocked on futex1, allowing us to really measure
248 			 * futex_wait functionality. For the PI case the first
249 			 * waiter is always awoken.
250 			 */
251 			if (!params.pi) {
252 				r = futex_cmp_requeue(&futex1, 0, &futex2, 0,
253 						      params.nrequeue,
254 						      futex_flag);
255 			} else {
256 				r = futex_cmp_requeue_pi(&futex1, 0, &futex2,
257 							 params.nrequeue,
258 							 futex_flag);
259 				wakeups++; /* assume no error */
260 			}
261 
262 			if (r < 0)
263 				err(EXIT_FAILURE, "couldn't requeue from %p to %p",
264 				    &futex1, &futex2);
265 
266 			nrequeued += r;
267 		}
268 
269 		gettimeofday(&end, NULL);
270 		timersub(&end, &start, &runtime);
271 
272 		update_stats(&requeued_stats, nrequeued);
273 		update_stats(&requeuetime_stats, runtime.tv_usec);
274 
275 		if (!params.silent) {
276 			if (!params.pi)
277 				printf("[Run %d]: Requeued %d of %d threads in "
278 				       "%.4f ms\n", j + 1, nrequeued,
279 				       params.nthreads,
280 				       runtime.tv_usec / (double)USEC_PER_MSEC);
281 			else {
282 				nrequeued -= wakeups;
283 				printf("[Run %d]: Awoke and Requeued (%d+%d) of "
284 				       "%d threads in %.4f ms\n",
285 				       j + 1, wakeups, nrequeued,
286 				       params.nthreads,
287 				       runtime.tv_usec / (double)USEC_PER_MSEC);
288 			}
289 
290 		}
291 
292 		if (!params.pi) {
293 			/* everybody should be blocked on futex2, wake'em up */
294 			nrequeued = futex_wake(&futex2, nrequeued, futex_flag);
295 			if (params.nthreads != nrequeued)
296 				warnx("couldn't wakeup all tasks (%d/%d)",
297 				      nrequeued, params.nthreads);
298 		}
299 
300 		for (i = 0; i < params.nthreads; i++) {
301 			ret = pthread_join(worker[i], NULL);
302 			if (ret)
303 				err(EXIT_FAILURE, "pthread_join");
304 		}
305 	}
306 
307 	/* cleanup & report results */
308 	cond_destroy(&thread_parent);
309 	cond_destroy(&thread_worker);
310 	mutex_destroy(&thread_lock);
311 
312 	print_summary();
313 
314 	free(worker);
315 	perf_cpu_map__put(cpu);
316 	return ret;
317 err:
318 	usage_with_options(bench_futex_requeue_usage, options);
319 	exit(EXIT_FAILURE);
320 }
321