]> git.saurik.com Git - apple/xnu.git/blame - tools/lldbmacros/scheduler.py
xnu-4570.20.62.tar.gz
[apple/xnu.git] / tools / lldbmacros / scheduler.py
CommitLineData
39236c6e
A
1from xnu import *
2from utils import *
3from process import *
5ba3f43e
A
4from misc import *
5from memory import *
39236c6e
A
6
7# TODO: write scheduler related macros here
8
39037602
A
9# Macro: showallprocrunqcount
10
11@lldb_command('showallprocrunqcount')
12def ShowAllProcRunQCount(cmd_args=None):
13 """ Prints out the runq count for all processors
14 """
15 out_str = "Processor\t# Runnable\n"
16 processor_itr = kern.globals.processor_list
17 while processor_itr:
18 out_str += "{:d}\t\t{:d}\n".format(processor_itr.cpu_id, processor_itr.runq.count)
19 processor_itr = processor_itr.processor_list
5ba3f43e 20 # out_str += "RT:\t\t{:d}\n".format(kern.globals.rt_runq.count)
39037602
A
21 print out_str
22
23# EndMacro: showallprocrunqcount
24
39236c6e 25# Macro: showinterrupts
3e170ce0 26
39236c6e
A
27@lldb_command('showinterrupts')
28def ShowInterrupts(cmd_args=None):
29 """ Prints IRQ, IPI and TMR counts for each CPU
39037602
A
30 """
31
5ba3f43e 32 if not kern.arch.startswith('arm'):
39037602
A
33 print "showinterrupts is only supported on arm/arm64"
34 return
35
3e170ce0 36 base_address = kern.GetLoadAddressForSymbol('CpuDataEntries')
5ba3f43e
A
37 struct_size = 16
38 x = 0
39 y = 0
40 while x < unsigned(kern.globals.machine_info.physical_cpu):
41 element = kern.GetValueFromAddress(base_address + (y * struct_size), 'uintptr_t *')[1]
42 if element:
43 cpu_data_entry = Cast(element, 'cpu_data_t *')
44 print "CPU {} IRQ: {:d}\n".format(y, cpu_data_entry.cpu_stat.irq_ex_cnt)
45 print "CPU {} IPI: {:d}\n".format(y, cpu_data_entry.cpu_stat.ipi_cnt)
46 print "CPU {} TMR: {:d}\n".format(y, cpu_data_entry.cpu_stat.timer_cnt)
47 x = x + 1
48 y = y + 1
49
39236c6e
A
50# EndMacro: showinterrupts
51
52# Macro: showactiveinterrupts
3e170ce0 53
39236c6e
A
54@lldb_command('showactiveinterrupts')
55def ShowActiveInterrupts(cmd_args=None):
56 """ Prints the interrupts that are unmasked & active with the Interrupt Controller
57 Usage: showactiveinterrupts <address of Interrupt Controller object>
58 """
59 if not cmd_args:
60 print "No arguments passed"
61 print ShowActiveInterrupts.__doc__
62 return False
63 aic = kern.GetValueFromAddress(cmd_args[0], 'AppleInterruptController *')
64 if not aic:
65 print "unknown arguments:", str(cmd_args)
66 return False
67
68 aic_base = unsigned(aic._aicBaseAddress)
69 current_interrupt = 0
70 aic_imc_base = aic_base + 0x4180
71 aic_him_offset = 0x80
72 current_pointer = aic_imc_base
73 unmasked = dereference(kern.GetValueFromAddress(current_pointer, 'uintptr_t *'))
74 active = dereference(kern.GetValueFromAddress(current_pointer + aic_him_offset, 'uintptr_t *'))
75 group_count = 0
76 mask = 1
77 while current_interrupt < 192:
78 if (((unmasked & mask) == 0) and (active & mask)):
79 print "Interrupt {:d} unmasked and active\n".format(current_interrupt)
80 current_interrupt = current_interrupt + 1
81 if (current_interrupt % 32 == 0):
82 mask = 1
83 group_count = group_count + 1
84 unmasked = dereference(kern.GetValueFromAddress(current_pointer + (4 * group_count), 'uintptr_t *'))
85 active = dereference(kern.GetValueFromAddress((current_pointer + aic_him_offset) + (4 * group_count), 'uintptr_t *'))
86 else:
87 mask = mask << 1
39236c6e
A
88# EndMacro: showactiveinterrupts
89
39037602
A
90# Macro: showirqbyipitimerratio
91@lldb_command('showirqbyipitimerratio')
92def ShowIrqByIpiTimerRatio(cmd_args=None):
93 """ Prints the ratio of IRQ by sum of IPI & TMR counts for each CPU
94 """
95 if kern.arch == "x86_64":
96 print "This macro is not supported on x86_64 architecture"
97 return
98
99 out_str = "IRQ-IT Ratio: "
100 base_address = kern.GetLoadAddressForSymbol('CpuDataEntries')
101 struct_size = 16
5ba3f43e
A
102 x = 0
103 y = 0
104 while x < unsigned(kern.globals.machine_info.physical_cpu):
105 element = kern.GetValueFromAddress(base_address + (y * struct_size), 'uintptr_t *')[1]
106 if element:
107 cpu_data_entry = Cast(element, 'cpu_data_t *')
108 out_str += " CPU {} [{:.2f}]".format(y, float(cpu_data_entry.cpu_stat.irq_ex_cnt)/(cpu_data_entry.cpu_stat.ipi_cnt + cpu_data_entry.cpu_stat.timer_cnt))
109 x = x + 1
110 y = y + 1
39037602
A
111 print out_str
112
113# EndMacro: showirqbyipitimerratio
114
115#Macro: showinterruptsourceinfo
116@lldb_command('showinterruptsourceinfo')
117def showinterruptsourceinfo(cmd_args = None):
118 """ Extract information of interrupt source causing interrupt storms.
119 """
120 if not cmd_args:
121 print "No arguments passed"
122 return False
123 #Dump IOInterruptVector object
124 print "--- Dumping IOInterruptVector object ---\n"
125 object_info = lldb_run_command("dumpobject {:s} IOInterruptVector".format(cmd_args[0]))
126 print object_info
127 print "--- Dumping IOFilterInterruptEventSource object ---\n"
128 #Dump the IOFilterInterruptEventSource object.
129 target_info=re.search('target =\s+(.*)',object_info)
130 target= target_info.group()
131 target= target.split()
132 #Dump the Object pointer of the source who is triggering the Interrupts.
133 vector_info=lldb_run_command("dumpobject {:s} ".format(target[2]))
134 print vector_info
135 owner_info= re.search('owner =\s+(.*)',vector_info)
136 owner= owner_info.group()
137 owner= owner.split()
138 print "\n\n"
139 out=lldb_run_command(" dumpobject {:s}".format(owner[2]))
140 print out
141
142# EndMacro: showinterruptsourceinfo
3e170ce0
A
143
144@lldb_command('showcurrentabstime')
145def ShowCurremtAbsTime(cmd_args=None):
146 """ Routine to print latest absolute time known to system before being stopped.
147 Usage: showcurrentabstime
148 """
149 pset = addressof(kern.globals.pset0)
150 cur_abstime = 0
151
152 while unsigned(pset) != 0:
39037602 153 for processor in ParanoidIterateLinkageChain(pset.active_queue, "processor_t", "processor_queue"):
3e170ce0
A
154 if unsigned(processor.last_dispatch) > cur_abstime:
155 cur_abstime = unsigned(processor.last_dispatch)
156
39037602 157 for processor in ParanoidIterateLinkageChain(pset.idle_queue, "processor_t", "processor_queue"):
3e170ce0
A
158 if unsigned(processor.last_dispatch) > cur_abstime:
159 cur_abstime = unsigned(processor.last_dispatch)
160
39037602 161 for processor in ParanoidIterateLinkageChain(pset.idle_secondary_queue, "processor_t", "processor_queue"):
3e170ce0
A
162 if unsigned(processor.last_dispatch) > cur_abstime:
163 cur_abstime = unsigned(processor.last_dispatch)
164
165 pset = pset.pset_list
166
167 print "Last dispatch time known: %d MATUs" % cur_abstime
168
169
170@lldb_command('abs2nano')
171def ShowAbstimeToNanoTime(cmd_args=[]):
172 """ convert mach_absolute_time units to nano seconds
173 Usage: (lldb) abs2nano <timestamp in MATUs>
174 """
175 if not cmd_args:
176 raise ArgumentError("Invalid argument")
177 timedata = ArgumentStringToInt(cmd_args[0])
39037602
A
178 ns = kern.GetNanotimeFromAbstime(timedata)
179 us = float(ns) / 1000
180 ms = us / 1000
181 s = ms / 1000
182
183 if s > 60 :
184 m = s / 60
185 h = m / 60
186 d = h / 24
187
188 print "{:d} ns, {:f} us, {:f} ms, {:f} s, {:f} m, {:f} h, {:f} d".format(ns, us, ms, s, m, h, d)
189 else:
190 print "{:d} ns, {:f} us, {:f} ms, {:f} s".format(ns, us, ms, s)
3e170ce0
A
191
192 # Macro: showschedhistory
193
5ba3f43e
A
194def GetRecentTimestamp():
195 """
196 Return a recent timestamp.
197 TODO: on x86, if not in the debugger, then look at the scheduler
198 """
199 if kern.arch == 'x86_64':
200 return kern.globals.debugger_entry_time
201 else :
202 return GetSchedMostRecentDispatch(False)
203
39037602
A
204def GetSchedMostRecentDispatch(show_processor_details=False):
205 """ Return the most recent dispatch on the system, printing processor
206 details if argument is true.
207 """
208 processor_list = kern.globals.processor_list
209
210 most_recent_dispatch = 0
211 current_processor = processor_list
212
213 while unsigned(current_processor) > 0:
214 active_thread = current_processor.active_thread
215 if unsigned(active_thread) != 0 :
216 task_val = active_thread.task
217 proc_val = Cast(task_val.bsd_info, 'proc *')
218 proc_name = "<unknown>" if unsigned(proc_val) == 0 else str(proc_val.p_name)
219
220 last_dispatch = unsigned(current_processor.last_dispatch)
221
222 if kern.arch == 'x86_64':
223 cpu_data = kern.globals.cpu_data_ptr[current_processor.cpu_id]
224 if (cpu_data != 0) :
225 cpu_debugger_time = max(cpu_data.debugger_entry_time, cpu_data.debugger_ipi_time)
226 time_since_dispatch = unsigned(cpu_debugger_time - last_dispatch)
227 time_since_dispatch_us = kern.GetNanotimeFromAbstime(time_since_dispatch) / 1000.0
228 time_since_debugger = unsigned(cpu_debugger_time - kern.globals.debugger_entry_time)
229 time_since_debugger_us = kern.GetNanotimeFromAbstime(time_since_debugger) / 1000.0
230
231 if show_processor_details:
232 print "Processor last dispatch: {:16d} Entered debugger: {:16d} ({:8.3f} us after dispatch, {:8.3f} us after debugger) Active thread: 0x{t:<16x} 0x{t.thread_id:<8x} {proc_name:s}".format(last_dispatch, cpu_debugger_time,
233 time_since_dispatch_us, time_since_debugger_us, t=active_thread, proc_name=proc_name)
234 else:
235 if show_processor_details:
236 print "Processor last dispatch: {:16d} Active thread: 0x{t:<16x} 0x{t.thread_id:<8x} {proc_name:s}".format(last_dispatch, t=active_thread, proc_name=proc_name)
237
238 if last_dispatch > most_recent_dispatch:
239 most_recent_dispatch = last_dispatch
240
241 current_processor = current_processor.processor_list
242
243 return most_recent_dispatch
244
5ba3f43e 245@header("{:<18s} {:<10s} {:>16s} {:>16s} {:>16s} {:>16s} {:>18s} {:>16s} {:>16s} {:>16s} {:>16s} {:2s} {:2s} {:2s} {:>2s} {:<19s} {:<9s} {:>10s} {:>10s} {:>10s} {:>10s} {:>10s} {:>11s} {:>8s}".format("thread", "id", "on-core", "off-core", "runnable", "prichange", "last-duration (us)", "since-off (us)", "since-on (us)", "pending (us)", "pri-change (us)", "BP", "SP", "TP", "MP", "sched-mode", "state", "cpu-usage", "delta", "sch-usage", "stamp", "shift", "task", "thread-name"))
3e170ce0 246def ShowThreadSchedHistory(thread, most_recent_dispatch):
39037602
A
247 """ Given a thread and the most recent dispatch time of a thread on the
248 system, print out details about scheduler history for the thread.
249 """
250
3e170ce0
A
251 thread_name = ""
252
39037602 253 if unsigned(thread.uthread) != 0:
3e170ce0 254 uthread = Cast(thread.uthread, 'uthread *')
39037602
A
255 # Doing the straightforward thing blows up weirdly, so use some indirections to get back on track
256 if unsigned(uthread.pth_name) != 0 :
257 thread_name = str(kern.GetValueFromAddress(unsigned(uthread.pth_name), 'char*'))
3e170ce0
A
258
259 task = thread.task
260 task_name = "unknown"
261 if task and unsigned(task.bsd_info):
262 p = Cast(task.bsd_info, 'proc *')
263 task_name = str(p.p_name)
264
265 sched_mode = ""
266
267 mode = str(thread.sched_mode)
268 if "TIMESHARE" in mode:
269 sched_mode+="timeshare"
270 elif "FIXED" in mode:
271 sched_mode+="fixed"
272 elif "REALTIME" in mode:
273 sched_mode+="realtime"
274
275 if (unsigned(thread.bound_processor) != 0):
276 sched_mode+="-bound"
277
278 # TH_SFLAG_THROTTLED
279 if (unsigned(thread.sched_flags) & 0x0004):
280 sched_mode+="-BG"
281
282 state = thread.state
283
284 thread_state_chars = {0x0:'', 0x1:'W', 0x2:'S', 0x4:'R', 0x8:'U', 0x10:'H', 0x20:'A', 0x40:'P', 0x80:'I'}
285 state_str = ''
286 mask = 0x1
287 while mask <= 0x80 :
288 state_str += thread_state_chars[int(state & mask)]
289 mask = mask << 1
290
291 last_on = thread.computation_epoch
292 last_off = thread.last_run_time
39037602 293 last_runnable = thread.last_made_runnable_time
5ba3f43e
A
294 last_prichange = thread.last_basepri_change_time
295
39037602
A
296 if int(last_runnable) == 18446744073709551615 :
297 last_runnable = 0
3e170ce0 298
5ba3f43e
A
299 if int(last_prichange) == 18446744073709551615 :
300 last_prichange = 0
301
3e170ce0
A
302 time_on_abs = unsigned(last_off - last_on)
303 time_on_us = kern.GetNanotimeFromAbstime(time_on_abs) / 1000.0
304
39037602
A
305 time_pending_abs = unsigned(most_recent_dispatch - last_runnable)
306 time_pending_us = kern.GetNanotimeFromAbstime(time_pending_abs) / 1000.0
5ba3f43e 307
39037602
A
308 if int(last_runnable) == 0 :
309 time_pending_us = 0
310
5ba3f43e
A
311 last_prichange_abs = unsigned(most_recent_dispatch - last_prichange)
312 last_prichange_us = kern.GetNanotimeFromAbstime(last_prichange_abs) / 1000.0
313
314 if int(last_prichange) == 0 :
315 last_prichange_us = 0
316
3e170ce0
A
317 time_since_off_abs = unsigned(most_recent_dispatch - last_off)
318 time_since_off_us = kern.GetNanotimeFromAbstime(time_since_off_abs) / 1000.0
319 time_since_on_abs = unsigned(most_recent_dispatch - last_on)
320 time_since_on_us = kern.GetNanotimeFromAbstime(time_since_on_abs) / 1000.0
321
5ba3f43e 322 fmt = "0x{t:<16x} 0x{t.thread_id:<8x} {t.computation_epoch:16d} {t.last_run_time:16d} {last_runnable:16d} {last_prichange:16d} {time_on_us:18.3f} {time_since_off_us:16.3f} {time_since_on_us:16.3f} {time_pending_us:16.3f} {last_prichange_us:16.3f}"
3e170ce0
A
323 fmt2 = " {t.base_pri:2d} {t.sched_pri:2d} {t.task_priority:2d} {t.max_priority:2d} {sched_mode:19s}"
324 fmt3 = " {state:9s} {t.cpu_usage:10d} {t.cpu_delta:10d} {t.sched_usage:10d} {t.sched_stamp:10d} {t.pri_shift:10d} {name:s} {thread_name:s}"
325
5ba3f43e 326 out_str = fmt.format(t=thread, time_on_us=time_on_us, time_since_off_us=time_since_off_us, time_since_on_us=time_since_on_us, last_runnable=last_runnable, time_pending_us=time_pending_us, last_prichange=last_prichange, last_prichange_us=last_prichange_us)
3e170ce0
A
327 out_str += fmt2.format(t=thread, sched_mode=sched_mode)
328 out_str += fmt3.format(t=thread, state=state_str, name=task_name, thread_name=thread_name)
5ba3f43e 329
39037602 330 print out_str
3e170ce0 331
5ba3f43e
A
332def SortThreads(threads, column):
333 if column != 'on-core' and column != 'off-core' and column != 'last-duration':
334 raise ArgumentError("unsupported sort column")
335 if column == 'on-core':
336 threads.sort(key=lambda t: t.computation_epoch)
337 elif column == 'off-core':
338 threads.sort(key=lambda t: t.last_run_time)
339 else:
340 threads.sort(key=lambda t: t.last_run_time - t.computation_epoch)
341
342@lldb_command('showschedhistory', 'S:')
343def ShowSchedHistory(cmd_args=None, cmd_options=None):
344 """ Routine to print out thread scheduling history, optionally sorted by a
345 column.
346
347 Usage: showschedhistory [-S on-core|off-core|last-duration] [<thread-ptr> ...]
3e170ce0
A
348 """
349
5ba3f43e
A
350 sort_column = None
351 if '-S' in cmd_options:
352 sort_column = cmd_options['-S']
353
39037602
A
354 if cmd_args:
355 most_recent_dispatch = GetSchedMostRecentDispatch(False)
3e170ce0 356
39037602 357 print ShowThreadSchedHistory.header
5ba3f43e
A
358
359 if sort_column:
360 threads = []
361 for thread_ptr in cmd_args:
362 threads.append(kern.GetValueFromAddress(ArgumentStringToInt(thread_ptr), 'thread *'))
363
364 SortThreads(threads, sort_column)
365
366 for thread in threads:
367 ShowThreadSchedHistory(thread, most_recent_dispatch)
368 else:
369 for thread_ptr in cmd_args:
370 thread = kern.GetValueFromAddress(ArgumentStringToInt(thread_ptr), 'thread *')
371 ShowThreadSchedHistory(thread, most_recent_dispatch)
3e170ce0 372
39037602 373 return
5ba3f43e 374
39037602 375 run_buckets = kern.globals.sched_run_buckets
3e170ce0 376
39037602
A
377 run_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')]
378 fixpri_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')]
379 share_fg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
380 share_ut_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
381 share_bg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
3e170ce0 382
39037602 383 sched_pri_shifts = kern.globals.sched_run_buckets
3e170ce0 384
39037602
A
385 share_fg_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
386 share_ut_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
387 share_bg_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
3e170ce0 388
3e170ce0 389
39037602
A
390 print "Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count, fixpri_count, g=kern.globals)
391 print "FG Timeshare threads: {:d} UT Timeshare threads: {:d} BG Timeshare threads: {:d}\n".format(share_fg_count, share_ut_count, share_bg_count)
392 print "Mach factor: {g.sched_mach_factor:d} Load factor: {g.sched_load_average:d} Sched tick: {g.sched_tick:d} timestamp: {g.sched_tick_last_abstime:d} interval:{g.sched_tick_interval:d}\n".format(g=kern.globals)
393 print "Fixed shift: {g.sched_fixed_shift:d} FG shift: {:d} UT shift: {:d} BG shift: {:d}\n".format(share_fg_shift, share_ut_shift, share_bg_shift, g=kern.globals)
394 print "sched_pri_decay_band_limit: {g.sched_pri_decay_band_limit:d} sched_decay_usage_age_factor: {g.sched_decay_usage_age_factor:d}\n".format(g=kern.globals)
3e170ce0 395
39037602
A
396 if kern.arch == 'x86_64':
397 print "debugger_entry_time: {g.debugger_entry_time:d}\n".format(g=kern.globals)
3e170ce0 398
39037602 399 most_recent_dispatch = GetSchedMostRecentDispatch(True)
3e170ce0
A
400 print "Most recent dispatch: " + str(most_recent_dispatch)
401
39037602 402 print ShowThreadSchedHistory.header
5ba3f43e
A
403
404 if sort_column:
405 threads = [t for t in IterateQueue(kern.globals.threads, 'thread *', 'threads')]
406
407 SortThreads(threads, sort_column)
408
409 for thread in threads:
410 ShowThreadSchedHistory(thread, most_recent_dispatch)
411 else:
412 for thread in IterateQueue(kern.globals.threads, 'thread *', 'threads'):
413 ShowThreadSchedHistory(thread, most_recent_dispatch)
3e170ce0 414
3e170ce0
A
415
416# EndMacro: showschedhistory
417
5ba3f43e
A
418def int32(n):
419 n = n & 0xffffffff
420 return (n ^ 0x80000000) - 0x80000000
39037602
A
421
422# Macro: showallprocessors
423
424def ShowGroupSetSummary(runq, task_map):
425 """ Internal function to print summary of group run queue
426 params: runq - value representing struct run_queue *
427 """
5ba3f43e
A
428
429 print " runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq.count, int32(runq.highq), runq.urgency)
39037602
A
430
431 runq_queue_i = 0
432 runq_queue_count = sizeof(runq.queues)/sizeof(runq.queues[0])
433
434 for runq_queue_i in xrange(runq_queue_count) :
435 runq_queue_head = addressof(runq.queues[runq_queue_i])
436 runq_queue_p = runq_queue_head.next
437
438 if unsigned(runq_queue_p) != unsigned(runq_queue_head):
439 runq_queue_this_count = 0
440
441 for entry in ParanoidIterateLinkageChain(runq_queue_head, "sched_entry_t", "entry_links"):
442 runq_queue_this_count += 1
443
444 print " Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head, runq_queue_i, runq_queue_this_count)
445 for entry in ParanoidIterateLinkageChain(runq_queue_head, "sched_entry_t", "entry_links"):
446 group_addr = unsigned(entry) - (sizeof(dereference(entry)) * unsigned(entry.sched_pri))
447 group = kern.GetValueFromAddress(unsigned(group_addr), 'sched_group_t')
448 task = task_map.get(unsigned(group), 0x0)
449 if task == 0x0 :
450 print "Cannot find task for group: {: <#012x}".format(group)
451 print "\tEntry [{: <#012x}] Priority {: <3d} Group {: <#012x} Task {: <#012x}\n".format(unsigned(entry), entry.sched_pri, unsigned(group), unsigned(task))
452
453@lldb_command('showrunq')
454def ShowRunq(cmd_args=None):
455 """ Routine to print information of a runq
456 Usage: showrunq <runq>
457 """
458
459 if not cmd_args:
460 print "No arguments passed"
461 print ShowRunq.__doc__
462 return False
463
464 runq = kern.GetValueFromAddress(cmd_args[0], 'struct run_queue *')
465 ShowRunQSummary(runq)
466
467def ShowRunQSummary(runq):
468 """ Internal function to print summary of run_queue
469 params: runq - value representing struct run_queue *
470 """
5ba3f43e
A
471
472 print " runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq.count, int32(runq.highq), runq.urgency)
39037602
A
473
474 runq_queue_i = 0
475 runq_queue_count = sizeof(runq.queues)/sizeof(runq.queues[0])
476
477 for runq_queue_i in xrange(runq_queue_count) :
478 runq_queue_head = addressof(runq.queues[runq_queue_i])
479 runq_queue_p = runq_queue_head.next
480
481 if unsigned(runq_queue_p) != unsigned(runq_queue_head):
482 runq_queue_this_count = 0
483
484 for thread in ParanoidIterateLinkageChain(runq_queue_head, "thread_t", "runq_links"):
485 runq_queue_this_count += 1
486
487 print " Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head, runq_queue_i, runq_queue_this_count)
488 print "\t" + GetThreadSummary.header + "\n"
489 for thread in ParanoidIterateLinkageChain(runq_queue_head, "thread_t", "runq_links"):
490 print "\t" + GetThreadSummary(thread) + "\n"
491 if config['verbosity'] > vHUMAN :
492 print "\t" + GetThreadBackTrace(thread, prefix="\t\t") + "\n"
493
5ba3f43e
A
494def ShowRTRunQSummary(rt_runq):
495 print " Realtime Queue ({:<#012x}) Count {:d}\n".format(addressof(rt_runq.queue), rt_runq.count)
496 if rt_runq.count != 0:
497 print "\t" + GetThreadSummary.header + "\n"
498 for rt_runq_thread in ParanoidIterateLinkageChain(rt_runq.queue, "thread_t", "runq_links"):
499 print "\t" + GetThreadSummary(rt_runq_thread) + "\n"
39037602
A
500
501def ShowGrrrSummary(grrr_runq):
502 """ Internal function to print summary of grrr_run_queue
503 params: grrr_runq - value representing struct grrr_run_queue *
504 """
505 print " GRRR Info: Count {: <10d} Weight {: <10d} Current Group {: <#012x}\n".format(grrr_runq.count,
506 grrr_runq.weight, grrr_runq.current_group)
507 grrr_group_i = 0
508 grrr_group_count = sizeof(grrr_runq.groups)/sizeof(grrr_runq.groups[0])
509 for grrr_group_i in xrange(grrr_group_count) :
510 grrr_group = addressof(grrr_runq.groups[grrr_group_i])
511 if grrr_group.count > 0:
512 print " Group {: <3d} [{: <#012x}] ".format(grrr_group.index, grrr_group)
513 print "Count {:d} Weight {:d}\n".format(grrr_group.count, grrr_group.weight)
514 grrr_group_client_head = addressof(grrr_group.clients)
515 print GetThreadSummary.header
516 for thread in ParanoidIterateLinkageChain(grrr_group_client_head, "thread_t", "runq_links"):
517 print "\t" + GetThreadSummary(thread) + "\n"
518 if config['verbosity'] > vHUMAN :
519 print "\t" + GetThreadBackTrace(thread, prefix="\t\t") + "\n"
520
521def ShowNextThread(processor):
522 if (processor.next_thread != 0) :
523 print " " + "Next thread:\n"
524 print "\t" + GetThreadSummary.header + "\n"
525 print "\t" + GetThreadSummary(processor.next_thread) + "\n"
526
527def ShowActiveThread(processor):
528 if (processor.active_thread != 0) :
529 print "\t" + GetThreadSummary.header + "\n"
530 print "\t" + GetThreadSummary(processor.active_thread) + "\n"
531
532@lldb_command('showallprocessors')
533@lldb_command('showscheduler')
534def ShowScheduler(cmd_args=None):
535 """ Routine to print information of all psets and processors
536 Usage: showscheduler
537 """
5ba3f43e 538 node = addressof(kern.globals.pset_node0)
39037602
A
539 show_grrr = 0
540 show_priority_runq = 0
541 show_priority_pset_runq = 0
542 show_group_pset_runq = 0
5ba3f43e
A
543 if unsigned(kern.globals.sched_current_dispatch) != 0 :
544 sched_string = str(kern.globals.sched_current_dispatch.sched_name)
545 else :
546 sched_string = str(kern.globals.sched_string)
39037602
A
547
548 if sched_string == "traditional":
549 show_priority_runq = 1
550 elif sched_string == "traditional_with_pset_runqueue":
551 show_priority_pset_runq = 1
552 elif sched_string == "grrr":
553 show_grrr = 1
554 elif sched_string == "multiq":
555 show_priority_runq = 1
556 show_group_pset_runq = 1
557 elif sched_string == "dualq":
558 show_priority_pset_runq = 1
559 show_priority_runq = 1
5ba3f43e
A
560 elif sched_string == "amp":
561 show_priority_pset_runq = 1
562 show_priority_runq = 1
39037602
A
563 else :
564 print "Unknown sched_string {:s}".format(sched_string)
565
5ba3f43e
A
566 if unsigned(kern.globals.sched_current_dispatch) != 0 :
567 print "Scheduler: {:s} ({:s})\n".format(sched_string,
568 kern.Symbolicate(unsigned(kern.globals.sched_current_dispatch)))
39037602
A
569
570 run_buckets = kern.globals.sched_run_buckets
571
572 run_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')]
573 fixpri_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')]
574 share_fg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
575 share_ut_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
576 share_bg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
577
578 print "Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count, fixpri_count, g=kern.globals)
579 print "FG Timeshare threads: {:d} UT Timeshare threads: {:d} BG Timeshare threads: {:d}\n".format(share_fg_count, share_ut_count, share_bg_count)
580
581 if show_group_pset_runq:
5ba3f43e
A
582 if hasattr(kern.globals, "multiq_sanity_check"):
583 print "multiq scheduler config: deep-drain {g.deep_drain:d}, ceiling {g.drain_ceiling:d}, depth limit {g.drain_depth_limit:d}, band limit {g.drain_band_limit:d}, sanity check {g.multiq_sanity_check:d}\n".format(g=kern.globals)
584 else:
585 print "multiq scheduler config: deep-drain {g.deep_drain:d}, ceiling {g.drain_ceiling:d}, depth limit {g.drain_depth_limit:d}, band limit {g.drain_band_limit:d}\n".format(g=kern.globals)
39037602
A
586
587 # Create a group->task mapping
588 task_map = {}
589 for task in kern.tasks:
590 task_map[unsigned(task.sched_group)] = task
591 for task in kern.terminated_tasks:
592 task_map[unsigned(task.sched_group)] = task
593
594 print " \n"
595
5ba3f43e
A
596 while node != 0:
597 pset = node.psets
598 pset = kern.GetValueFromAddress(unsigned(pset), 'struct processor_set *')
599
600 while pset != 0:
601 print "Processor Set {: <#012x} Count {:d} (cpu_id {:<#x}-{:<#x})\n".format(pset,
602 unsigned(pset.cpu_set_count), pset.cpu_set_low, pset.cpu_set_hi)
603
604 rt_runq = kern.GetValueFromAddress(unsigned(addressof(pset.rt_runq)), 'struct rt_queue *')
605 ShowRTRunQSummary(rt_runq)
39037602 606
5ba3f43e
A
607 if show_priority_pset_runq:
608 runq = kern.GetValueFromAddress(unsigned(addressof(pset.pset_runq)), 'struct run_queue *')
39037602 609 ShowRunQSummary(runq)
39037602 610
5ba3f43e
A
611 if show_group_pset_runq:
612 print "Main Runq:\n"
613 runq = kern.GetValueFromAddress(unsigned(addressof(pset.pset_runq)), 'struct run_queue *')
614 ShowGroupSetSummary(runq, task_map)
615 print "All Groups:\n"
616 # TODO: Possibly output task header for each group
617 for group in IterateQueue(kern.globals.sched_groups, "sched_group_t", "sched_groups"):
618 if (group.runq.count != 0) :
619 task = task_map.get(unsigned(group), "Unknown task!")
620 print "Group {: <#012x} Task {: <#012x}\n".format(unsigned(group), unsigned(task))
621 ShowRunQSummary(group.runq)
622 print " \n"
39037602 623
5ba3f43e
A
624 print "Active Processors:\n"
625 for processor in ParanoidIterateLinkageChain(pset.active_queue, "processor_t", "processor_queue"):
626 print " " + GetProcessorSummary(processor)
627 ShowActiveThread(processor)
628 ShowNextThread(processor)
39037602 629
5ba3f43e
A
630 if show_priority_runq:
631 runq = processor.runq
632 ShowRunQSummary(runq)
633 if show_grrr:
634 grrr_runq = processor.grrr_runq
635 ShowGrrrSummary(grrr_runq)
636 print " \n"
39037602
A
637
638
5ba3f43e
A
639 print "Idle Processors:\n"
640 for processor in ParanoidIterateLinkageChain(pset.idle_queue, "processor_t", "processor_queue"):
641 print " " + GetProcessorSummary(processor)
642 ShowActiveThread(processor)
643 ShowNextThread(processor)
39037602 644
5ba3f43e
A
645 if show_priority_runq:
646 ShowRunQSummary(processor.runq)
647 print " \n"
39037602
A
648
649
5ba3f43e
A
650 print "Idle Secondary Processors:\n"
651 for processor in ParanoidIterateLinkageChain(pset.idle_secondary_queue, "processor_t", "processor_queue"):
652 print " " + GetProcessorSummary(processor)
653 ShowActiveThread(processor)
654 ShowNextThread(processor)
39037602 655
5ba3f43e
A
656 if show_priority_runq:
657 print ShowRunQSummary(processor.runq)
658 print " \n"
659
660
661 pset = pset.pset_list
662
663 node = node.node_list
39037602
A
664
665 print "\nTerminate Queue: ({:<#012x})\n".format(addressof(kern.globals.thread_terminate_queue))
666 first = False
667 for thread in ParanoidIterateLinkageChain(kern.globals.thread_terminate_queue, "thread_t", "runq_links"):
668 if first:
669 print "\t" + GetThreadSummary.header + "\n"
670 first = True
671 print "\t" + GetThreadSummary(thread) + "\n"
672
673 print "\nCrashed Threads Queue: ({:<#012x})\n".format(addressof(kern.globals.crashed_threads_queue))
674 first = False
675 for thread in ParanoidIterateLinkageChain(kern.globals.crashed_threads_queue, "thread_t", "runq_links"):
676 if first:
677 print "\t" + GetThreadSummary.header + "\n"
678 first = True
679 print "\t" + GetThreadSummary(thread) + "\n"
680
681 print "\nWaiting For Kernel Stacks Queue: ({:<#012x})\n".format(addressof(kern.globals.thread_stack_queue))
682 first = False
683 for thread in ParanoidIterateLinkageChain(kern.globals.thread_stack_queue, "thread_t", "runq_links"):
684 if first:
685 print "\t" + GetThreadSummary.header + "\n"
686 first = True
687 print "\t" + GetThreadSummary(thread) + "\n"
688
689 print "\n"
690
691 print "\n"
692
693# EndMacro: showallprocessors
694
695
696def ParanoidIterateLinkageChain(queue_head, element_type, field_name, field_ofst=0):
697 """ Iterate over a Linkage Chain queue in kernel of type queue_head_t. (osfmk/kern/queue.h method 1)
698 This is equivalent to the qe_foreach_element() macro
699 Blows up aggressively and descriptively when something goes wrong iterating a queue.
700 Prints correctness errors, and throws exceptions on 'cannot proceed' errors
701 If this is annoying, set the global 'enable_paranoia' to false.
702
703 params:
704 queue_head - value : Value object for queue_head.
705 element_type - lldb.SBType : pointer type of the element which contains the queue_chain_t. Typically its structs like thread, task etc..
706 - str : OR a string describing the type. ex. 'task *'
707 field_name - str : Name of the field (in element) which holds a queue_chain_t
708 field_ofst - int : offset from the 'field_name' (in element) which holds a queue_chain_t
709 This is mostly useful if a particular element contains an array of queue_chain_t
710 returns:
711 A generator does not return. It is used for iterating.
712 value : An object thats of type (element_type). Always a pointer object
713 example usage:
714 for thread in IterateQueue(kern.globals.threads, 'thread *', 'threads'):
715 print thread.thread_id
716 """
717
718 if type(element_type) is str:
719 element_type = gettype(element_type)
720
721 # Some ways of constructing a queue head seem to end up with the
722 # struct object as the value and not a pointer to the struct head
723 # In that case, addressof will give us a pointer to the struct, which is what we need
724 if not queue_head.GetSBValue().GetType().IsPointerType() :
725 queue_head = addressof(queue_head)
726
727 # Mosh the value into a brand new value, to really get rid of its old cvalue history
728 queue_head = kern.GetValueFromAddress(unsigned(queue_head), 'struct queue_entry *')
729
730 if unsigned(queue_head) == 0:
731 if ParanoidIterateLinkageChain.enable_paranoia:
732 print "bad queue_head_t: {:s}".format(queue_head)
733 return
734
735 if element_type.IsPointerType():
5ba3f43e 736 struct_type = element_type.GetPointeeType()
39037602 737 else:
5ba3f43e
A
738 struct_type = element_type
739
740 elem_ofst = getfieldoffset(struct_type, field_name) + field_ofst
39037602
A
741
742 try:
743 link = queue_head.next
744 last_link = queue_head
745 try_read_next = unsigned(queue_head.next)
746 except:
747 print "Exception while looking at queue_head: {:>#18x}".format(unsigned(queue_head))
748 raise
749
750 if ParanoidIterateLinkageChain.enable_paranoia:
751 if unsigned(queue_head.next) == 0:
752 raise ValueError("NULL next pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev))
753 if unsigned(queue_head.prev) == 0:
754 print "NULL prev pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)
755 if unsigned(queue_head.next) == unsigned(queue_head) and unsigned(queue_head.prev) != unsigned(queue_head):
756 print "corrupt queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)
757
758 if ParanoidIterateLinkageChain.enable_debug :
759 print "starting at queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)
760
761 addr = 0
762 obj = 0
763
764 try:
765 while (unsigned(queue_head) != unsigned(link)):
766 if ParanoidIterateLinkageChain.enable_paranoia:
767 if unsigned(link.next) == 0:
768 raise ValueError("NULL next pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, link, link.next, link.prev))
769 if unsigned(link.prev) == 0:
770 print "NULL prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, link, link.next, link.prev)
771 if unsigned(last_link) != unsigned(link.prev):
772 print "Corrupt prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x} prev link: {:>#18x} ".format(
773 queue_head, link, link.next, link.prev, last_link)
774
775 addr = unsigned(link) - unsigned(elem_ofst);
776 obj = kern.GetValueFromAddress(addr, element_type)
777 if ParanoidIterateLinkageChain.enable_debug :
778 print "yielding link: {:>#18x} next: {:>#18x} prev: {:>#18x} addr: {:>#18x} obj: {:>#18x}".format(link, link.next, link.prev, addr, obj)
779 yield obj
780 last_link = link
781 link = link.next
782 except:
783 exc_info = sys.exc_info()
784 try:
785 print "Exception while iterating queue: {:>#18x} link: {:>#18x} addr: {:>#18x} obj: {:>#18x} last link: {:>#18x}".format(queue_head, link, addr, obj, last_link)
786 except:
787 import traceback
788 traceback.print_exc()
789 raise exc_info[0], exc_info[1], exc_info[2]
790
791ParanoidIterateLinkageChain.enable_paranoia = True
792ParanoidIterateLinkageChain.enable_debug = False
793
794# Macro: showallcallouts
5ba3f43e
A
795
796def ShowThreadCall(prefix, call):
797 """
798 Print a description of a thread_call_t and its relationship to its expected fire time
799 """
800 func = call.tc_call.func
801 param0 = call.tc_call.param0
802 param1 = call.tc_call.param1
803
804 iotes_desc = ""
805 iotes_callout = kern.GetLoadAddressForSymbol("_ZN18IOTimerEventSource17timeoutAndReleaseEPvS0_")
806 iotes_callout2 = kern.GetLoadAddressForSymbol("_ZN18IOTimerEventSource15timeoutSignaledEPvS0_")
807
808 if (unsigned(func) == unsigned(iotes_callout) or
809 unsigned(func) == unsigned(iotes_callout2)) :
810 iotes = Cast(call.tc_call.param0, 'IOTimerEventSource*')
811 func = iotes.action
812 param0 = iotes.owner
813 param1 = unsigned(iotes)
814
815 func_name = kern.Symbolicate(func)
816 if (func_name == "") :
817 func_name = FindKmodNameForAddr(func)
818
819 call_entry = call.tc_call
820
821 recent_timestamp = GetRecentTimestamp()
822
823 # THREAD_CALL_CONTINUOUS 0x100
824 kern.globals.mach_absolutetime_asleep
825 if (call.tc_flags & 0x100) :
826 timer_fire = call_entry.deadline - (recent_timestamp + kern.globals.mach_absolutetime_asleep)
827 else :
828 timer_fire = call_entry.deadline - recent_timestamp
829
830 timer_fire_s = kern.GetNanotimeFromAbstime(timer_fire) / 1000000000.0
831
832 ttd_s = kern.GetNanotimeFromAbstime(call.tc_ttd) / 1000000000.0
833
834 print "{:s}{:#018x}: {:18d} {:18d} {:03.06f} {:03.06f} {:#018x}({:#018x},{:#018x}) ({:s})".format(prefix,
835 unsigned(call), call_entry.deadline, call.tc_soft_deadline, ttd_s, timer_fire_s,
836 func, param0, param1, func_name)
837
39037602
A
838@lldb_command('showallcallouts')
839def ShowAllCallouts(cmd_args=None):
5ba3f43e 840 """ Prints out the pending and delayed thread calls for the thread call groups
39037602 841 """
5ba3f43e
A
842
843 index_max = GetEnumValue('thread_call_index_t::THREAD_CALL_INDEX_MAX')
844
845 for i in range (0, index_max) :
846 group = kern.globals.thread_call_groups[i]
847
848 print "Group {i:d}: {g.tcg_name:s} ({:>#18x})".format(addressof(group), i=i, g=group)
849 print "\t" +"Active: {g.active_count:d} Idle: {g.idle_count:d}\n".format(g=group)
850 print "\t" +"Blocked: {g.blocked_count:d} Pending: {g.pending_count:d}\n".format(g=group)
851 print "\t" +"Target: {g.target_thread_count:d}\n".format(g=group)
852
853 print "\t" +"Pending Queue: ({:>#18x})\n".format(addressof(group.pending_queue))
854 for call in ParanoidIterateLinkageChain(group.pending_queue, "thread_call_t", "tc_call.q_link"):
855 ShowThreadCall("\t\t", call)
856
857 print "\t" +"Delayed Queue (Absolute Time): ({:>#18x}) timer: ({:>#18x})\n".format(
858 addressof(group.delayed_queues[0]), addressof(group.delayed_timers[0]))
859 for call in ParanoidIterateLinkageChain(group.delayed_queues[0], "thread_call_t", "tc_call.q_link"):
860 ShowThreadCall("\t\t", call)
861
862 print "\t" +"Delayed Queue (Continuous Time): ({:>#18x}) timer: ({:>#18x})\n".format(
863 addressof(group.delayed_queues[1]), addressof(group.delayed_timers[1]))
864 for call in ParanoidIterateLinkageChain(group.delayed_queues[1], "thread_call_t", "tc_call.q_link"):
865 ShowThreadCall("\t\t", call)
39037602
A
866
867# EndMacro: showallcallouts
868