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