1# futex contention
2# (c) 2010, Arnaldo Carvalho de Melo <acme@redhat.com>
3# Licensed under the terms of the GNU GPL License version 2
4#
5# Translation of:
6#
7# http://sourceware.org/systemtap/wiki/WSFutexContention
8#
9# to perf python scripting.
10#
11# Measures futex contention
12
13from __future__ import print_function
14
15import os, sys
16sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
17from Util import *
18
19process_names = {}
20thread_thislock = {}
21thread_blocktime = {}
22
23lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time
24process_names = {} # long-lived pid-to-execname mapping
25
26def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm, callchain,
27			      nr, uaddr, op, val, utime, uaddr2, val3):
28	cmd = op & FUTEX_CMD_MASK
29	if cmd != FUTEX_WAIT:
30		return # we don't care about originators of WAKE events
31
32	process_names[tid] = comm
33	thread_thislock[tid] = uaddr
34	thread_blocktime[tid] = nsecs(s, ns)
35
36def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm, callchain,
37			     nr, ret):
38	if tid in thread_blocktime:
39		elapsed = nsecs(s, ns) - thread_blocktime[tid]
40		add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed)
41		del thread_blocktime[tid]
42		del thread_thislock[tid]
43
44def trace_begin():
45	print("Press control+C to stop and show the summary")
46
47def trace_end():
48	for (tid, lock) in lock_waits:
49		min, max, avg, count = lock_waits[tid, lock]
50		print("%s[%d] lock %x contended %d times, %d avg ns" %
51			(process_names[tid], tid, lock, count, avg))
52
53