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