1#!/usr/bin/python
2#
3# Cpu task migration overview toy
4#
5# Copyright (C) 2010 Frederic Weisbecker <[email protected]>
6#
7# perf trace event handlers have been generated by perf trace -g python
8#
9# The whole is licensed under the terms of the GNU GPL License version 2
10
11
12try:
13	import wx
14except ImportError:
15	raise ImportError, "You need to install the wxpython lib for this script"
16
17import os
18import sys
19
20from collections import defaultdict
21from UserList import UserList
22
23sys.path.append(os.environ['PERF_EXEC_PATH'] + \
24	'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
25
26from perf_trace_context import *
27from Core import *
28
29class RootFrame(wx.Frame):
30	def __init__(self, timeslices, parent = None, id = -1, title = "Migration"):
31		wx.Frame.__init__(self, parent, id, title)
32
33		(self.screen_width, self.screen_height) = wx.GetDisplaySize()
34		self.screen_width -= 10
35		self.screen_height -= 10
36		self.zoom = 0.5
37		self.scroll_scale = 20
38		self.timeslices = timeslices
39		(self.ts_start, self.ts_end) = timeslices.interval()
40		self.update_width_virtual()
41
42		# whole window panel
43		self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height))
44
45		# scrollable container
46		self.scroll = wx.ScrolledWindow(self.panel)
47		self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, 100 / 10)
48		self.scroll.EnableScrolling(True, True)
49		self.scroll.SetFocus()
50
51		# scrollable drawing area
52		self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width, self.screen_height / 2))
53		self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint)
54		self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
55		self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
56		self.scroll.Bind(wx.EVT_PAINT, self.on_paint)
57
58		self.scroll.Fit()
59		self.Fit()
60
61		self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, -1, wx.SIZE_USE_EXISTING)
62
63		self.max_cpu = -1
64		self.txt = None
65
66		self.Show(True)
67
68	def us_to_px(self, val):
69		return val / (10 ** 3) * self.zoom
70
71	def px_to_us(self, val):
72		return (val / self.zoom) * (10 ** 3)
73
74	def scroll_start(self):
75		(x, y) = self.scroll.GetViewStart()
76		return (x * self.scroll_scale, y * self.scroll_scale)
77
78	def scroll_start_us(self):
79		(x, y) = self.scroll_start()
80		return self.px_to_us(x)
81
82	def update_rectangle_cpu(self, dc, slice, cpu, offset_time):
83		rq = slice.rqs[cpu]
84
85		if slice.total_load != 0:
86			load_rate = rq.load() / float(slice.total_load)
87		else:
88			load_rate = 0
89
90
91		offset_px = self.us_to_px(slice.start - offset_time)
92		width_px = self.us_to_px(slice.end - slice.start)
93		(x, y) = self.scroll_start()
94
95		if width_px == 0:
96			return
97
98		offset_py = 100 + (cpu * 150)
99		width_py = 100
100
101		if cpu in slice.event_cpus:
102			rgb = rq.event.color()
103			if rgb is not None:
104				(r, g, b) = rgb
105				color = wx.Colour(r, g, b)
106				brush = wx.Brush(color, wx.SOLID)
107				dc.SetBrush(brush)
108				dc.DrawRectangle(offset_px, offset_py, width_px, 5)
109				width_py -= 5
110				offset_py += 5
111
112		red_power = int(0xff - (0xff * load_rate))
113		color = wx.Colour(0xff, red_power, red_power)
114		brush = wx.Brush(color, wx.SOLID)
115		dc.SetBrush(brush)
116		dc.DrawRectangle(offset_px, offset_py, width_px, width_py)
117
118	def update_rectangles(self, dc, start, end):
119		if len(self.timeslices) == 0:
120			return
121		start += self.timeslices[0].start
122		end += self.timeslices[0].start
123
124		color = wx.Colour(0, 0, 0)
125		brush = wx.Brush(color, wx.SOLID)
126		dc.SetBrush(brush)
127
128		i = self.timeslices.find_time_slice(start)
129		if i == -1:
130			return
131
132		for i in xrange(i, len(self.timeslices)):
133			timeslice = self.timeslices[i]
134			if timeslice.start > end:
135				return
136
137			for cpu in timeslice.rqs:
138				self.update_rectangle_cpu(dc, timeslice, cpu, self.timeslices[0].start)
139				if cpu > self.max_cpu:
140					self.max_cpu = cpu
141
142	def on_paint(self, event):
143		color = wx.Colour(0xff, 0xff, 0xff)
144		brush = wx.Brush(color, wx.SOLID)
145		dc = wx.PaintDC(self.scroll_panel)
146		dc.SetBrush(brush)
147
148		width = min(self.width_virtual, self.screen_width)
149		(x, y) = self.scroll_start()
150		start = self.px_to_us(x)
151		end = self.px_to_us(x + width)
152		self.update_rectangles(dc, start, end)
153
154	def cpu_from_ypixel(self, y):
155		y -= 100
156		cpu = y / 150
157		height = y % 150
158
159		if cpu < 0 or cpu > self.max_cpu or height > 100:
160			return -1
161
162		return cpu
163
164	def update_summary(self, cpu, t):
165		idx = self.timeslices.find_time_slice(t)
166		if idx == -1:
167			return
168
169		ts = self.timeslices[idx]
170		rq = ts.rqs[cpu]
171		raw = "CPU: %d\n" % cpu
172		raw += "Last event : %s\n" % rq.event.__repr__()
173		raw += "Timestamp : %d.%06d\n" % (ts.start / (10 ** 9), (ts.start % (10 ** 9)) / 1000)
174		raw += "Duration : %6d us\n" % ((ts.end - ts.start) / (10 ** 6))
175		raw += "Load = %d\n" % rq.load()
176		for t in rq.tasks:
177			raw += "%s \n" % thread_name(t)
178
179		if self.txt:
180			self.txt.Destroy()
181		self.txt = wx.StaticText(self.panel, -1, raw, (0, (self.screen_height / 2) + 50))
182
183
184	def on_mouse_down(self, event):
185		(x, y) = event.GetPositionTuple()
186		cpu = self.cpu_from_ypixel(y)
187		if cpu == -1:
188			return
189
190		t = self.px_to_us(x) + self.timeslices[0].start
191
192		self.update_summary(cpu, t)
193
194
195	def update_width_virtual(self):
196		self.width_virtual = self.us_to_px(self.ts_end - self.ts_start)
197
198	def __zoom(self, x):
199		self.update_width_virtual()
200		(xpos, ypos) = self.scroll.GetViewStart()
201		xpos = self.us_to_px(x) / self.scroll_scale
202		self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, 100 / 10, xpos, ypos)
203		self.Refresh()
204
205	def zoom_in(self):
206		x = self.scroll_start_us()
207		self.zoom *= 2
208		self.__zoom(x)
209
210	def zoom_out(self):
211		x = self.scroll_start_us()
212		self.zoom /= 2
213		self.__zoom(x)
214
215
216	def on_key_press(self, event):
217		key = event.GetRawKeyCode()
218		if key == ord("+"):
219			self.zoom_in()
220			return
221		if key == ord("-"):
222			self.zoom_out()
223			return
224
225		key = event.GetKeyCode()
226		(x, y) = self.scroll.GetViewStart()
227		if key == wx.WXK_RIGHT:
228			self.scroll.Scroll(x + 1, y)
229		elif key == wx.WXK_LEFT:
230			self.scroll.Scroll(x -1, y)
231
232
233threads = { 0 : "idle"}
234
235def thread_name(pid):
236	return "%s:%d" % (threads[pid], pid)
237
238class EventHeaders:
239	def __init__(self, common_cpu, common_secs, common_nsecs,
240		     common_pid, common_comm):
241		self.cpu = common_cpu
242		self.secs = common_secs
243		self.nsecs = common_nsecs
244		self.pid = common_pid
245		self.comm = common_comm
246
247	def ts(self):
248		return (self.secs * (10 ** 9)) + self.nsecs
249
250	def ts_format(self):
251		return "%d.%d" % (self.secs, int(self.nsecs / 1000))
252
253
254def taskState(state):
255	states = {
256		0 : "R",
257		1 : "S",
258		2 : "D",
259		64: "DEAD"
260	}
261
262	if state not in states:
263		return "Unknown"
264
265	return states[state]
266
267
268class RunqueueEventUnknown:
269	@staticmethod
270	def color():
271		return None
272
273	def __repr__(self):
274		return "unknown"
275
276class RunqueueEventSleep:
277	@staticmethod
278	def color():
279		return (0, 0, 0xff)
280
281	def __init__(self, sleeper):
282		self.sleeper = sleeper
283
284	def __repr__(self):
285		return "%s gone to sleep" % thread_name(self.sleeper)
286
287class RunqueueEventWakeup:
288	@staticmethod
289	def color():
290		return (0xff, 0xff, 0)
291
292	def __init__(self, wakee):
293		self.wakee = wakee
294
295	def __repr__(self):
296		return "%s woke up" % thread_name(self.wakee)
297
298class RunqueueEventFork:
299	@staticmethod
300	def color():
301		return (0, 0xff, 0)
302
303	def __init__(self, child):
304		self.child = child
305
306	def __repr__(self):
307		return "new forked task %s" % thread_name(self.child)
308
309class RunqueueMigrateIn:
310	@staticmethod
311	def color():
312		return (0, 0xf0, 0xff)
313
314	def __init__(self, new):
315		self.new = new
316
317	def __repr__(self):
318		return "task migrated in %s" % thread_name(self.new)
319
320class RunqueueMigrateOut:
321	@staticmethod
322	def color():
323		return (0xff, 0, 0xff)
324
325	def __init__(self, old):
326		self.old = old
327
328	def __repr__(self):
329		return "task migrated out %s" % thread_name(self.old)
330
331class RunqueueSnapshot:
332	def __init__(self, tasks = [0], event = RunqueueEventUnknown()):
333		self.tasks = tuple(tasks)
334		self.event = event
335
336	def sched_switch(self, prev, prev_state, next):
337		event = RunqueueEventUnknown()
338
339		if taskState(prev_state) == "R" and next in self.tasks \
340			and prev in self.tasks:
341			return self
342
343		if taskState(prev_state) != "R":
344			event = RunqueueEventSleep(prev)
345
346		next_tasks = list(self.tasks[:])
347		if prev in self.tasks:
348			if taskState(prev_state) != "R":
349				next_tasks.remove(prev)
350		elif taskState(prev_state) == "R":
351			next_tasks.append(prev)
352
353		if next not in next_tasks:
354			next_tasks.append(next)
355
356		return RunqueueSnapshot(next_tasks, event)
357
358	def migrate_out(self, old):
359		if old not in self.tasks:
360			return self
361		next_tasks = [task for task in self.tasks if task != old]
362
363		return RunqueueSnapshot(next_tasks, RunqueueMigrateOut(old))
364
365	def __migrate_in(self, new, event):
366		if new in self.tasks:
367			self.event = event
368			return self
369		next_tasks = self.tasks[:] + tuple([new])
370
371		return RunqueueSnapshot(next_tasks, event)
372
373	def migrate_in(self, new):
374		return self.__migrate_in(new, RunqueueMigrateIn(new))
375
376	def wake_up(self, new):
377		return self.__migrate_in(new, RunqueueEventWakeup(new))
378
379	def wake_up_new(self, new):
380		return self.__migrate_in(new, RunqueueEventFork(new))
381
382	def load(self):
383		""" Provide the number of tasks on the runqueue.
384		    Don't count idle"""
385		return len(self.tasks) - 1
386
387	def __repr__(self):
388		ret = self.tasks.__repr__()
389		ret += self.origin_tostring()
390
391		return ret
392
393class TimeSlice:
394	def __init__(self, start, prev):
395		self.start = start
396		self.prev = prev
397		self.end = start
398		# cpus that triggered the event
399		self.event_cpus = []
400		if prev is not None:
401			self.total_load = prev.total_load
402			self.rqs = prev.rqs.copy()
403		else:
404			self.rqs = defaultdict(RunqueueSnapshot)
405			self.total_load = 0
406
407	def __update_total_load(self, old_rq, new_rq):
408		diff = new_rq.load() - old_rq.load()
409		self.total_load += diff
410
411	def sched_switch(self, ts_list, prev, prev_state, next, cpu):
412		old_rq = self.prev.rqs[cpu]
413		new_rq = old_rq.sched_switch(prev, prev_state, next)
414
415		if old_rq is new_rq:
416			return
417
418		self.rqs[cpu] = new_rq
419		self.__update_total_load(old_rq, new_rq)
420		ts_list.append(self)
421		self.event_cpus = [cpu]
422
423	def migrate(self, ts_list, new, old_cpu, new_cpu):
424		if old_cpu == new_cpu:
425			return
426		old_rq = self.prev.rqs[old_cpu]
427		out_rq = old_rq.migrate_out(new)
428		self.rqs[old_cpu] = out_rq
429		self.__update_total_load(old_rq, out_rq)
430
431		new_rq = self.prev.rqs[new_cpu]
432		in_rq = new_rq.migrate_in(new)
433		self.rqs[new_cpu] = in_rq
434		self.__update_total_load(new_rq, in_rq)
435
436		ts_list.append(self)
437
438		if old_rq is not out_rq:
439			self.event_cpus.append(old_cpu)
440		self.event_cpus.append(new_cpu)
441
442	def wake_up(self, ts_list, pid, cpu, fork):
443		old_rq = self.prev.rqs[cpu]
444		if fork:
445			new_rq = old_rq.wake_up_new(pid)
446		else:
447			new_rq = old_rq.wake_up(pid)
448
449		if new_rq is old_rq:
450			return
451		self.rqs[cpu] = new_rq
452		self.__update_total_load(old_rq, new_rq)
453		ts_list.append(self)
454		self.event_cpus = [cpu]
455
456	def next(self, t):
457		self.end = t
458		return TimeSlice(t, self)
459
460class TimeSliceList(UserList):
461	def __init__(self, arg = []):
462		self.data = arg
463
464	def get_time_slice(self, ts):
465		if len(self.data) == 0:
466			slice = TimeSlice(ts, TimeSlice(-1, None))
467		else:
468			slice = self.data[-1].next(ts)
469		return slice
470
471	def find_time_slice(self, ts):
472		start = 0
473		end = len(self.data)
474		found = -1
475		searching = True
476		while searching:
477			if start == end or start == end - 1:
478				searching = False
479
480			i = (end + start) / 2
481			if self.data[i].start <= ts and self.data[i].end >= ts:
482				found = i
483				end = i
484				continue
485
486			if self.data[i].end < ts:
487				start = i
488
489			elif self.data[i].start > ts:
490				end = i
491
492		return found
493
494	def interval(self):
495		if len(self.data) == 0:
496			return (0, 0)
497
498		return (self.data[0].start, self.data[-1].end)
499
500
501class SchedEventProxy:
502	def __init__(self):
503		self.current_tsk = defaultdict(lambda : -1)
504		self.timeslices = TimeSliceList()
505
506	def sched_switch(self, headers, prev_comm, prev_pid, prev_prio, prev_state,
507			 next_comm, next_pid, next_prio):
508		""" Ensure the task we sched out this cpu is really the one
509		    we logged. Otherwise we may have missed traces """
510
511		on_cpu_task = self.current_tsk[headers.cpu]
512
513		if on_cpu_task != -1 and on_cpu_task != prev_pid:
514			print "Sched switch event rejected ts: %s cpu: %d prev: %s(%d) next: %s(%d)" % \
515				(headers.ts_format(), headers.cpu, prev_comm, prev_pid, next_comm, next_pid)
516
517		threads[prev_pid] = prev_comm
518		threads[next_pid] = next_comm
519		self.current_tsk[headers.cpu] = next_pid
520
521		ts = self.timeslices.get_time_slice(headers.ts())
522		ts.sched_switch(self.timeslices, prev_pid, prev_state, next_pid, headers.cpu)
523
524	def migrate(self, headers, pid, prio, orig_cpu, dest_cpu):
525		ts = self.timeslices.get_time_slice(headers.ts())
526		ts.migrate(self.timeslices, pid, orig_cpu, dest_cpu)
527
528	def wake_up(self, headers, comm, pid, success, target_cpu, fork):
529		if success == 0:
530			return
531		ts = self.timeslices.get_time_slice(headers.ts())
532		ts.wake_up(self.timeslices, pid, target_cpu, fork)
533
534
535def trace_begin():
536	global parser
537	parser = SchedEventProxy()
538
539def trace_end():
540	app = wx.App(False)
541	timeslices = parser.timeslices
542	frame = RootFrame(timeslices)
543	app.MainLoop()
544
545def sched__sched_stat_runtime(event_name, context, common_cpu,
546	common_secs, common_nsecs, common_pid, common_comm,
547	comm, pid, runtime, vruntime):
548	pass
549
550def sched__sched_stat_iowait(event_name, context, common_cpu,
551	common_secs, common_nsecs, common_pid, common_comm,
552	comm, pid, delay):
553	pass
554
555def sched__sched_stat_sleep(event_name, context, common_cpu,
556	common_secs, common_nsecs, common_pid, common_comm,
557	comm, pid, delay):
558	pass
559
560def sched__sched_stat_wait(event_name, context, common_cpu,
561	common_secs, common_nsecs, common_pid, common_comm,
562	comm, pid, delay):
563	pass
564
565def sched__sched_process_fork(event_name, context, common_cpu,
566	common_secs, common_nsecs, common_pid, common_comm,
567	parent_comm, parent_pid, child_comm, child_pid):
568	pass
569
570def sched__sched_process_wait(event_name, context, common_cpu,
571	common_secs, common_nsecs, common_pid, common_comm,
572	comm, pid, prio):
573	pass
574
575def sched__sched_process_exit(event_name, context, common_cpu,
576	common_secs, common_nsecs, common_pid, common_comm,
577	comm, pid, prio):
578	pass
579
580def sched__sched_process_free(event_name, context, common_cpu,
581	common_secs, common_nsecs, common_pid, common_comm,
582	comm, pid, prio):
583	pass
584
585def sched__sched_migrate_task(event_name, context, common_cpu,
586	common_secs, common_nsecs, common_pid, common_comm,
587	comm, pid, prio, orig_cpu,
588	dest_cpu):
589	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
590				common_pid, common_comm)
591	parser.migrate(headers, pid, prio, orig_cpu, dest_cpu)
592
593def sched__sched_switch(event_name, context, common_cpu,
594	common_secs, common_nsecs, common_pid, common_comm,
595	prev_comm, prev_pid, prev_prio, prev_state,
596	next_comm, next_pid, next_prio):
597
598	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
599				common_pid, common_comm)
600	parser.sched_switch(headers, prev_comm, prev_pid, prev_prio, prev_state,
601			 next_comm, next_pid, next_prio)
602
603def sched__sched_wakeup_new(event_name, context, common_cpu,
604	common_secs, common_nsecs, common_pid, common_comm,
605	comm, pid, prio, success,
606	target_cpu):
607	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
608				common_pid, common_comm)
609	parser.wake_up(headers, comm, pid, success, target_cpu, 1)
610
611def sched__sched_wakeup(event_name, context, common_cpu,
612	common_secs, common_nsecs, common_pid, common_comm,
613	comm, pid, prio, success,
614	target_cpu):
615	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
616				common_pid, common_comm)
617	parser.wake_up(headers, comm, pid, success, target_cpu, 0)
618
619def sched__sched_wait_task(event_name, context, common_cpu,
620	common_secs, common_nsecs, common_pid, common_comm,
621	comm, pid, prio):
622	pass
623
624def sched__sched_kthread_stop_ret(event_name, context, common_cpu,
625	common_secs, common_nsecs, common_pid, common_comm,
626	ret):
627	pass
628
629def sched__sched_kthread_stop(event_name, context, common_cpu,
630	common_secs, common_nsecs, common_pid, common_comm,
631	comm, pid):
632	pass
633
634def trace_unhandled(event_name, context, common_cpu, common_secs, common_nsecs,
635		common_pid, common_comm):
636	pass
637