3 # top-like utility for displaying kvm statistics
5 # Copyright 2006-2008 Qumranet Technologies
6 # Copyright 2008-2011 Red Hat, Inc.
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 vendor_exit_reasons = {
145 'vmx': vmx_exit_reasons,
146 'svm': svm_exit_reasons,
151 for line in file('/proc/cpuinfo').readlines():
152 if line.startswith('flags'):
153 for flag in line.split():
154 if flag in vendor_exit_reasons:
155 exit_reasons = vendor_exit_reasons[flag]
158 'kvm_exit': ('exit_reason', exit_reasons)
162 return dict((x[1], x[0]) for x in d.iteritems())
165 filters[f] = (filters[f][0], invert(filters[f][1]))
167 import ctypes, struct, array
169 libc = ctypes.CDLL('libc.so.6')
170 syscall = libc.syscall
171 class perf_event_attr(ctypes.Structure):
172 _fields_ = [('type', ctypes.c_uint32),
173 ('size', ctypes.c_uint32),
174 ('config', ctypes.c_uint64),
175 ('sample_freq', ctypes.c_uint64),
176 ('sample_type', ctypes.c_uint64),
177 ('read_format', ctypes.c_uint64),
178 ('flags', ctypes.c_uint64),
179 ('wakeup_events', ctypes.c_uint32),
180 ('bp_type', ctypes.c_uint32),
181 ('bp_addr', ctypes.c_uint64),
182 ('bp_len', ctypes.c_uint64),
184 def _perf_event_open(attr, pid, cpu, group_fd, flags):
185 return syscall(298, ctypes.pointer(attr), ctypes.c_int(pid),
186 ctypes.c_int(cpu), ctypes.c_int(group_fd),
187 ctypes.c_long(flags))
189 PERF_TYPE_HARDWARE = 0
190 PERF_TYPE_SOFTWARE = 1
191 PERF_TYPE_TRACEPOINT = 2
192 PERF_TYPE_HW_CACHE = 3
194 PERF_TYPE_BREAKPOINT = 5
196 PERF_SAMPLE_IP = 1 << 0
197 PERF_SAMPLE_TID = 1 << 1
198 PERF_SAMPLE_TIME = 1 << 2
199 PERF_SAMPLE_ADDR = 1 << 3
200 PERF_SAMPLE_READ = 1 << 4
201 PERF_SAMPLE_CALLCHAIN = 1 << 5
202 PERF_SAMPLE_ID = 1 << 6
203 PERF_SAMPLE_CPU = 1 << 7
204 PERF_SAMPLE_PERIOD = 1 << 8
205 PERF_SAMPLE_STREAM_ID = 1 << 9
206 PERF_SAMPLE_RAW = 1 << 10
208 PERF_FORMAT_TOTAL_TIME_ENABLED = 1 << 0
209 PERF_FORMAT_TOTAL_TIME_RUNNING = 1 << 1
210 PERF_FORMAT_ID = 1 << 2
211 PERF_FORMAT_GROUP = 1 << 3
215 sys_tracing = '/sys/kernel/debug/tracing'
218 def __init__(self, cpu):
220 self.group_leader = None
222 def add_event(self, name, event_set, tracepoint, filter = None):
223 self.events.append(Event(group = self,
224 name = name, event_set = event_set,
225 tracepoint = tracepoint, filter = filter))
226 if len(self.events) == 1:
227 self.file = os.fdopen(self.events[0].fd)
229 bytes = 8 * (1 + len(self.events))
230 fmt = 'xxxxxxxx' + 'q' * len(self.events)
231 return dict(zip([event.name for event in self.events],
232 struct.unpack(fmt, self.file.read(bytes))))
235 def __init__(self, group, name, event_set, tracepoint, filter = None):
237 attr = perf_event_attr()
238 attr.type = PERF_TYPE_TRACEPOINT
239 attr.size = ctypes.sizeof(attr)
240 id_path = os.path.join(sys_tracing, 'events', event_set,
242 id = int(file(id_path).read())
244 attr.sample_type = (PERF_SAMPLE_RAW
247 attr.sample_period = 1
248 attr.read_format = PERF_FORMAT_GROUP
251 group_leader = group.events[0].fd
252 fd = _perf_event_open(attr, -1, group.cpu, group_leader, 0)
254 raise Exception('perf_event_open failed')
257 fcntl.ioctl(fd, 0x40082406, filter)
261 fcntl.ioctl(self.fd, 0x00002400, 0)
264 fcntl.ioctl(self.fd, 0x00002401, 0)
266 class TracepointProvider(object):
268 path = os.path.join(sys_tracing, 'events', 'kvm')
270 for f in os.listdir(path)
271 if os.path.isdir(os.path.join(path, f))]
275 subfield, values = filters[f]
276 for name, number in values.iteritems():
277 extra.append(f + '(' + name + ')')
283 def _setup(self, _fields):
284 self._fields = _fields
285 cpure = r'cpu([0-9]+)'
286 self.cpus = [int(re.match(cpure, x).group(1))
287 for x in os.listdir('/sys/devices/system/cpu')
288 if re.match(cpure, x)]
290 nfiles = len(self.cpus) * 1000
291 resource.setrlimit(resource.RLIMIT_NOFILE, (nfiles, nfiles))
293 self.group_leaders = []
294 for cpu in self.cpus:
299 m = re.match(r'(.*)\((.*)\)', name)
301 tracepoint, sub = m.groups()
302 filter = '%s==%d\0' % (filters[tracepoint][0],
303 filters[tracepoint][1][sub])
304 event = group.add_event(name, event_set = 'kvm',
305 tracepoint = tracepoint,
307 self.group_leaders.append(group)
308 def select(self, fields):
309 for group in self.group_leaders:
310 for event in group.events:
311 if event.name in fields:
316 from collections import defaultdict
317 ret = defaultdict(int)
318 for group in self.group_leaders:
319 for name, val in group.read().iteritems():
324 def __init__(self, provider, fields = None):
325 self.provider = provider
326 self.fields_filter = fields
331 if not self.fields_filter:
333 return re.match(self.fields_filter, key) is not None
334 self.values = dict([(key, None)
335 for key in provider.fields()
337 self.provider.select(self.values.keys())
338 def set_fields_filter(self, fields_filter):
339 self.fields_filter = fields_filter
342 new = self.provider.read()
343 for key in self.provider.fields():
344 oldval = self.values.get(key, (0, 0))
347 if oldval is not None:
348 newdelta = newval - oldval[0]
349 self.values[key] = (newval, newdelta)
352 if not os.access('/sys/kernel/debug', os.F_OK):
353 print 'Please enable CONFIG_DEBUG_FS in your kernel'
355 if not os.access('/sys/kernel/debug/kvm', os.F_OK):
356 print "Please mount debugfs ('mount -t debugfs debugfs /sys/kernel/debug')"
357 print "and ensure the kvm modules are loaded"
363 def tui(screen, stats):
364 curses.use_default_colors()
367 fields_filter = stats.fields_filter
368 def update_drilldown():
369 if not fields_filter:
371 stats.set_fields_filter(None)
373 stats.set_fields_filter(r'^[^\(]*$')
375 def refresh(sleeptime):
377 screen.addstr(0, 0, 'kvm statistics')
382 return (-s[x][1], -s[x][0])
385 for key in sorted(s.keys(), key = sortkey):
386 if row >= screen.getmaxyx()[0]:
389 if not values[0] and not values[1]:
392 screen.addstr(row, col, key)
394 screen.addstr(row, col, '%10d' % (values[0],))
396 if values[1] is not None:
397 screen.addstr(row, col, '%8d' % (values[1] / sleeptime,))
404 curses.halfdelay(int(sleeptime * 10))
409 drilldown = not drilldown
413 except KeyboardInterrupt:
422 for key in sorted(s.keys()):
424 print '%-22s%10d%10d' % (key, values[0], values[1])
427 keys = sorted(stats.get().iterkeys())
430 print '%10s' % k[0:9],
435 print ' %9d' % s[k][1],
441 if line % banner_repeat == 0:
446 options = optparse.OptionParser()
447 options.add_option('-1', '--once', '--batch',
448 action = 'store_true',
451 help = 'run in batch mode for one second',
453 options.add_option('-l', '--log',
454 action = 'store_true',
457 help = 'run in logging mode (like vmstat)',
459 options.add_option('-f', '--fields',
463 help = 'fields to display (regex)',
465 (options, args) = options.parse_args(sys.argv)
468 provider = TracepointProvider()
470 provider = DebugfsProvider()
472 stats = Stats(provider, fields = options.fields)
476 elif not options.once:
477 import curses.wrapper
478 curses.wrapper(tui, stats)