7 # TODO: write scheduler related macros here
9 # Macro: showallprocrunqcount
11 @lldb_command('showallprocrunqcount')
12 def ShowAllProcRunQCount(cmd_args
=None):
13 """ Prints out the runq count for all processors
15 out_str
= "Processor\t# Runnable\n"
16 processor_itr
= kern
.globals.processor_list
18 out_str
+= "{:d}\t\t{:d}\n".format(processor_itr
.cpu_id
, processor_itr
.runq
.count
)
19 processor_itr
= processor_itr
.processor_list
20 # out_str += "RT:\t\t{:d}\n".format(kern.globals.rt_runq.count)
23 # EndMacro: showallprocrunqcount
25 # Macro: showinterrupts
27 @lldb_command('showinterrupts')
28 def ShowInterrupts(cmd_args
=None):
29 """ Prints IRQ, IPI and TMR counts for each CPU
32 if not kern
.arch
.startswith('arm'):
33 print "showinterrupts is only supported on arm/arm64"
36 base_address
= kern
.GetLoadAddressForSymbol('CpuDataEntries')
40 while x
< unsigned(kern
.globals.machine_info
.physical_cpu
):
41 element
= kern
.GetValueFromAddress(base_address
+ (y
* struct_size
), 'uintptr_t *')[1]
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
)
50 # EndMacro: showinterrupts
52 # Macro: showactiveinterrupts
54 @lldb_command('showactiveinterrupts')
55 def ShowActiveInterrupts(cmd_args
=None):
56 """ Prints the interrupts that are unmasked & active with the Interrupt Controller
57 Usage: showactiveinterrupts <address of Interrupt Controller object>
60 print "No arguments passed"
61 print ShowActiveInterrupts
.__doc
__
63 aic
= kern
.GetValueFromAddress(cmd_args
[0], 'AppleInterruptController *')
65 print "unknown arguments:", str(cmd_args
)
68 aic_base
= unsigned(aic
._aicBaseAddress
)
70 aic_imc_base
= aic_base
+ 0x4180
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 *'))
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):
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 *'))
88 # EndMacro: showactiveinterrupts
90 # Macro: showirqbyipitimerratio
91 @lldb_command('showirqbyipitimerratio')
92 def ShowIrqByIpiTimerRatio(cmd_args
=None):
93 """ Prints the ratio of IRQ by sum of IPI & TMR counts for each CPU
95 if kern
.arch
== "x86_64":
96 print "This macro is not supported on x86_64 architecture"
99 out_str
= "IRQ-IT Ratio: "
100 base_address
= kern
.GetLoadAddressForSymbol('CpuDataEntries')
104 while x
< unsigned(kern
.globals.machine_info
.physical_cpu
):
105 element
= kern
.GetValueFromAddress(base_address
+ (y
* struct_size
), 'uintptr_t *')[1]
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
))
113 # EndMacro: showirqbyipitimerratio
115 #Macro: showinterruptsourceinfo
116 @lldb_command('showinterruptsourceinfo')
117 def showinterruptsourceinfo(cmd_args
= None):
118 """ Extract information of interrupt source causing interrupt storms.
121 print "No arguments passed"
123 #Dump IOInterruptVector object
124 print "--- Dumping IOInterruptVector object ---\n"
125 object_info
= lldb_run_command("dumpobject {:s} IOInterruptVector".format(cmd_args
[0]))
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]))
135 owner_info
= re
.search('owner =\s+(.*)',vector_info
)
136 owner
= owner_info
.group()
139 out
=lldb_run_command(" dumpobject {:s}".format(owner
[2]))
142 # EndMacro: showinterruptsourceinfo
144 @lldb_command('showcurrentabstime')
145 def ShowCurremtAbsTime(cmd_args
=None):
146 """ Routine to print latest absolute time known to system before being stopped.
147 Usage: showcurrentabstime
149 pset
= addressof(kern
.globals.pset0
)
150 processor_array
= kern
.globals.processor_array
153 while unsigned(pset
) != 0:
154 cpu_bitmap
= int(pset
.cpu_bitmask
)
155 for cpuid
in IterateBitmap(cpu_bitmap
):
156 processor
= processor_array
[cpuid
]
157 if unsigned(processor
.last_dispatch
) > cur_abstime
:
158 cur_abstime
= unsigned(processor
.last_dispatch
)
160 pset
= pset
.pset_list
162 print "Last dispatch time known: %d MATUs" % cur_abstime
165 @lldb_command('abs2nano')
166 def ShowAbstimeToNanoTime(cmd_args
=[]):
167 """ convert mach_absolute_time units to nano seconds
168 Usage: (lldb) abs2nano <timestamp in MATUs>
171 raise ArgumentError("Invalid argument")
172 timedata
= ArgumentStringToInt(cmd_args
[0])
173 ns
= kern
.GetNanotimeFromAbstime(timedata
)
174 us
= float(ns
) / 1000
183 print "{:d} ns, {:f} us, {:f} ms, {:f} s, {:f} m, {:f} h, {:f} d".format(ns
, us
, ms
, s
, m
, h
, d
)
185 print "{:d} ns, {:f} us, {:f} ms, {:f} s".format(ns
, us
, ms
, s
)
187 # Macro: showschedhistory
189 def GetRecentTimestamp():
191 Return a recent timestamp.
192 TODO: on x86, if not in the debugger, then look at the scheduler
194 if kern
.arch
== 'x86_64':
195 return kern
.globals.debugger_entry_time
197 return GetSchedMostRecentDispatch(False)
199 def GetSchedMostRecentDispatch(show_processor_details
=False):
200 """ Return the most recent dispatch on the system, printing processor
201 details if argument is true.
203 processor_list
= kern
.globals.processor_list
205 most_recent_dispatch
= 0
206 current_processor
= processor_list
208 while unsigned(current_processor
) > 0:
209 active_thread
= current_processor
.active_thread
210 if unsigned(active_thread
) != 0 :
211 task_val
= active_thread
.task
212 proc_val
= Cast(task_val
.bsd_info
, 'proc *')
213 proc_name
= "<unknown>" if unsigned(proc_val
) == 0 else str(proc_val
.p_name
)
215 last_dispatch
= unsigned(current_processor
.last_dispatch
)
217 if kern
.arch
== 'x86_64':
218 cpu_data
= kern
.globals.cpu_data_ptr
[current_processor
.cpu_id
]
220 cpu_debugger_time
= max(cpu_data
.debugger_entry_time
, cpu_data
.debugger_ipi_time
)
221 time_since_dispatch
= unsigned(cpu_debugger_time
- last_dispatch
)
222 time_since_dispatch_us
= kern
.GetNanotimeFromAbstime(time_since_dispatch
) / 1000.0
223 time_since_debugger
= unsigned(cpu_debugger_time
- kern
.globals.debugger_entry_time
)
224 time_since_debugger_us
= kern
.GetNanotimeFromAbstime(time_since_debugger
) / 1000.0
226 if show_processor_details
:
227 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
,
228 time_since_dispatch_us
, time_since_debugger_us
, t
=active_thread
, proc_name
=proc_name
)
230 if show_processor_details
:
231 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 if last_dispatch
> most_recent_dispatch
:
234 most_recent_dispatch
= last_dispatch
236 current_processor
= current_processor
.processor_list
238 return most_recent_dispatch
240 @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"))
241 def ShowThreadSchedHistory(thread
, most_recent_dispatch
):
242 """ Given a thread and the most recent dispatch time of a thread on the
243 system, print out details about scheduler history for the thread.
248 if unsigned(thread
.uthread
) != 0:
249 uthread
= Cast(thread
.uthread
, 'uthread *')
250 # Doing the straightforward thing blows up weirdly, so use some indirections to get back on track
251 if unsigned(uthread
.pth_name
) != 0 :
252 thread_name
= str(kern
.GetValueFromAddress(unsigned(uthread
.pth_name
), 'char*'))
255 task_name
= "unknown"
256 if task
and unsigned(task
.bsd_info
):
257 p
= Cast(task
.bsd_info
, 'proc *')
258 task_name
= str(p
.p_name
)
262 mode
= str(thread
.sched_mode
)
263 if "TIMESHARE" in mode
:
264 sched_mode
+="timeshare"
265 elif "FIXED" in mode
:
267 elif "REALTIME" in mode
:
268 sched_mode
+="realtime"
270 if (unsigned(thread
.bound_processor
) != 0):
274 if (unsigned(thread
.sched_flags
) & 0x0004):
279 thread_state_chars
= {0x0:'', 0x1:'W', 0x2:'S', 0x4:'R', 0x8:'U', 0x10:'H', 0x20:'A', 0x40:'P', 0x80:'I'}
283 state_str
+= thread_state_chars
[int(state
& mask
)]
286 last_on
= thread
.computation_epoch
287 last_off
= thread
.last_run_time
288 last_runnable
= thread
.last_made_runnable_time
289 last_prichange
= thread
.last_basepri_change_time
291 if int(last_runnable
) == 18446744073709551615 :
294 if int(last_prichange
) == 18446744073709551615 :
297 time_on_abs
= unsigned(last_off
- last_on
)
298 time_on_us
= kern
.GetNanotimeFromAbstime(time_on_abs
) / 1000.0
300 time_pending_abs
= unsigned(most_recent_dispatch
- last_runnable
)
301 time_pending_us
= kern
.GetNanotimeFromAbstime(time_pending_abs
) / 1000.0
303 if int(last_runnable
) == 0 :
306 last_prichange_abs
= unsigned(most_recent_dispatch
- last_prichange
)
307 last_prichange_us
= kern
.GetNanotimeFromAbstime(last_prichange_abs
) / 1000.0
309 if int(last_prichange
) == 0 :
310 last_prichange_us
= 0
312 time_since_off_abs
= unsigned(most_recent_dispatch
- last_off
)
313 time_since_off_us
= kern
.GetNanotimeFromAbstime(time_since_off_abs
) / 1000.0
314 time_since_on_abs
= unsigned(most_recent_dispatch
- last_on
)
315 time_since_on_us
= kern
.GetNanotimeFromAbstime(time_since_on_abs
) / 1000.0
317 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}"
318 fmt2
= " {t.base_pri:2d} {t.sched_pri:2d} {t.task_priority:2d} {t.max_priority:2d} {sched_mode:19s}"
319 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 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
)
322 out_str
+= fmt2
.format(t
=thread
, sched_mode
=sched_mode
)
323 out_str
+= fmt3
.format(t
=thread
, state
=state_str
, name
=task_name
, thread_name
=thread_name
)
327 def SortThreads(threads
, column
):
328 if column
!= 'on-core' and column
!= 'off-core' and column
!= 'last-duration':
329 raise ArgumentError("unsupported sort column")
330 if column
== 'on-core':
331 threads
.sort(key
=lambda t
: t
.computation_epoch
)
332 elif column
== 'off-core':
333 threads
.sort(key
=lambda t
: t
.last_run_time
)
335 threads
.sort(key
=lambda t
: t
.last_run_time
- t
.computation_epoch
)
337 @lldb_command('showschedhistory', 'S:')
338 def ShowSchedHistory(cmd_args
=None, cmd_options
=None):
339 """ Routine to print out thread scheduling history, optionally sorted by a
342 Usage: showschedhistory [-S on-core|off-core|last-duration] [<thread-ptr> ...]
346 if '-S' in cmd_options
:
347 sort_column
= cmd_options
['-S']
350 most_recent_dispatch
= GetSchedMostRecentDispatch(False)
352 print ShowThreadSchedHistory
.header
356 for thread_ptr
in cmd_args
:
357 threads
.append(kern
.GetValueFromAddress(ArgumentStringToInt(thread_ptr
), 'thread *'))
359 SortThreads(threads
, sort_column
)
361 for thread
in threads
:
362 ShowThreadSchedHistory(thread
, most_recent_dispatch
)
364 for thread_ptr
in cmd_args
:
365 thread
= kern
.GetValueFromAddress(ArgumentStringToInt(thread_ptr
), 'thread *')
366 ShowThreadSchedHistory(thread
, most_recent_dispatch
)
370 run_buckets
= kern
.globals.sched_run_buckets
372 run_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')]
373 fixpri_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')]
374 share_fg_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
375 share_df_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')]
376 share_ut_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
377 share_bg_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
379 sched_pri_shifts
= kern
.globals.sched_run_buckets
381 share_fg_shift
= sched_pri_shifts
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
382 share_df_shift
= sched_pri_shifts
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')]
383 share_ut_shift
= sched_pri_shifts
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
384 share_bg_shift
= sched_pri_shifts
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
387 print "Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count
, fixpri_count
, g
=kern
.globals)
388 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
)
389 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)
390 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)
391 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)
393 if kern
.arch
== 'x86_64':
394 print "debugger_entry_time: {g.debugger_entry_time:d}\n".format(g
=kern
.globals)
396 most_recent_dispatch
= GetSchedMostRecentDispatch(True)
397 print "Most recent dispatch: " + str(most_recent_dispatch
)
399 print ShowThreadSchedHistory
.header
402 threads
= [t
for t
in IterateQueue(kern
.globals.threads
, 'thread *', 'threads')]
404 SortThreads(threads
, sort_column
)
406 for thread
in threads
:
407 ShowThreadSchedHistory(thread
, most_recent_dispatch
)
409 for thread
in IterateQueue(kern
.globals.threads
, 'thread *', 'threads'):
410 ShowThreadSchedHistory(thread
, most_recent_dispatch
)
413 # EndMacro: showschedhistory
417 return (n ^
0x80000000) - 0x80000000
419 # Macro: showallprocessors
421 def ShowGroupSetSummary(runq
, task_map
):
422 """ Internal function to print summary of group run queue
423 params: runq - value representing struct run_queue *
426 print " runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq
.count
, int32(runq
.highq
), runq
.urgency
)
429 runq_queue_count
= sizeof(runq
.queues
)/sizeof(runq
.queues
[0])
431 for runq_queue_i
in xrange(runq_queue_count
) :
432 runq_queue_head
= addressof(runq
.queues
[runq_queue_i
])
433 runq_queue_p
= runq_queue_head
.next
435 if unsigned(runq_queue_p
) != unsigned(runq_queue_head
):
436 runq_queue_this_count
= 0
438 for entry
in ParanoidIterateLinkageChain(runq_queue_head
, "sched_entry_t", "entry_links"):
439 runq_queue_this_count
+= 1
441 print " Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head
, runq_queue_i
, runq_queue_this_count
)
442 for entry
in ParanoidIterateLinkageChain(runq_queue_head
, "sched_entry_t", "entry_links"):
443 group_addr
= unsigned(entry
) - (sizeof(dereference(entry
)) * unsigned(entry
.sched_pri
))
444 group
= kern
.GetValueFromAddress(unsigned(group_addr
), 'sched_group_t')
445 task
= task_map
.get(unsigned(group
), 0x0)
447 print "Cannot find task for group: {: <#012x}".format(group
)
448 print "\tEntry [{: <#012x}] Priority {: <3d} Group {: <#012x} Task {: <#012x}\n".format(unsigned(entry
), entry
.sched_pri
, unsigned(group
), unsigned(task
))
450 @lldb_command('showrunq')
451 def ShowRunq(cmd_args
=None):
452 """ Routine to print information of a runq
453 Usage: showrunq <runq>
457 print "No arguments passed"
458 print ShowRunq
.__doc
__
461 runq
= kern
.GetValueFromAddress(cmd_args
[0], 'struct run_queue *')
462 ShowRunQSummary(runq
)
464 def ShowRunQSummary(runq
):
465 """ Internal function to print summary of run_queue
466 params: runq - value representing struct run_queue *
469 print " runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq
.count
, int32(runq
.highq
), runq
.urgency
)
472 runq_queue_count
= sizeof(runq
.queues
)/sizeof(runq
.queues
[0])
474 for runq_queue_i
in xrange(runq_queue_count
) :
475 runq_queue_head
= addressof(runq
.queues
[runq_queue_i
])
476 runq_queue_p
= runq_queue_head
.next
478 if unsigned(runq_queue_p
) != unsigned(runq_queue_head
):
479 runq_queue_this_count
= 0
481 for thread
in ParanoidIterateLinkageChain(runq_queue_head
, "thread_t", "runq_links"):
482 runq_queue_this_count
+= 1
484 print " Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head
, runq_queue_i
, runq_queue_this_count
)
485 print "\t" + GetThreadSummary
.header
+ "\n"
486 for thread
in ParanoidIterateLinkageChain(runq_queue_head
, "thread_t", "runq_links"):
487 print "\t" + GetThreadSummary(thread
) + "\n"
488 if config
['verbosity'] > vHUMAN
:
489 print "\t" + GetThreadBackTrace(thread
, prefix
="\t\t") + "\n"
491 def ShowRTRunQSummary(rt_runq
):
492 print " Realtime Queue ({:<#012x}) Count {:d}\n".format(addressof(rt_runq
.queue
), rt_runq
.count
)
493 if rt_runq
.count
!= 0:
494 print "\t" + GetThreadSummary
.header
+ "\n"
495 for rt_runq_thread
in ParanoidIterateLinkageChain(rt_runq
.queue
, "thread_t", "runq_links"):
496 print "\t" + GetThreadSummary(rt_runq_thread
) + "\n"
498 def ShowGrrrSummary(grrr_runq
):
499 """ Internal function to print summary of grrr_run_queue
500 params: grrr_runq - value representing struct grrr_run_queue *
502 print " GRRR Info: Count {: <10d} Weight {: <10d} Current Group {: <#012x}\n".format(grrr_runq
.count
,
503 grrr_runq
.weight
, grrr_runq
.current_group
)
505 grrr_group_count
= sizeof(grrr_runq
.groups
)/sizeof(grrr_runq
.groups
[0])
506 for grrr_group_i
in xrange(grrr_group_count
) :
507 grrr_group
= addressof(grrr_runq
.groups
[grrr_group_i
])
508 if grrr_group
.count
> 0:
509 print " Group {: <3d} [{: <#012x}] ".format(grrr_group
.index
, grrr_group
)
510 print "Count {:d} Weight {:d}\n".format(grrr_group
.count
, grrr_group
.weight
)
511 grrr_group_client_head
= addressof(grrr_group
.clients
)
512 print GetThreadSummary
.header
513 for thread
in ParanoidIterateLinkageChain(grrr_group_client_head
, "thread_t", "runq_links"):
514 print "\t" + GetThreadSummary(thread
) + "\n"
515 if config
['verbosity'] > vHUMAN
:
516 print "\t" + GetThreadBackTrace(thread
, prefix
="\t\t") + "\n"
518 def ShowNextThread(processor
):
519 if (processor
.next_thread
!= 0) :
520 print " " + "Next thread:\n"
521 print "\t" + GetThreadSummary
.header
+ "\n"
522 print "\t" + GetThreadSummary(processor
.next_thread
) + "\n"
524 def ShowActiveThread(processor
):
525 if (processor
.active_thread
!= 0) :
526 print "\t" + GetThreadSummary
.header
+ "\n"
527 print "\t" + GetThreadSummary(processor
.active_thread
) + "\n"
529 @lldb_command('showallprocessors')
530 @lldb_command('showscheduler')
531 def ShowScheduler(cmd_args
=None):
532 """ Routine to print information of all psets and processors
535 node
= addressof(kern
.globals.pset_node0
)
537 show_priority_runq
= 0
538 show_priority_pset_runq
= 0
539 show_group_pset_runq
= 0
540 if unsigned(kern
.globals.sched_current_dispatch
) != 0 :
541 sched_string
= str(kern
.globals.sched_current_dispatch
.sched_name
)
543 sched_string
= str(kern
.globals.sched_string
)
545 if sched_string
== "traditional":
546 show_priority_runq
= 1
547 elif sched_string
== "traditional_with_pset_runqueue":
548 show_priority_pset_runq
= 1
549 elif sched_string
== "grrr":
551 elif sched_string
== "multiq":
552 show_priority_runq
= 1
553 show_group_pset_runq
= 1
554 elif sched_string
== "dualq":
555 show_priority_pset_runq
= 1
556 show_priority_runq
= 1
557 elif sched_string
== "amp":
558 show_priority_pset_runq
= 1
559 show_priority_runq
= 1
561 print "Unknown sched_string {:s}".format(sched_string
)
563 if unsigned(kern
.globals.sched_current_dispatch
) != 0 :
564 print "Scheduler: {:s} ({:s})\n".format(sched_string
,
565 kern
.Symbolicate(unsigned(kern
.globals.sched_current_dispatch
)))
567 run_buckets
= kern
.globals.sched_run_buckets
569 run_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')]
570 fixpri_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')]
571 share_fg_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
572 share_df_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')]
573 share_ut_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
574 share_bg_count
= run_buckets
[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
576 print "Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count
, fixpri_count
, g
=kern
.globals)
577 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
)
579 if show_group_pset_runq
:
580 if hasattr(kern
.globals, "multiq_sanity_check"):
581 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)
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}\n".format(g
=kern
.globals)
585 # Create a group->task mapping
587 for task
in kern
.tasks
:
588 task_map
[unsigned(task
.sched_group
)] = task
589 for task
in kern
.terminated_tasks
:
590 task_map
[unsigned(task
.sched_group
)] = task
596 pset
= kern
.GetValueFromAddress(unsigned(pset
), 'struct processor_set *')
599 print "Processor Set {: <#012x} Count {:d} (cpu_id {:<#x}-{:<#x})\n".format(pset
,
600 unsigned(pset
.cpu_set_count
), pset
.cpu_set_low
, pset
.cpu_set_hi
)
602 rt_runq
= kern
.GetValueFromAddress(unsigned(addressof(pset
.rt_runq
)), 'struct rt_queue *')
603 ShowRTRunQSummary(rt_runq
)
605 if show_priority_pset_runq
:
606 runq
= kern
.GetValueFromAddress(unsigned(addressof(pset
.pset_runq
)), 'struct run_queue *')
607 ShowRunQSummary(runq
)
609 if show_group_pset_runq
:
611 runq
= kern
.GetValueFromAddress(unsigned(addressof(pset
.pset_runq
)), 'struct run_queue *')
612 ShowGroupSetSummary(runq
, task_map
)
613 print "All Groups:\n"
614 # TODO: Possibly output task header for each group
615 for group
in IterateQueue(kern
.globals.sched_groups
, "sched_group_t", "sched_groups"):
616 if (group
.runq
.count
!= 0) :
617 task
= task_map
.get(unsigned(group
), "Unknown task!")
618 print "Group {: <#012x} Task {: <#012x}\n".format(unsigned(group
), unsigned(task
))
619 ShowRunQSummary(group
.runq
)
622 processor_array
= kern
.globals.processor_array
624 print "Active Processors:\n"
625 active_bitmap
= int(pset
.cpu_state_map
[5]) |
int(pset
.cpu_state_map
[6])
626 for cpuid
in IterateBitmap(active_bitmap
):
627 processor
= processor_array
[cpuid
]
629 print " " + GetProcessorSummary(processor
)
630 ShowActiveThread(processor
)
631 ShowNextThread(processor
)
633 if show_priority_runq
:
634 runq
= processor
.runq
635 ShowRunQSummary(runq
)
637 grrr_runq
= processor
.grrr_runq
638 ShowGrrrSummary(grrr_runq
)
642 print "Idle Processors:\n"
643 idle_bitmap
= int(pset
.cpu_state_map
[4]) & int(pset
.primary_map
)
644 for cpuid
in IterateBitmap(idle_bitmap
):
645 processor
= processor_array
[cpuid
]
647 print " " + GetProcessorSummary(processor
)
648 ShowActiveThread(processor
)
649 ShowNextThread(processor
)
651 if show_priority_runq
:
652 ShowRunQSummary(processor
.runq
)
656 print "Idle Secondary Processors:\n"
657 idle_bitmap
= int(pset
.cpu_state_map
[4]) & ~
(int(pset
.primary_map
))
658 for cpuid
in IterateBitmap(idle_bitmap
):
659 processor
= processor_array
[cpuid
]
661 print " " + GetProcessorSummary(processor
)
662 ShowActiveThread(processor
)
663 ShowNextThread(processor
)
665 if show_priority_runq
:
666 print ShowRunQSummary(processor
.runq
)
670 print "Other Processors:\n"
672 for i
in range(0, 4):
673 other_bitmap |
= int(pset
.cpu_state_map
[i
])
674 other_bitmap
&= int(pset
.cpu_bitmask
)
675 for cpuid
in IterateBitmap(other_bitmap
):
676 processor
= processor_array
[cpuid
]
678 print " " + GetProcessorSummary(processor
)
679 ShowActiveThread(processor
)
680 ShowNextThread(processor
)
682 if show_priority_runq
:
683 ShowRunQSummary(processor
.runq
)
687 pset
= pset
.pset_list
689 node
= node
.node_list
691 print "\nTerminate Queue: ({:<#012x})\n".format(addressof(kern
.globals.thread_terminate_queue
))
693 for thread
in ParanoidIterateLinkageChain(kern
.globals.thread_terminate_queue
, "thread_t", "runq_links"):
695 print "\t" + GetThreadSummary
.header
+ "\n"
697 print "\t" + GetThreadSummary(thread
) + "\n"
699 print "\nCrashed Threads Queue: ({:<#012x})\n".format(addressof(kern
.globals.crashed_threads_queue
))
701 for thread
in ParanoidIterateLinkageChain(kern
.globals.crashed_threads_queue
, "thread_t", "runq_links"):
703 print "\t" + GetThreadSummary
.header
+ "\n"
705 print "\t" + GetThreadSummary(thread
) + "\n"
707 print "\nWaiting For Kernel Stacks Queue: ({:<#012x})\n".format(addressof(kern
.globals.thread_stack_queue
))
709 for thread
in ParanoidIterateLinkageChain(kern
.globals.thread_stack_queue
, "thread_t", "runq_links"):
711 print "\t" + GetThreadSummary
.header
+ "\n"
713 print "\t" + GetThreadSummary(thread
) + "\n"
719 # EndMacro: showallprocessors
722 def ParanoidIterateLinkageChain(queue_head
, element_type
, field_name
, field_ofst
=0):
723 """ Iterate over a Linkage Chain queue in kernel of type queue_head_t. (osfmk/kern/queue.h method 1)
724 This is equivalent to the qe_foreach_element() macro
725 Blows up aggressively and descriptively when something goes wrong iterating a queue.
726 Prints correctness errors, and throws exceptions on 'cannot proceed' errors
727 If this is annoying, set the global 'enable_paranoia' to false.
730 queue_head - value : Value object for queue_head.
731 element_type - lldb.SBType : pointer type of the element which contains the queue_chain_t. Typically its structs like thread, task etc..
732 - str : OR a string describing the type. ex. 'task *'
733 field_name - str : Name of the field (in element) which holds a queue_chain_t
734 field_ofst - int : offset from the 'field_name' (in element) which holds a queue_chain_t
735 This is mostly useful if a particular element contains an array of queue_chain_t
737 A generator does not return. It is used for iterating.
738 value : An object thats of type (element_type). Always a pointer object
740 for thread in IterateQueue(kern.globals.threads, 'thread *', 'threads'):
741 print thread.thread_id
744 if type(element_type
) is str:
745 element_type
= gettype(element_type
)
747 # Some ways of constructing a queue head seem to end up with the
748 # struct object as the value and not a pointer to the struct head
749 # In that case, addressof will give us a pointer to the struct, which is what we need
750 if not queue_head
.GetSBValue().GetType().IsPointerType() :
751 queue_head
= addressof(queue_head
)
753 # Mosh the value into a brand new value, to really get rid of its old cvalue history
754 queue_head
= kern
.GetValueFromAddress(unsigned(queue_head
), 'struct queue_entry *')
756 if unsigned(queue_head
) == 0:
757 if ParanoidIterateLinkageChain
.enable_paranoia
:
758 print "bad queue_head_t: {:s}".format(queue_head
)
761 if element_type
.IsPointerType():
762 struct_type
= element_type
.GetPointeeType()
764 struct_type
= element_type
766 elem_ofst
= getfieldoffset(struct_type
, field_name
) + field_ofst
769 link
= queue_head
.next
770 last_link
= queue_head
771 try_read_next
= unsigned(queue_head
.next
)
773 print "Exception while looking at queue_head: {:>#18x}".format(unsigned(queue_head
))
776 if ParanoidIterateLinkageChain
.enable_paranoia
:
777 if unsigned(queue_head
.next
) == 0:
778 raise ValueError("NULL next pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head
, queue_head
.next
, queue_head
.prev
))
779 if unsigned(queue_head
.prev
) == 0:
780 print "NULL prev pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head
, queue_head
.next
, queue_head
.prev
)
781 if unsigned(queue_head
.next
) == unsigned(queue_head
) and unsigned(queue_head
.prev
) != unsigned(queue_head
):
782 print "corrupt queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head
, queue_head
.next
, queue_head
.prev
)
784 if ParanoidIterateLinkageChain
.enable_debug
:
785 print "starting at queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head
, queue_head
.next
, queue_head
.prev
)
791 while (unsigned(queue_head
) != unsigned(link
)):
792 if ParanoidIterateLinkageChain
.enable_paranoia
:
793 if unsigned(link
.next
) == 0:
794 raise ValueError("NULL next pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head
, link
, link
.next
, link
.prev
))
795 if unsigned(link
.prev
) == 0:
796 print "NULL prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head
, link
, link
.next
, link
.prev
)
797 if unsigned(last_link
) != unsigned(link
.prev
):
798 print "Corrupt prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x} prev link: {:>#18x} ".format(
799 queue_head
, link
, link
.next
, link
.prev
, last_link
)
801 addr
= unsigned(link
) - unsigned(elem_ofst
);
802 obj
= kern
.GetValueFromAddress(addr
, element_type
)
803 if ParanoidIterateLinkageChain
.enable_debug
:
804 print "yielding link: {:>#18x} next: {:>#18x} prev: {:>#18x} addr: {:>#18x} obj: {:>#18x}".format(link
, link
.next
, link
.prev
, addr
, obj
)
809 exc_info
= sys
.exc_info()
811 print "Exception while iterating queue: {:>#18x} link: {:>#18x} addr: {:>#18x} obj: {:>#18x} last link: {:>#18x}".format(queue_head
, link
, addr
, obj
, last_link
)
814 traceback
.print_exc()
815 raise exc_info
[0], exc_info
[1], exc_info
[2]
817 ParanoidIterateLinkageChain
.enable_paranoia
= True
818 ParanoidIterateLinkageChain
.enable_debug
= False
820 def bit_first(bitmap
):
821 return bitmap
.bit_length() - 1
823 def lsb_first(bitmap
):
824 bitmap
= bitmap
& -bitmap
825 return bit_first(bitmap
)
827 def IterateBitmap(bitmap
):
828 """ Iterate over a bitmap, returning the index of set bits starting from 0
831 bitmap - value : bitmap
833 A generator does not return. It is used for iterating.
834 value : index of a set bit
836 for cpuid in IterateBitmap(running_bitmap):
837 print processor_array[cpuid]
839 i
= lsb_first(bitmap
)
842 bitmap
= bitmap
& ~
((1 << (i
+ 1)) - 1)
843 i
= lsb_first(bitmap
)
846 # Macro: showallcallouts
848 def ShowThreadCall(prefix
, call
):
850 Print a description of a thread_call_t and its relationship to its expected fire time
852 func
= call
.tc_call
.func
853 param0
= call
.tc_call
.param0
854 param1
= call
.tc_call
.param1
857 iotes_callout
= kern
.GetLoadAddressForSymbol("_ZN18IOTimerEventSource17timeoutAndReleaseEPvS0_")
858 iotes_callout2
= kern
.GetLoadAddressForSymbol("_ZN18IOTimerEventSource15timeoutSignaledEPvS0_")
860 if (unsigned(func
) == unsigned(iotes_callout
) or
861 unsigned(func
) == unsigned(iotes_callout2
)) :
862 iotes
= Cast(call
.tc_call
.param0
, 'IOTimerEventSource*')
865 param1
= unsigned(iotes
)
867 func_name
= kern
.Symbolicate(func
)
868 if (func_name
== "") :
869 func_name
= FindKmodNameForAddr(func
)
871 call_entry
= call
.tc_call
873 recent_timestamp
= GetRecentTimestamp()
875 # THREAD_CALL_CONTINUOUS 0x100
876 kern
.globals.mach_absolutetime_asleep
877 if (call
.tc_flags
& 0x100) :
878 timer_fire
= call_entry
.deadline
- (recent_timestamp
+ kern
.globals.mach_absolutetime_asleep
)
880 timer_fire
= call_entry
.deadline
- recent_timestamp
882 timer_fire_s
= kern
.GetNanotimeFromAbstime(timer_fire
) / 1000000000.0
884 ttd_s
= kern
.GetNanotimeFromAbstime(call
.tc_ttd
) / 1000000000.0
886 print "{:s}{:#018x}: {:18d} {:18d} {:03.06f} {:03.06f} {:#018x}({:#018x},{:#018x}) ({:s})".format(prefix
,
887 unsigned(call
), call_entry
.deadline
, call
.tc_soft_deadline
, ttd_s
, timer_fire_s
,
888 func
, param0
, param1
, func_name
)
890 @lldb_command('showallcallouts')
891 def ShowAllCallouts(cmd_args
=None):
892 """ Prints out the pending and delayed thread calls for the thread call groups
895 index_max
= GetEnumValue('thread_call_index_t::THREAD_CALL_INDEX_MAX')
897 for i
in range (0, index_max
) :
898 group
= kern
.globals.thread_call_groups
[i
]
900 print "Group {i:d}: {g.tcg_name:s} ({:>#18x})".format(addressof(group
), i
=i
, g
=group
)
901 print "\t" +"Active: {g.active_count:d} Idle: {g.idle_count:d}\n".format(g
=group
)
902 print "\t" +"Blocked: {g.blocked_count:d} Pending: {g.pending_count:d}\n".format(g
=group
)
903 print "\t" +"Target: {g.target_thread_count:d}\n".format(g
=group
)
905 print "\t" +"Pending Queue: ({:>#18x})\n".format(addressof(group
.pending_queue
))
906 for call
in ParanoidIterateLinkageChain(group
.pending_queue
, "thread_call_t", "tc_call.q_link"):
907 ShowThreadCall("\t\t", call
)
909 print "\t" +"Delayed Queue (Absolute Time): ({:>#18x}) timer: ({:>#18x})\n".format(
910 addressof(group
.delayed_queues
[0]), addressof(group
.delayed_timers
[0]))
911 for call
in ParanoidIterateLinkageChain(group
.delayed_queues
[0], "thread_call_t", "tc_call.q_link"):
912 ShowThreadCall("\t\t", call
)
914 print "\t" +"Delayed Queue (Continuous Time): ({:>#18x}) timer: ({:>#18x})\n".format(
915 addressof(group
.delayed_queues
[1]), addressof(group
.delayed_timers
[1]))
916 for call
in ParanoidIterateLinkageChain(group
.delayed_queues
[1], "thread_call_t", "tc_call.q_link"):
917 ShowThreadCall("\t\t", call
)
919 # EndMacro: showallcallouts