]> git.saurik.com Git - apple/xnu.git/blob - tools/lldbmacros/scheduler.py
xnu-6153.101.6.tar.gz
[apple/xnu.git] / tools / lldbmacros / scheduler.py
1 from xnu import *
2 from utils import *
3 from process import *
4 from misc import *
5 from memory import *
6
7 # TODO: write scheduler related macros here
8
9 # Macro: showallprocrunqcount
10
11 @lldb_command('showallprocrunqcount')
12 def 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
20 # out_str += "RT:\t\t{:d}\n".format(kern.globals.rt_runq.count)
21 print out_str
22
23 # EndMacro: showallprocrunqcount
24
25 # Macro: showinterrupts
26
27 @lldb_command('showinterrupts')
28 def ShowInterrupts(cmd_args=None):
29 """ Prints IRQ, IPI and TMR counts for each CPU
30 """
31
32 if not kern.arch.startswith('arm'):
33 print "showinterrupts is only supported on arm/arm64"
34 return
35
36 base_address = kern.GetLoadAddressForSymbol('CpuDataEntries')
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 {} PMI: {:d}\n".format(y, cpu_data_entry.cpu_monotonic.mtc_npmis)
47 print "CPU {} TMR: {:d}\n".format(y, cpu_data_entry.cpu_stat.timer_cnt)
48 x = x + 1
49 y = y + 1
50
51 # EndMacro: showinterrupts
52
53 # Macro: showactiveinterrupts
54
55 @lldb_command('showactiveinterrupts')
56 def 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
89 # EndMacro: showactiveinterrupts
90
91 # Macro: showirqbyipitimerratio
92 @lldb_command('showirqbyipitimerratio')
93 def 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
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
112 print out_str
113
114 # EndMacro: showirqbyipitimerratio
115
116 #Macro: showinterruptsourceinfo
117 @lldb_command('showinterruptsourceinfo')
118 def 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
144
145 @lldb_command('showcurrentabstime')
146 def 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)
151 processor_array = kern.globals.processor_array
152 cur_abstime = 0
153
154 while unsigned(pset) != 0:
155 cpu_bitmap = int(pset.cpu_bitmask)
156 for cpuid in IterateBitmap(cpu_bitmap):
157 processor = processor_array[cpuid]
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 bucketStr = ["FIXPRI (>UI)", "TIMESHARE_FG", "TIMESHARE_IN", "TIMESHARE_DF", "TIMESHARE_UT", "TIMESHARE_BG"]
166
167 @header(" {:>18s} | {:>20s} | {:>20s} | {:>10s} | {:>10s}".format('Thread Group', 'Interactivity Score', 'Last Timeshare Tick', 'pri_shift', 'highq'))
168 def GetSchedClutchBucketSummary(clutch_bucket):
169 return " 0x{:>16x} | {:>20d} | {:>20d} | {:>10d} | {:>10d}".format(clutch_bucket.scb_clutch.sc_tg, clutch_bucket.scb_interactivity_score, clutch_bucket.scb_timeshare_tick, clutch_bucket.scb_pri_shift, clutch_bucket.scb_runq.highq)
170
171 def ShowSchedClutchForPset(pset):
172 root_clutch = pset.pset_clutch_root
173 print "\n{:s} : {:d}\n\n".format("Current Timestamp", GetRecentTimestamp())
174 print "{:>10s} | {:>20s} | {:>30s} | {:>18s} | {:>10s} | {:>10s} | {:>30s} | {:>30s} | {:>15s} | ".format("Root", "Root Buckets", "Clutch Buckets", "Address", "Priority", "Count", "CPU Usage (MATUs)", "CPU Blocked (MATUs)", "Deadline (abs)") + GetSchedClutchBucketSummary.header
175 print "=" * 300
176 print "{:>10s} | {:>20s} | {:>30s} | 0x{:16x} | {:>10d} | {:>10d} | {:>30s} | {:>30s} | {:>15s} | ".format("Root", "*", "*", addressof(root_clutch), root_clutch.scr_priority, root_clutch.scr_thr_count, "*", "*", "*")
177 print "-" * 300
178
179 for i in range(0, 6):
180 root_bucket = root_clutch.scr_buckets[i]
181 print "{:>10s} | {:>20s} | {:>30s} | 0x{:16x} | {:>10s} | {:>10s} | {:>30s} | {:>30s} | {:>15d} | ".format("*", bucketStr[i], "*", addressof(root_bucket), "*", "*", "*", "*", root_bucket.scrb_deadline)
182 clutch_bucket_runq = root_bucket.scrb_clutch_buckets
183 clutch_bucket_list = []
184 for pri in range(0,128):
185 clutch_bucket_circleq = clutch_bucket_runq.scbrq_queues[pri]
186 for clutch_bucket in IterateCircleQueue(clutch_bucket_circleq, 'struct sched_clutch_bucket', 'scb_runqlink'):
187 clutch_bucket_list.append(clutch_bucket)
188 if len(clutch_bucket_list) > 0:
189 clutch_bucket_list.sort(key=lambda x: x.scb_priority, reverse=True)
190 for clutch_bucket in clutch_bucket_list:
191 cpu_used = clutch_bucket.scb_cpu_data.cpu_data.scbcd_cpu_used
192 cpu_blocked = clutch_bucket.scb_cpu_data.cpu_data.scbcd_cpu_blocked
193 print "{:>10s} | {:>20s} | {:>30s} | 0x{:16x} | {:>10d} | {:>10d} | {:>30d} | {:>30d} | {:>15s} | ".format("*", "*", clutch_bucket.scb_clutch.sc_tg.tg_name, clutch_bucket, clutch_bucket.scb_priority, clutch_bucket.scb_thr_count, cpu_used, cpu_blocked, "*") + GetSchedClutchBucketSummary(clutch_bucket)
194 print "-" * 300
195
196 @lldb_command('showschedclutch')
197 def ShowSchedClutch(cmd_args=[]):
198 """ Routine to print the clutch scheduler hierarchy.
199 Usage: showschedclutch <pset>
200 """
201 if not cmd_args:
202 raise ArgumentError("Invalid argument")
203 pset = kern.GetValueFromAddress(cmd_args[0], "processor_set_t")
204 ShowSchedClutchForPset(pset)
205
206 @lldb_command('showschedclutchroot')
207 def ShowSchedClutchRoot(cmd_args=[]):
208 """ show information about the root of the sched clutch hierarchy
209 Usage: showschedclutchroot <root>
210 """
211 if not cmd_args:
212 raise ArgumentError("Invalid argument")
213 root = kern.GetValueFromAddress(cmd_args[0], "struct sched_clutch_root *")
214 if not root:
215 print "unknown arguments:", str(cmd_args)
216 return False
217 print "{:>30s} : 0x{:16x}".format("Root", root)
218 print "{:>30s} : 0x{:16x}".format("Pset", root.scr_pset)
219 print "{:>30s} : {:d}".format("Priority", root.scr_priority)
220 print "{:>30s} : {:d}".format("Urgency", root.scr_urgency)
221 print "{:>30s} : {:d}".format("Threads", root.scr_thr_count)
222 print "{:>30s} : {:d}".format("Current Timestamp", GetRecentTimestamp())
223 print "{:>30s} : {:b} (BG/UT/DF/IN/FG/FIX/NULL)".format("Runnable Root Buckets Bitmap", int(root.scr_runnable_bitmap[0]))
224
225 @lldb_command('showschedclutchrootbucket')
226 def ShowSchedClutchRootBucket(cmd_args=[]):
227 """ show information about a root bucket in the sched clutch hierarchy
228 Usage: showschedclutchrootbucket <root_bucket>
229 """
230 if not cmd_args:
231 raise ArgumentError("Invalid argument")
232 root_bucket = kern.GetValueFromAddress(cmd_args[0], "struct sched_clutch_root_bucket *")
233 if not root_bucket:
234 print "unknown arguments:", str(cmd_args)
235 return False
236 print "{:<30s} : 0x{:16x}".format("Root Bucket", root_bucket)
237 print "{:<30s} : {:s}".format("Bucket Name", bucketStr[int(root_bucket.scrb_bucket)])
238 print "{:<30s} : {:d}".format("Deadline", root_bucket.scrb_deadline)
239 print "{:<30s} : {:d}".format("Current Timestamp", GetRecentTimestamp())
240 print "\n"
241 clutch_bucket_runq = root_bucket.scrb_clutch_buckets
242 clutch_bucket_list = []
243 for pri in range(0,128):
244 clutch_bucket_circleq = clutch_bucket_runq.scbrq_queues[pri]
245 for clutch_bucket in IterateCircleQueue(clutch_bucket_circleq, 'struct sched_clutch_bucket', 'scb_runqlink'):
246 clutch_bucket_list.append(clutch_bucket)
247 if len(clutch_bucket_list) > 0:
248 print "=" * 240
249 print "{:>30s} | {:>18s} | {:>20s} | {:>20s} | ".format("Name", "Clutch Bucket", "Priority", "Count") + GetSchedClutchBucketSummary.header
250 print "=" * 240
251 clutch_bucket_list.sort(key=lambda x: x.scb_priority, reverse=True)
252 for clutch_bucket in clutch_bucket_list:
253 print "{:>30s} | 0x{:16x} | {:>20d} | {:>20d} | ".format(clutch_bucket.scb_clutch.sc_tg.tg_name, clutch_bucket, clutch_bucket.scb_priority, clutch_bucket.scb_thr_count) + GetSchedClutchBucketSummary(clutch_bucket)
254
255 @lldb_command('showschedclutchbucket')
256 def ShowSchedClutchBucket(cmd_args=[]):
257 """ show information about a clutch bucket in the sched clutch hierarchy
258 Usage: showschedclutchbucket <clutch_bucket>
259 """
260 if not cmd_args:
261 raise ArgumentError("Invalid argument")
262 clutch_bucket = kern.GetValueFromAddress(cmd_args[0], "struct sched_clutch_bucket *")
263 if not clutch_bucket:
264 print "unknown arguments:", str(cmd_args)
265 return False
266 print "{:<30s} : 0x{:16x}".format("Clutch Bucket", clutch_bucket)
267 print "{:<30s} : {:s}".format("TG Name", clutch_bucket.scb_clutch.sc_tg.tg_name)
268 print "{:<30s} : {:d}".format("Priority", clutch_bucket.scb_priority)
269 print "{:<30s} : {:d}".format("Thread Count", clutch_bucket.scb_thr_count)
270 print "{:<30s} : 0x{:16x}".format("Thread Group", clutch_bucket.scb_clutch.sc_tg)
271 cpu_used = clutch_bucket.scb_cpu_data.cpu_data.scbcd_cpu_used
272 cpu_blocked = clutch_bucket.scb_cpu_data.cpu_data.scbcd_cpu_blocked
273 print "{:<30s} : {:d}".format("CPU Used (MATUs)", cpu_used)
274 print "{:<30s} : {:d}".format("CPU Blocked (MATUs)", cpu_blocked)
275 print "{:<30s} : {:d}".format("Interactivity Score", clutch_bucket.scb_interactivity_score)
276 print "{:<30s} : {:d}".format("Last Timeshare Update Tick", clutch_bucket.scb_timeshare_tick)
277 print "{:<30s} : {:d}".format("Priority Shift", clutch_bucket.scb_pri_shift)
278 print "\n"
279 runq = clutch_bucket.scb_clutchpri_prioq
280 thread_list = []
281 for thread in IteratePriorityQueue(runq, 'struct thread', 'sched_clutchpri_link'):
282 thread_list.append(thread)
283 if len(thread_list) > 0:
284 print "=" * 240
285 print GetThreadSummary.header + "{:s}".format("Process Name")
286 print "=" * 240
287 for thread in thread_list:
288 proc = Cast(thread.task.bsd_info, 'proc *')
289 print GetThreadSummary(thread) + "{:s}".format(str(proc.p_comm))
290
291 @lldb_command('abs2nano')
292 def ShowAbstimeToNanoTime(cmd_args=[]):
293 """ convert mach_absolute_time units to nano seconds
294 Usage: (lldb) abs2nano <timestamp in MATUs>
295 """
296 if not cmd_args:
297 raise ArgumentError("Invalid argument")
298 timedata = ArgumentStringToInt(cmd_args[0])
299 ns = kern.GetNanotimeFromAbstime(timedata)
300 us = float(ns) / 1000
301 ms = us / 1000
302 s = ms / 1000
303
304 if s > 60 :
305 m = s / 60
306 h = m / 60
307 d = h / 24
308
309 print "{:d} ns, {:f} us, {:f} ms, {:f} s, {:f} m, {:f} h, {:f} d".format(ns, us, ms, s, m, h, d)
310 else:
311 print "{:d} ns, {:f} us, {:f} ms, {:f} s".format(ns, us, ms, s)
312
313 # Macro: showschedhistory
314
315 def GetRecentTimestamp():
316 """
317 Return a recent timestamp.
318 TODO: on x86, if not in the debugger, then look at the scheduler
319 """
320 if kern.arch == 'x86_64':
321 return kern.globals.debugger_entry_time
322 else :
323 return GetSchedMostRecentDispatch(False)
324
325 def GetSchedMostRecentDispatch(show_processor_details=False):
326 """ Return the most recent dispatch on the system, printing processor
327 details if argument is true.
328 """
329 processor_list = kern.globals.processor_list
330
331 most_recent_dispatch = 0
332 current_processor = processor_list
333
334 while unsigned(current_processor) > 0:
335 active_thread = current_processor.active_thread
336 if unsigned(active_thread) != 0 :
337 task_val = active_thread.task
338 proc_val = Cast(task_val.bsd_info, 'proc *')
339 proc_name = "<unknown>" if unsigned(proc_val) == 0 else str(proc_val.p_name)
340
341 last_dispatch = unsigned(current_processor.last_dispatch)
342
343 if kern.arch == 'x86_64':
344 cpu_data = kern.globals.cpu_data_ptr[current_processor.cpu_id]
345 if (cpu_data != 0) :
346 cpu_debugger_time = max(cpu_data.debugger_entry_time, cpu_data.debugger_ipi_time)
347 time_since_dispatch = unsigned(cpu_debugger_time - last_dispatch)
348 time_since_dispatch_us = kern.GetNanotimeFromAbstime(time_since_dispatch) / 1000.0
349 time_since_debugger = unsigned(cpu_debugger_time - kern.globals.debugger_entry_time)
350 time_since_debugger_us = kern.GetNanotimeFromAbstime(time_since_debugger) / 1000.0
351
352 if show_processor_details:
353 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,
354 time_since_dispatch_us, time_since_debugger_us, t=active_thread, proc_name=proc_name)
355 else:
356 if show_processor_details:
357 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)
358
359 if last_dispatch > most_recent_dispatch:
360 most_recent_dispatch = last_dispatch
361
362 current_processor = current_processor.processor_list
363
364 return most_recent_dispatch
365
366 @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"))
367 def ShowThreadSchedHistory(thread, most_recent_dispatch):
368 """ Given a thread and the most recent dispatch time of a thread on the
369 system, print out details about scheduler history for the thread.
370 """
371
372 thread_name = ""
373
374 if unsigned(thread.uthread) != 0:
375 uthread = Cast(thread.uthread, 'uthread *')
376 # Doing the straightforward thing blows up weirdly, so use some indirections to get back on track
377 if unsigned(uthread.pth_name) != 0 :
378 thread_name = str(kern.GetValueFromAddress(unsigned(uthread.pth_name), 'char*'))
379
380 task = thread.task
381 task_name = "unknown"
382 if task and unsigned(task.bsd_info):
383 p = Cast(task.bsd_info, 'proc *')
384 task_name = str(p.p_name)
385
386 sched_mode = ""
387
388 mode = str(thread.sched_mode)
389 if "TIMESHARE" in mode:
390 sched_mode+="timeshare"
391 elif "FIXED" in mode:
392 sched_mode+="fixed"
393 elif "REALTIME" in mode:
394 sched_mode+="realtime"
395
396 if (unsigned(thread.bound_processor) != 0):
397 sched_mode+="-bound"
398
399 # TH_SFLAG_THROTTLED
400 if (unsigned(thread.sched_flags) & 0x0004):
401 sched_mode+="-BG"
402
403 state = thread.state
404
405 thread_state_chars = {0x0:'', 0x1:'W', 0x2:'S', 0x4:'R', 0x8:'U', 0x10:'H', 0x20:'A', 0x40:'P', 0x80:'I'}
406 state_str = ''
407 mask = 0x1
408 while mask <= 0x80 :
409 state_str += thread_state_chars[int(state & mask)]
410 mask = mask << 1
411
412 last_on = thread.computation_epoch
413 last_off = thread.last_run_time
414 last_runnable = thread.last_made_runnable_time
415 last_prichange = thread.last_basepri_change_time
416
417 if int(last_runnable) == 18446744073709551615 :
418 last_runnable = 0
419
420 if int(last_prichange) == 18446744073709551615 :
421 last_prichange = 0
422
423 time_on_abs = unsigned(last_off - last_on)
424 time_on_us = kern.GetNanotimeFromAbstime(time_on_abs) / 1000.0
425
426 time_pending_abs = unsigned(most_recent_dispatch - last_runnable)
427 time_pending_us = kern.GetNanotimeFromAbstime(time_pending_abs) / 1000.0
428
429 if int(last_runnable) == 0 :
430 time_pending_us = 0
431
432 last_prichange_abs = unsigned(most_recent_dispatch - last_prichange)
433 last_prichange_us = kern.GetNanotimeFromAbstime(last_prichange_abs) / 1000.0
434
435 if int(last_prichange) == 0 :
436 last_prichange_us = 0
437
438 time_since_off_abs = unsigned(most_recent_dispatch - last_off)
439 time_since_off_us = kern.GetNanotimeFromAbstime(time_since_off_abs) / 1000.0
440 time_since_on_abs = unsigned(most_recent_dispatch - last_on)
441 time_since_on_us = kern.GetNanotimeFromAbstime(time_since_on_abs) / 1000.0
442
443 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}"
444 fmt2 = " {t.base_pri:2d} {t.sched_pri:2d} {t.task_priority:2d} {t.max_priority:2d} {sched_mode:19s}"
445 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}"
446
447 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)
448 out_str += fmt2.format(t=thread, sched_mode=sched_mode)
449 out_str += fmt3.format(t=thread, state=state_str, name=task_name, thread_name=thread_name)
450
451 print out_str
452
453 def SortThreads(threads, column):
454 if column != 'on-core' and column != 'off-core' and column != 'last-duration':
455 raise ArgumentError("unsupported sort column")
456 if column == 'on-core':
457 threads.sort(key=lambda t: t.computation_epoch)
458 elif column == 'off-core':
459 threads.sort(key=lambda t: t.last_run_time)
460 else:
461 threads.sort(key=lambda t: t.last_run_time - t.computation_epoch)
462
463 @lldb_command('showschedhistory', 'S:')
464 def ShowSchedHistory(cmd_args=None, cmd_options=None):
465 """ Routine to print out thread scheduling history, optionally sorted by a
466 column.
467
468 Usage: showschedhistory [-S on-core|off-core|last-duration] [<thread-ptr> ...]
469 """
470
471 sort_column = None
472 if '-S' in cmd_options:
473 sort_column = cmd_options['-S']
474
475 if cmd_args:
476 most_recent_dispatch = GetSchedMostRecentDispatch(False)
477
478 print ShowThreadSchedHistory.header
479
480 if sort_column:
481 threads = []
482 for thread_ptr in cmd_args:
483 threads.append(kern.GetValueFromAddress(ArgumentStringToInt(thread_ptr), 'thread *'))
484
485 SortThreads(threads, sort_column)
486
487 for thread in threads:
488 ShowThreadSchedHistory(thread, most_recent_dispatch)
489 else:
490 for thread_ptr in cmd_args:
491 thread = kern.GetValueFromAddress(ArgumentStringToInt(thread_ptr), 'thread *')
492 ShowThreadSchedHistory(thread, most_recent_dispatch)
493
494 return
495
496 run_buckets = kern.globals.sched_run_buckets
497
498 run_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')]
499 fixpri_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')]
500 share_fg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
501 share_df_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')]
502 share_ut_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
503 share_bg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
504
505 sched_pri_shifts = kern.globals.sched_run_buckets
506
507 share_fg_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
508 share_df_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')]
509 share_ut_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
510 share_bg_shift = sched_pri_shifts[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
511
512
513 print "Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count, fixpri_count, g=kern.globals)
514 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)
515 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)
516 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)
517 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)
518
519 if kern.arch == 'x86_64':
520 print "debugger_entry_time: {g.debugger_entry_time:d}\n".format(g=kern.globals)
521
522 most_recent_dispatch = GetSchedMostRecentDispatch(True)
523 print "Most recent dispatch: " + str(most_recent_dispatch)
524
525 print ShowThreadSchedHistory.header
526
527 if sort_column:
528 threads = [t for t in IterateQueue(kern.globals.threads, 'thread *', 'threads')]
529
530 SortThreads(threads, sort_column)
531
532 for thread in threads:
533 ShowThreadSchedHistory(thread, most_recent_dispatch)
534 else:
535 for thread in IterateQueue(kern.globals.threads, 'thread *', 'threads'):
536 ShowThreadSchedHistory(thread, most_recent_dispatch)
537
538
539 # EndMacro: showschedhistory
540
541 def int32(n):
542 n = n & 0xffffffff
543 return (n ^ 0x80000000) - 0x80000000
544
545 # Macro: showallprocessors
546
547 def ShowGroupSetSummary(runq, task_map):
548 """ Internal function to print summary of group run queue
549 params: runq - value representing struct run_queue *
550 """
551
552 print " runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq.count, int32(runq.highq), runq.urgency)
553
554 runq_queue_i = 0
555 runq_queue_count = sizeof(runq.queues)/sizeof(runq.queues[0])
556
557 for runq_queue_i in xrange(runq_queue_count) :
558 runq_queue_head = addressof(runq.queues[runq_queue_i])
559 runq_queue_p = runq_queue_head.next
560
561 if unsigned(runq_queue_p) != unsigned(runq_queue_head):
562 runq_queue_this_count = 0
563
564 for entry in ParanoidIterateLinkageChain(runq_queue_head, "sched_entry_t", "entry_links", circleQueue=True):
565 runq_queue_this_count += 1
566
567 print " Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head, runq_queue_i, runq_queue_this_count)
568 for entry in ParanoidIterateLinkageChain(runq_queue_head, "sched_entry_t", "entry_links", circleQueue=True):
569 group_addr = unsigned(entry) - (sizeof(dereference(entry)) * unsigned(entry.sched_pri))
570 group = kern.GetValueFromAddress(unsigned(group_addr), 'sched_group_t')
571 task = task_map.get(unsigned(group), 0x0)
572 if task == 0x0 :
573 print "Cannot find task for group: {: <#012x}".format(group)
574 print "\tEntry [{: <#012x}] Priority {: <3d} Group {: <#012x} Task {: <#012x}\n".format(unsigned(entry), entry.sched_pri, unsigned(group), unsigned(task))
575
576 @lldb_command('showrunq')
577 def ShowRunq(cmd_args=None):
578 """ Routine to print information of a runq
579 Usage: showrunq <runq>
580 """
581
582 if not cmd_args:
583 print "No arguments passed"
584 print ShowRunq.__doc__
585 return False
586
587 runq = kern.GetValueFromAddress(cmd_args[0], 'struct run_queue *')
588 ShowRunQSummary(runq)
589
590 def ShowRunQSummary(runq):
591 """ Internal function to print summary of run_queue
592 params: runq - value representing struct run_queue *
593 """
594
595 print " runq: count {: <10d} highq: {: <10d} urgency {: <10d}\n".format(runq.count, int32(runq.highq), runq.urgency)
596
597 runq_queue_i = 0
598 runq_queue_count = sizeof(runq.queues)/sizeof(runq.queues[0])
599
600 for runq_queue_i in xrange(runq_queue_count) :
601 runq_queue_head = addressof(runq.queues[runq_queue_i])
602 runq_queue_p = runq_queue_head.head
603
604 if unsigned(runq_queue_p):
605 runq_queue_this_count = 0
606
607 for thread in ParanoidIterateLinkageChain(runq_queue_head, "thread_t", "runq_links", circleQueue=True):
608 runq_queue_this_count += 1
609
610 print " Queue [{: <#012x}] Priority {: <3d} count {:d}\n".format(runq_queue_head, runq_queue_i, runq_queue_this_count)
611 print "\t" + GetThreadSummary.header + "\n"
612 for thread in ParanoidIterateLinkageChain(runq_queue_head, "thread_t", "runq_links", circleQueue=True):
613 print "\t" + GetThreadSummary(thread) + "\n"
614 if config['verbosity'] > vHUMAN :
615 print "\t" + GetThreadBackTrace(thread, prefix="\t\t") + "\n"
616
617 def ShowRTRunQSummary(rt_runq):
618 if (hex(rt_runq.count) == hex(0xfdfdfdfd)) :
619 print " Realtime Queue ({:<#012x}) uninitialized\n".format(addressof(rt_runq.queue))
620 return
621 print " Realtime Queue ({:<#012x}) Count {:d}\n".format(addressof(rt_runq.queue), rt_runq.count)
622 if rt_runq.count != 0:
623 print "\t" + GetThreadSummary.header + "\n"
624 for rt_runq_thread in ParanoidIterateLinkageChain(rt_runq.queue, "thread_t", "runq_links", circleQueue=True):
625 print "\t" + GetThreadSummary(rt_runq_thread) + "\n"
626
627 def ShowGrrrSummary(grrr_runq):
628 """ Internal function to print summary of grrr_run_queue
629 params: grrr_runq - value representing struct grrr_run_queue *
630 """
631 print " GRRR Info: Count {: <10d} Weight {: <10d} Current Group {: <#012x}\n".format(grrr_runq.count,
632 grrr_runq.weight, grrr_runq.current_group)
633 grrr_group_i = 0
634 grrr_group_count = sizeof(grrr_runq.groups)/sizeof(grrr_runq.groups[0])
635 for grrr_group_i in xrange(grrr_group_count) :
636 grrr_group = addressof(grrr_runq.groups[grrr_group_i])
637 if grrr_group.count > 0:
638 print " Group {: <3d} [{: <#012x}] ".format(grrr_group.index, grrr_group)
639 print "Count {:d} Weight {:d}\n".format(grrr_group.count, grrr_group.weight)
640 grrr_group_client_head = addressof(grrr_group.clients)
641 print GetThreadSummary.header
642 for thread in ParanoidIterateLinkageChain(grrr_group_client_head, "thread_t", "runq_links", circleQueue=True):
643 print "\t" + GetThreadSummary(thread) + "\n"
644 if config['verbosity'] > vHUMAN :
645 print "\t" + GetThreadBackTrace(thread, prefix="\t\t") + "\n"
646
647 def ShowActiveThread(processor):
648 if (processor.active_thread != 0) :
649 print "\t" + GetThreadSummary.header + "\n"
650 print "\t" + GetThreadSummary(processor.active_thread) + "\n"
651
652 @lldb_command('showallprocessors')
653 @lldb_command('showscheduler')
654 def ShowScheduler(cmd_args=None):
655 """ Routine to print information of all psets and processors
656 Usage: showscheduler
657 """
658 node = addressof(kern.globals.pset_node0)
659 show_grrr = 0
660 show_priority_runq = 0
661 show_priority_pset_runq = 0
662 show_group_pset_runq = 0
663 show_clutch = 0
664 sched_string = str(kern.globals.sched_string)
665
666 if sched_string == "traditional":
667 show_priority_runq = 1
668 elif sched_string == "traditional_with_pset_runqueue":
669 show_priority_pset_runq = 1
670 elif sched_string == "grrr":
671 show_grrr = 1
672 elif sched_string == "multiq":
673 show_priority_runq = 1
674 show_group_pset_runq = 1
675 elif sched_string == "dualq":
676 show_priority_pset_runq = 1
677 show_priority_runq = 1
678 elif sched_string == "amp":
679 show_priority_pset_runq = 1
680 show_priority_runq = 1
681 elif sched_string == "clutch":
682 show_clutch = 1
683 else :
684 print "Unknown sched_string {:s}".format(sched_string)
685
686 print "Scheduler: {:s}\n".format(sched_string)
687
688 if show_clutch == 0:
689 run_buckets = kern.globals.sched_run_buckets
690 run_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_RUN')]
691 fixpri_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_FIXPRI')]
692 share_fg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_FG')]
693 share_df_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_DF')]
694 share_ut_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_UT')]
695 share_bg_count = run_buckets[GetEnumValue('sched_bucket_t::TH_BUCKET_SHARE_BG')]
696 print "Processors: {g.processor_avail_count:d} Runnable threads: {:d} Fixpri threads: {:d}\n".format(run_count, fixpri_count, g=kern.globals)
697 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)
698
699 processor_offline = GetEnumValue('processor_state_t::PROCESSOR_OFF_LINE')
700 processor_idle = GetEnumValue('processor_state_t::PROCESSOR_IDLE')
701 processor_dispatching = GetEnumValue('processor_state_t::PROCESSOR_DISPATCHING')
702 processor_running = GetEnumValue('processor_state_t::PROCESSOR_RUNNING')
703
704 if show_group_pset_runq:
705 if hasattr(kern.globals, "multiq_sanity_check"):
706 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)
707 else:
708 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)
709
710 # Create a group->task mapping
711 task_map = {}
712 for task in kern.tasks:
713 task_map[unsigned(task.sched_group)] = task
714 for task in kern.terminated_tasks:
715 task_map[unsigned(task.sched_group)] = task
716
717 print " \n"
718
719 while node != 0:
720 pset = node.psets
721 pset = kern.GetValueFromAddress(unsigned(pset), 'struct processor_set *')
722
723 while pset != 0:
724 print "Processor Set {: <#012x} Count {:d} (cpu_id {:<#x}-{:<#x})\n".format(pset,
725 unsigned(pset.cpu_set_count), pset.cpu_set_low, pset.cpu_set_hi)
726
727 rt_runq = kern.GetValueFromAddress(unsigned(addressof(pset.rt_runq)), 'struct rt_queue *')
728 ShowRTRunQSummary(rt_runq)
729
730 if show_priority_pset_runq:
731 runq = kern.GetValueFromAddress(unsigned(addressof(pset.pset_runq)), 'struct run_queue *')
732 ShowRunQSummary(runq)
733
734 if show_group_pset_runq:
735 print "Main Runq:\n"
736 runq = kern.GetValueFromAddress(unsigned(addressof(pset.pset_runq)), 'struct run_queue *')
737 ShowGroupSetSummary(runq, task_map)
738 print "All Groups:\n"
739 # TODO: Possibly output task header for each group
740 for group in IterateQueue(kern.globals.sched_groups, "sched_group_t", "sched_groups"):
741 if (group.runq.count != 0) :
742 task = task_map.get(unsigned(group), "Unknown task!")
743 print "Group {: <#012x} Task {: <#012x}\n".format(unsigned(group), unsigned(task))
744 ShowRunQSummary(group.runq)
745 print " \n"
746
747 processor_array = kern.globals.processor_array
748
749 print "Active Processors:\n"
750 active_bitmap = int(pset.cpu_state_map[processor_dispatching]) | int(pset.cpu_state_map[processor_running])
751 for cpuid in IterateBitmap(active_bitmap):
752 processor = processor_array[cpuid]
753 if processor != 0:
754 print " " + GetProcessorSummary(processor)
755 ShowActiveThread(processor)
756
757 if show_priority_runq:
758 runq = processor.runq
759 ShowRunQSummary(runq)
760 if show_grrr:
761 grrr_runq = processor.grrr_runq
762 ShowGrrrSummary(grrr_runq)
763 print " \n"
764
765
766 print "Idle Processors:\n"
767 idle_bitmap = int(pset.cpu_state_map[processor_idle]) & int(pset.primary_map)
768 for cpuid in IterateBitmap(idle_bitmap):
769 processor = processor_array[cpuid]
770 if processor != 0:
771 print " " + GetProcessorSummary(processor)
772 ShowActiveThread(processor)
773
774 if show_priority_runq:
775 ShowRunQSummary(processor.runq)
776 print " \n"
777
778
779 print "Idle Secondary Processors:\n"
780 idle_bitmap = int(pset.cpu_state_map[processor_idle]) & ~(int(pset.primary_map))
781 for cpuid in IterateBitmap(idle_bitmap):
782 processor = processor_array[cpuid]
783 if processor != 0:
784 print " " + GetProcessorSummary(processor)
785 ShowActiveThread(processor)
786
787 if show_priority_runq:
788 print ShowRunQSummary(processor.runq)
789 print " \n"
790
791
792 print "Other Processors:\n"
793 other_bitmap = 0
794 for i in range(processor_offline, processor_idle):
795 other_bitmap |= int(pset.cpu_state_map[i])
796 other_bitmap &= int(pset.cpu_bitmask)
797 for cpuid in IterateBitmap(other_bitmap):
798 processor = processor_array[cpuid]
799 if processor != 0:
800 print " " + GetProcessorSummary(processor)
801 ShowActiveThread(processor)
802
803 if show_priority_runq:
804 ShowRunQSummary(processor.runq)
805 print " \n"
806
807 if show_clutch:
808 print "=== Clutch Scheduler Hierarchy ===\n\n"
809 ShowSchedClutchForPset(pset)
810
811 pset = pset.pset_list
812
813 node = node.node_list
814
815 print "\nCrashed Threads Queue: ({:<#012x})\n".format(addressof(kern.globals.crashed_threads_queue))
816 first = True
817 for thread in ParanoidIterateLinkageChain(kern.globals.crashed_threads_queue, "thread_t", "runq_links"):
818 if first:
819 print "\t" + GetThreadSummary.header
820 first = False
821 print "\t" + GetThreadSummary(thread)
822
823 def dump_mpsc_thread_queue(name, head):
824 head = addressof(head)
825 print "\n{:s}: ({:<#012x})\n".format(name, head)
826 first = True
827 for thread in IterateMPSCQueue(head.mpd_queue, 'struct thread', 'mpsc_links'):
828 if first:
829 print "\t" + GetThreadSummary.header
830 first = False
831 print "\t" + GetThreadSummary(thread)
832
833 dump_mpsc_thread_queue("Terminate Queue", kern.globals.thread_terminate_queue)
834 dump_mpsc_thread_queue("Waiting For Kernel Stacks Queue", kern.globals.thread_stack_queue)
835 dump_mpsc_thread_queue("Thread Exception Queue", kern.globals.thread_exception_queue)
836 dump_mpsc_thread_queue("Thread Deallocate Queue", kern.globals.thread_deallocate_queue)
837
838 print "\n"
839
840 print "\n"
841
842 # EndMacro: showallprocessors
843
844
845 def ParanoidIterateLinkageChain(queue_head, element_type, field_name, field_ofst=0, circleQueue=False):
846 """ Iterate over a Linkage Chain queue in kernel of type queue_head_t or circle_queue_head_t. (osfmk/kern/queue.h method 1 or circle_queue.h)
847 This is equivalent to the qe_foreach_element() macro
848 Blows up aggressively and descriptively when something goes wrong iterating a queue.
849 Prints correctness errors, and throws exceptions on 'cannot proceed' errors
850 If this is annoying, set the global 'enable_paranoia' to false.
851
852 params:
853 queue_head - value : Value object for queue_head.
854 element_type - lldb.SBType : pointer type of the element which contains the queue_chain_t. Typically its structs like thread, task etc..
855 - str : OR a string describing the type. ex. 'task *'
856 field_name - str : Name of the field (in element) which holds a queue_chain_t
857 field_ofst - int : offset from the 'field_name' (in element) which holds a queue_chain_t
858 This is mostly useful if a particular element contains an array of queue_chain_t
859 returns:
860 A generator does not return. It is used for iterating.
861 value : An object thats of type (element_type). Always a pointer object
862 example usage:
863 for thread in IterateQueue(kern.globals.threads, 'thread *', 'threads'):
864 print thread.thread_id
865 """
866
867 if type(element_type) is str:
868 element_type = gettype(element_type)
869
870 # Some ways of constructing a queue head seem to end up with the
871 # struct object as the value and not a pointer to the struct head
872 # In that case, addressof will give us a pointer to the struct, which is what we need
873 if not queue_head.GetSBValue().GetType().IsPointerType() :
874 queue_head = addressof(queue_head)
875
876 if circleQueue:
877 # Mosh the value into a brand new value, to really get rid of its old cvalue history
878 queue_head = kern.GetValueFromAddress(unsigned(queue_head), 'struct circle_queue_head *').head
879 else:
880 # Mosh the value into a brand new value, to really get rid of its old cvalue history
881 queue_head = kern.GetValueFromAddress(unsigned(queue_head), 'struct queue_entry *')
882
883 if unsigned(queue_head) == 0:
884 if not circleQueue and ParanoidIterateLinkageChain.enable_paranoia:
885 print "bad queue_head_t: {:s}".format(queue_head)
886 return
887
888 if element_type.IsPointerType():
889 struct_type = element_type.GetPointeeType()
890 else:
891 struct_type = element_type
892
893 elem_ofst = getfieldoffset(struct_type, field_name) + field_ofst
894
895 try:
896 link = queue_head.next
897 last_link = queue_head
898 try_read_next = unsigned(queue_head.next)
899 except:
900 print "Exception while looking at queue_head: {:>#18x}".format(unsigned(queue_head))
901 raise
902
903 if ParanoidIterateLinkageChain.enable_paranoia:
904 if unsigned(queue_head.next) == 0:
905 raise ValueError("NULL next pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev))
906 if unsigned(queue_head.prev) == 0:
907 print "NULL prev pointer on head: queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)
908 if unsigned(queue_head.next) == unsigned(queue_head) and unsigned(queue_head.prev) != unsigned(queue_head):
909 print "corrupt queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)
910
911 if ParanoidIterateLinkageChain.enable_debug :
912 print "starting at queue_head {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, queue_head.next, queue_head.prev)
913
914 addr = 0
915 obj = 0
916
917 try:
918 while True:
919 if not circleQueue and unsigned(queue_head) == unsigned(link):
920 break;
921 if ParanoidIterateLinkageChain.enable_paranoia:
922 if unsigned(link.next) == 0:
923 raise ValueError("NULL next pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, link, link.next, link.prev))
924 if unsigned(link.prev) == 0:
925 print "NULL prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x}".format(queue_head, link, link.next, link.prev)
926 if unsigned(last_link) != unsigned(link.prev):
927 print "Corrupt prev pointer: queue_head {:>#18x} link: {:>#18x} next: {:>#18x} prev: {:>#18x} prev link: {:>#18x} ".format(
928 queue_head, link, link.next, link.prev, last_link)
929
930 addr = unsigned(link) - unsigned(elem_ofst);
931 obj = kern.GetValueFromAddress(addr, element_type)
932 if ParanoidIterateLinkageChain.enable_debug :
933 print "yielding link: {:>#18x} next: {:>#18x} prev: {:>#18x} addr: {:>#18x} obj: {:>#18x}".format(link, link.next, link.prev, addr, obj)
934 yield obj
935 last_link = link
936 link = link.next
937 if circleQueue and unsigned(queue_head) == unsigned(link):
938 break;
939 except:
940 exc_info = sys.exc_info()
941 try:
942 print "Exception while iterating queue: {:>#18x} link: {:>#18x} addr: {:>#18x} obj: {:>#18x} last link: {:>#18x}".format(queue_head, link, addr, obj, last_link)
943 except:
944 import traceback
945 traceback.print_exc()
946 raise exc_info[0], exc_info[1], exc_info[2]
947
948 ParanoidIterateLinkageChain.enable_paranoia = True
949 ParanoidIterateLinkageChain.enable_debug = False
950
951 def bit_first(bitmap):
952 return bitmap.bit_length() - 1
953
954 def lsb_first(bitmap):
955 bitmap = bitmap & -bitmap
956 return bit_first(bitmap)
957
958 def IterateBitmap(bitmap):
959 """ Iterate over a bitmap, returning the index of set bits starting from 0
960
961 params:
962 bitmap - value : bitmap
963 returns:
964 A generator does not return. It is used for iterating.
965 value : index of a set bit
966 example usage:
967 for cpuid in IterateBitmap(running_bitmap):
968 print processor_array[cpuid]
969 """
970 i = lsb_first(bitmap)
971 while (i >= 0):
972 yield i
973 bitmap = bitmap & ~((1 << (i + 1)) - 1)
974 i = lsb_first(bitmap)
975
976
977 # Macro: showallcallouts
978
979 def ShowThreadCall(prefix, call):
980 """
981 Print a description of a thread_call_t and its relationship to its expected fire time
982 """
983 func = call.tc_call.func
984 param0 = call.tc_call.param0
985 param1 = call.tc_call.param1
986
987 iotes_desc = ""
988 iotes_callout = kern.GetLoadAddressForSymbol("_ZN18IOTimerEventSource17timeoutAndReleaseEPvS0_")
989 iotes_callout2 = kern.GetLoadAddressForSymbol("_ZN18IOTimerEventSource15timeoutSignaledEPvS0_")
990
991 if (unsigned(func) == unsigned(iotes_callout) or
992 unsigned(func) == unsigned(iotes_callout2)) :
993 iotes = Cast(call.tc_call.param0, 'IOTimerEventSource*')
994 func = iotes.action
995 param0 = iotes.owner
996 param1 = unsigned(iotes)
997
998 func_name = kern.Symbolicate(func)
999 if (func_name == "") :
1000 func_name = FindKmodNameForAddr(func)
1001
1002 call_entry = call.tc_call
1003
1004 recent_timestamp = GetRecentTimestamp()
1005
1006 # THREAD_CALL_CONTINUOUS 0x100
1007 kern.globals.mach_absolutetime_asleep
1008 if (call.tc_flags & 0x100) :
1009 timer_fire = call_entry.deadline - (recent_timestamp + kern.globals.mach_absolutetime_asleep)
1010 else :
1011 timer_fire = call_entry.deadline - recent_timestamp
1012
1013 timer_fire_s = kern.GetNanotimeFromAbstime(timer_fire) / 1000000000.0
1014
1015 ttd_s = kern.GetNanotimeFromAbstime(call.tc_ttd) / 1000000000.0
1016
1017 print "{:s}{:#018x}: {:18d} {:18d} {:03.06f} {:03.06f} {:#018x}({:#018x},{:#018x}) ({:s})".format(prefix,
1018 unsigned(call), call_entry.deadline, call.tc_soft_deadline, ttd_s, timer_fire_s,
1019 func, param0, param1, func_name)
1020
1021 @lldb_command('showallcallouts')
1022 def ShowAllCallouts(cmd_args=None):
1023 """ Prints out the pending and delayed thread calls for the thread call groups
1024 """
1025
1026 index_max = GetEnumValue('thread_call_index_t::THREAD_CALL_INDEX_MAX')
1027
1028 for i in range (0, index_max) :
1029 group = kern.globals.thread_call_groups[i]
1030
1031 print "Group {i:d}: {g.tcg_name:s} ({:>#18x})".format(addressof(group), i=i, g=group)
1032 print "\t" +"Active: {g.active_count:d} Idle: {g.idle_count:d}\n".format(g=group)
1033 print "\t" +"Blocked: {g.blocked_count:d} Pending: {g.pending_count:d}\n".format(g=group)
1034 print "\t" +"Target: {g.target_thread_count:d}\n".format(g=group)
1035
1036 print "\t" +"Pending Queue: ({:>#18x})\n".format(addressof(group.pending_queue))
1037 for call in ParanoidIterateLinkageChain(group.pending_queue, "thread_call_t", "tc_call.q_link"):
1038 ShowThreadCall("\t\t", call)
1039
1040 print "\t" +"Delayed Queue (Absolute Time): ({:>#18x}) timer: ({:>#18x})\n".format(
1041 addressof(group.delayed_queues[0]), addressof(group.delayed_timers[0]))
1042 for call in ParanoidIterateLinkageChain(group.delayed_queues[0], "thread_call_t", "tc_call.q_link"):
1043 ShowThreadCall("\t\t", call)
1044
1045 print "\t" +"Delayed Queue (Continuous Time): ({:>#18x}) timer: ({:>#18x})\n".format(
1046 addressof(group.delayed_queues[1]), addressof(group.delayed_timers[1]))
1047 for call in ParanoidIterateLinkageChain(group.delayed_queues[1], "thread_call_t", "tc_call.q_link"):
1048 ShowThreadCall("\t\t", call)
1049
1050 # EndMacro: showallcallouts
1051