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