4 import sys
, os
, time
, optparse
6 class DebugfsProvider(object):
8 self
.base
= '/sys/kernel/debug/kvm'
9 self
._fields
= os
.listdir(self
.base
)
12 def select(self
, fields
):
16 return int(file(self
.base
+ '/' + key
).read())
17 return dict([(key
, val(key
)) for key
in self
._fields
])
21 1: 'EXTERNAL_INTERRUPT',
23 7: 'PENDING_INTERRUPT',
47 36: 'MWAIT_INSTRUCTION',
48 39: 'MONITOR_INSTRUCTION',
49 40: 'PAUSE_INSTRUCTION',
50 41: 'MCE_DURING_VMENTRY',
51 43: 'TPR_BELOW_THRESHOLD',
90 0x065: 'CR0_SEL_WRITE',
114 0x07d: 'TASK_SWITCH',
115 0x07e: 'FERR_FREEZE',
133 vendor_exit_reasons
= {
134 'vmx': vmx_exit_reasons
,
135 'svm': svm_exit_reasons
,
140 for line
in file('/proc/cpuinfo').readlines():
141 if line
.startswith('flags'):
142 for flag
in line
.split():
143 if flag
in vendor_exit_reasons
:
144 exit_reasons
= vendor_exit_reasons
[flag
]
147 'kvm_exit': ('exit_reason', exit_reasons
)
151 return dict((x
[1], x
[0]) for x
in d
.iteritems())
154 filters
[f
] = (filters
[f
][0], invert(filters
[f
][1]))
156 import ctypes
, struct
, array
158 libc
= ctypes
.CDLL('libc.so.6')
159 syscall
= libc
.syscall
160 class perf_event_attr(ctypes
.Structure
):
161 _fields_
= [('type', ctypes
.c_uint32
),
162 ('size', ctypes
.c_uint32
),
163 ('config', ctypes
.c_uint64
),
164 ('sample_freq', ctypes
.c_uint64
),
165 ('sample_type', ctypes
.c_uint64
),
166 ('read_format', ctypes
.c_uint64
),
167 ('flags', ctypes
.c_uint64
),
168 ('wakeup_events', ctypes
.c_uint32
),
169 ('bp_type', ctypes
.c_uint32
),
170 ('bp_addr', ctypes
.c_uint64
),
171 ('bp_len', ctypes
.c_uint64
),
173 def _perf_event_open(attr
, pid
, cpu
, group_fd
, flags
):
174 return syscall(298, ctypes
.pointer(attr
), ctypes
.c_int(pid
),
175 ctypes
.c_int(cpu
), ctypes
.c_int(group_fd
),
176 ctypes
.c_long(flags
))
178 PERF_TYPE_HARDWARE
= 0
179 PERF_TYPE_SOFTWARE
= 1
180 PERF_TYPE_TRACEPOINT
= 2
181 PERF_TYPE_HW_CACHE
= 3
183 PERF_TYPE_BREAKPOINT
= 5
185 PERF_SAMPLE_IP
= 1 << 0
186 PERF_SAMPLE_TID
= 1 << 1
187 PERF_SAMPLE_TIME
= 1 << 2
188 PERF_SAMPLE_ADDR
= 1 << 3
189 PERF_SAMPLE_READ
= 1 << 4
190 PERF_SAMPLE_CALLCHAIN
= 1 << 5
191 PERF_SAMPLE_ID
= 1 << 6
192 PERF_SAMPLE_CPU
= 1 << 7
193 PERF_SAMPLE_PERIOD
= 1 << 8
194 PERF_SAMPLE_STREAM_ID
= 1 << 9
195 PERF_SAMPLE_RAW
= 1 << 10
197 PERF_FORMAT_TOTAL_TIME_ENABLED
= 1 << 0
198 PERF_FORMAT_TOTAL_TIME_RUNNING
= 1 << 1
199 PERF_FORMAT_ID
= 1 << 2
200 PERF_FORMAT_GROUP
= 1 << 3
204 sys_tracing
= '/sys/kernel/debug/tracing'
207 def __init__(self
, cpu
):
209 self
.group_leader
= None
211 def add_event(self
, name
, event_set
, tracepoint
, filter = None):
212 self
.events
.append(Event(group
= self
,
213 name
= name
, event_set
= event_set
,
214 tracepoint
= tracepoint
, filter = filter))
215 if len(self
.events
) == 1:
216 self
.file = os
.fdopen(self
.events
[0].fd
)
218 bytes
= 8 * (1 + len(self
.events
))
219 fmt
= 'xxxxxxxx' + 'q' * len(self
.events
)
220 return dict(zip([event
.name
for event
in self
.events
],
221 struct
.unpack(fmt
, self
.file.read(bytes
))))
224 def __init__(self
, group
, name
, event_set
, tracepoint
, filter = None):
226 attr
= perf_event_attr()
227 attr
.type = PERF_TYPE_TRACEPOINT
228 attr
.size
= ctypes
.sizeof(attr
)
229 id_path
= os
.path
.join(sys_tracing
, 'events', event_set
,
231 id = int(file(id_path
).read())
233 attr
.sample_type
= (PERF_SAMPLE_RAW
236 attr
.sample_period
= 1
237 attr
.read_format
= PERF_FORMAT_GROUP
240 group_leader
= group
.events
[0].fd
241 fd
= _perf_event_open(attr
, -1, group
.cpu
, group_leader
, 0)
243 raise Exception('perf_event_open failed')
246 fcntl
.ioctl(fd
, 0x40082406, filter)
250 fcntl
.ioctl(self
.fd
, 0x00002400, 0)
253 fcntl
.ioctl(self
.fd
, 0x00002401, 0)
255 class TracepointProvider(object):
257 path
= os
.path
.join(sys_tracing
, 'events', 'kvm')
259 for f
in os
.listdir(path
)
260 if os
.path
.isdir(os
.path
.join(path
, f
))]
264 subfield
, values
= filters
[f
]
265 for name
, number
in values
.iteritems():
266 extra
.append(f
+ '(' + name
+ ')')
271 def select(self
, _fields
):
272 self
._fields
= _fields
273 cpure
= r
'cpu([0-9]+)'
274 self
.cpus
= [int(re
.match(cpure
, x
).group(1))
275 for x
in os
.listdir('/sys/devices/system/cpu')
276 if re
.match(cpure
, x
)]
278 nfiles
= len(self
.cpus
) * 1000
279 resource
.setrlimit(resource
.RLIMIT_NOFILE
, (nfiles
, nfiles
))
281 self
.group_leaders
= []
282 for cpu
in self
.cpus
:
287 m
= re
.match(r
'(.*)\((.*)\)', name
)
289 tracepoint
, sub
= m
.groups()
290 filter = '%s==%d\0' % (filters
[tracepoint
][0],
291 filters
[tracepoint
][1][sub
])
292 event
= group
.add_event(name
, event_set
= 'kvm',
293 tracepoint
= tracepoint
,
295 self
.group_leaders
.append(group
)
297 from collections
import defaultdict
298 ret
= defaultdict(int)
299 for group
in self
.group_leaders
:
300 for name
, val
in group
.read().iteritems():
305 def __init__(self
, provider
, fields
= None):
310 return re
.match(fields
, key
) != None
311 self
.provider
= provider
312 self
.values
= dict([(key
, None)
313 for key
in provider
.fields()
315 self
.provider
.select(self
.values
.keys())
317 new
= self
.provider
.read()
318 for key
in self
.provider
.fields():
319 oldval
= self
.values
[key
]
322 if oldval
is not None:
323 newdelta
= newval
- oldval
[0]
324 self
.values
[key
] = (newval
, newdelta
)
327 if not os
.access('/sys/kernel/debug', os
.F_OK
):
328 print 'Please enable CONFIG_DEBUG_FS in your kernel'
330 if not os
.access('/sys/kernel/debug/kvm', os
.F_OK
):
331 print "Please mount debugfs ('mount -t debugfs debugfs /sys/kernel/debug')"
332 print "and ensure the kvm modules are loaded"
338 def tui(screen
, stats
):
339 curses
.use_default_colors()
341 def refresh(sleeptime
):
343 screen
.addstr(0, 0, 'kvm statistics')
348 return (-s
[x
][1], -s
[x
][0])
351 for key
in sorted(s
.keys(), key
= sortkey
):
352 if row
>= screen
.getmaxyx()[0]:
355 if not values
[0] and not values
[1]:
358 screen
.addstr(row
, col
, key
)
360 screen
.addstr(row
, col
, '%10d' % (values
[0],))
362 if values
[1] is not None:
363 screen
.addstr(row
, col
, '%8d' % (values
[1] / sleeptime
,))
370 curses
.halfdelay(int(sleeptime
* 10))
376 except KeyboardInterrupt:
385 for key
in sorted(s
.keys()):
387 print '%-22s%10d%10d' % (key
, values
[0], values
[1])
390 keys
= sorted(stats
.get().iterkeys())
393 print '%10s' % k
[0:9],
398 print ' %9d' % s
[k
][1],
404 if line
% banner_repeat
== 0:
409 options
= optparse
.OptionParser()
410 options
.add_option('-1', '--once', '--batch',
411 action
= 'store_true',
414 help = 'run in batch mode for one second',
416 options
.add_option('-l', '--log',
417 action
= 'store_true',
420 help = 'run in logging mode (like vmstat)',
422 options
.add_option('-f', '--fields',
426 help = 'fields to display (regex)',
428 (options
, args
) = options
.parse_args(sys
.argv
)
431 provider
= TracepointProvider()
433 provider
= DebugfsProvider()
435 stats
= Stats(provider
, fields
= options
.fields
)
439 elif not options
.once
:
440 import curses
.wrapper
441 curses
.wrapper(tui
, stats
)