Debian Codegraph @

src/hwlatdetect/hwlatdetect.py

raw symbols SCIP
1 #!/usr/bin/python3
2 """ Module to detect smis """
3
4 # SPDX-License-Identifier: GPL-2.0-only
5
6 # (C) 2018,2019 Clark Williams <[email protected]>
7 # (C) 2015,2016 Clark Williams <[email protected]>
8 # (C) 2009 Clark Williams <[email protected]>
9
10 import abc
11 import errno
12 import os
13 import os.path
14 import subprocess
15 import sys
16 import time
17
18 version = "0.8"
19 debugging = False
20 quiet = False
21 watch = False
22
23
24 def debug(dstr):
25 """ print debugging string if debugging is on """
26 if debugging:
27 print(dstr)
28
29
30 def info(istr):
31 " print info string if quiet is not on """
32 if not quiet:
33 print(istr)
34
35
36 def group_sep(num_hex):
37 """ Add a comma as a grouping separator every 32 bits to a hexadecimal number. """
38 return ','.join([num_hex[max(i - 8, 0):i] for i in range(len(num_hex), 0, -8)][::-1])
39
40
41 def key_values(fields):
42 """ Extract key:value pairs from a list of fields and return them as a dictionary """
43 return {
44 k: v
45 for field in fields
46 if ':' in field
47 for k, v in [field.split(":", 1)]
48 if k and v
49 }
50
51
52 #
53 # Class used to manage mounting and umounting the debugfs
54 # filesystem. Note that if an instance of this class mounts
55 # the debugfs, it will unmount when cleaning up, but if it
56 # discovers that debugfs is already mounted, it will leave
57 # it mounted.
58 #
59 class DebugFS:
60 """ class to manage mounting/umounting the debugfs """
61 def __init__(self):
62 self.premounted = False
63 self.mounted = False
64 self.mountpoint = ''
65 with open('/proc/mounts') as f:
66 for l in f:
67 field = l.split()
68 if field[2] == "debugfs":
69 self.premounted = True
70 self.mountpoint = field[1]
71 break
72
73 def mount(self, path='/sys/kernel/debug'):
74 """ mount debugfs unless already mounted """
75 if self.premounted or self.mounted:
76 debug("not mounting debugfs")
77 return True
78 debug(f"mounting debugfs at {path}")
79 self.mountpoint = path
80 cmd = ['/bin/mount', '-t', 'debugfs', 'none', path]
81 self.mounted = (subprocess.call(cmd) == 0)
82 if not self.mounted:
83 raise RuntimeError("Failed to mount debugfs")
84 return self.mounted
85
86 def umount(self):
87 """ unmount debugfs if not premounted """
88 if self.premounted or not self.mounted:
89 debug("not umounting debugfs")
90 return True
91 debug("umounting debugfs")
92 cmd = ['/bin/umount', self.mountpoint]
93 self.mounted = subprocess.call(cmd) != 0
94 if self.mounted:
95 raise RuntimeError("Failed to umount debugfs")
96 return not self.mounted
97
98 def getval(self, item, nonblocking=False):
99 """ get value of mountpoint/item """
100 path = os.path.join(self.mountpoint, item)
101 if nonblocking is False:
102 with open(path) as f:
103 val = f.readline()
104 else:
105 f = os.fdopen(os.open(path, os.O_RDONLY | os.O_NONBLOCK), "r")
106 try:
107 val = f.readline()
108 except OSError as e:
109 print(f"errno: {e}")
110 if e.errno == errno.EAGAIN:
111 val = None
112 else:
113 raise
114 f.close()
115 return val
116
117 def putval(self, item, value):
118 """ write value to mountpoint/item """
119 path = os.path.join(self.mountpoint, item)
120 with open(path, "w") as f:
121 f.write(str(value))
122 f.flush()
123
124 def getpath(self, item):
125 """ get mountpoint/item """
126 return os.path.join(self.mountpoint, item)
127
128
129 class DetectorNotAvailable(Exception):
130 """ Exception class for when tracer is not available """
131
132 def __init__(self, name, msg):
133 self.args = (name, msg)
134 self.name = name
135 self.msg = msg
136
137
138 class Detector:
139 """ base class for detector modules """
140
141 def __init__(self):
142 self.type = "unknown"
143 if os.getuid() != 0:
144 raise RuntimeError("Must be root")
145 self.debugfs = DebugFS()
146 if not self.debugfs.mount():
147 raise RuntimeError("failed to mount debugfs")
148 self.samples = []
149 self.testduration = 30 # in seconds
150 self.have_msr = False
151 self.initsmi = []
152 if os.path.exists('/usr/sbin/rdmsr'):
153 self.have_msr = True
154 self.initsmi = self.getsmicounts()
155 self.dma_latency_handle = None
156
157 def getsmicounts(self):
158 counts = []
159 if self.have_msr:
160 p = subprocess.Popen(['/usr/sbin/rdmsr', '-a', '-d', '0x34'], stdout=subprocess.PIPE)
161 p.wait()
162 counts = [int(x.strip()) for x in p.stdout.readlines()]
163 return counts
164
165 # methods for preventing/enabling c-state transitions
166 #
167 # opening /dev/cpu_dma_latency and writing a 32-bit zero to that file will
168 # prevent c-state transitions while the file descriptor is open.
169 #
170 # use c_states_off() to disable c-state transitions
171 # use c_states_on() to close the file descriptor and re-enable c-states
172 #
173 def c_states_off(self):
174 """ disable c-state transitions """
175 if os.path.exists("/dev/cpu_dma_latency"):
176 self.dma_latency_handle = os.open("/dev/cpu_dma_latency", os.O_WRONLY)
177 os.write(self.dma_latency_handle, b'\x00\x00\x00\x00')
178 debug("c-states disabled")
179
180 def c_states_on(self):
181 """ close the file descriptor and re-enable c-states """
182 if self.dma_latency_handle:
183 os.close(self.dma_latency_handle)
184 debug("c-states enabled")
185
186 @abc.abstractmethod
187 def cleanup(self):
188 ''' abstract cleanup method, must override '''
189
190 @abc.abstractmethod
191 def get(self, field):
192 ''' get the value of a debugfs field '''
193
194 @abc.abstractmethod
195 def set(self, field, val):
196 ''' set a value in a debugfs field '''
197
198 @abc.abstractmethod
199 def save(self, output=None):
200 ''' save sample data to output '''
201
202 @abc.abstractmethod
203 def display(self):
204 ''' output the sample data as a string '''
205
206 def start(self):
207 """ enable the detector """
208 count = 0
209 threshold = int(self.get("threshold"))
210 self.c_states_off()
211 debug(f"enabling detector module (threshold: {threshold})")
212 self.set("enable", 1)
213 while self.get("enable") == 0:
214 debug("still disabled, retrying in a bit")
215 count += 1
216 time.sleep(0.1)
217 debug(f"retrying enable of detector module ({count})")
218 self.set("enable", 1)
219 if self.get("threshold") != threshold:
220 debug("start: threshold reset by start, fixing")
221 self.set("threshold", threshold)
222 debug(f"detector module enabled (threshold: {int(self.get('threshold'))})")
223
224 def stop(self):
225 """ disable the detector """
226 count = 0
227 debug("disabling detector module")
228 self.set("enable", 0)
229 while self.get("enable") == 1:
230 debug("still enabled, retrying in a bit")
231 count += 1
232 time.sleep(0.1)
233 debug(f"retrying disable of detector module({count})")
234 self.set("enable", 0)
235 self.c_states_on()
236 debug("detector module disabled")
237
238 @abc.abstractmethod
239 def detect(self):
240 ''' get detector output '''
241
242
243 class Tracer(Detector):
244 """ Class to handle running the hwlat tracer module of ftrace """
245
246 __field_translation = {
247 'width' : "hwlat_detector/width",
248 'window' : "hwlat_detector/window",
249 'enable' : "tracing_on",
250 'threshold' : "tracing_thresh",
251 'cpumask' : "tracing_cpumask",
252 }
253
254 class Sample:
255 'private class for tracer sample data'
256 __slots__ = 'cpu', 'timestamp', 'inner', 'outer', 'count'
257
258 def __init__(self, line):
259 fields = line.split()
260 if len(fields) < 8:
261 raise ValueError(f"Unexpected trace format: {line}")
262
263 kv = key_values(fields)
264
265 # Parse CPU number from either [NNN] or NNd.... format
266 cpu_field = fields[1]
267 if not cpu_field:
268 raise ValueError(f"Empty CPU field in: {line}")
269
270 if cpu_field[0] == '[':
271 # nolatency-format: [007]
272 self.cpu = int(cpu_field[1:-1])
273 else:
274 # latency-format: 13d....
275 self.cpu = int(cpu_field[:-5])
276 i, o = fields[6].split('/')
277 ts = fields[7][3:]
278 self.timestamp = str(ts)
279 self.inner = int(i)
280 self.outer = int(o)
281 self.count = int(kv["count"]) if "count" in kv else None
282
283 def __str__(self):
284 if self.count is not None:
285 return f"ts: {self.timestamp}, inner:{self.inner}, outer:{self.outer}, cpu:{self.cpu}, count:{self.count}"
286 return f"ts: {self.timestamp}, inner:{self.inner}, outer:{self.outer}, cpu:{self.cpu}"
287
288 def display(self):
289 """ convert object to string and print """
290 print(str(self))
291
292 def largest(self):
293 """ return largest value of inner or outer """
294 return max(self.inner, self.outer)
295
296 def translate(self, field):
297 path = self.debugfs.getpath('tracing')
298 if field not in Tracer.__field_translation:
299 return os.path.join(path, field)
300 return os.path.join(path, Tracer.__field_translation[field])
301
302 def __init__(self):
303 super().__init__()
304 path = self.debugfs.getpath('tracing/hwlat_detector')
305 if not os.path.exists(path):
306 raise DetectorNotAvailable("hwlat", "hwlat tracer not available")
307 self.type = "tracer"
308 self.samples = []
309 self.first = None
310 self.last = None
311 self.set("enable", 0)
312 self.set('current_tracer', 'hwlat')
313
314 def set(self, field, val):
315 path = self.translate(field)
316 self.debugfs.putval(path, str(val))
317
318 def get(self, field):
319 if field == "count":
320 # Use new count field if available, otherwise fall back to sample count
321 if self.samples and self.samples[0].count is not None:
322 return sum(s.count for s in self.samples)
323 return len(self.samples)
324 if field == "max":
325 max = 0
326 for values in self.samples:
327 s = int(values.largest())
328 if s > max:
329 max = s
330 return max
331 return self.debugfs.getval(self.translate(field))
332
333 def detect(self):
334 self.samples = []
335 testend = time.time() + self.testduration
336 pollcnt = 0
337 self.start()
338 try:
339 while time.time() < testend:
340 pollcnt += 1
341 val = self.get_sample()
342 while val:
343 self.first = self.first or val.timestamp
344 self.last = val.timestamp
345 self.samples.append(val)
346 if watch:
347 val.display()
348 val = self.get_sample()
349 time.sleep(0.1)
350 except KeyboardInterrupt as e:
351 print("interrupted")
352 self.stop()
353 return self.samples
354
355 def get_sample(self):
356 val = None
357 line = self.debugfs.getval("tracing/trace_pipe", nonblocking=True)
358 if line:
359 val = self.Sample(line)
360 return val
361
362 def save(self, output=None):
363 """ save samples """
364 if output:
365 with open(output, "w") as f:
366 for s in self.samples:
367 f.write(f"{s}\n")
368 print(f"report saved to {output} ({len(self.samples)} samples)")
369
370 def display(self):
371 for s in self.samples:
372 s.display()
373
374 def cleanup(self):
375 self.set("tracing_on", "0")
376 self.set("current_tracer", "nop")
377 if not self.debugfs.umount():
378 raise RuntimeError("Failed to unmount debugfs")
379
380
381 def seconds(sval):
382 "convert input string to value in seconds"
383 if sval.isdigit():
384 return int(sval)
385 if sval[-2].isalpha():
386 raise RuntimeError(f"illegal suffix for seconds: '{sval[-2:-1]}'")
387 if sval[-1:] == 's':
388 return int(sval[0:-1])
389 if sval[-1:] == 'm':
390 return int(sval[0:-1]) * 60
391 if sval[-1:] == 'h':
392 return int(sval[0:-1]) * 3600
393 if sval[-1:] == 'd':
394 return int(sval[0:-1]) * 86400
395 if sval[-1:] == 'w':
396 return int(sval[0:-1]) * 86400 * 7
397 raise RuntimeError(f"invalid input for seconds: '{sval}'")
398
399
400 def milliseconds(sval):
401 "convert input string to millsecond value"
402 if sval.isdigit():
403 return int(sval)
404 if sval[-2:] == 'ms':
405 return int(sval[0:-2])
406 if sval[-1] == 's':
407 return int(sval[0:-2]) * 1000
408 if sval[-1] == 'm':
409 return int(sval[0:-1]) * 1000 * 60
410 if sval[-1] == 'h':
411 return int(sval[0:-1]) * 1000 * 60 * 60
412 raise RuntimeError(f"invalid input for milliseconds: {sval}")
413
414
415 def microseconds(sval):
416 "convert input string to microsecond value"
417 if sval.isdigit():
418 return int(sval)
419 if sval[-2:] == 'ms':
420 return int(sval[0:-2]) * 1000
421 if sval[-2:] == 'us':
422 return int(sval[0:-2])
423 if sval[-1:] == 's':
424 return int(sval[0:-1]) * 1000 * 1000
425 raise RuntimeError(f"invalid input for microseconds: '{sval}'")
426
427
428 if __name__ == '__main__':
429 from argparse import ArgumentParser
430
431 parser = ArgumentParser()
432 parser.add_argument("--duration", default=None,
433 dest="duration",
434 help="total time to test for hardware latency: <n>{smdw}")
435
436 parser.add_argument("--threshold", default=None,
437 dest="threshold",
438 help="value above which is considered an hardware latency")
439
440 parser.add_argument("--hardlimit", default=None,
441 dest="hardlimit",
442 help="value above which the test is considered to fail")
443
444 parser.add_argument("--window", default=None,
445 dest="window",
446 help="time between samples")
447
448 parser.add_argument("--width", default=None,
449 dest="width",
450 help="time to actually measure")
451
452 parser.add_argument("--report", default=None,
453 dest="report",
454 help="filename for sample data")
455
456 parser.add_argument("--cpu-list", default=None,
457 dest="cpulist",
458 help="the CPUs for hwlat thread to move across")
459
460 parser.add_argument("--debug", action="store_true", default=False,
461 dest="debug",
462 help="turn on debugging prints")
463
464 parser.add_argument("--quiet", action="store_true", default=False,
465 dest="quiet",
466 help="turn off all screen output")
467
468 parser.add_argument("--watch", action="store_true", default=False,
469 dest="watch",
470 help="print sample data to stdout as it arrives")
471
472 args = parser.parse_args()
473
474 # need these before creating detector instance
475 if args.debug:
476 debugging = True
477 quiet = False
478 debug("debugging prints turned on")
479
480 if args.quiet:
481 quiet = True
482 debugging = False
483
484 detect = Tracer()
485
486 if args.threshold:
487 t = microseconds(args.threshold)
488 detect.set("threshold", t)
489 debug(f"threshold set to {t}us")
490
491 if args.hardlimit:
492 hardlimit = microseconds(args.hardlimit)
493 else:
494 hardlimit = int(detect.get("threshold"))
495 debug(f"hardlimit set to {hardlimit}us")
496
497 if args.window:
498 w = microseconds(args.window)
499 width = w//2
500 if w < int(detect.get("width")):
501 debug(f"shrinking width to {width} for new window of {w}")
502 detect.set("width", width)
503 debug(f"window parameter = {w}")
504 detect.set("window", w)
505 debug(f"window for sampling set to {w}us")
506
507 if args.width:
508 w = microseconds(args.width)
509 if w > int(detect.get("window")):
510 debug(f"widening window to {w*2} for new width of {w}")
511 detect.set("window", w*2)
512 debug(f"width parameter = {w}")
513 detect.set("width", w)
514 debug(f"sample width set to {w}us")
515
516 if args.duration:
517 detect.testduration = seconds(args.duration)
518 else:
519 detect.testduration = 120 # 2 minutes
520 debug(f"test duration is {detect.testduration}s")
521
522 if args.watch:
523 watch = True
524
525 reportfile = args.report
526
527 if args.cpulist:
528 cpumask = 0
529 for c in args.cpulist.split(','):
530 l, r = 0, 0
531 if '-' in c:
532 l, r = map(int, c.split('-'))
533 else:
534 l, r = map(int, [c, c])
535 for i in range(l, r + 1):
536 cpumask |= (1 << i)
537 debug(f"set tracing_cpumask to {cpumask:x}")
538 detect.set("cpumask", group_sep(f"{cpumask:x}"))
539
540 info(f"hwlatdetect: test duration {detect.testduration} seconds")
541 info(f" detector: {detect.type}")
542 info(" parameters:")
543 info(f" CPU list: {args.cpulist}")
544 info(f" Latency threshold: {int(detect.get('threshold'))}us")
545 info(f" Sample window: {int(detect.get('window'))}us")
546 info(f" Sample width: {int(detect.get('width'))}us")
547 info(f" Non-sampling period: {(int(detect.get('window')) - int(detect.get('width')))}us")
548 info(f" Output File: {reportfile}")
549 info("\nStarting test")
550
551 detect.detect()
552
553 info("test finished")
554
555 max_latency = detect.get("max")
556 if max_latency == 0:
557 info("Max Latency: Below threshold")
558 else:
559 info(f"Max Latency: {int(max_latency)}us")
560
561 info(f"Samples recorded: {len(detect.samples)}")
562
563 exceeding = detect.get("count")
564 info(f"Samples exceeding threshold: {exceeding}")
565
566 if exceeding > 1:
567 width = int(detect.get('width'))
568 if width > 0:
569 mtbf = (((float(detect.last) - float(detect.first)) * int(detect.get('window'))) / ((exceeding - 1) * width))
570 info(f"MTBF: {mtbf:.3f} seconds")
571
572 if detect.have_msr:
573 finishsmi = detect.getsmicounts()
574 total_smis = 0
575 for i, count in enumerate(finishsmi):
576 if count > detect.initsmi[i]:
577 smis = count - detect.initsmi[i]
578 total_smis += smis
579 print(f"{smis} SMIs occured on cpu {i}")
580 info(f"SMIs during run: {total_smis}")
581
582 maxlatency = int(detect.get("max"))
583
584 if reportfile:
585 detect.save(reportfile)
586
587 if not watch:
588 detect.display()
589
590 detect.cleanup()
591 sys.exit(maxlatency > hardlimit)