iocost_monitor.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #!/usr/bin/env drgn
  2. #
  3. # Copyright (C) 2019 Tejun Heo <tj@kernel.org>
  4. # Copyright (C) 2019 Facebook
  5. desc = """
  6. This is a drgn script to monitor the blk-iocost cgroup controller.
  7. See the comment at the top of block/blk-iocost.c for more details.
  8. For drgn, visit https://github.com/osandov/drgn.
  9. """
  10. import sys
  11. import re
  12. import time
  13. import json
  14. import math
  15. import drgn
  16. from drgn import container_of
  17. from drgn.helpers.linux.list import list_for_each_entry,list_empty
  18. from drgn.helpers.linux.radixtree import radix_tree_for_each,radix_tree_lookup
  19. import argparse
  20. parser = argparse.ArgumentParser(description=desc,
  21. formatter_class=argparse.RawTextHelpFormatter)
  22. parser.add_argument('devname', metavar='DEV',
  23. help='Target block device name (e.g. sda)')
  24. parser.add_argument('--cgroup', action='append', metavar='REGEX',
  25. help='Regex for target cgroups, ')
  26. parser.add_argument('--interval', '-i', metavar='SECONDS', type=float, default=1,
  27. help='Monitoring interval in seconds (0 exits immediately '
  28. 'after checking requirements)')
  29. parser.add_argument('--json', action='store_true',
  30. help='Output in json')
  31. args = parser.parse_args()
  32. def err(s):
  33. print(s, file=sys.stderr, flush=True)
  34. sys.exit(1)
  35. try:
  36. blkcg_root = prog['blkcg_root']
  37. plid = prog['blkcg_policy_iocost'].plid.value_()
  38. except:
  39. err('The kernel does not have iocost enabled')
  40. IOC_RUNNING = prog['IOC_RUNNING'].value_()
  41. WEIGHT_ONE = prog['WEIGHT_ONE'].value_()
  42. VTIME_PER_SEC = prog['VTIME_PER_SEC'].value_()
  43. VTIME_PER_USEC = prog['VTIME_PER_USEC'].value_()
  44. AUTOP_SSD_FAST = prog['AUTOP_SSD_FAST'].value_()
  45. AUTOP_SSD_DFL = prog['AUTOP_SSD_DFL'].value_()
  46. AUTOP_SSD_QD1 = prog['AUTOP_SSD_QD1'].value_()
  47. AUTOP_HDD = prog['AUTOP_HDD'].value_()
  48. autop_names = {
  49. AUTOP_SSD_FAST: 'ssd_fast',
  50. AUTOP_SSD_DFL: 'ssd_dfl',
  51. AUTOP_SSD_QD1: 'ssd_qd1',
  52. AUTOP_HDD: 'hdd',
  53. }
  54. class BlkgIterator:
  55. def __init__(self, root_blkcg, q_id, include_dying=False):
  56. self.include_dying = include_dying
  57. self.blkgs = []
  58. self.walk(root_blkcg, q_id, '')
  59. def blkcg_name(blkcg):
  60. return blkcg.css.cgroup.kn.name.string_().decode('utf-8')
  61. def walk(self, blkcg, q_id, parent_path):
  62. if not self.include_dying and \
  63. not (blkcg.css.flags.value_() & prog['CSS_ONLINE'].value_()):
  64. return
  65. name = BlkgIterator.blkcg_name(blkcg)
  66. path = parent_path + '/' + name if parent_path else name
  67. blkg = drgn.Object(prog, 'struct blkcg_gq',
  68. address=radix_tree_lookup(blkcg.blkg_tree.address_of_(), q_id))
  69. if not blkg.address_:
  70. return
  71. self.blkgs.append((path if path else '/', blkg))
  72. for c in list_for_each_entry('struct blkcg',
  73. blkcg.css.children.address_of_(), 'css.sibling'):
  74. self.walk(c, q_id, path)
  75. def __iter__(self):
  76. return iter(self.blkgs)
  77. class IocStat:
  78. def __init__(self, ioc):
  79. global autop_names
  80. self.enabled = ioc.enabled.value_()
  81. self.running = ioc.running.value_() == IOC_RUNNING
  82. self.period_ms = ioc.period_us.value_() / 1_000
  83. self.period_at = ioc.period_at.value_() / 1_000_000
  84. self.vperiod_at = ioc.period_at_vtime.value_() / VTIME_PER_SEC
  85. self.vrate_pct = ioc.vtime_base_rate.value_() * 100 / VTIME_PER_USEC
  86. self.ivrate_pct = ioc.vtime_rate.counter.value_() * 100 / VTIME_PER_USEC
  87. self.busy_level = ioc.busy_level.value_()
  88. self.autop_idx = ioc.autop_idx.value_()
  89. self.user_cost_model = ioc.user_cost_model.value_()
  90. self.user_qos_params = ioc.user_qos_params.value_()
  91. if self.autop_idx in autop_names:
  92. self.autop_name = autop_names[self.autop_idx]
  93. else:
  94. self.autop_name = '?'
  95. def dict(self, now):
  96. return { 'device' : devname,
  97. 'timestamp' : now,
  98. 'enabled' : self.enabled,
  99. 'running' : self.running,
  100. 'period_ms' : self.period_ms,
  101. 'period_at' : self.period_at,
  102. 'period_vtime_at' : self.vperiod_at,
  103. 'busy_level' : self.busy_level,
  104. 'vrate_pct' : self.vrate_pct,
  105. 'ivrate_pct' : self.ivrate_pct,
  106. }
  107. def table_preamble_str(self):
  108. state = ('RUN' if self.running else 'IDLE') if self.enabled else 'OFF'
  109. output = f'{devname} {state:4} ' \
  110. f'per={self.period_ms}ms ' \
  111. f'cur_per={self.period_at:.3f}:v{self.vperiod_at:.3f} ' \
  112. f'busy={self.busy_level:+3} ' \
  113. f'vrate={self.vrate_pct:6.2f}%:{self.ivrate_pct:6.2f}% ' \
  114. f'params={self.autop_name}'
  115. if self.user_cost_model or self.user_qos_params:
  116. output += f'({"C" if self.user_cost_model else ""}{"Q" if self.user_qos_params else ""})'
  117. return output
  118. def table_header_str(self):
  119. return f'{"":25} active {"weight":>9} {"hweight%":>13} {"inflt%":>6} ' \
  120. f'{"usage%":>6} {"wait":>7} {"debt":>7} {"delay":>7}'
  121. class IocgStat:
  122. def __init__(self, iocg):
  123. ioc = iocg.ioc
  124. blkg = iocg.pd.blkg
  125. self.is_active = not list_empty(iocg.active_list.address_of_())
  126. self.weight = iocg.weight.value_() / WEIGHT_ONE
  127. self.active = iocg.active.value_() / WEIGHT_ONE
  128. self.inuse = iocg.inuse.value_() / WEIGHT_ONE
  129. self.hwa_pct = iocg.hweight_active.value_() * 100 / WEIGHT_ONE
  130. self.hwi_pct = iocg.hweight_inuse.value_() * 100 / WEIGHT_ONE
  131. self.address = iocg.value_()
  132. vdone = iocg.done_vtime.counter.value_()
  133. vtime = iocg.vtime.counter.value_()
  134. vrate = ioc.vtime_rate.counter.value_()
  135. period_vtime = ioc.period_us.value_() * vrate
  136. if period_vtime:
  137. self.inflight_pct = (vtime - vdone) * 100 / period_vtime
  138. else:
  139. self.inflight_pct = 0
  140. self.usage = (100 * iocg.usage_delta_us.value_() /
  141. ioc.period_us.value_()) if self.active else 0
  142. self.wait_ms = (iocg.stat.wait_us.value_() -
  143. iocg.last_stat.wait_us.value_()) / 1000
  144. self.debt_ms = iocg.abs_vdebt.value_() / VTIME_PER_USEC / 1000
  145. if blkg.use_delay.counter.value_() != 0:
  146. self.delay_ms = blkg.delay_nsec.counter.value_() / 1_000_000
  147. else:
  148. self.delay_ms = 0
  149. def dict(self, now, path):
  150. out = { 'cgroup' : path,
  151. 'timestamp' : now,
  152. 'is_active' : self.is_active,
  153. 'weight' : self.weight,
  154. 'weight_active' : self.active,
  155. 'weight_inuse' : self.inuse,
  156. 'hweight_active_pct' : self.hwa_pct,
  157. 'hweight_inuse_pct' : self.hwi_pct,
  158. 'inflight_pct' : self.inflight_pct,
  159. 'usage_pct' : self.usage,
  160. 'wait_ms' : self.wait_ms,
  161. 'debt_ms' : self.debt_ms,
  162. 'delay_ms' : self.delay_ms,
  163. 'address' : self.address }
  164. return out
  165. def table_row_str(self, path):
  166. out = f'{path[-28:]:28} ' \
  167. f'{"*" if self.is_active else " "} ' \
  168. f'{round(self.inuse):5}/{round(self.active):5} ' \
  169. f'{self.hwi_pct:6.2f}/{self.hwa_pct:6.2f} ' \
  170. f'{self.inflight_pct:6.2f} ' \
  171. f'{min(self.usage, 999):6.2f} ' \
  172. f'{self.wait_ms:7.2f} ' \
  173. f'{self.debt_ms:7.2f} ' \
  174. f'{self.delay_ms:7.2f}'
  175. out = out.rstrip(':')
  176. return out
  177. # handle args
  178. table_fmt = not args.json
  179. interval = args.interval
  180. devname = args.devname
  181. if args.json:
  182. table_fmt = False
  183. re_str = None
  184. if args.cgroup:
  185. for r in args.cgroup:
  186. if re_str is None:
  187. re_str = r
  188. else:
  189. re_str += '|' + r
  190. filter_re = re.compile(re_str) if re_str else None
  191. # Locate the roots
  192. q_id = None
  193. root_iocg = None
  194. ioc = None
  195. for i, ptr in radix_tree_for_each(blkcg_root.blkg_tree.address_of_()):
  196. blkg = drgn.Object(prog, 'struct blkcg_gq', address=ptr)
  197. try:
  198. if devname == blkg.q.mq_kobj.parent.name.string_().decode('utf-8'):
  199. q_id = blkg.q.id.value_()
  200. if blkg.pd[plid]:
  201. root_iocg = container_of(blkg.pd[plid], 'struct ioc_gq', 'pd')
  202. ioc = root_iocg.ioc
  203. break
  204. except:
  205. pass
  206. if ioc is None:
  207. err(f'Could not find ioc for {devname}');
  208. if interval == 0:
  209. sys.exit(0)
  210. # Keep printing
  211. while True:
  212. now = time.time()
  213. iocstat = IocStat(ioc)
  214. output = ''
  215. if table_fmt:
  216. output += '\n' + iocstat.table_preamble_str()
  217. output += '\n' + iocstat.table_header_str()
  218. else:
  219. output += json.dumps(iocstat.dict(now))
  220. for path, blkg in BlkgIterator(blkcg_root, q_id):
  221. if filter_re and not filter_re.match(path):
  222. continue
  223. if not blkg.pd[plid]:
  224. continue
  225. iocg = container_of(blkg.pd[plid], 'struct ioc_gq', 'pd')
  226. iocg_stat = IocgStat(iocg)
  227. if not filter_re and not iocg_stat.is_active:
  228. continue
  229. if table_fmt:
  230. output += '\n' + iocg_stat.table_row_str(path)
  231. else:
  232. output += '\n' + json.dumps(iocg_stat.dict(now, path))
  233. print(output)
  234. sys.stdout.flush()
  235. time.sleep(interval)