1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2015 Davidlohr Bueso.
4  *
5  * Block a bunch of threads and let parallel waker threads wakeup an
6  * equal amount of them. The program output reflects the avg latency
7  * for each individual thread to service its share of work. Ultimately
8  * it can be used to measure futex_wake() changes.
9  */
10 #include "bench.h"
11 #include <linux/compiler.h>
12 #include "../util/debug.h"
13 
14 #ifndef HAVE_PTHREAD_BARRIER
15 int bench_futex_wake_parallel(int argc __maybe_unused, const char **argv __maybe_unused)
16 {
17 	pr_err("%s: pthread_barrier_t unavailable, disabling this test...\n", __func__);
18 	return 0;
19 }
20 #else /* HAVE_PTHREAD_BARRIER */
21 /* For the CLR_() macros */
22 #include <string.h>
23 #include <pthread.h>
24 
25 #include <signal.h>
26 #include "../util/stat.h"
27 #include <subcmd/parse-options.h>
28 #include <linux/kernel.h>
29 #include <linux/time64.h>
30 #include <errno.h>
31 #include "futex.h"
32 #include <perf/cpumap.h>
33 
34 #include <err.h>
35 #include <stdlib.h>
36 #include <sys/time.h>
37 #include <sys/mman.h>
38 
39 struct thread_data {
40 	pthread_t worker;
41 	unsigned int nwoken;
42 	struct timeval runtime;
43 };
44 
45 static unsigned int nwakes = 1;
46 
47 /* all threads will block on the same futex -- hash bucket chaos ;) */
48 static u_int32_t futex = 0;
49 
50 static pthread_t *blocked_worker;
51 static bool done = false;
52 static pthread_mutex_t thread_lock;
53 static pthread_cond_t thread_parent, thread_worker;
54 static pthread_barrier_t barrier;
55 static struct stats waketime_stats, wakeup_stats;
56 static unsigned int threads_starting;
57 static int futex_flag = 0;
58 
59 static struct bench_futex_parameters params;
60 
61 static const struct option options[] = {
62 	OPT_UINTEGER('t', "threads", &params.nthreads, "Specify amount of threads"),
63 	OPT_UINTEGER('w', "nwakers", &params.nwakes, "Specify amount of waking threads"),
64 	OPT_BOOLEAN( 's', "silent",  &params.silent, "Silent mode: do not display data/details"),
65 	OPT_BOOLEAN( 'S', "shared",  &params.fshared, "Use shared futexes instead of private ones"),
66 	OPT_BOOLEAN( 'm', "mlockall", &params.mlockall, "Lock all current and future memory"),
67 
68 	OPT_END()
69 };
70 
71 static const char * const bench_futex_wake_parallel_usage[] = {
72 	"perf bench futex wake-parallel <options>",
73 	NULL
74 };
75 
76 static void *waking_workerfn(void *arg)
77 {
78 	struct thread_data *waker = (struct thread_data *) arg;
79 	struct timeval start, end;
80 
81 	pthread_barrier_wait(&barrier);
82 
83 	gettimeofday(&start, NULL);
84 
85 	waker->nwoken = futex_wake(&futex, nwakes, futex_flag);
86 	if (waker->nwoken != nwakes)
87 		warnx("couldn't wakeup all tasks (%d/%d)",
88 		      waker->nwoken, nwakes);
89 
90 	gettimeofday(&end, NULL);
91 	timersub(&end, &start, &waker->runtime);
92 
93 	pthread_exit(NULL);
94 	return NULL;
95 }
96 
97 static void wakeup_threads(struct thread_data *td, pthread_attr_t thread_attr)
98 {
99 	unsigned int i;
100 
101 	pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
102 
103 	pthread_barrier_init(&barrier, NULL, params.nwakes + 1);
104 
105 	/* create and block all threads */
106 	for (i = 0; i < params.nwakes; i++) {
107 		/*
108 		 * Thread creation order will impact per-thread latency
109 		 * as it will affect the order to acquire the hb spinlock.
110 		 * For now let the scheduler decide.
111 		 */
112 		if (pthread_create(&td[i].worker, &thread_attr,
113 				   waking_workerfn, (void *)&td[i]))
114 			err(EXIT_FAILURE, "pthread_create");
115 	}
116 
117 	pthread_barrier_wait(&barrier);
118 
119 	for (i = 0; i < params.nwakes; i++)
120 		if (pthread_join(td[i].worker, NULL))
121 			err(EXIT_FAILURE, "pthread_join");
122 
123 	pthread_barrier_destroy(&barrier);
124 }
125 
126 static void *blocked_workerfn(void *arg __maybe_unused)
127 {
128 	pthread_mutex_lock(&thread_lock);
129 	threads_starting--;
130 	if (!threads_starting)
131 		pthread_cond_signal(&thread_parent);
132 	pthread_cond_wait(&thread_worker, &thread_lock);
133 	pthread_mutex_unlock(&thread_lock);
134 
135 	while (1) { /* handle spurious wakeups */
136 		if (futex_wait(&futex, 0, NULL, futex_flag) != EINTR)
137 			break;
138 	}
139 
140 	pthread_exit(NULL);
141 	return NULL;
142 }
143 
144 static void block_threads(pthread_t *w, pthread_attr_t thread_attr,
145 			  struct perf_cpu_map *cpu)
146 {
147 	cpu_set_t *cpuset;
148 	unsigned int i;
149 	int nrcpus = perf_cpu_map__nr(cpu);
150 	size_t size;
151 
152 	threads_starting = params.nthreads;
153 
154 	cpuset = CPU_ALLOC(nrcpus);
155 	BUG_ON(!cpuset);
156 	size = CPU_ALLOC_SIZE(nrcpus);
157 
158 	/* create and block all threads */
159 	for (i = 0; i < params.nthreads; i++) {
160 		CPU_ZERO_S(size, cpuset);
161 		CPU_SET_S(perf_cpu_map__cpu(cpu, i % perf_cpu_map__nr(cpu)).cpu, size, cpuset);
162 
163 		if (pthread_attr_setaffinity_np(&thread_attr, size, cpuset)) {
164 			CPU_FREE(cpuset);
165 			err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
166 		}
167 
168 		if (pthread_create(&w[i], &thread_attr, blocked_workerfn, NULL)) {
169 			CPU_FREE(cpuset);
170 			err(EXIT_FAILURE, "pthread_create");
171 		}
172 	}
173 	CPU_FREE(cpuset);
174 }
175 
176 static void print_run(struct thread_data *waking_worker, unsigned int run_num)
177 {
178 	unsigned int i, wakeup_avg;
179 	double waketime_avg, waketime_stddev;
180 	struct stats __waketime_stats, __wakeup_stats;
181 
182 	init_stats(&__wakeup_stats);
183 	init_stats(&__waketime_stats);
184 
185 	for (i = 0; i < params.nwakes; i++) {
186 		update_stats(&__waketime_stats, waking_worker[i].runtime.tv_usec);
187 		update_stats(&__wakeup_stats, waking_worker[i].nwoken);
188 	}
189 
190 	waketime_avg = avg_stats(&__waketime_stats);
191 	waketime_stddev = stddev_stats(&__waketime_stats);
192 	wakeup_avg = avg_stats(&__wakeup_stats);
193 
194 	printf("[Run %d]: Avg per-thread latency (waking %d/%d threads) "
195 	       "in %.4f ms (+-%.2f%%)\n", run_num + 1, wakeup_avg,
196 	       params.nthreads, waketime_avg / USEC_PER_MSEC,
197 	       rel_stddev_stats(waketime_stddev, waketime_avg));
198 }
199 
200 static void print_summary(void)
201 {
202 	unsigned int wakeup_avg;
203 	double waketime_avg, waketime_stddev;
204 
205 	waketime_avg = avg_stats(&waketime_stats);
206 	waketime_stddev = stddev_stats(&waketime_stats);
207 	wakeup_avg = avg_stats(&wakeup_stats);
208 
209 	printf("Avg per-thread latency (waking %d/%d threads) in %.4f ms (+-%.2f%%)\n",
210 	       wakeup_avg,
211 	       params.nthreads,
212 	       waketime_avg / USEC_PER_MSEC,
213 	       rel_stddev_stats(waketime_stddev, waketime_avg));
214 }
215 
216 
217 static void do_run_stats(struct thread_data *waking_worker)
218 {
219 	unsigned int i;
220 
221 	for (i = 0; i < params.nwakes; i++) {
222 		update_stats(&waketime_stats, waking_worker[i].runtime.tv_usec);
223 		update_stats(&wakeup_stats, waking_worker[i].nwoken);
224 	}
225 
226 }
227 
228 static void toggle_done(int sig __maybe_unused,
229 			siginfo_t *info __maybe_unused,
230 			void *uc __maybe_unused)
231 {
232 	done = true;
233 }
234 
235 int bench_futex_wake_parallel(int argc, const char **argv)
236 {
237 	int ret = 0;
238 	unsigned int i, j;
239 	struct sigaction act;
240 	pthread_attr_t thread_attr;
241 	struct thread_data *waking_worker;
242 	struct perf_cpu_map *cpu;
243 
244 	argc = parse_options(argc, argv, options,
245 			     bench_futex_wake_parallel_usage, 0);
246 	if (argc) {
247 		usage_with_options(bench_futex_wake_parallel_usage, options);
248 		exit(EXIT_FAILURE);
249 	}
250 
251 	memset(&act, 0, sizeof(act));
252 	sigfillset(&act.sa_mask);
253 	act.sa_sigaction = toggle_done;
254 	sigaction(SIGINT, &act, NULL);
255 
256 	if (params.mlockall) {
257 		if (mlockall(MCL_CURRENT | MCL_FUTURE))
258 			err(EXIT_FAILURE, "mlockall");
259 	}
260 
261 	cpu = perf_cpu_map__new(NULL);
262 	if (!cpu)
263 		err(EXIT_FAILURE, "calloc");
264 
265 	if (!params.nthreads)
266 		params.nthreads = perf_cpu_map__nr(cpu);
267 
268 	/* some sanity checks */
269 	if (params.nwakes > params.nthreads ||
270 	    !params.nwakes)
271 		params.nwakes = params.nthreads;
272 
273 	if (params.nthreads % params.nwakes)
274 		errx(EXIT_FAILURE, "Must be perfectly divisible");
275 	/*
276 	 * Each thread will wakeup nwakes tasks in
277 	 * a single futex_wait call.
278 	 */
279 	nwakes = params.nthreads/params.nwakes;
280 
281 	blocked_worker = calloc(params.nthreads, sizeof(*blocked_worker));
282 	if (!blocked_worker)
283 		err(EXIT_FAILURE, "calloc");
284 
285 	if (!params.fshared)
286 		futex_flag = FUTEX_PRIVATE_FLAG;
287 
288 	printf("Run summary [PID %d]: blocking on %d threads (at [%s] "
289 	       "futex %p), %d threads waking up %d at a time.\n\n",
290 	       getpid(), params.nthreads, params.fshared ? "shared":"private",
291 	       &futex, params.nwakes, nwakes);
292 
293 	init_stats(&wakeup_stats);
294 	init_stats(&waketime_stats);
295 
296 	pthread_attr_init(&thread_attr);
297 	pthread_mutex_init(&thread_lock, NULL);
298 	pthread_cond_init(&thread_parent, NULL);
299 	pthread_cond_init(&thread_worker, NULL);
300 
301 	for (j = 0; j < bench_repeat && !done; j++) {
302 		waking_worker = calloc(params.nwakes, sizeof(*waking_worker));
303 		if (!waking_worker)
304 			err(EXIT_FAILURE, "calloc");
305 
306 		/* create, launch & block all threads */
307 		block_threads(blocked_worker, thread_attr, cpu);
308 
309 		/* make sure all threads are already blocked */
310 		pthread_mutex_lock(&thread_lock);
311 		while (threads_starting)
312 			pthread_cond_wait(&thread_parent, &thread_lock);
313 		pthread_cond_broadcast(&thread_worker);
314 		pthread_mutex_unlock(&thread_lock);
315 
316 		usleep(100000);
317 
318 		/* Ok, all threads are patiently blocked, start waking folks up */
319 		wakeup_threads(waking_worker, thread_attr);
320 
321 		for (i = 0; i < params.nthreads; i++) {
322 			ret = pthread_join(blocked_worker[i], NULL);
323 			if (ret)
324 				err(EXIT_FAILURE, "pthread_join");
325 		}
326 
327 		do_run_stats(waking_worker);
328 		if (!params.silent)
329 			print_run(waking_worker, j);
330 
331 		free(waking_worker);
332 	}
333 
334 	/* cleanup & report results */
335 	pthread_cond_destroy(&thread_parent);
336 	pthread_cond_destroy(&thread_worker);
337 	pthread_mutex_destroy(&thread_lock);
338 	pthread_attr_destroy(&thread_attr);
339 
340 	print_summary();
341 
342 	free(blocked_worker);
343 	perf_cpu_map__put(cpu);
344 	return ret;
345 }
346 #endif /* HAVE_PTHREAD_BARRIER */
347