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