1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2013  Davidlohr Bueso <davidlohr@hp.com>
4  *
5  * futex-wake: Block a bunch of threads on a futex and wake'em up, N at a time.
6  *
7  * This program is particularly useful to measure the latency of nthread wakeups
8  * in non-error situations:  all waiters are queued and all wake calls wakeup
9  * one or more tasks, and thus the waitqueue is never empty.
10  */
11 
12 /* For the CLR_() macros */
13 #include <string.h>
14 #include <pthread.h>
15 
16 #include <signal.h>
17 #include "../util/mutex.h"
18 #include "../util/stat.h"
19 #include <subcmd/parse-options.h>
20 #include <linux/compiler.h>
21 #include <linux/kernel.h>
22 #include <linux/time64.h>
23 #include <errno.h>
24 #include <perf/cpumap.h>
25 #include "bench.h"
26 #include "futex.h"
27 
28 #include <err.h>
29 #include <stdlib.h>
30 #include <sys/time.h>
31 #include <sys/mman.h>
32 
33 /* all threads will block on the same futex */
34 static u_int32_t futex1 = 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 waketime_stats, wakeup_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 wakeups to do at a time.
48 	 * Default to 1 in order to make the kernel work more.
49 	 */
50 	.nwakes  = 1,
51 };
52 
53 static const struct option options[] = {
54 	OPT_INTEGER( 'b', "buckets", &params.nbuckets, "Specify amount of hash buckets"),
55 	OPT_UINTEGER('t', "threads", &params.nthreads, "Specify amount of threads"),
56 	OPT_UINTEGER('w', "nwakes",  &params.nwakes, "Specify amount of threads to wake at once"),
57 	OPT_BOOLEAN( 's', "silent",  &params.silent, "Silent mode: do not display data/details"),
58 	OPT_BOOLEAN( 'S', "shared",  &params.fshared, "Use shared futexes instead of private ones"),
59 	OPT_BOOLEAN( 'm', "mlockall", &params.mlockall, "Lock all current and future memory"),
60 
61 	OPT_END()
62 };
63 
64 static const char * const bench_futex_wake_usage[] = {
65 	"perf bench futex wake <options>",
66 	NULL
67 };
68 
workerfn(void * arg __maybe_unused)69 static void *workerfn(void *arg __maybe_unused)
70 {
71 	mutex_lock(&thread_lock);
72 	threads_starting--;
73 	if (!threads_starting)
74 		cond_signal(&thread_parent);
75 	cond_wait(&thread_worker, &thread_lock);
76 	mutex_unlock(&thread_lock);
77 
78 	while (1) {
79 		if (futex_wait(&futex1, 0, NULL, futex_flag) != EINTR)
80 			break;
81 	}
82 
83 	pthread_exit(NULL);
84 	return NULL;
85 }
86 
print_summary(void)87 static void print_summary(void)
88 {
89 	double waketime_avg = avg_stats(&waketime_stats);
90 	double waketime_stddev = stddev_stats(&waketime_stats);
91 	unsigned int wakeup_avg = avg_stats(&wakeup_stats);
92 
93 	printf("Wokeup %d of %d threads in %.4f ms (+-%.2f%%)\n",
94 	       wakeup_avg,
95 	       params.nthreads,
96 	       waketime_avg / USEC_PER_MSEC,
97 	       rel_stddev_stats(waketime_stddev, waketime_avg));
98 	futex_print_nbuckets(&params);
99 }
100 
block_threads(pthread_t * w,struct perf_cpu_map * cpu)101 static void block_threads(pthread_t *w, struct perf_cpu_map *cpu)
102 {
103 	cpu_set_t *cpuset;
104 	unsigned int i;
105 	size_t size;
106 	int nrcpus = cpu__max_cpu().cpu;
107 	threads_starting = params.nthreads;
108 
109 	cpuset = CPU_ALLOC(nrcpus);
110 	BUG_ON(!cpuset);
111 	size = CPU_ALLOC_SIZE(nrcpus);
112 
113 	/* create and block all threads */
114 	for (i = 0; i < params.nthreads; i++) {
115 		pthread_attr_t thread_attr;
116 
117 		pthread_attr_init(&thread_attr);
118 		CPU_ZERO_S(size, cpuset);
119 		CPU_SET_S(perf_cpu_map__cpu(cpu, i % perf_cpu_map__nr(cpu)).cpu, size, cpuset);
120 
121 		if (pthread_attr_setaffinity_np(&thread_attr, size, cpuset)) {
122 			CPU_FREE(cpuset);
123 			err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
124 		}
125 
126 		if (pthread_create(&w[i], &thread_attr, workerfn, NULL)) {
127 			CPU_FREE(cpuset);
128 			err(EXIT_FAILURE, "pthread_create");
129 		}
130 		pthread_attr_destroy(&thread_attr);
131 	}
132 	CPU_FREE(cpuset);
133 }
134 
toggle_done(int sig __maybe_unused,siginfo_t * info __maybe_unused,void * uc __maybe_unused)135 static void toggle_done(int sig __maybe_unused,
136 			siginfo_t *info __maybe_unused,
137 			void *uc __maybe_unused)
138 {
139 	done = true;
140 }
141 
bench_futex_wake(int argc,const char ** argv)142 int bench_futex_wake(int argc, const char **argv)
143 {
144 	int ret = 0;
145 	unsigned int i, j;
146 	struct sigaction act;
147 	struct perf_cpu_map *cpu;
148 
149 	argc = parse_options(argc, argv, options, bench_futex_wake_usage, 0);
150 	if (argc) {
151 		usage_with_options(bench_futex_wake_usage, options);
152 		exit(EXIT_FAILURE);
153 	}
154 
155 	cpu = perf_cpu_map__new_online_cpus();
156 	if (!cpu)
157 		err(EXIT_FAILURE, "calloc");
158 
159 	memset(&act, 0, sizeof(act));
160 	sigfillset(&act.sa_mask);
161 	act.sa_sigaction = toggle_done;
162 	sigaction(SIGINT, &act, NULL);
163 
164 	if (params.mlockall) {
165 		if (mlockall(MCL_CURRENT | MCL_FUTURE))
166 			err(EXIT_FAILURE, "mlockall");
167 	}
168 
169 	if (!params.nthreads)
170 		params.nthreads = perf_cpu_map__nr(cpu);
171 
172 	worker = calloc(params.nthreads, sizeof(*worker));
173 	if (!worker)
174 		err(EXIT_FAILURE, "calloc");
175 
176 	if (!params.fshared)
177 		futex_flag = FUTEX_PRIVATE_FLAG;
178 
179 	printf("Run summary [PID %d]: blocking on %d threads (at [%s] futex %p), "
180 	       "waking up %d at a time.\n\n",
181 	       getpid(), params.nthreads, params.fshared ? "shared":"private",
182 	       &futex1, params.nwakes);
183 
184 	init_stats(&wakeup_stats);
185 	init_stats(&waketime_stats);
186 	mutex_init(&thread_lock);
187 	cond_init(&thread_parent);
188 	cond_init(&thread_worker);
189 
190 	for (j = 0; j < bench_repeat && !done; j++) {
191 		unsigned int nwoken = 0;
192 		struct timeval start, end, runtime;
193 
194 		/* create, launch & block all threads */
195 		block_threads(worker, cpu);
196 
197 		/* make sure all threads are already blocked */
198 		mutex_lock(&thread_lock);
199 		while (threads_starting)
200 			cond_wait(&thread_parent, &thread_lock);
201 		cond_broadcast(&thread_worker);
202 		mutex_unlock(&thread_lock);
203 
204 		usleep(100000);
205 
206 		/* Ok, all threads are patiently blocked, start waking folks up */
207 		gettimeofday(&start, NULL);
208 		while (nwoken != params.nthreads)
209 			nwoken += futex_wake(&futex1,
210 					     params.nwakes, futex_flag);
211 		gettimeofday(&end, NULL);
212 		timersub(&end, &start, &runtime);
213 
214 		update_stats(&wakeup_stats, nwoken);
215 		update_stats(&waketime_stats, runtime.tv_usec);
216 
217 		if (!params.silent) {
218 			printf("[Run %d]: Wokeup %d of %d threads in %.4f ms\n",
219 			       j + 1, nwoken, params.nthreads,
220 			       runtime.tv_usec / (double)USEC_PER_MSEC);
221 		}
222 
223 		for (i = 0; i < params.nthreads; i++) {
224 			ret = pthread_join(worker[i], NULL);
225 			if (ret)
226 				err(EXIT_FAILURE, "pthread_join");
227 		}
228 
229 	}
230 
231 	/* cleanup & report results */
232 	cond_destroy(&thread_parent);
233 	cond_destroy(&thread_worker);
234 	mutex_destroy(&thread_lock);
235 
236 	print_summary();
237 
238 	free(worker);
239 	perf_cpu_map__put(cpu);
240 	return ret;
241 }
242