1# Util.py - Python extension for perf script, miscellaneous utility code
2#
3# Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com>
4#
5# This software may be distributed under the terms of the GNU General
6# Public License ("GPL") version 2 as published by the Free Software
7# Foundation.
8from __future__ import print_function
9
10import errno, os
11
12FUTEX_WAIT = 0
13FUTEX_WAKE = 1
14FUTEX_PRIVATE_FLAG = 128
15FUTEX_CLOCK_REALTIME = 256
16FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME)
17
18NSECS_PER_SEC    = 1000000000
19
20def avg(total, n):
21    return total / n
22
23def nsecs(secs, nsecs):
24    return secs * NSECS_PER_SEC + nsecs
25
26def nsecs_secs(nsecs):
27    return nsecs / NSECS_PER_SEC
28
29def nsecs_nsecs(nsecs):
30    return nsecs % NSECS_PER_SEC
31
32def nsecs_str(nsecs):
33    str = "%5u.%09u" % (nsecs_secs(nsecs), nsecs_nsecs(nsecs)),
34    return str
35
36def add_stats(dict, key, value):
37	if key not in dict:
38		dict[key] = (value, value, value, 1)
39	else:
40		min, max, avg, count = dict[key]
41		if value < min:
42			min = value
43		if value > max:
44			max = value
45		avg = (avg + value) / 2
46		dict[key] = (min, max, avg, count + 1)
47
48def clear_term():
49    print("\x1b[H\x1b[2J")
50
51audit_package_warned = False
52
53try:
54	import audit
55	machine_to_id = {
56		'x86_64': audit.MACH_86_64,
57		'alpha'	: audit.MACH_ALPHA,
58		'ia64'	: audit.MACH_IA64,
59		'ppc'	: audit.MACH_PPC,
60		'ppc64'	: audit.MACH_PPC64,
61		'ppc64le' : audit.MACH_PPC64LE,
62		's390'	: audit.MACH_S390,
63		's390x'	: audit.MACH_S390X,
64		'i386'	: audit.MACH_X86,
65		'i586'	: audit.MACH_X86,
66		'i686'	: audit.MACH_X86,
67	}
68	try:
69		machine_to_id['armeb'] = audit.MACH_ARMEB
70	except:
71		pass
72	machine_id = machine_to_id[os.uname()[4]]
73except:
74	if not audit_package_warned:
75		audit_package_warned = True
76		print("Install the audit-libs-python package to get syscall names.\n"
77                    "For example:\n  # apt-get install python-audit (Ubuntu)"
78                    "\n  # yum install audit-libs-python (Fedora)"
79                    "\n  etc.\n")
80
81def syscall_name(id):
82	try:
83		return audit.audit_syscall_to_name(id, machine_id)
84	except:
85		return str(id)
86
87def strerror(nr):
88	try:
89		return errno.errorcode[abs(nr)]
90	except:
91		return "Unknown %d errno" % nr
92