3 # top-like utility for displaying kvm statistics
5 # Copyright 2006-2008 Qumranet Technologies
6 # Copyright 2008-2011 Red Hat, Inc.
9 # Avi Kivity <avi@redhat.com>
11 # This work is licensed under the terms of the GNU GPL, version 2. See
12 # the COPYING file in the top-level directory.
15 import sys
, os
, time
, optparse
17 class DebugfsProvider(object):
19 self
.base
= '/sys/kernel/debug/kvm'
20 self
._fields
= os
.listdir(self
.base
)
23 def select(self
, fields
):
27 return int(file(self
.base
+ '/' + key
).read())
28 return dict([(key
, val(key
)) for key
in self
._fields
])
32 1: 'EXTERNAL_INTERRUPT',
34 7: 'PENDING_INTERRUPT',
58 36: 'MWAIT_INSTRUCTION',
59 39: 'MONITOR_INSTRUCTION',
60 40: 'PAUSE_INSTRUCTION',
61 41: 'MCE_DURING_VMENTRY',
62 43: 'TPR_BELOW_THRESHOLD',
101 0x065: 'CR0_SEL_WRITE',
125 0x07d: 'TASK_SWITCH',
126 0x07e: 'FERR_FREEZE',
144 # From include/uapi/linux/kvm.h, KVM_EXIT_xxx
145 userspace_exit_reasons
= {
153 7: 'IRQ_WINDOW_OPEN',
163 17: 'INTERNAL_ERROR',
173 'vmx': vmx_exit_reasons
,
174 'svm': svm_exit_reasons
,
177 sc_perf_evt_open
= None
182 'sc_perf_evt_open' : 298,
183 'exit_reasons' : x86_exit_reasons
[flag
],
188 'sc_perf_evt_open' : 331
191 def detect_platform():
192 for line
in file('/proc/cpuinfo').readlines():
193 if line
.startswith('flags'):
194 for flag
in line
.split():
195 if flag
in x86_exit_reasons
:
198 elif line
.startswith('vendor_id'):
199 for flag
in line
.split():
200 if flag
== 'IBM/S390':
207 return dict((x
[1], x
[0]) for x
in d
.iteritems())
210 filters
['kvm_userspace_exit'] = ('reason', invert(userspace_exit_reasons
))
212 filters
['kvm_exit'] = ('exit_reason', invert(exit_reasons
))
214 import ctypes
, struct
, array
216 libc
= ctypes
.CDLL('libc.so.6')
217 syscall
= libc
.syscall
218 class perf_event_attr(ctypes
.Structure
):
219 _fields_
= [('type', ctypes
.c_uint32
),
220 ('size', ctypes
.c_uint32
),
221 ('config', ctypes
.c_uint64
),
222 ('sample_freq', ctypes
.c_uint64
),
223 ('sample_type', ctypes
.c_uint64
),
224 ('read_format', ctypes
.c_uint64
),
225 ('flags', ctypes
.c_uint64
),
226 ('wakeup_events', ctypes
.c_uint32
),
227 ('bp_type', ctypes
.c_uint32
),
228 ('bp_addr', ctypes
.c_uint64
),
229 ('bp_len', ctypes
.c_uint64
),
231 def _perf_event_open(attr
, pid
, cpu
, group_fd
, flags
):
232 return syscall(sc_perf_evt_open
, ctypes
.pointer(attr
), ctypes
.c_int(pid
),
233 ctypes
.c_int(cpu
), ctypes
.c_int(group_fd
),
234 ctypes
.c_long(flags
))
236 PERF_TYPE_HARDWARE
= 0
237 PERF_TYPE_SOFTWARE
= 1
238 PERF_TYPE_TRACEPOINT
= 2
239 PERF_TYPE_HW_CACHE
= 3
241 PERF_TYPE_BREAKPOINT
= 5
243 PERF_SAMPLE_IP
= 1 << 0
244 PERF_SAMPLE_TID
= 1 << 1
245 PERF_SAMPLE_TIME
= 1 << 2
246 PERF_SAMPLE_ADDR
= 1 << 3
247 PERF_SAMPLE_READ
= 1 << 4
248 PERF_SAMPLE_CALLCHAIN
= 1 << 5
249 PERF_SAMPLE_ID
= 1 << 6
250 PERF_SAMPLE_CPU
= 1 << 7
251 PERF_SAMPLE_PERIOD
= 1 << 8
252 PERF_SAMPLE_STREAM_ID
= 1 << 9
253 PERF_SAMPLE_RAW
= 1 << 10
255 PERF_FORMAT_TOTAL_TIME_ENABLED
= 1 << 0
256 PERF_FORMAT_TOTAL_TIME_RUNNING
= 1 << 1
257 PERF_FORMAT_ID
= 1 << 2
258 PERF_FORMAT_GROUP
= 1 << 3
262 sys_tracing
= '/sys/kernel/debug/tracing'
265 def __init__(self
, cpu
):
267 self
.group_leader
= None
269 def add_event(self
, name
, event_set
, tracepoint
, filter = None):
270 self
.events
.append(Event(group
= self
,
271 name
= name
, event_set
= event_set
,
272 tracepoint
= tracepoint
, filter = filter))
273 if len(self
.events
) == 1:
274 self
.file = os
.fdopen(self
.events
[0].fd
)
276 bytes
= 8 * (1 + len(self
.events
))
277 fmt
= 'xxxxxxxx' + 'q' * len(self
.events
)
278 return dict(zip([event
.name
for event
in self
.events
],
279 struct
.unpack(fmt
, self
.file.read(bytes
))))
282 def __init__(self
, group
, name
, event_set
, tracepoint
, filter = None):
284 attr
= perf_event_attr()
285 attr
.type = PERF_TYPE_TRACEPOINT
286 attr
.size
= ctypes
.sizeof(attr
)
287 id_path
= os
.path
.join(sys_tracing
, 'events', event_set
,
289 id = int(file(id_path
).read())
291 attr
.sample_type
= (PERF_SAMPLE_RAW
294 attr
.sample_period
= 1
295 attr
.read_format
= PERF_FORMAT_GROUP
298 group_leader
= group
.events
[0].fd
299 fd
= _perf_event_open(attr
, -1, group
.cpu
, group_leader
, 0)
301 raise Exception('perf_event_open failed')
304 fcntl
.ioctl(fd
, 0x40082406, filter)
308 fcntl
.ioctl(self
.fd
, 0x00002400, 0)
311 fcntl
.ioctl(self
.fd
, 0x00002401, 0)
313 class TracepointProvider(object):
315 path
= os
.path
.join(sys_tracing
, 'events', 'kvm')
317 for f
in os
.listdir(path
)
318 if os
.path
.isdir(os
.path
.join(path
, f
))]
322 subfield
, values
= filters
[f
]
323 for name
, number
in values
.iteritems():
324 extra
.append(f
+ '(' + name
+ ')')
331 def _online_cpus(self
):
333 pattern
= r
'cpu([0-9]+)'
334 basedir
= '/sys/devices/system/cpu'
335 for entry
in os
.listdir(basedir
):
336 match
= re
.match(pattern
, entry
)
339 path
= os
.path
.join(basedir
, entry
, 'online')
340 if os
.path
.exists(path
) and open(path
).read().strip() != '1':
342 l
.append(int(match
.group(1)))
345 def _setup(self
, _fields
):
346 self
._fields
= _fields
347 cpus
= self
._online
_cpus
()
349 nfiles
= len(cpus
) * 1000
350 resource
.setrlimit(resource
.RLIMIT_NOFILE
, (nfiles
, nfiles
))
352 self
.group_leaders
= []
358 m
= re
.match(r
'(.*)\((.*)\)', name
)
360 tracepoint
, sub
= m
.groups()
361 filter = '%s==%d\0' % (filters
[tracepoint
][0],
362 filters
[tracepoint
][1][sub
])
363 event
= group
.add_event(name
, event_set
= 'kvm',
364 tracepoint
= tracepoint
,
366 self
.group_leaders
.append(group
)
367 def select(self
, fields
):
368 for group
in self
.group_leaders
:
369 for event
in group
.events
:
370 if event
.name
in fields
:
375 from collections
import defaultdict
376 ret
= defaultdict(int)
377 for group
in self
.group_leaders
:
378 for name
, val
in group
.read().iteritems():
383 def __init__(self
, providers
, fields
= None):
384 self
.providers
= providers
385 self
.fields_filter
= fields
390 if not self
.fields_filter
:
392 return re
.match(self
.fields_filter
, key
) is not None
395 provider_fields
= [key
for key
in d
.fields() if wanted(key
)]
396 for key
in provider_fields
:
397 self
.values
[key
] = None
398 d
.select(provider_fields
)
399 def set_fields_filter(self
, fields_filter
):
400 self
.fields_filter
= fields_filter
405 for key
in d
.fields():
406 oldval
= self
.values
.get(key
, (0, 0))
409 if oldval
is not None:
410 newdelta
= newval
- oldval
[0]
411 self
.values
[key
] = (newval
, newdelta
)
414 if not os
.access('/sys/kernel/debug', os
.F_OK
):
415 print 'Please enable CONFIG_DEBUG_FS in your kernel'
417 if not os
.access('/sys/kernel/debug/kvm', os
.F_OK
):
418 print "Please mount debugfs ('mount -t debugfs debugfs /sys/kernel/debug')"
419 print "and ensure the kvm modules are loaded"
425 def tui(screen
, stats
):
426 curses
.use_default_colors()
429 fields_filter
= stats
.fields_filter
430 def update_drilldown():
431 if not fields_filter
:
433 stats
.set_fields_filter(None)
435 stats
.set_fields_filter(r
'^[^\(]*$')
437 def refresh(sleeptime
):
439 screen
.addstr(0, 0, 'kvm statistics')
444 return (-s
[x
][1], -s
[x
][0])
447 for key
in sorted(s
.keys(), key
= sortkey
):
448 if row
>= screen
.getmaxyx()[0]:
451 if not values
[0] and not values
[1]:
454 screen
.addstr(row
, col
, key
)
456 screen
.addstr(row
, col
, '%10d' % (values
[0],))
458 if values
[1] is not None:
459 screen
.addstr(row
, col
, '%8d' % (values
[1] / sleeptime
,))
466 curses
.halfdelay(int(sleeptime
* 10))
471 drilldown
= not drilldown
475 except KeyboardInterrupt:
484 for key
in sorted(s
.keys()):
486 print '%-22s%10d%10d' % (key
, values
[0], values
[1])
489 keys
= sorted(stats
.get().iterkeys())
492 print '%10s' % k
[0:9],
497 print ' %9d' % s
[k
][1],
503 if line
% banner_repeat
== 0:
508 options
= optparse
.OptionParser()
509 options
.add_option('-1', '--once', '--batch',
510 action
= 'store_true',
513 help = 'run in batch mode for one second',
515 options
.add_option('-l', '--log',
516 action
= 'store_true',
519 help = 'run in logging mode (like vmstat)',
521 options
.add_option('-t', '--tracepoints',
522 action
= 'store_true',
524 dest
= 'tracepoints',
525 help = 'retrieve statistics from tracepoints',
527 options
.add_option('-d', '--debugfs',
528 action
= 'store_true',
531 help = 'retrieve statistics from debugfs',
533 options
.add_option('-f', '--fields',
537 help = 'fields to display (regex)',
539 (options
, args
) = options
.parse_args(sys
.argv
)
542 if options
.tracepoints
:
543 providers
.append(TracepointProvider())
545 providers
.append(DebugfsProvider())
547 if len(providers
) == 0:
549 providers
= [TracepointProvider()]
551 providers
= [DebugfsProvider()]
553 stats
= Stats(providers
, fields
= options
.fields
)
557 elif not options
.once
:
558 import curses
.wrapper
559 curses
.wrapper(tui
, stats
)