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