1#!/usr/bin/python
2#
3# Cpu task migration overview toy
4#
5# Copyright (C) 2010 Frederic Weisbecker <fweisbec@gmail.com>
6#
7# perf script event handlers have been generated by perf script -g python
8#
9# This software is distributed under the terms of the GNU General
10# Public License ("GPL") version 2 as published by the Free Software
11# Foundation.
12from __future__ import print_function
13
14import os
15import sys
16
17from collections import defaultdict
18try:
19    from UserList import UserList
20except ImportError:
21    # Python 3: UserList moved to the collections package
22    from collections import UserList
23
24sys.path.append(os.environ['PERF_EXEC_PATH'] + \
25	'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
26sys.path.append('scripts/python/Perf-Trace-Util/lib/Perf/Trace')
27
28from perf_trace_context import *
29from Core import *
30from SchedGui import *
31
32
33threads = { 0 : "idle"}
34
35def thread_name(pid):
36	return "%s:%d" % (threads[pid], pid)
37
38class RunqueueEventUnknown:
39	@staticmethod
40	def color():
41		return None
42
43	def __repr__(self):
44		return "unknown"
45
46class RunqueueEventSleep:
47	@staticmethod
48	def color():
49		return (0, 0, 0xff)
50
51	def __init__(self, sleeper):
52		self.sleeper = sleeper
53
54	def __repr__(self):
55		return "%s gone to sleep" % thread_name(self.sleeper)
56
57class RunqueueEventWakeup:
58	@staticmethod
59	def color():
60		return (0xff, 0xff, 0)
61
62	def __init__(self, wakee):
63		self.wakee = wakee
64
65	def __repr__(self):
66		return "%s woke up" % thread_name(self.wakee)
67
68class RunqueueEventFork:
69	@staticmethod
70	def color():
71		return (0, 0xff, 0)
72
73	def __init__(self, child):
74		self.child = child
75
76	def __repr__(self):
77		return "new forked task %s" % thread_name(self.child)
78
79class RunqueueMigrateIn:
80	@staticmethod
81	def color():
82		return (0, 0xf0, 0xff)
83
84	def __init__(self, new):
85		self.new = new
86
87	def __repr__(self):
88		return "task migrated in %s" % thread_name(self.new)
89
90class RunqueueMigrateOut:
91	@staticmethod
92	def color():
93		return (0xff, 0, 0xff)
94
95	def __init__(self, old):
96		self.old = old
97
98	def __repr__(self):
99		return "task migrated out %s" % thread_name(self.old)
100
101class RunqueueSnapshot:
102	def __init__(self, tasks = [0], event = RunqueueEventUnknown()):
103		self.tasks = tuple(tasks)
104		self.event = event
105
106	def sched_switch(self, prev, prev_state, next):
107		event = RunqueueEventUnknown()
108
109		if taskState(prev_state) == "R" and next in self.tasks \
110			and prev in self.tasks:
111			return self
112
113		if taskState(prev_state) != "R":
114			event = RunqueueEventSleep(prev)
115
116		next_tasks = list(self.tasks[:])
117		if prev in self.tasks:
118			if taskState(prev_state) != "R":
119				next_tasks.remove(prev)
120		elif taskState(prev_state) == "R":
121			next_tasks.append(prev)
122
123		if next not in next_tasks:
124			next_tasks.append(next)
125
126		return RunqueueSnapshot(next_tasks, event)
127
128	def migrate_out(self, old):
129		if old not in self.tasks:
130			return self
131		next_tasks = [task for task in self.tasks if task != old]
132
133		return RunqueueSnapshot(next_tasks, RunqueueMigrateOut(old))
134
135	def __migrate_in(self, new, event):
136		if new in self.tasks:
137			self.event = event
138			return self
139		next_tasks = self.tasks[:] + tuple([new])
140
141		return RunqueueSnapshot(next_tasks, event)
142
143	def migrate_in(self, new):
144		return self.__migrate_in(new, RunqueueMigrateIn(new))
145
146	def wake_up(self, new):
147		return self.__migrate_in(new, RunqueueEventWakeup(new))
148
149	def wake_up_new(self, new):
150		return self.__migrate_in(new, RunqueueEventFork(new))
151
152	def load(self):
153		""" Provide the number of tasks on the runqueue.
154		    Don't count idle"""
155		return len(self.tasks) - 1
156
157	def __repr__(self):
158		ret = self.tasks.__repr__()
159		ret += self.origin_tostring()
160
161		return ret
162
163class TimeSlice:
164	def __init__(self, start, prev):
165		self.start = start
166		self.prev = prev
167		self.end = start
168		# cpus that triggered the event
169		self.event_cpus = []
170		if prev is not None:
171			self.total_load = prev.total_load
172			self.rqs = prev.rqs.copy()
173		else:
174			self.rqs = defaultdict(RunqueueSnapshot)
175			self.total_load = 0
176
177	def __update_total_load(self, old_rq, new_rq):
178		diff = new_rq.load() - old_rq.load()
179		self.total_load += diff
180
181	def sched_switch(self, ts_list, prev, prev_state, next, cpu):
182		old_rq = self.prev.rqs[cpu]
183		new_rq = old_rq.sched_switch(prev, prev_state, next)
184
185		if old_rq is new_rq:
186			return
187
188		self.rqs[cpu] = new_rq
189		self.__update_total_load(old_rq, new_rq)
190		ts_list.append(self)
191		self.event_cpus = [cpu]
192
193	def migrate(self, ts_list, new, old_cpu, new_cpu):
194		if old_cpu == new_cpu:
195			return
196		old_rq = self.prev.rqs[old_cpu]
197		out_rq = old_rq.migrate_out(new)
198		self.rqs[old_cpu] = out_rq
199		self.__update_total_load(old_rq, out_rq)
200
201		new_rq = self.prev.rqs[new_cpu]
202		in_rq = new_rq.migrate_in(new)
203		self.rqs[new_cpu] = in_rq
204		self.__update_total_load(new_rq, in_rq)
205
206		ts_list.append(self)
207
208		if old_rq is not out_rq:
209			self.event_cpus.append(old_cpu)
210		self.event_cpus.append(new_cpu)
211
212	def wake_up(self, ts_list, pid, cpu, fork):
213		old_rq = self.prev.rqs[cpu]
214		if fork:
215			new_rq = old_rq.wake_up_new(pid)
216		else:
217			new_rq = old_rq.wake_up(pid)
218
219		if new_rq is old_rq:
220			return
221		self.rqs[cpu] = new_rq
222		self.__update_total_load(old_rq, new_rq)
223		ts_list.append(self)
224		self.event_cpus = [cpu]
225
226	def next(self, t):
227		self.end = t
228		return TimeSlice(t, self)
229
230class TimeSliceList(UserList):
231	def __init__(self, arg = []):
232		self.data = arg
233
234	def get_time_slice(self, ts):
235		if len(self.data) == 0:
236			slice = TimeSlice(ts, TimeSlice(-1, None))
237		else:
238			slice = self.data[-1].next(ts)
239		return slice
240
241	def find_time_slice(self, ts):
242		start = 0
243		end = len(self.data)
244		found = -1
245		searching = True
246		while searching:
247			if start == end or start == end - 1:
248				searching = False
249
250			i = (end + start) / 2
251			if self.data[i].start <= ts and self.data[i].end >= ts:
252				found = i
253				end = i
254				continue
255
256			if self.data[i].end < ts:
257				start = i
258
259			elif self.data[i].start > ts:
260				end = i
261
262		return found
263
264	def set_root_win(self, win):
265		self.root_win = win
266
267	def mouse_down(self, cpu, t):
268		idx = self.find_time_slice(t)
269		if idx == -1:
270			return
271
272		ts = self[idx]
273		rq = ts.rqs[cpu]
274		raw = "CPU: %d\n" % cpu
275		raw += "Last event : %s\n" % rq.event.__repr__()
276		raw += "Timestamp : %d.%06d\n" % (ts.start / (10 ** 9), (ts.start % (10 ** 9)) / 1000)
277		raw += "Duration : %6d us\n" % ((ts.end - ts.start) / (10 ** 6))
278		raw += "Load = %d\n" % rq.load()
279		for t in rq.tasks:
280			raw += "%s \n" % thread_name(t)
281
282		self.root_win.update_summary(raw)
283
284	def update_rectangle_cpu(self, slice, cpu):
285		rq = slice.rqs[cpu]
286
287		if slice.total_load != 0:
288			load_rate = rq.load() / float(slice.total_load)
289		else:
290			load_rate = 0
291
292		red_power = int(0xff - (0xff * load_rate))
293		color = (0xff, red_power, red_power)
294
295		top_color = None
296
297		if cpu in slice.event_cpus:
298			top_color = rq.event.color()
299
300		self.root_win.paint_rectangle_zone(cpu, color, top_color, slice.start, slice.end)
301
302	def fill_zone(self, start, end):
303		i = self.find_time_slice(start)
304		if i == -1:
305			return
306
307		for i in range(i, len(self.data)):
308			timeslice = self.data[i]
309			if timeslice.start > end:
310				return
311
312			for cpu in timeslice.rqs:
313				self.update_rectangle_cpu(timeslice, cpu)
314
315	def interval(self):
316		if len(self.data) == 0:
317			return (0, 0)
318
319		return (self.data[0].start, self.data[-1].end)
320
321	def nr_rectangles(self):
322		last_ts = self.data[-1]
323		max_cpu = 0
324		for cpu in last_ts.rqs:
325			if cpu > max_cpu:
326				max_cpu = cpu
327		return max_cpu
328
329
330class SchedEventProxy:
331	def __init__(self):
332		self.current_tsk = defaultdict(lambda : -1)
333		self.timeslices = TimeSliceList()
334
335	def sched_switch(self, headers, prev_comm, prev_pid, prev_prio, prev_state,
336			 next_comm, next_pid, next_prio):
337		""" Ensure the task we sched out this cpu is really the one
338		    we logged. Otherwise we may have missed traces """
339
340		on_cpu_task = self.current_tsk[headers.cpu]
341
342		if on_cpu_task != -1 and on_cpu_task != prev_pid:
343			print("Sched switch event rejected ts: %s cpu: %d prev: %s(%d) next: %s(%d)" % \
344				headers.ts_format(), headers.cpu, prev_comm, prev_pid, next_comm, next_pid)
345
346		threads[prev_pid] = prev_comm
347		threads[next_pid] = next_comm
348		self.current_tsk[headers.cpu] = next_pid
349
350		ts = self.timeslices.get_time_slice(headers.ts())
351		ts.sched_switch(self.timeslices, prev_pid, prev_state, next_pid, headers.cpu)
352
353	def migrate(self, headers, pid, prio, orig_cpu, dest_cpu):
354		ts = self.timeslices.get_time_slice(headers.ts())
355		ts.migrate(self.timeslices, pid, orig_cpu, dest_cpu)
356
357	def wake_up(self, headers, comm, pid, success, target_cpu, fork):
358		if success == 0:
359			return
360		ts = self.timeslices.get_time_slice(headers.ts())
361		ts.wake_up(self.timeslices, pid, target_cpu, fork)
362
363
364def trace_begin():
365	global parser
366	parser = SchedEventProxy()
367
368def trace_end():
369	app = wx.App(False)
370	timeslices = parser.timeslices
371	frame = RootFrame(timeslices, "Migration")
372	app.MainLoop()
373
374def sched__sched_stat_runtime(event_name, context, common_cpu,
375	common_secs, common_nsecs, common_pid, common_comm,
376	common_callchain, comm, pid, runtime, vruntime):
377	pass
378
379def sched__sched_stat_iowait(event_name, context, common_cpu,
380	common_secs, common_nsecs, common_pid, common_comm,
381	common_callchain, comm, pid, delay):
382	pass
383
384def sched__sched_stat_sleep(event_name, context, common_cpu,
385	common_secs, common_nsecs, common_pid, common_comm,
386	common_callchain, comm, pid, delay):
387	pass
388
389def sched__sched_stat_wait(event_name, context, common_cpu,
390	common_secs, common_nsecs, common_pid, common_comm,
391	common_callchain, comm, pid, delay):
392	pass
393
394def sched__sched_process_fork(event_name, context, common_cpu,
395	common_secs, common_nsecs, common_pid, common_comm,
396	common_callchain, parent_comm, parent_pid, child_comm, child_pid):
397	pass
398
399def sched__sched_process_wait(event_name, context, common_cpu,
400	common_secs, common_nsecs, common_pid, common_comm,
401	common_callchain, comm, pid, prio):
402	pass
403
404def sched__sched_process_exit(event_name, context, common_cpu,
405	common_secs, common_nsecs, common_pid, common_comm,
406	common_callchain, comm, pid, prio):
407	pass
408
409def sched__sched_process_free(event_name, context, common_cpu,
410	common_secs, common_nsecs, common_pid, common_comm,
411	common_callchain, comm, pid, prio):
412	pass
413
414def sched__sched_migrate_task(event_name, context, common_cpu,
415	common_secs, common_nsecs, common_pid, common_comm,
416	common_callchain, comm, pid, prio, orig_cpu,
417	dest_cpu):
418	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
419				common_pid, common_comm, common_callchain)
420	parser.migrate(headers, pid, prio, orig_cpu, dest_cpu)
421
422def sched__sched_switch(event_name, context, common_cpu,
423	common_secs, common_nsecs, common_pid, common_comm, common_callchain,
424	prev_comm, prev_pid, prev_prio, prev_state,
425	next_comm, next_pid, next_prio):
426
427	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
428				common_pid, common_comm, common_callchain)
429	parser.sched_switch(headers, prev_comm, prev_pid, prev_prio, prev_state,
430			 next_comm, next_pid, next_prio)
431
432def sched__sched_wakeup_new(event_name, context, common_cpu,
433	common_secs, common_nsecs, common_pid, common_comm,
434	common_callchain, comm, pid, prio, success,
435	target_cpu):
436	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
437				common_pid, common_comm, common_callchain)
438	parser.wake_up(headers, comm, pid, success, target_cpu, 1)
439
440def sched__sched_wakeup(event_name, context, common_cpu,
441	common_secs, common_nsecs, common_pid, common_comm,
442	common_callchain, comm, pid, prio, success,
443	target_cpu):
444	headers = EventHeaders(common_cpu, common_secs, common_nsecs,
445				common_pid, common_comm, common_callchain)
446	parser.wake_up(headers, comm, pid, success, target_cpu, 0)
447
448def sched__sched_wait_task(event_name, context, common_cpu,
449	common_secs, common_nsecs, common_pid, common_comm,
450	common_callchain, comm, pid, prio):
451	pass
452
453def sched__sched_kthread_stop_ret(event_name, context, common_cpu,
454	common_secs, common_nsecs, common_pid, common_comm,
455	common_callchain, ret):
456	pass
457
458def sched__sched_kthread_stop(event_name, context, common_cpu,
459	common_secs, common_nsecs, common_pid, common_comm,
460	common_callchain, comm, pid):
461	pass
462
463def trace_unhandled(event_name, context, event_fields_dict):
464	pass
465