blob: 4ec1fa5b6373bc0eaadd707caf470dbda0d11686 [file] [log] [blame]
Jan Kiszka626c4272011-10-07 09:37:49 +02001#!/usr/bin/python
2#
3# top-like utility for displaying kvm statistics
4#
5# Copyright 2006-2008 Qumranet Technologies
6# Copyright 2008-2011 Red Hat, Inc.
7#
8# Authors:
9# Avi Kivity <avi@redhat.com>
10#
11# This work is licensed under the terms of the GNU GPL, version 2. See
12# the COPYING file in the top-level directory.
13
14import curses
15import sys, os, time, optparse
16
17class DebugfsProvider(object):
18 def __init__(self):
19 self.base = '/sys/kernel/debug/kvm'
20 self._fields = os.listdir(self.base)
21 def fields(self):
22 return self._fields
23 def select(self, fields):
24 self._fields = fields
25 def read(self):
26 def val(key):
27 return int(file(self.base + '/' + key).read())
28 return dict([(key, val(key)) for key in self._fields])
29
30vmx_exit_reasons = {
31 0: 'EXCEPTION_NMI',
32 1: 'EXTERNAL_INTERRUPT',
33 2: 'TRIPLE_FAULT',
34 7: 'PENDING_INTERRUPT',
35 8: 'NMI_WINDOW',
36 9: 'TASK_SWITCH',
37 10: 'CPUID',
38 12: 'HLT',
39 14: 'INVLPG',
40 15: 'RDPMC',
41 16: 'RDTSC',
42 18: 'VMCALL',
43 19: 'VMCLEAR',
44 20: 'VMLAUNCH',
45 21: 'VMPTRLD',
46 22: 'VMPTRST',
47 23: 'VMREAD',
48 24: 'VMRESUME',
49 25: 'VMWRITE',
50 26: 'VMOFF',
51 27: 'VMON',
52 28: 'CR_ACCESS',
53 29: 'DR_ACCESS',
54 30: 'IO_INSTRUCTION',
55 31: 'MSR_READ',
56 32: 'MSR_WRITE',
57 33: 'INVALID_STATE',
58 36: 'MWAIT_INSTRUCTION',
59 39: 'MONITOR_INSTRUCTION',
60 40: 'PAUSE_INSTRUCTION',
61 41: 'MCE_DURING_VMENTRY',
62 43: 'TPR_BELOW_THRESHOLD',
63 44: 'APIC_ACCESS',
64 48: 'EPT_VIOLATION',
65 49: 'EPT_MISCONFIG',
66 54: 'WBINVD',
67 55: 'XSETBV',
68}
69
70svm_exit_reasons = {
71 0x000: 'READ_CR0',
72 0x003: 'READ_CR3',
73 0x004: 'READ_CR4',
74 0x008: 'READ_CR8',
75 0x010: 'WRITE_CR0',
76 0x013: 'WRITE_CR3',
77 0x014: 'WRITE_CR4',
78 0x018: 'WRITE_CR8',
79 0x020: 'READ_DR0',
80 0x021: 'READ_DR1',
81 0x022: 'READ_DR2',
82 0x023: 'READ_DR3',
83 0x024: 'READ_DR4',
84 0x025: 'READ_DR5',
85 0x026: 'READ_DR6',
86 0x027: 'READ_DR7',
87 0x030: 'WRITE_DR0',
88 0x031: 'WRITE_DR1',
89 0x032: 'WRITE_DR2',
90 0x033: 'WRITE_DR3',
91 0x034: 'WRITE_DR4',
92 0x035: 'WRITE_DR5',
93 0x036: 'WRITE_DR6',
94 0x037: 'WRITE_DR7',
95 0x040: 'EXCP_BASE',
96 0x060: 'INTR',
97 0x061: 'NMI',
98 0x062: 'SMI',
99 0x063: 'INIT',
100 0x064: 'VINTR',
101 0x065: 'CR0_SEL_WRITE',
102 0x066: 'IDTR_READ',
103 0x067: 'GDTR_READ',
104 0x068: 'LDTR_READ',
105 0x069: 'TR_READ',
106 0x06a: 'IDTR_WRITE',
107 0x06b: 'GDTR_WRITE',
108 0x06c: 'LDTR_WRITE',
109 0x06d: 'TR_WRITE',
110 0x06e: 'RDTSC',
111 0x06f: 'RDPMC',
112 0x070: 'PUSHF',
113 0x071: 'POPF',
114 0x072: 'CPUID',
115 0x073: 'RSM',
116 0x074: 'IRET',
117 0x075: 'SWINT',
118 0x076: 'INVD',
119 0x077: 'PAUSE',
120 0x078: 'HLT',
121 0x079: 'INVLPG',
122 0x07a: 'INVLPGA',
123 0x07b: 'IOIO',
124 0x07c: 'MSR',
125 0x07d: 'TASK_SWITCH',
126 0x07e: 'FERR_FREEZE',
127 0x07f: 'SHUTDOWN',
128 0x080: 'VMRUN',
129 0x081: 'VMMCALL',
130 0x082: 'VMLOAD',
131 0x083: 'VMSAVE',
132 0x084: 'STGI',
133 0x085: 'CLGI',
134 0x086: 'SKINIT',
135 0x087: 'RDTSCP',
136 0x088: 'ICEBP',
137 0x089: 'WBINVD',
138 0x08a: 'MONITOR',
139 0x08b: 'MWAIT',
140 0x08c: 'MWAIT_COND',
141 0x400: 'NPF',
142}
143
Michael Ellerman27d318a2014-06-17 17:54:31 +1000144# From include/uapi/linux/kvm.h, KVM_EXIT_xxx
145userspace_exit_reasons = {
146 0: 'UNKNOWN',
147 1: 'EXCEPTION',
148 2: 'IO',
149 3: 'HYPERCALL',
150 4: 'DEBUG',
151 5: 'HLT',
152 6: 'MMIO',
153 7: 'IRQ_WINDOW_OPEN',
154 8: 'SHUTDOWN',
155 9: 'FAIL_ENTRY',
156 10: 'INTR',
157 11: 'SET_TPR',
158 12: 'TPR_ACCESS',
159 13: 'S390_SIEIC',
160 14: 'S390_RESET',
161 15: 'DCR',
162 16: 'NMI',
163 17: 'INTERNAL_ERROR',
164 18: 'OSI',
165 19: 'PAPR_HCALL',
166 20: 'S390_UCONTROL',
167 21: 'WATCHDOG',
168 22: 'S390_TSCH',
169 23: 'EPR',
Jens Freimannc5854ac2012-06-06 02:05:18 +0000170}
171
Jan Kiszka626c4272011-10-07 09:37:49 +0200172vendor_exit_reasons = {
173 'vmx': vmx_exit_reasons,
174 'svm': svm_exit_reasons,
175}
176
Heinz Graalfs1b3e6f82012-10-29 02:13:20 +0000177syscall_numbers = {
178 'IBM/S390': 331,
179}
180
181sc_perf_evt_open = 298
182
Jan Kiszka626c4272011-10-07 09:37:49 +0200183exit_reasons = None
184
185for line in file('/proc/cpuinfo').readlines():
Jens Freimannc5854ac2012-06-06 02:05:18 +0000186 if line.startswith('flags') or line.startswith('vendor_id'):
Jan Kiszka626c4272011-10-07 09:37:49 +0200187 for flag in line.split():
188 if flag in vendor_exit_reasons:
189 exit_reasons = vendor_exit_reasons[flag]
Heinz Graalfs1b3e6f82012-10-29 02:13:20 +0000190 if flag in syscall_numbers:
191 sc_perf_evt_open = syscall_numbers[flag]
Jan Kiszka626c4272011-10-07 09:37:49 +0200192
193def invert(d):
194 return dict((x[1], x[0]) for x in d.iteritems())
195
Michael Ellerman27d318a2014-06-17 17:54:31 +1000196filters = {}
197filters['kvm_userspace_exit'] = ('reason', invert(userspace_exit_reasons))
198if exit_reasons:
199 filters['kvm_exit'] = ('exit_reason', invert(exit_reasons))
Jan Kiszka626c4272011-10-07 09:37:49 +0200200
201import ctypes, struct, array
202
203libc = ctypes.CDLL('libc.so.6')
204syscall = libc.syscall
205class perf_event_attr(ctypes.Structure):
206 _fields_ = [('type', ctypes.c_uint32),
207 ('size', ctypes.c_uint32),
208 ('config', ctypes.c_uint64),
209 ('sample_freq', ctypes.c_uint64),
210 ('sample_type', ctypes.c_uint64),
211 ('read_format', ctypes.c_uint64),
212 ('flags', ctypes.c_uint64),
213 ('wakeup_events', ctypes.c_uint32),
214 ('bp_type', ctypes.c_uint32),
215 ('bp_addr', ctypes.c_uint64),
216 ('bp_len', ctypes.c_uint64),
217 ]
218def _perf_event_open(attr, pid, cpu, group_fd, flags):
Heinz Graalfs1b3e6f82012-10-29 02:13:20 +0000219 return syscall(sc_perf_evt_open, ctypes.pointer(attr), ctypes.c_int(pid),
Jan Kiszka626c4272011-10-07 09:37:49 +0200220 ctypes.c_int(cpu), ctypes.c_int(group_fd),
221 ctypes.c_long(flags))
222
223PERF_TYPE_HARDWARE = 0
224PERF_TYPE_SOFTWARE = 1
225PERF_TYPE_TRACEPOINT = 2
226PERF_TYPE_HW_CACHE = 3
227PERF_TYPE_RAW = 4
228PERF_TYPE_BREAKPOINT = 5
229
230PERF_SAMPLE_IP = 1 << 0
231PERF_SAMPLE_TID = 1 << 1
232PERF_SAMPLE_TIME = 1 << 2
233PERF_SAMPLE_ADDR = 1 << 3
234PERF_SAMPLE_READ = 1 << 4
235PERF_SAMPLE_CALLCHAIN = 1 << 5
236PERF_SAMPLE_ID = 1 << 6
237PERF_SAMPLE_CPU = 1 << 7
238PERF_SAMPLE_PERIOD = 1 << 8
239PERF_SAMPLE_STREAM_ID = 1 << 9
240PERF_SAMPLE_RAW = 1 << 10
241
242PERF_FORMAT_TOTAL_TIME_ENABLED = 1 << 0
243PERF_FORMAT_TOTAL_TIME_RUNNING = 1 << 1
244PERF_FORMAT_ID = 1 << 2
245PERF_FORMAT_GROUP = 1 << 3
246
247import re
248
249sys_tracing = '/sys/kernel/debug/tracing'
250
251class Group(object):
252 def __init__(self, cpu):
253 self.events = []
254 self.group_leader = None
255 self.cpu = cpu
256 def add_event(self, name, event_set, tracepoint, filter = None):
257 self.events.append(Event(group = self,
258 name = name, event_set = event_set,
259 tracepoint = tracepoint, filter = filter))
260 if len(self.events) == 1:
261 self.file = os.fdopen(self.events[0].fd)
262 def read(self):
263 bytes = 8 * (1 + len(self.events))
264 fmt = 'xxxxxxxx' + 'q' * len(self.events)
265 return dict(zip([event.name for event in self.events],
266 struct.unpack(fmt, self.file.read(bytes))))
267
268class Event(object):
269 def __init__(self, group, name, event_set, tracepoint, filter = None):
270 self.name = name
271 attr = perf_event_attr()
272 attr.type = PERF_TYPE_TRACEPOINT
273 attr.size = ctypes.sizeof(attr)
274 id_path = os.path.join(sys_tracing, 'events', event_set,
275 tracepoint, 'id')
276 id = int(file(id_path).read())
277 attr.config = id
278 attr.sample_type = (PERF_SAMPLE_RAW
279 | PERF_SAMPLE_TIME
280 | PERF_SAMPLE_CPU)
281 attr.sample_period = 1
282 attr.read_format = PERF_FORMAT_GROUP
283 group_leader = -1
284 if group.events:
285 group_leader = group.events[0].fd
286 fd = _perf_event_open(attr, -1, group.cpu, group_leader, 0)
287 if fd == -1:
288 raise Exception('perf_event_open failed')
289 if filter:
290 import fcntl
291 fcntl.ioctl(fd, 0x40082406, filter)
292 self.fd = fd
293 def enable(self):
294 import fcntl
295 fcntl.ioctl(self.fd, 0x00002400, 0)
296 def disable(self):
297 import fcntl
298 fcntl.ioctl(self.fd, 0x00002401, 0)
299
300class TracepointProvider(object):
301 def __init__(self):
302 path = os.path.join(sys_tracing, 'events', 'kvm')
303 fields = [f
304 for f in os.listdir(path)
305 if os.path.isdir(os.path.join(path, f))]
306 extra = []
307 for f in fields:
308 if f in filters:
309 subfield, values = filters[f]
310 for name, number in values.iteritems():
311 extra.append(f + '(' + name + ')')
312 fields += extra
313 self._setup(fields)
314 self.select(fields)
315 def fields(self):
316 return self._fields
Michael Ellerman763952d2014-06-17 17:54:30 +1000317
318 def _online_cpus(self):
319 l = []
320 pattern = r'cpu([0-9]+)'
321 basedir = '/sys/devices/system/cpu'
322 for entry in os.listdir(basedir):
323 match = re.match(pattern, entry)
324 if not match:
325 continue
326 path = os.path.join(basedir, entry, 'online')
327 if os.path.exists(path) and open(path).read().strip() != '1':
328 continue
329 l.append(int(match.group(1)))
330 return l
331
Jan Kiszka626c4272011-10-07 09:37:49 +0200332 def _setup(self, _fields):
333 self._fields = _fields
Michael Ellerman763952d2014-06-17 17:54:30 +1000334 cpus = self._online_cpus()
Jan Kiszka626c4272011-10-07 09:37:49 +0200335 import resource
Michael Ellerman763952d2014-06-17 17:54:30 +1000336 nfiles = len(cpus) * 1000
Jan Kiszka626c4272011-10-07 09:37:49 +0200337 resource.setrlimit(resource.RLIMIT_NOFILE, (nfiles, nfiles))
338 events = []
339 self.group_leaders = []
Michael Ellerman763952d2014-06-17 17:54:30 +1000340 for cpu in cpus:
Jan Kiszka626c4272011-10-07 09:37:49 +0200341 group = Group(cpu)
342 for name in _fields:
343 tracepoint = name
344 filter = None
345 m = re.match(r'(.*)\((.*)\)', name)
346 if m:
347 tracepoint, sub = m.groups()
348 filter = '%s==%d\0' % (filters[tracepoint][0],
349 filters[tracepoint][1][sub])
350 event = group.add_event(name, event_set = 'kvm',
351 tracepoint = tracepoint,
352 filter = filter)
353 self.group_leaders.append(group)
354 def select(self, fields):
355 for group in self.group_leaders:
356 for event in group.events:
357 if event.name in fields:
358 event.enable()
359 else:
360 event.disable()
361 def read(self):
362 from collections import defaultdict
363 ret = defaultdict(int)
364 for group in self.group_leaders:
365 for name, val in group.read().iteritems():
366 ret[name] += val
367 return ret
368
369class Stats:
Paolo Bonzinib763adf2014-05-21 12:42:26 +0200370 def __init__(self, providers, fields = None):
371 self.providers = providers
Jan Kiszka626c4272011-10-07 09:37:49 +0200372 self.fields_filter = fields
373 self._update()
374 def _update(self):
375 def wanted(key):
376 import re
377 if not self.fields_filter:
378 return True
379 return re.match(self.fields_filter, key) is not None
Paolo Bonzinib763adf2014-05-21 12:42:26 +0200380 self.values = dict()
381 for d in providers:
382 provider_fields = [key for key in d.fields() if wanted(key)]
383 for key in provider_fields:
384 self.values[key] = None
385 d.select(provider_fields)
Jan Kiszka626c4272011-10-07 09:37:49 +0200386 def set_fields_filter(self, fields_filter):
387 self.fields_filter = fields_filter
388 self._update()
389 def get(self):
Paolo Bonzinib763adf2014-05-21 12:42:26 +0200390 for d in providers:
391 new = d.read()
392 for key in d.fields():
393 oldval = self.values.get(key, (0, 0))
394 newval = new[key]
395 newdelta = None
396 if oldval is not None:
397 newdelta = newval - oldval[0]
398 self.values[key] = (newval, newdelta)
Jan Kiszka626c4272011-10-07 09:37:49 +0200399 return self.values
400
401if not os.access('/sys/kernel/debug', os.F_OK):
402 print 'Please enable CONFIG_DEBUG_FS in your kernel'
403 sys.exit(1)
404if not os.access('/sys/kernel/debug/kvm', os.F_OK):
405 print "Please mount debugfs ('mount -t debugfs debugfs /sys/kernel/debug')"
406 print "and ensure the kvm modules are loaded"
407 sys.exit(1)
408
409label_width = 40
410number_width = 10
411
412def tui(screen, stats):
413 curses.use_default_colors()
414 curses.noecho()
415 drilldown = False
416 fields_filter = stats.fields_filter
417 def update_drilldown():
418 if not fields_filter:
419 if drilldown:
420 stats.set_fields_filter(None)
421 else:
422 stats.set_fields_filter(r'^[^\(]*$')
423 update_drilldown()
424 def refresh(sleeptime):
425 screen.erase()
426 screen.addstr(0, 0, 'kvm statistics')
427 row = 2
428 s = stats.get()
429 def sortkey(x):
430 if s[x][1]:
431 return (-s[x][1], -s[x][0])
432 else:
433 return (0, -s[x][0])
434 for key in sorted(s.keys(), key = sortkey):
435 if row >= screen.getmaxyx()[0]:
436 break
437 values = s[key]
438 if not values[0] and not values[1]:
439 break
440 col = 1
441 screen.addstr(row, col, key)
442 col += label_width
443 screen.addstr(row, col, '%10d' % (values[0],))
444 col += number_width
445 if values[1] is not None:
446 screen.addstr(row, col, '%8d' % (values[1] / sleeptime,))
447 row += 1
448 screen.refresh()
449
450 sleeptime = 0.25
451 while True:
452 refresh(sleeptime)
453 curses.halfdelay(int(sleeptime * 10))
454 sleeptime = 3
455 try:
456 c = screen.getkey()
457 if c == 'x':
458 drilldown = not drilldown
459 update_drilldown()
460 if c == 'q':
461 break
462 except KeyboardInterrupt:
463 break
464 except curses.error:
465 continue
466
467def batch(stats):
468 s = stats.get()
469 time.sleep(1)
470 s = stats.get()
471 for key in sorted(s.keys()):
472 values = s[key]
473 print '%-22s%10d%10d' % (key, values[0], values[1])
474
475def log(stats):
476 keys = sorted(stats.get().iterkeys())
477 def banner():
478 for k in keys:
479 print '%10s' % k[0:9],
480 print
481 def statline():
482 s = stats.get()
483 for k in keys:
484 print ' %9d' % s[k][1],
485 print
486 line = 0
487 banner_repeat = 20
488 while True:
489 time.sleep(1)
490 if line % banner_repeat == 0:
491 banner()
492 statline()
493 line += 1
494
495options = optparse.OptionParser()
496options.add_option('-1', '--once', '--batch',
497 action = 'store_true',
498 default = False,
499 dest = 'once',
500 help = 'run in batch mode for one second',
501 )
502options.add_option('-l', '--log',
503 action = 'store_true',
504 default = False,
505 dest = 'log',
506 help = 'run in logging mode (like vmstat)',
507 )
Paolo Bonzinib763adf2014-05-21 12:42:26 +0200508options.add_option('-t', '--tracepoints',
509 action = 'store_true',
510 default = False,
511 dest = 'tracepoints',
512 help = 'retrieve statistics from tracepoints',
513 )
514options.add_option('-d', '--debugfs',
515 action = 'store_true',
516 default = False,
517 dest = 'debugfs',
518 help = 'retrieve statistics from debugfs',
519 )
Jan Kiszka626c4272011-10-07 09:37:49 +0200520options.add_option('-f', '--fields',
521 action = 'store',
522 default = None,
523 dest = 'fields',
524 help = 'fields to display (regex)',
525 )
526(options, args) = options.parse_args(sys.argv)
527
Paolo Bonzinib763adf2014-05-21 12:42:26 +0200528providers = []
529if options.tracepoints:
530 providers.append(TracepointProvider())
531if options.debugfs:
532 providers.append(DebugfsProvider())
Jan Kiszka626c4272011-10-07 09:37:49 +0200533
Paolo Bonzinib763adf2014-05-21 12:42:26 +0200534if len(providers) == 0:
535 try:
536 providers = [TracepointProvider()]
537 except:
538 providers = [DebugfsProvider()]
539
540stats = Stats(providers, fields = options.fields)
Jan Kiszka626c4272011-10-07 09:37:49 +0200541
542if options.log:
543 log(stats)
544elif not options.once:
545 import curses.wrapper
546 curses.wrapper(tui, stats)
547else:
548 batch(stats)