xref: /openbmc/linux/tools/perf/bench/numa.c (revision 3d3337de)
1 /*
2  * numa.c
3  *
4  * numa: Simulate NUMA-sensitive workload and measure their NUMA performance
5  */
6 
7 #include "../perf.h"
8 #include "../builtin.h"
9 #include "../util/util.h"
10 #include "../util/parse-options.h"
11 
12 #include "bench.h"
13 
14 #include <errno.h>
15 #include <sched.h>
16 #include <stdio.h>
17 #include <assert.h>
18 #include <malloc.h>
19 #include <signal.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <pthread.h>
24 #include <sys/mman.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 #include <sys/wait.h>
28 #include <sys/prctl.h>
29 #include <sys/types.h>
30 
31 #include <numa.h>
32 #include <numaif.h>
33 
34 /*
35  * Regular printout to the terminal, supressed if -q is specified:
36  */
37 #define tprintf(x...) do { if (g && g->p.show_details >= 0) printf(x); } while (0)
38 
39 /*
40  * Debug printf:
41  */
42 #define dprintf(x...) do { if (g && g->p.show_details >= 1) printf(x); } while (0)
43 
44 struct thread_data {
45 	int			curr_cpu;
46 	cpu_set_t		bind_cpumask;
47 	int			bind_node;
48 	u8			*process_data;
49 	int			process_nr;
50 	int			thread_nr;
51 	int			task_nr;
52 	unsigned int		loops_done;
53 	u64			val;
54 	u64			runtime_ns;
55 	u64			system_time_ns;
56 	u64			user_time_ns;
57 	double			speed_gbs;
58 	pthread_mutex_t		*process_lock;
59 };
60 
61 /* Parameters set by options: */
62 
63 struct params {
64 	/* Startup synchronization: */
65 	bool			serialize_startup;
66 
67 	/* Task hierarchy: */
68 	int			nr_proc;
69 	int			nr_threads;
70 
71 	/* Working set sizes: */
72 	const char		*mb_global_str;
73 	const char		*mb_proc_str;
74 	const char		*mb_proc_locked_str;
75 	const char		*mb_thread_str;
76 
77 	double			mb_global;
78 	double			mb_proc;
79 	double			mb_proc_locked;
80 	double			mb_thread;
81 
82 	/* Access patterns to the working set: */
83 	bool			data_reads;
84 	bool			data_writes;
85 	bool			data_backwards;
86 	bool			data_zero_memset;
87 	bool			data_rand_walk;
88 	u32			nr_loops;
89 	u32			nr_secs;
90 	u32			sleep_usecs;
91 
92 	/* Working set initialization: */
93 	bool			init_zero;
94 	bool			init_random;
95 	bool			init_cpu0;
96 
97 	/* Misc options: */
98 	int			show_details;
99 	int			run_all;
100 	int			thp;
101 
102 	long			bytes_global;
103 	long			bytes_process;
104 	long			bytes_process_locked;
105 	long			bytes_thread;
106 
107 	int			nr_tasks;
108 	bool			show_quiet;
109 
110 	bool			show_convergence;
111 	bool			measure_convergence;
112 
113 	int			perturb_secs;
114 	int			nr_cpus;
115 	int			nr_nodes;
116 
117 	/* Affinity options -C and -N: */
118 	char			*cpu_list_str;
119 	char			*node_list_str;
120 };
121 
122 
123 /* Global, read-writable area, accessible to all processes and threads: */
124 
125 struct global_info {
126 	u8			*data;
127 
128 	pthread_mutex_t		startup_mutex;
129 	int			nr_tasks_started;
130 
131 	pthread_mutex_t		startup_done_mutex;
132 
133 	pthread_mutex_t		start_work_mutex;
134 	int			nr_tasks_working;
135 
136 	pthread_mutex_t		stop_work_mutex;
137 	u64			bytes_done;
138 
139 	struct thread_data	*threads;
140 
141 	/* Convergence latency measurement: */
142 	bool			all_converged;
143 	bool			stop_work;
144 
145 	int			print_once;
146 
147 	struct params		p;
148 };
149 
150 static struct global_info	*g = NULL;
151 
152 static int parse_cpus_opt(const struct option *opt, const char *arg, int unset);
153 static int parse_nodes_opt(const struct option *opt, const char *arg, int unset);
154 
155 struct params p0;
156 
157 static const struct option options[] = {
158 	OPT_INTEGER('p', "nr_proc"	, &p0.nr_proc,		"number of processes"),
159 	OPT_INTEGER('t', "nr_threads"	, &p0.nr_threads,	"number of threads per process"),
160 
161 	OPT_STRING('G', "mb_global"	, &p0.mb_global_str,	"MB", "global  memory (MBs)"),
162 	OPT_STRING('P', "mb_proc"	, &p0.mb_proc_str,	"MB", "process memory (MBs)"),
163 	OPT_STRING('L', "mb_proc_locked", &p0.mb_proc_locked_str,"MB", "process serialized/locked memory access (MBs), <= process_memory"),
164 	OPT_STRING('T', "mb_thread"	, &p0.mb_thread_str,	"MB", "thread  memory (MBs)"),
165 
166 	OPT_UINTEGER('l', "nr_loops"	, &p0.nr_loops,		"max number of loops to run"),
167 	OPT_UINTEGER('s', "nr_secs"	, &p0.nr_secs,		"max number of seconds to run"),
168 	OPT_UINTEGER('u', "usleep"	, &p0.sleep_usecs,	"usecs to sleep per loop iteration"),
169 
170 	OPT_BOOLEAN('R', "data_reads"	, &p0.data_reads,	"access the data via writes (can be mixed with -W)"),
171 	OPT_BOOLEAN('W', "data_writes"	, &p0.data_writes,	"access the data via writes (can be mixed with -R)"),
172 	OPT_BOOLEAN('B', "data_backwards", &p0.data_backwards,	"access the data backwards as well"),
173 	OPT_BOOLEAN('Z', "data_zero_memset", &p0.data_zero_memset,"access the data via glibc bzero only"),
174 	OPT_BOOLEAN('r', "data_rand_walk", &p0.data_rand_walk,	"access the data with random (32bit LFSR) walk"),
175 
176 
177 	OPT_BOOLEAN('z', "init_zero"	, &p0.init_zero,	"bzero the initial allocations"),
178 	OPT_BOOLEAN('I', "init_random"	, &p0.init_random,	"randomize the contents of the initial allocations"),
179 	OPT_BOOLEAN('0', "init_cpu0"	, &p0.init_cpu0,	"do the initial allocations on CPU#0"),
180 	OPT_INTEGER('x', "perturb_secs", &p0.perturb_secs,	"perturb thread 0/0 every X secs, to test convergence stability"),
181 
182 	OPT_INCR   ('d', "show_details"	, &p0.show_details,	"Show details"),
183 	OPT_INCR   ('a', "all"		, &p0.run_all,		"Run all tests in the suite"),
184 	OPT_INTEGER('H', "thp"		, &p0.thp,		"MADV_NOHUGEPAGE < 0 < MADV_HUGEPAGE"),
185 	OPT_BOOLEAN('c', "show_convergence", &p0.show_convergence, "show convergence details"),
186 	OPT_BOOLEAN('m', "measure_convergence",	&p0.measure_convergence, "measure convergence latency"),
187 	OPT_BOOLEAN('q', "quiet"	, &p0.show_quiet,	"bzero the initial allocations"),
188 	OPT_BOOLEAN('S', "serialize-startup", &p0.serialize_startup,"serialize thread startup"),
189 
190 	/* Special option string parsing callbacks: */
191         OPT_CALLBACK('C', "cpus", NULL, "cpu[,cpu2,...cpuN]",
192 			"bind the first N tasks to these specific cpus (the rest is unbound)",
193 			parse_cpus_opt),
194         OPT_CALLBACK('M', "memnodes", NULL, "node[,node2,...nodeN]",
195 			"bind the first N tasks to these specific memory nodes (the rest is unbound)",
196 			parse_nodes_opt),
197 	OPT_END()
198 };
199 
200 static const char * const bench_numa_usage[] = {
201 	"perf bench numa <options>",
202 	NULL
203 };
204 
205 static const char * const numa_usage[] = {
206 	"perf bench numa mem [<options>]",
207 	NULL
208 };
209 
210 static cpu_set_t bind_to_cpu(int target_cpu)
211 {
212 	cpu_set_t orig_mask, mask;
213 	int ret;
214 
215 	ret = sched_getaffinity(0, sizeof(orig_mask), &orig_mask);
216 	BUG_ON(ret);
217 
218 	CPU_ZERO(&mask);
219 
220 	if (target_cpu == -1) {
221 		int cpu;
222 
223 		for (cpu = 0; cpu < g->p.nr_cpus; cpu++)
224 			CPU_SET(cpu, &mask);
225 	} else {
226 		BUG_ON(target_cpu < 0 || target_cpu >= g->p.nr_cpus);
227 		CPU_SET(target_cpu, &mask);
228 	}
229 
230 	ret = sched_setaffinity(0, sizeof(mask), &mask);
231 	BUG_ON(ret);
232 
233 	return orig_mask;
234 }
235 
236 static cpu_set_t bind_to_node(int target_node)
237 {
238 	int cpus_per_node = g->p.nr_cpus/g->p.nr_nodes;
239 	cpu_set_t orig_mask, mask;
240 	int cpu;
241 	int ret;
242 
243 	BUG_ON(cpus_per_node*g->p.nr_nodes != g->p.nr_cpus);
244 	BUG_ON(!cpus_per_node);
245 
246 	ret = sched_getaffinity(0, sizeof(orig_mask), &orig_mask);
247 	BUG_ON(ret);
248 
249 	CPU_ZERO(&mask);
250 
251 	if (target_node == -1) {
252 		for (cpu = 0; cpu < g->p.nr_cpus; cpu++)
253 			CPU_SET(cpu, &mask);
254 	} else {
255 		int cpu_start = (target_node + 0) * cpus_per_node;
256 		int cpu_stop  = (target_node + 1) * cpus_per_node;
257 
258 		BUG_ON(cpu_stop > g->p.nr_cpus);
259 
260 		for (cpu = cpu_start; cpu < cpu_stop; cpu++)
261 			CPU_SET(cpu, &mask);
262 	}
263 
264 	ret = sched_setaffinity(0, sizeof(mask), &mask);
265 	BUG_ON(ret);
266 
267 	return orig_mask;
268 }
269 
270 static void bind_to_cpumask(cpu_set_t mask)
271 {
272 	int ret;
273 
274 	ret = sched_setaffinity(0, sizeof(mask), &mask);
275 	BUG_ON(ret);
276 }
277 
278 static void mempol_restore(void)
279 {
280 	int ret;
281 
282 	ret = set_mempolicy(MPOL_DEFAULT, NULL, g->p.nr_nodes-1);
283 
284 	BUG_ON(ret);
285 }
286 
287 static void bind_to_memnode(int node)
288 {
289 	unsigned long nodemask;
290 	int ret;
291 
292 	if (node == -1)
293 		return;
294 
295 	BUG_ON(g->p.nr_nodes > (int)sizeof(nodemask));
296 	nodemask = 1L << node;
297 
298 	ret = set_mempolicy(MPOL_BIND, &nodemask, sizeof(nodemask)*8);
299 	dprintf("binding to node %d, mask: %016lx => %d\n", node, nodemask, ret);
300 
301 	BUG_ON(ret);
302 }
303 
304 #define HPSIZE (2*1024*1024)
305 
306 #define set_taskname(fmt...)				\
307 do {							\
308 	char name[20];					\
309 							\
310 	snprintf(name, 20, fmt);			\
311 	prctl(PR_SET_NAME, name);			\
312 } while (0)
313 
314 static u8 *alloc_data(ssize_t bytes0, int map_flags,
315 		      int init_zero, int init_cpu0, int thp, int init_random)
316 {
317 	cpu_set_t orig_mask;
318 	ssize_t bytes;
319 	u8 *buf;
320 	int ret;
321 
322 	if (!bytes0)
323 		return NULL;
324 
325 	/* Allocate and initialize all memory on CPU#0: */
326 	if (init_cpu0) {
327 		orig_mask = bind_to_node(0);
328 		bind_to_memnode(0);
329 	}
330 
331 	bytes = bytes0 + HPSIZE;
332 
333 	buf = (void *)mmap(0, bytes, PROT_READ|PROT_WRITE, MAP_ANON|map_flags, -1, 0);
334 	BUG_ON(buf == (void *)-1);
335 
336 	if (map_flags == MAP_PRIVATE) {
337 		if (thp > 0) {
338 			ret = madvise(buf, bytes, MADV_HUGEPAGE);
339 			if (ret && !g->print_once) {
340 				g->print_once = 1;
341 				printf("WARNING: Could not enable THP - do: 'echo madvise > /sys/kernel/mm/transparent_hugepage/enabled'\n");
342 			}
343 		}
344 		if (thp < 0) {
345 			ret = madvise(buf, bytes, MADV_NOHUGEPAGE);
346 			if (ret && !g->print_once) {
347 				g->print_once = 1;
348 				printf("WARNING: Could not disable THP: run a CONFIG_TRANSPARENT_HUGEPAGE kernel?\n");
349 			}
350 		}
351 	}
352 
353 	if (init_zero) {
354 		bzero(buf, bytes);
355 	} else {
356 		/* Initialize random contents, different in each word: */
357 		if (init_random) {
358 			u64 *wbuf = (void *)buf;
359 			long off = rand();
360 			long i;
361 
362 			for (i = 0; i < bytes/8; i++)
363 				wbuf[i] = i + off;
364 		}
365 	}
366 
367 	/* Align to 2MB boundary: */
368 	buf = (void *)(((unsigned long)buf + HPSIZE-1) & ~(HPSIZE-1));
369 
370 	/* Restore affinity: */
371 	if (init_cpu0) {
372 		bind_to_cpumask(orig_mask);
373 		mempol_restore();
374 	}
375 
376 	return buf;
377 }
378 
379 static void free_data(void *data, ssize_t bytes)
380 {
381 	int ret;
382 
383 	if (!data)
384 		return;
385 
386 	ret = munmap(data, bytes);
387 	BUG_ON(ret);
388 }
389 
390 /*
391  * Create a shared memory buffer that can be shared between processes, zeroed:
392  */
393 static void * zalloc_shared_data(ssize_t bytes)
394 {
395 	return alloc_data(bytes, MAP_SHARED, 1, g->p.init_cpu0,  g->p.thp, g->p.init_random);
396 }
397 
398 /*
399  * Create a shared memory buffer that can be shared between processes:
400  */
401 static void * setup_shared_data(ssize_t bytes)
402 {
403 	return alloc_data(bytes, MAP_SHARED, 0, g->p.init_cpu0,  g->p.thp, g->p.init_random);
404 }
405 
406 /*
407  * Allocate process-local memory - this will either be shared between
408  * threads of this process, or only be accessed by this thread:
409  */
410 static void * setup_private_data(ssize_t bytes)
411 {
412 	return alloc_data(bytes, MAP_PRIVATE, 0, g->p.init_cpu0,  g->p.thp, g->p.init_random);
413 }
414 
415 /*
416  * Return a process-shared (global) mutex:
417  */
418 static void init_global_mutex(pthread_mutex_t *mutex)
419 {
420 	pthread_mutexattr_t attr;
421 
422 	pthread_mutexattr_init(&attr);
423 	pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
424 	pthread_mutex_init(mutex, &attr);
425 }
426 
427 static int parse_cpu_list(const char *arg)
428 {
429 	p0.cpu_list_str = strdup(arg);
430 
431 	dprintf("got CPU list: {%s}\n", p0.cpu_list_str);
432 
433 	return 0;
434 }
435 
436 static int parse_setup_cpu_list(void)
437 {
438 	struct thread_data *td;
439 	char *str0, *str;
440 	int t;
441 
442 	if (!g->p.cpu_list_str)
443 		return 0;
444 
445 	dprintf("g->p.nr_tasks: %d\n", g->p.nr_tasks);
446 
447 	str0 = str = strdup(g->p.cpu_list_str);
448 	t = 0;
449 
450 	BUG_ON(!str);
451 
452 	tprintf("# binding tasks to CPUs:\n");
453 	tprintf("#  ");
454 
455 	while (true) {
456 		int bind_cpu, bind_cpu_0, bind_cpu_1;
457 		char *tok, *tok_end, *tok_step, *tok_len, *tok_mul;
458 		int bind_len;
459 		int step;
460 		int mul;
461 
462 		tok = strsep(&str, ",");
463 		if (!tok)
464 			break;
465 
466 		tok_end = strstr(tok, "-");
467 
468 		dprintf("\ntoken: {%s}, end: {%s}\n", tok, tok_end);
469 		if (!tok_end) {
470 			/* Single CPU specified: */
471 			bind_cpu_0 = bind_cpu_1 = atol(tok);
472 		} else {
473 			/* CPU range specified (for example: "5-11"): */
474 			bind_cpu_0 = atol(tok);
475 			bind_cpu_1 = atol(tok_end + 1);
476 		}
477 
478 		step = 1;
479 		tok_step = strstr(tok, "#");
480 		if (tok_step) {
481 			step = atol(tok_step + 1);
482 			BUG_ON(step <= 0 || step >= g->p.nr_cpus);
483 		}
484 
485 		/*
486 		 * Mask length.
487 		 * Eg: "--cpus 8_4-16#4" means: '--cpus 8_4,12_4,16_4',
488 		 * where the _4 means the next 4 CPUs are allowed.
489 		 */
490 		bind_len = 1;
491 		tok_len = strstr(tok, "_");
492 		if (tok_len) {
493 			bind_len = atol(tok_len + 1);
494 			BUG_ON(bind_len <= 0 || bind_len > g->p.nr_cpus);
495 		}
496 
497 		/* Multiplicator shortcut, "0x8" is a shortcut for: "0,0,0,0,0,0,0,0" */
498 		mul = 1;
499 		tok_mul = strstr(tok, "x");
500 		if (tok_mul) {
501 			mul = atol(tok_mul + 1);
502 			BUG_ON(mul <= 0);
503 		}
504 
505 		dprintf("CPUs: %d_%d-%d#%dx%d\n", bind_cpu_0, bind_len, bind_cpu_1, step, mul);
506 
507 		if (bind_cpu_0 >= g->p.nr_cpus || bind_cpu_1 >= g->p.nr_cpus) {
508 			printf("\nTest not applicable, system has only %d CPUs.\n", g->p.nr_cpus);
509 			return -1;
510 		}
511 
512 		BUG_ON(bind_cpu_0 < 0 || bind_cpu_1 < 0);
513 		BUG_ON(bind_cpu_0 > bind_cpu_1);
514 
515 		for (bind_cpu = bind_cpu_0; bind_cpu <= bind_cpu_1; bind_cpu += step) {
516 			int i;
517 
518 			for (i = 0; i < mul; i++) {
519 				int cpu;
520 
521 				if (t >= g->p.nr_tasks) {
522 					printf("\n# NOTE: ignoring bind CPUs starting at CPU#%d\n #", bind_cpu);
523 					goto out;
524 				}
525 				td = g->threads + t;
526 
527 				if (t)
528 					tprintf(",");
529 				if (bind_len > 1) {
530 					tprintf("%2d/%d", bind_cpu, bind_len);
531 				} else {
532 					tprintf("%2d", bind_cpu);
533 				}
534 
535 				CPU_ZERO(&td->bind_cpumask);
536 				for (cpu = bind_cpu; cpu < bind_cpu+bind_len; cpu++) {
537 					BUG_ON(cpu < 0 || cpu >= g->p.nr_cpus);
538 					CPU_SET(cpu, &td->bind_cpumask);
539 				}
540 				t++;
541 			}
542 		}
543 	}
544 out:
545 
546 	tprintf("\n");
547 
548 	if (t < g->p.nr_tasks)
549 		printf("# NOTE: %d tasks bound, %d tasks unbound\n", t, g->p.nr_tasks - t);
550 
551 	free(str0);
552 	return 0;
553 }
554 
555 static int parse_cpus_opt(const struct option *opt __maybe_unused,
556 			  const char *arg, int unset __maybe_unused)
557 {
558 	if (!arg)
559 		return -1;
560 
561 	return parse_cpu_list(arg);
562 }
563 
564 static int parse_node_list(const char *arg)
565 {
566 	p0.node_list_str = strdup(arg);
567 
568 	dprintf("got NODE list: {%s}\n", p0.node_list_str);
569 
570 	return 0;
571 }
572 
573 static int parse_setup_node_list(void)
574 {
575 	struct thread_data *td;
576 	char *str0, *str;
577 	int t;
578 
579 	if (!g->p.node_list_str)
580 		return 0;
581 
582 	dprintf("g->p.nr_tasks: %d\n", g->p.nr_tasks);
583 
584 	str0 = str = strdup(g->p.node_list_str);
585 	t = 0;
586 
587 	BUG_ON(!str);
588 
589 	tprintf("# binding tasks to NODEs:\n");
590 	tprintf("# ");
591 
592 	while (true) {
593 		int bind_node, bind_node_0, bind_node_1;
594 		char *tok, *tok_end, *tok_step, *tok_mul;
595 		int step;
596 		int mul;
597 
598 		tok = strsep(&str, ",");
599 		if (!tok)
600 			break;
601 
602 		tok_end = strstr(tok, "-");
603 
604 		dprintf("\ntoken: {%s}, end: {%s}\n", tok, tok_end);
605 		if (!tok_end) {
606 			/* Single NODE specified: */
607 			bind_node_0 = bind_node_1 = atol(tok);
608 		} else {
609 			/* NODE range specified (for example: "5-11"): */
610 			bind_node_0 = atol(tok);
611 			bind_node_1 = atol(tok_end + 1);
612 		}
613 
614 		step = 1;
615 		tok_step = strstr(tok, "#");
616 		if (tok_step) {
617 			step = atol(tok_step + 1);
618 			BUG_ON(step <= 0 || step >= g->p.nr_nodes);
619 		}
620 
621 		/* Multiplicator shortcut, "0x8" is a shortcut for: "0,0,0,0,0,0,0,0" */
622 		mul = 1;
623 		tok_mul = strstr(tok, "x");
624 		if (tok_mul) {
625 			mul = atol(tok_mul + 1);
626 			BUG_ON(mul <= 0);
627 		}
628 
629 		dprintf("NODEs: %d-%d #%d\n", bind_node_0, bind_node_1, step);
630 
631 		if (bind_node_0 >= g->p.nr_nodes || bind_node_1 >= g->p.nr_nodes) {
632 			printf("\nTest not applicable, system has only %d nodes.\n", g->p.nr_nodes);
633 			return -1;
634 		}
635 
636 		BUG_ON(bind_node_0 < 0 || bind_node_1 < 0);
637 		BUG_ON(bind_node_0 > bind_node_1);
638 
639 		for (bind_node = bind_node_0; bind_node <= bind_node_1; bind_node += step) {
640 			int i;
641 
642 			for (i = 0; i < mul; i++) {
643 				if (t >= g->p.nr_tasks) {
644 					printf("\n# NOTE: ignoring bind NODEs starting at NODE#%d\n", bind_node);
645 					goto out;
646 				}
647 				td = g->threads + t;
648 
649 				if (!t)
650 					tprintf(" %2d", bind_node);
651 				else
652 					tprintf(",%2d", bind_node);
653 
654 				td->bind_node = bind_node;
655 				t++;
656 			}
657 		}
658 	}
659 out:
660 
661 	tprintf("\n");
662 
663 	if (t < g->p.nr_tasks)
664 		printf("# NOTE: %d tasks mem-bound, %d tasks unbound\n", t, g->p.nr_tasks - t);
665 
666 	free(str0);
667 	return 0;
668 }
669 
670 static int parse_nodes_opt(const struct option *opt __maybe_unused,
671 			  const char *arg, int unset __maybe_unused)
672 {
673 	if (!arg)
674 		return -1;
675 
676 	return parse_node_list(arg);
677 
678 	return 0;
679 }
680 
681 #define BIT(x) (1ul << x)
682 
683 static inline uint32_t lfsr_32(uint32_t lfsr)
684 {
685 	const uint32_t taps = BIT(1) | BIT(5) | BIT(6) | BIT(31);
686 	return (lfsr>>1) ^ ((0x0u - (lfsr & 0x1u)) & taps);
687 }
688 
689 /*
690  * Make sure there's real data dependency to RAM (when read
691  * accesses are enabled), so the compiler, the CPU and the
692  * kernel (KSM, zero page, etc.) cannot optimize away RAM
693  * accesses:
694  */
695 static inline u64 access_data(u64 *data __attribute__((unused)), u64 val)
696 {
697 	if (g->p.data_reads)
698 		val += *data;
699 	if (g->p.data_writes)
700 		*data = val + 1;
701 	return val;
702 }
703 
704 /*
705  * The worker process does two types of work, a forwards going
706  * loop and a backwards going loop.
707  *
708  * We do this so that on multiprocessor systems we do not create
709  * a 'train' of processing, with highly synchronized processes,
710  * skewing the whole benchmark.
711  */
712 static u64 do_work(u8 *__data, long bytes, int nr, int nr_max, int loop, u64 val)
713 {
714 	long words = bytes/sizeof(u64);
715 	u64 *data = (void *)__data;
716 	long chunk_0, chunk_1;
717 	u64 *d0, *d, *d1;
718 	long off;
719 	long i;
720 
721 	BUG_ON(!data && words);
722 	BUG_ON(data && !words);
723 
724 	if (!data)
725 		return val;
726 
727 	/* Very simple memset() work variant: */
728 	if (g->p.data_zero_memset && !g->p.data_rand_walk) {
729 		bzero(data, bytes);
730 		return val;
731 	}
732 
733 	/* Spread out by PID/TID nr and by loop nr: */
734 	chunk_0 = words/nr_max;
735 	chunk_1 = words/g->p.nr_loops;
736 	off = nr*chunk_0 + loop*chunk_1;
737 
738 	while (off >= words)
739 		off -= words;
740 
741 	if (g->p.data_rand_walk) {
742 		u32 lfsr = nr + loop + val;
743 		int j;
744 
745 		for (i = 0; i < words/1024; i++) {
746 			long start, end;
747 
748 			lfsr = lfsr_32(lfsr);
749 
750 			start = lfsr % words;
751 			end = min(start + 1024, words-1);
752 
753 			if (g->p.data_zero_memset) {
754 				bzero(data + start, (end-start) * sizeof(u64));
755 			} else {
756 				for (j = start; j < end; j++)
757 					val = access_data(data + j, val);
758 			}
759 		}
760 	} else if (!g->p.data_backwards || (nr + loop) & 1) {
761 
762 		d0 = data + off;
763 		d  = data + off + 1;
764 		d1 = data + words;
765 
766 		/* Process data forwards: */
767 		for (;;) {
768 			if (unlikely(d >= d1))
769 				d = data;
770 			if (unlikely(d == d0))
771 				break;
772 
773 			val = access_data(d, val);
774 
775 			d++;
776 		}
777 	} else {
778 		/* Process data backwards: */
779 
780 		d0 = data + off;
781 		d  = data + off - 1;
782 		d1 = data + words;
783 
784 		/* Process data forwards: */
785 		for (;;) {
786 			if (unlikely(d < data))
787 				d = data + words-1;
788 			if (unlikely(d == d0))
789 				break;
790 
791 			val = access_data(d, val);
792 
793 			d--;
794 		}
795 	}
796 
797 	return val;
798 }
799 
800 static void update_curr_cpu(int task_nr, unsigned long bytes_worked)
801 {
802 	unsigned int cpu;
803 
804 	cpu = sched_getcpu();
805 
806 	g->threads[task_nr].curr_cpu = cpu;
807 	prctl(0, bytes_worked);
808 }
809 
810 #define MAX_NR_NODES	64
811 
812 /*
813  * Count the number of nodes a process's threads
814  * are spread out on.
815  *
816  * A count of 1 means that the process is compressed
817  * to a single node. A count of g->p.nr_nodes means it's
818  * spread out on the whole system.
819  */
820 static int count_process_nodes(int process_nr)
821 {
822 	char node_present[MAX_NR_NODES] = { 0, };
823 	int nodes;
824 	int n, t;
825 
826 	for (t = 0; t < g->p.nr_threads; t++) {
827 		struct thread_data *td;
828 		int task_nr;
829 		int node;
830 
831 		task_nr = process_nr*g->p.nr_threads + t;
832 		td = g->threads + task_nr;
833 
834 		node = numa_node_of_cpu(td->curr_cpu);
835 		node_present[node] = 1;
836 	}
837 
838 	nodes = 0;
839 
840 	for (n = 0; n < MAX_NR_NODES; n++)
841 		nodes += node_present[n];
842 
843 	return nodes;
844 }
845 
846 /*
847  * Count the number of distinct process-threads a node contains.
848  *
849  * A count of 1 means that the node contains only a single
850  * process. If all nodes on the system contain at most one
851  * process then we are well-converged.
852  */
853 static int count_node_processes(int node)
854 {
855 	int processes = 0;
856 	int t, p;
857 
858 	for (p = 0; p < g->p.nr_proc; p++) {
859 		for (t = 0; t < g->p.nr_threads; t++) {
860 			struct thread_data *td;
861 			int task_nr;
862 			int n;
863 
864 			task_nr = p*g->p.nr_threads + t;
865 			td = g->threads + task_nr;
866 
867 			n = numa_node_of_cpu(td->curr_cpu);
868 			if (n == node) {
869 				processes++;
870 				break;
871 			}
872 		}
873 	}
874 
875 	return processes;
876 }
877 
878 static void calc_convergence_compression(int *strong)
879 {
880 	unsigned int nodes_min, nodes_max;
881 	int p;
882 
883 	nodes_min = -1;
884 	nodes_max =  0;
885 
886 	for (p = 0; p < g->p.nr_proc; p++) {
887 		unsigned int nodes = count_process_nodes(p);
888 
889 		nodes_min = min(nodes, nodes_min);
890 		nodes_max = max(nodes, nodes_max);
891 	}
892 
893 	/* Strong convergence: all threads compress on a single node: */
894 	if (nodes_min == 1 && nodes_max == 1) {
895 		*strong = 1;
896 	} else {
897 		*strong = 0;
898 		tprintf(" {%d-%d}", nodes_min, nodes_max);
899 	}
900 }
901 
902 static void calc_convergence(double runtime_ns_max, double *convergence)
903 {
904 	unsigned int loops_done_min, loops_done_max;
905 	int process_groups;
906 	int nodes[MAX_NR_NODES];
907 	int distance;
908 	int nr_min;
909 	int nr_max;
910 	int strong;
911 	int sum;
912 	int nr;
913 	int node;
914 	int cpu;
915 	int t;
916 
917 	if (!g->p.show_convergence && !g->p.measure_convergence)
918 		return;
919 
920 	for (node = 0; node < g->p.nr_nodes; node++)
921 		nodes[node] = 0;
922 
923 	loops_done_min = -1;
924 	loops_done_max = 0;
925 
926 	for (t = 0; t < g->p.nr_tasks; t++) {
927 		struct thread_data *td = g->threads + t;
928 		unsigned int loops_done;
929 
930 		cpu = td->curr_cpu;
931 
932 		/* Not all threads have written it yet: */
933 		if (cpu < 0)
934 			continue;
935 
936 		node = numa_node_of_cpu(cpu);
937 
938 		nodes[node]++;
939 
940 		loops_done = td->loops_done;
941 		loops_done_min = min(loops_done, loops_done_min);
942 		loops_done_max = max(loops_done, loops_done_max);
943 	}
944 
945 	nr_max = 0;
946 	nr_min = g->p.nr_tasks;
947 	sum = 0;
948 
949 	for (node = 0; node < g->p.nr_nodes; node++) {
950 		nr = nodes[node];
951 		nr_min = min(nr, nr_min);
952 		nr_max = max(nr, nr_max);
953 		sum += nr;
954 	}
955 	BUG_ON(nr_min > nr_max);
956 
957 	BUG_ON(sum > g->p.nr_tasks);
958 
959 	if (0 && (sum < g->p.nr_tasks))
960 		return;
961 
962 	/*
963 	 * Count the number of distinct process groups present
964 	 * on nodes - when we are converged this will decrease
965 	 * to g->p.nr_proc:
966 	 */
967 	process_groups = 0;
968 
969 	for (node = 0; node < g->p.nr_nodes; node++) {
970 		int processes = count_node_processes(node);
971 
972 		nr = nodes[node];
973 		tprintf(" %2d/%-2d", nr, processes);
974 
975 		process_groups += processes;
976 	}
977 
978 	distance = nr_max - nr_min;
979 
980 	tprintf(" [%2d/%-2d]", distance, process_groups);
981 
982 	tprintf(" l:%3d-%-3d (%3d)",
983 		loops_done_min, loops_done_max, loops_done_max-loops_done_min);
984 
985 	if (loops_done_min && loops_done_max) {
986 		double skew = 1.0 - (double)loops_done_min/loops_done_max;
987 
988 		tprintf(" [%4.1f%%]", skew * 100.0);
989 	}
990 
991 	calc_convergence_compression(&strong);
992 
993 	if (strong && process_groups == g->p.nr_proc) {
994 		if (!*convergence) {
995 			*convergence = runtime_ns_max;
996 			tprintf(" (%6.1fs converged)\n", *convergence/1e9);
997 			if (g->p.measure_convergence) {
998 				g->all_converged = true;
999 				g->stop_work = true;
1000 			}
1001 		}
1002 	} else {
1003 		if (*convergence) {
1004 			tprintf(" (%6.1fs de-converged)", runtime_ns_max/1e9);
1005 			*convergence = 0;
1006 		}
1007 		tprintf("\n");
1008 	}
1009 }
1010 
1011 static void show_summary(double runtime_ns_max, int l, double *convergence)
1012 {
1013 	tprintf("\r #  %5.1f%%  [%.1f mins]",
1014 		(double)(l+1)/g->p.nr_loops*100.0, runtime_ns_max/1e9 / 60.0);
1015 
1016 	calc_convergence(runtime_ns_max, convergence);
1017 
1018 	if (g->p.show_details >= 0)
1019 		fflush(stdout);
1020 }
1021 
1022 static void *worker_thread(void *__tdata)
1023 {
1024 	struct thread_data *td = __tdata;
1025 	struct timeval start0, start, stop, diff;
1026 	int process_nr = td->process_nr;
1027 	int thread_nr = td->thread_nr;
1028 	unsigned long last_perturbance;
1029 	int task_nr = td->task_nr;
1030 	int details = g->p.show_details;
1031 	int first_task, last_task;
1032 	double convergence = 0;
1033 	u64 val = td->val;
1034 	double runtime_ns_max;
1035 	u8 *global_data;
1036 	u8 *process_data;
1037 	u8 *thread_data;
1038 	u64 bytes_done;
1039 	long work_done;
1040 	u32 l;
1041 	struct rusage rusage;
1042 
1043 	bind_to_cpumask(td->bind_cpumask);
1044 	bind_to_memnode(td->bind_node);
1045 
1046 	set_taskname("thread %d/%d", process_nr, thread_nr);
1047 
1048 	global_data = g->data;
1049 	process_data = td->process_data;
1050 	thread_data = setup_private_data(g->p.bytes_thread);
1051 
1052 	bytes_done = 0;
1053 
1054 	last_task = 0;
1055 	if (process_nr == g->p.nr_proc-1 && thread_nr == g->p.nr_threads-1)
1056 		last_task = 1;
1057 
1058 	first_task = 0;
1059 	if (process_nr == 0 && thread_nr == 0)
1060 		first_task = 1;
1061 
1062 	if (details >= 2) {
1063 		printf("#  thread %2d / %2d global mem: %p, process mem: %p, thread mem: %p\n",
1064 			process_nr, thread_nr, global_data, process_data, thread_data);
1065 	}
1066 
1067 	if (g->p.serialize_startup) {
1068 		pthread_mutex_lock(&g->startup_mutex);
1069 		g->nr_tasks_started++;
1070 		pthread_mutex_unlock(&g->startup_mutex);
1071 
1072 		/* Here we will wait for the main process to start us all at once: */
1073 		pthread_mutex_lock(&g->start_work_mutex);
1074 		g->nr_tasks_working++;
1075 
1076 		/* Last one wake the main process: */
1077 		if (g->nr_tasks_working == g->p.nr_tasks)
1078 			pthread_mutex_unlock(&g->startup_done_mutex);
1079 
1080 		pthread_mutex_unlock(&g->start_work_mutex);
1081 	}
1082 
1083 	gettimeofday(&start0, NULL);
1084 
1085 	start = stop = start0;
1086 	last_perturbance = start.tv_sec;
1087 
1088 	for (l = 0; l < g->p.nr_loops; l++) {
1089 		start = stop;
1090 
1091 		if (g->stop_work)
1092 			break;
1093 
1094 		val += do_work(global_data,  g->p.bytes_global,  process_nr, g->p.nr_proc,	l, val);
1095 		val += do_work(process_data, g->p.bytes_process, thread_nr,  g->p.nr_threads,	l, val);
1096 		val += do_work(thread_data,  g->p.bytes_thread,  0,          1,		l, val);
1097 
1098 		if (g->p.sleep_usecs) {
1099 			pthread_mutex_lock(td->process_lock);
1100 			usleep(g->p.sleep_usecs);
1101 			pthread_mutex_unlock(td->process_lock);
1102 		}
1103 		/*
1104 		 * Amount of work to be done under a process-global lock:
1105 		 */
1106 		if (g->p.bytes_process_locked) {
1107 			pthread_mutex_lock(td->process_lock);
1108 			val += do_work(process_data, g->p.bytes_process_locked, thread_nr,  g->p.nr_threads,	l, val);
1109 			pthread_mutex_unlock(td->process_lock);
1110 		}
1111 
1112 		work_done = g->p.bytes_global + g->p.bytes_process +
1113 			    g->p.bytes_process_locked + g->p.bytes_thread;
1114 
1115 		update_curr_cpu(task_nr, work_done);
1116 		bytes_done += work_done;
1117 
1118 		if (details < 0 && !g->p.perturb_secs && !g->p.measure_convergence && !g->p.nr_secs)
1119 			continue;
1120 
1121 		td->loops_done = l;
1122 
1123 		gettimeofday(&stop, NULL);
1124 
1125 		/* Check whether our max runtime timed out: */
1126 		if (g->p.nr_secs) {
1127 			timersub(&stop, &start0, &diff);
1128 			if ((u32)diff.tv_sec >= g->p.nr_secs) {
1129 				g->stop_work = true;
1130 				break;
1131 			}
1132 		}
1133 
1134 		/* Update the summary at most once per second: */
1135 		if (start.tv_sec == stop.tv_sec)
1136 			continue;
1137 
1138 		/*
1139 		 * Perturb the first task's equilibrium every g->p.perturb_secs seconds,
1140 		 * by migrating to CPU#0:
1141 		 */
1142 		if (first_task && g->p.perturb_secs && (int)(stop.tv_sec - last_perturbance) >= g->p.perturb_secs) {
1143 			cpu_set_t orig_mask;
1144 			int target_cpu;
1145 			int this_cpu;
1146 
1147 			last_perturbance = stop.tv_sec;
1148 
1149 			/*
1150 			 * Depending on where we are running, move into
1151 			 * the other half of the system, to create some
1152 			 * real disturbance:
1153 			 */
1154 			this_cpu = g->threads[task_nr].curr_cpu;
1155 			if (this_cpu < g->p.nr_cpus/2)
1156 				target_cpu = g->p.nr_cpus-1;
1157 			else
1158 				target_cpu = 0;
1159 
1160 			orig_mask = bind_to_cpu(target_cpu);
1161 
1162 			/* Here we are running on the target CPU already */
1163 			if (details >= 1)
1164 				printf(" (injecting perturbalance, moved to CPU#%d)\n", target_cpu);
1165 
1166 			bind_to_cpumask(orig_mask);
1167 		}
1168 
1169 		if (details >= 3) {
1170 			timersub(&stop, &start, &diff);
1171 			runtime_ns_max = diff.tv_sec * 1000000000;
1172 			runtime_ns_max += diff.tv_usec * 1000;
1173 
1174 			if (details >= 0) {
1175 				printf(" #%2d / %2d: %14.2lf nsecs/op [val: %016"PRIx64"]\n",
1176 					process_nr, thread_nr, runtime_ns_max / bytes_done, val);
1177 			}
1178 			fflush(stdout);
1179 		}
1180 		if (!last_task)
1181 			continue;
1182 
1183 		timersub(&stop, &start0, &diff);
1184 		runtime_ns_max = diff.tv_sec * 1000000000ULL;
1185 		runtime_ns_max += diff.tv_usec * 1000ULL;
1186 
1187 		show_summary(runtime_ns_max, l, &convergence);
1188 	}
1189 
1190 	gettimeofday(&stop, NULL);
1191 	timersub(&stop, &start0, &diff);
1192 	td->runtime_ns = diff.tv_sec * 1000000000ULL;
1193 	td->runtime_ns += diff.tv_usec * 1000ULL;
1194 	td->speed_gbs = bytes_done / (td->runtime_ns / 1e9) / 1e9;
1195 
1196 	getrusage(RUSAGE_THREAD, &rusage);
1197 	td->system_time_ns = rusage.ru_stime.tv_sec * 1000000000ULL;
1198 	td->system_time_ns += rusage.ru_stime.tv_usec * 1000ULL;
1199 	td->user_time_ns = rusage.ru_utime.tv_sec * 1000000000ULL;
1200 	td->user_time_ns += rusage.ru_utime.tv_usec * 1000ULL;
1201 
1202 	free_data(thread_data, g->p.bytes_thread);
1203 
1204 	pthread_mutex_lock(&g->stop_work_mutex);
1205 	g->bytes_done += bytes_done;
1206 	pthread_mutex_unlock(&g->stop_work_mutex);
1207 
1208 	return NULL;
1209 }
1210 
1211 /*
1212  * A worker process starts a couple of threads:
1213  */
1214 static void worker_process(int process_nr)
1215 {
1216 	pthread_mutex_t process_lock;
1217 	struct thread_data *td;
1218 	pthread_t *pthreads;
1219 	u8 *process_data;
1220 	int task_nr;
1221 	int ret;
1222 	int t;
1223 
1224 	pthread_mutex_init(&process_lock, NULL);
1225 	set_taskname("process %d", process_nr);
1226 
1227 	/*
1228 	 * Pick up the memory policy and the CPU binding of our first thread,
1229 	 * so that we initialize memory accordingly:
1230 	 */
1231 	task_nr = process_nr*g->p.nr_threads;
1232 	td = g->threads + task_nr;
1233 
1234 	bind_to_memnode(td->bind_node);
1235 	bind_to_cpumask(td->bind_cpumask);
1236 
1237 	pthreads = zalloc(g->p.nr_threads * sizeof(pthread_t));
1238 	process_data = setup_private_data(g->p.bytes_process);
1239 
1240 	if (g->p.show_details >= 3) {
1241 		printf(" # process %2d global mem: %p, process mem: %p\n",
1242 			process_nr, g->data, process_data);
1243 	}
1244 
1245 	for (t = 0; t < g->p.nr_threads; t++) {
1246 		task_nr = process_nr*g->p.nr_threads + t;
1247 		td = g->threads + task_nr;
1248 
1249 		td->process_data = process_data;
1250 		td->process_nr   = process_nr;
1251 		td->thread_nr    = t;
1252 		td->task_nr	 = task_nr;
1253 		td->val          = rand();
1254 		td->curr_cpu	 = -1;
1255 		td->process_lock = &process_lock;
1256 
1257 		ret = pthread_create(pthreads + t, NULL, worker_thread, td);
1258 		BUG_ON(ret);
1259 	}
1260 
1261 	for (t = 0; t < g->p.nr_threads; t++) {
1262                 ret = pthread_join(pthreads[t], NULL);
1263 		BUG_ON(ret);
1264 	}
1265 
1266 	free_data(process_data, g->p.bytes_process);
1267 	free(pthreads);
1268 }
1269 
1270 static void print_summary(void)
1271 {
1272 	if (g->p.show_details < 0)
1273 		return;
1274 
1275 	printf("\n ###\n");
1276 	printf(" # %d %s will execute (on %d nodes, %d CPUs):\n",
1277 		g->p.nr_tasks, g->p.nr_tasks == 1 ? "task" : "tasks", g->p.nr_nodes, g->p.nr_cpus);
1278 	printf(" #      %5dx %5ldMB global  shared mem operations\n",
1279 			g->p.nr_loops, g->p.bytes_global/1024/1024);
1280 	printf(" #      %5dx %5ldMB process shared mem operations\n",
1281 			g->p.nr_loops, g->p.bytes_process/1024/1024);
1282 	printf(" #      %5dx %5ldMB thread  local  mem operations\n",
1283 			g->p.nr_loops, g->p.bytes_thread/1024/1024);
1284 
1285 	printf(" ###\n");
1286 
1287 	printf("\n ###\n"); fflush(stdout);
1288 }
1289 
1290 static void init_thread_data(void)
1291 {
1292 	ssize_t size = sizeof(*g->threads)*g->p.nr_tasks;
1293 	int t;
1294 
1295 	g->threads = zalloc_shared_data(size);
1296 
1297 	for (t = 0; t < g->p.nr_tasks; t++) {
1298 		struct thread_data *td = g->threads + t;
1299 		int cpu;
1300 
1301 		/* Allow all nodes by default: */
1302 		td->bind_node = -1;
1303 
1304 		/* Allow all CPUs by default: */
1305 		CPU_ZERO(&td->bind_cpumask);
1306 		for (cpu = 0; cpu < g->p.nr_cpus; cpu++)
1307 			CPU_SET(cpu, &td->bind_cpumask);
1308 	}
1309 }
1310 
1311 static void deinit_thread_data(void)
1312 {
1313 	ssize_t size = sizeof(*g->threads)*g->p.nr_tasks;
1314 
1315 	free_data(g->threads, size);
1316 }
1317 
1318 static int init(void)
1319 {
1320 	g = (void *)alloc_data(sizeof(*g), MAP_SHARED, 1, 0, 0 /* THP */, 0);
1321 
1322 	/* Copy over options: */
1323 	g->p = p0;
1324 
1325 	g->p.nr_cpus = numa_num_configured_cpus();
1326 
1327 	g->p.nr_nodes = numa_max_node() + 1;
1328 
1329 	/* char array in count_process_nodes(): */
1330 	BUG_ON(g->p.nr_nodes > MAX_NR_NODES || g->p.nr_nodes < 0);
1331 
1332 	if (g->p.show_quiet && !g->p.show_details)
1333 		g->p.show_details = -1;
1334 
1335 	/* Some memory should be specified: */
1336 	if (!g->p.mb_global_str && !g->p.mb_proc_str && !g->p.mb_thread_str)
1337 		return -1;
1338 
1339 	if (g->p.mb_global_str) {
1340 		g->p.mb_global = atof(g->p.mb_global_str);
1341 		BUG_ON(g->p.mb_global < 0);
1342 	}
1343 
1344 	if (g->p.mb_proc_str) {
1345 		g->p.mb_proc = atof(g->p.mb_proc_str);
1346 		BUG_ON(g->p.mb_proc < 0);
1347 	}
1348 
1349 	if (g->p.mb_proc_locked_str) {
1350 		g->p.mb_proc_locked = atof(g->p.mb_proc_locked_str);
1351 		BUG_ON(g->p.mb_proc_locked < 0);
1352 		BUG_ON(g->p.mb_proc_locked > g->p.mb_proc);
1353 	}
1354 
1355 	if (g->p.mb_thread_str) {
1356 		g->p.mb_thread = atof(g->p.mb_thread_str);
1357 		BUG_ON(g->p.mb_thread < 0);
1358 	}
1359 
1360 	BUG_ON(g->p.nr_threads <= 0);
1361 	BUG_ON(g->p.nr_proc <= 0);
1362 
1363 	g->p.nr_tasks = g->p.nr_proc*g->p.nr_threads;
1364 
1365 	g->p.bytes_global		= g->p.mb_global	*1024L*1024L;
1366 	g->p.bytes_process		= g->p.mb_proc		*1024L*1024L;
1367 	g->p.bytes_process_locked	= g->p.mb_proc_locked	*1024L*1024L;
1368 	g->p.bytes_thread		= g->p.mb_thread	*1024L*1024L;
1369 
1370 	g->data = setup_shared_data(g->p.bytes_global);
1371 
1372 	/* Startup serialization: */
1373 	init_global_mutex(&g->start_work_mutex);
1374 	init_global_mutex(&g->startup_mutex);
1375 	init_global_mutex(&g->startup_done_mutex);
1376 	init_global_mutex(&g->stop_work_mutex);
1377 
1378 	init_thread_data();
1379 
1380 	tprintf("#\n");
1381 	if (parse_setup_cpu_list() || parse_setup_node_list())
1382 		return -1;
1383 	tprintf("#\n");
1384 
1385 	print_summary();
1386 
1387 	return 0;
1388 }
1389 
1390 static void deinit(void)
1391 {
1392 	free_data(g->data, g->p.bytes_global);
1393 	g->data = NULL;
1394 
1395 	deinit_thread_data();
1396 
1397 	free_data(g, sizeof(*g));
1398 	g = NULL;
1399 }
1400 
1401 /*
1402  * Print a short or long result, depending on the verbosity setting:
1403  */
1404 static void print_res(const char *name, double val,
1405 		      const char *txt_unit, const char *txt_short, const char *txt_long)
1406 {
1407 	if (!name)
1408 		name = "main,";
1409 
1410 	if (g->p.show_quiet)
1411 		printf(" %-30s %15.3f, %-15s %s\n", name, val, txt_unit, txt_short);
1412 	else
1413 		printf(" %14.3f %s\n", val, txt_long);
1414 }
1415 
1416 static int __bench_numa(const char *name)
1417 {
1418 	struct timeval start, stop, diff;
1419 	u64 runtime_ns_min, runtime_ns_sum;
1420 	pid_t *pids, pid, wpid;
1421 	double delta_runtime;
1422 	double runtime_avg;
1423 	double runtime_sec_max;
1424 	double runtime_sec_min;
1425 	int wait_stat;
1426 	double bytes;
1427 	int i, t, p;
1428 
1429 	if (init())
1430 		return -1;
1431 
1432 	pids = zalloc(g->p.nr_proc * sizeof(*pids));
1433 	pid = -1;
1434 
1435 	/* All threads try to acquire it, this way we can wait for them to start up: */
1436 	pthread_mutex_lock(&g->start_work_mutex);
1437 
1438 	if (g->p.serialize_startup) {
1439 		tprintf(" #\n");
1440 		tprintf(" # Startup synchronization: ..."); fflush(stdout);
1441 	}
1442 
1443 	gettimeofday(&start, NULL);
1444 
1445 	for (i = 0; i < g->p.nr_proc; i++) {
1446 		pid = fork();
1447 		dprintf(" # process %2d: PID %d\n", i, pid);
1448 
1449 		BUG_ON(pid < 0);
1450 		if (!pid) {
1451 			/* Child process: */
1452 			worker_process(i);
1453 
1454 			exit(0);
1455 		}
1456 		pids[i] = pid;
1457 
1458 	}
1459 	/* Wait for all the threads to start up: */
1460 	while (g->nr_tasks_started != g->p.nr_tasks)
1461 		usleep(1000);
1462 
1463 	BUG_ON(g->nr_tasks_started != g->p.nr_tasks);
1464 
1465 	if (g->p.serialize_startup) {
1466 		double startup_sec;
1467 
1468 		pthread_mutex_lock(&g->startup_done_mutex);
1469 
1470 		/* This will start all threads: */
1471 		pthread_mutex_unlock(&g->start_work_mutex);
1472 
1473 		/* This mutex is locked - the last started thread will wake us: */
1474 		pthread_mutex_lock(&g->startup_done_mutex);
1475 
1476 		gettimeofday(&stop, NULL);
1477 
1478 		timersub(&stop, &start, &diff);
1479 
1480 		startup_sec = diff.tv_sec * 1000000000.0;
1481 		startup_sec += diff.tv_usec * 1000.0;
1482 		startup_sec /= 1e9;
1483 
1484 		tprintf(" threads initialized in %.6f seconds.\n", startup_sec);
1485 		tprintf(" #\n");
1486 
1487 		start = stop;
1488 		pthread_mutex_unlock(&g->startup_done_mutex);
1489 	} else {
1490 		gettimeofday(&start, NULL);
1491 	}
1492 
1493 	/* Parent process: */
1494 
1495 
1496 	for (i = 0; i < g->p.nr_proc; i++) {
1497 		wpid = waitpid(pids[i], &wait_stat, 0);
1498 		BUG_ON(wpid < 0);
1499 		BUG_ON(!WIFEXITED(wait_stat));
1500 
1501 	}
1502 
1503 	runtime_ns_sum = 0;
1504 	runtime_ns_min = -1LL;
1505 
1506 	for (t = 0; t < g->p.nr_tasks; t++) {
1507 		u64 thread_runtime_ns = g->threads[t].runtime_ns;
1508 
1509 		runtime_ns_sum += thread_runtime_ns;
1510 		runtime_ns_min = min(thread_runtime_ns, runtime_ns_min);
1511 	}
1512 
1513 	gettimeofday(&stop, NULL);
1514 	timersub(&stop, &start, &diff);
1515 
1516 	BUG_ON(bench_format != BENCH_FORMAT_DEFAULT);
1517 
1518 	tprintf("\n ###\n");
1519 	tprintf("\n");
1520 
1521 	runtime_sec_max = diff.tv_sec * 1000000000.0;
1522 	runtime_sec_max += diff.tv_usec * 1000.0;
1523 	runtime_sec_max /= 1e9;
1524 
1525 	runtime_sec_min = runtime_ns_min/1e9;
1526 
1527 	bytes = g->bytes_done;
1528 	runtime_avg = (double)runtime_ns_sum / g->p.nr_tasks / 1e9;
1529 
1530 	if (g->p.measure_convergence) {
1531 		print_res(name, runtime_sec_max,
1532 			"secs,", "NUMA-convergence-latency", "secs latency to NUMA-converge");
1533 	}
1534 
1535 	print_res(name, runtime_sec_max,
1536 		"secs,", "runtime-max/thread",	"secs slowest (max) thread-runtime");
1537 
1538 	print_res(name, runtime_sec_min,
1539 		"secs,", "runtime-min/thread",	"secs fastest (min) thread-runtime");
1540 
1541 	print_res(name, runtime_avg,
1542 		"secs,", "runtime-avg/thread",	"secs average thread-runtime");
1543 
1544 	delta_runtime = (runtime_sec_max - runtime_sec_min)/2.0;
1545 	print_res(name, delta_runtime / runtime_sec_max * 100.0,
1546 		"%,", "spread-runtime/thread",	"% difference between max/avg runtime");
1547 
1548 	print_res(name, bytes / g->p.nr_tasks / 1e9,
1549 		"GB,", "data/thread",		"GB data processed, per thread");
1550 
1551 	print_res(name, bytes / 1e9,
1552 		"GB,", "data-total",		"GB data processed, total");
1553 
1554 	print_res(name, runtime_sec_max * 1e9 / (bytes / g->p.nr_tasks),
1555 		"nsecs,", "runtime/byte/thread","nsecs/byte/thread runtime");
1556 
1557 	print_res(name, bytes / g->p.nr_tasks / 1e9 / runtime_sec_max,
1558 		"GB/sec,", "thread-speed",	"GB/sec/thread speed");
1559 
1560 	print_res(name, bytes / runtime_sec_max / 1e9,
1561 		"GB/sec,", "total-speed",	"GB/sec total speed");
1562 
1563 	if (g->p.show_details >= 2) {
1564 		char tname[32];
1565 		struct thread_data *td;
1566 		for (p = 0; p < g->p.nr_proc; p++) {
1567 			for (t = 0; t < g->p.nr_threads; t++) {
1568 				memset(tname, 0, 32);
1569 				td = g->threads + p*g->p.nr_threads + t;
1570 				snprintf(tname, 32, "process%d:thread%d", p, t);
1571 				print_res(tname, td->speed_gbs,
1572 					"GB/sec",	"thread-speed", "GB/sec/thread speed");
1573 				print_res(tname, td->system_time_ns / 1e9,
1574 					"secs",	"thread-system-time", "system CPU time/thread");
1575 				print_res(tname, td->user_time_ns / 1e9,
1576 					"secs",	"thread-user-time", "user CPU time/thread");
1577 			}
1578 		}
1579 	}
1580 
1581 	free(pids);
1582 
1583 	deinit();
1584 
1585 	return 0;
1586 }
1587 
1588 #define MAX_ARGS 50
1589 
1590 static int command_size(const char **argv)
1591 {
1592 	int size = 0;
1593 
1594 	while (*argv) {
1595 		size++;
1596 		argv++;
1597 	}
1598 
1599 	BUG_ON(size >= MAX_ARGS);
1600 
1601 	return size;
1602 }
1603 
1604 static void init_params(struct params *p, const char *name, int argc, const char **argv)
1605 {
1606 	int i;
1607 
1608 	printf("\n # Running %s \"perf bench numa", name);
1609 
1610 	for (i = 0; i < argc; i++)
1611 		printf(" %s", argv[i]);
1612 
1613 	printf("\"\n");
1614 
1615 	memset(p, 0, sizeof(*p));
1616 
1617 	/* Initialize nonzero defaults: */
1618 
1619 	p->serialize_startup		= 1;
1620 	p->data_reads			= true;
1621 	p->data_writes			= true;
1622 	p->data_backwards		= true;
1623 	p->data_rand_walk		= true;
1624 	p->nr_loops			= -1;
1625 	p->init_random			= true;
1626 	p->mb_global_str		= "1";
1627 	p->nr_proc			= 1;
1628 	p->nr_threads			= 1;
1629 	p->nr_secs			= 5;
1630 	p->run_all			= argc == 1;
1631 }
1632 
1633 static int run_bench_numa(const char *name, const char **argv)
1634 {
1635 	int argc = command_size(argv);
1636 
1637 	init_params(&p0, name, argc, argv);
1638 	argc = parse_options(argc, argv, options, bench_numa_usage, 0);
1639 	if (argc)
1640 		goto err;
1641 
1642 	if (__bench_numa(name))
1643 		goto err;
1644 
1645 	return 0;
1646 
1647 err:
1648 	return -1;
1649 }
1650 
1651 #define OPT_BW_RAM		"-s",  "20", "-zZq",    "--thp", " 1", "--no-data_rand_walk"
1652 #define OPT_BW_RAM_NOTHP	OPT_BW_RAM,		"--thp", "-1"
1653 
1654 #define OPT_CONV		"-s", "100", "-zZ0qcm", "--thp", " 1"
1655 #define OPT_CONV_NOTHP		OPT_CONV,		"--thp", "-1"
1656 
1657 #define OPT_BW			"-s",  "20", "-zZ0q",   "--thp", " 1"
1658 #define OPT_BW_NOTHP		OPT_BW,			"--thp", "-1"
1659 
1660 /*
1661  * The built-in test-suite executed by "perf bench numa -a".
1662  *
1663  * (A minimum of 4 nodes and 16 GB of RAM is recommended.)
1664  */
1665 static const char *tests[][MAX_ARGS] = {
1666    /* Basic single-stream NUMA bandwidth measurements: */
1667    { "RAM-bw-local,",	  "mem",  "-p",  "1",  "-t",  "1", "-P", "1024",
1668 			  "-C" ,   "0", "-M",   "0", OPT_BW_RAM },
1669    { "RAM-bw-local-NOTHP,",
1670 			  "mem",  "-p",  "1",  "-t",  "1", "-P", "1024",
1671 			  "-C" ,   "0", "-M",   "0", OPT_BW_RAM_NOTHP },
1672    { "RAM-bw-remote,",	  "mem",  "-p",  "1",  "-t",  "1", "-P", "1024",
1673 			  "-C" ,   "0", "-M",   "1", OPT_BW_RAM },
1674 
1675    /* 2-stream NUMA bandwidth measurements: */
1676    { "RAM-bw-local-2x,",  "mem",  "-p",  "2",  "-t",  "1", "-P", "1024",
1677 			   "-C", "0,2", "-M", "0x2", OPT_BW_RAM },
1678    { "RAM-bw-remote-2x,", "mem",  "-p",  "2",  "-t",  "1", "-P", "1024",
1679 		 	   "-C", "0,2", "-M", "1x2", OPT_BW_RAM },
1680 
1681    /* Cross-stream NUMA bandwidth measurement: */
1682    { "RAM-bw-cross,",     "mem",  "-p",  "2",  "-t",  "1", "-P", "1024",
1683 		 	   "-C", "0,8", "-M", "1,0", OPT_BW_RAM },
1684 
1685    /* Convergence latency measurements: */
1686    { " 1x3-convergence,", "mem",  "-p",  "1", "-t",  "3", "-P",  "512", OPT_CONV },
1687    { " 1x4-convergence,", "mem",  "-p",  "1", "-t",  "4", "-P",  "512", OPT_CONV },
1688    { " 1x6-convergence,", "mem",  "-p",  "1", "-t",  "6", "-P", "1020", OPT_CONV },
1689    { " 2x3-convergence,", "mem",  "-p",  "3", "-t",  "3", "-P", "1020", OPT_CONV },
1690    { " 3x3-convergence,", "mem",  "-p",  "3", "-t",  "3", "-P", "1020", OPT_CONV },
1691    { " 4x4-convergence,", "mem",  "-p",  "4", "-t",  "4", "-P",  "512", OPT_CONV },
1692    { " 4x4-convergence-NOTHP,",
1693 			  "mem",  "-p",  "4", "-t",  "4", "-P",  "512", OPT_CONV_NOTHP },
1694    { " 4x6-convergence,", "mem",  "-p",  "4", "-t",  "6", "-P", "1020", OPT_CONV },
1695    { " 4x8-convergence,", "mem",  "-p",  "4", "-t",  "8", "-P",  "512", OPT_CONV },
1696    { " 8x4-convergence,", "mem",  "-p",  "8", "-t",  "4", "-P",  "512", OPT_CONV },
1697    { " 8x4-convergence-NOTHP,",
1698 			  "mem",  "-p",  "8", "-t",  "4", "-P",  "512", OPT_CONV_NOTHP },
1699    { " 3x1-convergence,", "mem",  "-p",  "3", "-t",  "1", "-P",  "512", OPT_CONV },
1700    { " 4x1-convergence,", "mem",  "-p",  "4", "-t",  "1", "-P",  "512", OPT_CONV },
1701    { " 8x1-convergence,", "mem",  "-p",  "8", "-t",  "1", "-P",  "512", OPT_CONV },
1702    { "16x1-convergence,", "mem",  "-p", "16", "-t",  "1", "-P",  "256", OPT_CONV },
1703    { "32x1-convergence,", "mem",  "-p", "32", "-t",  "1", "-P",  "128", OPT_CONV },
1704 
1705    /* Various NUMA process/thread layout bandwidth measurements: */
1706    { " 2x1-bw-process,",  "mem",  "-p",  "2", "-t",  "1", "-P", "1024", OPT_BW },
1707    { " 3x1-bw-process,",  "mem",  "-p",  "3", "-t",  "1", "-P", "1024", OPT_BW },
1708    { " 4x1-bw-process,",  "mem",  "-p",  "4", "-t",  "1", "-P", "1024", OPT_BW },
1709    { " 8x1-bw-process,",  "mem",  "-p",  "8", "-t",  "1", "-P", " 512", OPT_BW },
1710    { " 8x1-bw-process-NOTHP,",
1711 			  "mem",  "-p",  "8", "-t",  "1", "-P", " 512", OPT_BW_NOTHP },
1712    { "16x1-bw-process,",  "mem",  "-p", "16", "-t",  "1", "-P",  "256", OPT_BW },
1713 
1714    { " 4x1-bw-thread,",	  "mem",  "-p",  "1", "-t",  "4", "-T",  "256", OPT_BW },
1715    { " 8x1-bw-thread,",	  "mem",  "-p",  "1", "-t",  "8", "-T",  "256", OPT_BW },
1716    { "16x1-bw-thread,",   "mem",  "-p",  "1", "-t", "16", "-T",  "128", OPT_BW },
1717    { "32x1-bw-thread,",   "mem",  "-p",  "1", "-t", "32", "-T",   "64", OPT_BW },
1718 
1719    { " 2x3-bw-thread,",	  "mem",  "-p",  "2", "-t",  "3", "-P",  "512", OPT_BW },
1720    { " 4x4-bw-thread,",	  "mem",  "-p",  "4", "-t",  "4", "-P",  "512", OPT_BW },
1721    { " 4x6-bw-thread,",	  "mem",  "-p",  "4", "-t",  "6", "-P",  "512", OPT_BW },
1722    { " 4x8-bw-thread,",	  "mem",  "-p",  "4", "-t",  "8", "-P",  "512", OPT_BW },
1723    { " 4x8-bw-thread-NOTHP,",
1724 			  "mem",  "-p",  "4", "-t",  "8", "-P",  "512", OPT_BW_NOTHP },
1725    { " 3x3-bw-thread,",	  "mem",  "-p",  "3", "-t",  "3", "-P",  "512", OPT_BW },
1726    { " 5x5-bw-thread,",	  "mem",  "-p",  "5", "-t",  "5", "-P",  "512", OPT_BW },
1727 
1728    { "2x16-bw-thread,",   "mem",  "-p",  "2", "-t", "16", "-P",  "512", OPT_BW },
1729    { "1x32-bw-thread,",   "mem",  "-p",  "1", "-t", "32", "-P", "2048", OPT_BW },
1730 
1731    { "numa02-bw,",	  "mem",  "-p",  "1", "-t", "32", "-T",   "32", OPT_BW },
1732    { "numa02-bw-NOTHP,",  "mem",  "-p",  "1", "-t", "32", "-T",   "32", OPT_BW_NOTHP },
1733    { "numa01-bw-thread,", "mem",  "-p",  "2", "-t", "16", "-T",  "192", OPT_BW },
1734    { "numa01-bw-thread-NOTHP,",
1735 			  "mem",  "-p",  "2", "-t", "16", "-T",  "192", OPT_BW_NOTHP },
1736 };
1737 
1738 static int bench_all(void)
1739 {
1740 	int nr = ARRAY_SIZE(tests);
1741 	int ret;
1742 	int i;
1743 
1744 	ret = system("echo ' #'; echo ' # Running test on: '$(uname -a); echo ' #'");
1745 	BUG_ON(ret < 0);
1746 
1747 	for (i = 0; i < nr; i++) {
1748 		run_bench_numa(tests[i][0], tests[i] + 1);
1749 	}
1750 
1751 	printf("\n");
1752 
1753 	return 0;
1754 }
1755 
1756 int bench_numa(int argc, const char **argv, const char *prefix __maybe_unused)
1757 {
1758 	init_params(&p0, "main,", argc, argv);
1759 	argc = parse_options(argc, argv, options, bench_numa_usage, 0);
1760 	if (argc)
1761 		goto err;
1762 
1763 	if (p0.run_all)
1764 		return bench_all();
1765 
1766 	if (__bench_numa(NULL))
1767 		goto err;
1768 
1769 	return 0;
1770 
1771 err:
1772 	usage_with_options(numa_usage, options);
1773 	return -1;
1774 }
1775