thpmaps 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. # Copyright (C) 2024 ARM Ltd.
  4. #
  5. # Utility providing smaps-like output detailing transparent hugepage usage.
  6. # For more info, run:
  7. # ./thpmaps --help
  8. #
  9. # Requires numpy:
  10. # pip3 install numpy
  11. import argparse
  12. import collections
  13. import math
  14. import os
  15. import re
  16. import resource
  17. import shutil
  18. import sys
  19. import textwrap
  20. import time
  21. import numpy as np
  22. with open('/sys/kernel/mm/transparent_hugepage/hpage_pmd_size') as f:
  23. PAGE_SIZE = resource.getpagesize()
  24. PAGE_SHIFT = int(math.log2(PAGE_SIZE))
  25. PMD_SIZE = int(f.read())
  26. PMD_ORDER = int(math.log2(PMD_SIZE / PAGE_SIZE))
  27. def align_forward(v, a):
  28. return (v + (a - 1)) & ~(a - 1)
  29. def align_offset(v, a):
  30. return v & (a - 1)
  31. def kbnr(kb):
  32. # Convert KB to number of pages.
  33. return (kb << 10) >> PAGE_SHIFT
  34. def nrkb(nr):
  35. # Convert number of pages to KB.
  36. return (nr << PAGE_SHIFT) >> 10
  37. def odkb(order):
  38. # Convert page order to KB.
  39. return (PAGE_SIZE << order) >> 10
  40. def cont_ranges_all(search, index):
  41. # Given a list of arrays, find the ranges for which values are monotonically
  42. # incrementing in all arrays. all arrays in search and index must be the
  43. # same size.
  44. sz = len(search[0])
  45. r = np.full(sz, 2)
  46. d = np.diff(search[0]) == 1
  47. for dd in [np.diff(arr) == 1 for arr in search[1:]]:
  48. d &= dd
  49. r[1:] -= d
  50. r[:-1] -= d
  51. return [np.repeat(arr, r).reshape(-1, 2) for arr in index]
  52. class ArgException(Exception):
  53. pass
  54. class FileIOException(Exception):
  55. pass
  56. class BinArrayFile:
  57. # Base class used to read /proc/<pid>/pagemap and /proc/kpageflags into a
  58. # numpy array. Use inherrited class in a with clause to ensure file is
  59. # closed when it goes out of scope.
  60. def __init__(self, filename, element_size):
  61. self.element_size = element_size
  62. self.filename = filename
  63. self.fd = os.open(self.filename, os.O_RDONLY)
  64. def cleanup(self):
  65. os.close(self.fd)
  66. def __enter__(self):
  67. return self
  68. def __exit__(self, exc_type, exc_val, exc_tb):
  69. self.cleanup()
  70. def _readin(self, offset, buffer):
  71. length = os.preadv(self.fd, (buffer,), offset)
  72. if len(buffer) != length:
  73. raise FileIOException('error: {} failed to read {} bytes at {:x}'
  74. .format(self.filename, len(buffer), offset))
  75. def _toarray(self, buf):
  76. assert(self.element_size == 8)
  77. return np.frombuffer(buf, dtype=np.uint64)
  78. def getv(self, vec):
  79. vec *= self.element_size
  80. offsets = vec[:, 0]
  81. lengths = (np.diff(vec) + self.element_size).reshape(len(vec))
  82. buf = bytearray(int(np.sum(lengths)))
  83. view = memoryview(buf)
  84. pos = 0
  85. for offset, length in zip(offsets, lengths):
  86. offset = int(offset)
  87. length = int(length)
  88. self._readin(offset, view[pos:pos+length])
  89. pos += length
  90. return self._toarray(buf)
  91. def get(self, index, nr=1):
  92. offset = index * self.element_size
  93. length = nr * self.element_size
  94. buf = bytearray(length)
  95. self._readin(offset, buf)
  96. return self._toarray(buf)
  97. PM_PAGE_PRESENT = 1 << 63
  98. PM_PFN_MASK = (1 << 55) - 1
  99. class PageMap(BinArrayFile):
  100. # Read ranges of a given pid's pagemap into a numpy array.
  101. def __init__(self, pid='self'):
  102. super().__init__(f'/proc/{pid}/pagemap', 8)
  103. KPF_ANON = 1 << 12
  104. KPF_COMPOUND_HEAD = 1 << 15
  105. KPF_COMPOUND_TAIL = 1 << 16
  106. KPF_THP = 1 << 22
  107. class KPageFlags(BinArrayFile):
  108. # Read ranges of /proc/kpageflags into a numpy array.
  109. def __init__(self):
  110. super().__init__(f'/proc/kpageflags', 8)
  111. vma_all_stats = set([
  112. "Size",
  113. "Rss",
  114. "Pss",
  115. "Pss_Dirty",
  116. "Shared_Clean",
  117. "Shared_Dirty",
  118. "Private_Clean",
  119. "Private_Dirty",
  120. "Referenced",
  121. "Anonymous",
  122. "KSM",
  123. "LazyFree",
  124. "AnonHugePages",
  125. "ShmemPmdMapped",
  126. "FilePmdMapped",
  127. "Shared_Hugetlb",
  128. "Private_Hugetlb",
  129. "Swap",
  130. "SwapPss",
  131. "Locked",
  132. ])
  133. vma_min_stats = set([
  134. "Rss",
  135. "Anonymous",
  136. "AnonHugePages",
  137. "ShmemPmdMapped",
  138. "FilePmdMapped",
  139. ])
  140. VMA = collections.namedtuple('VMA', [
  141. 'name',
  142. 'start',
  143. 'end',
  144. 'read',
  145. 'write',
  146. 'execute',
  147. 'private',
  148. 'pgoff',
  149. 'major',
  150. 'minor',
  151. 'inode',
  152. 'stats',
  153. ])
  154. class VMAList:
  155. # A container for VMAs, parsed from /proc/<pid>/smaps. Iterate over the
  156. # instance to receive VMAs.
  157. def __init__(self, pid='self', stats=[]):
  158. self.vmas = []
  159. with open(f'/proc/{pid}/smaps', 'r') as file:
  160. for line in file:
  161. elements = line.split()
  162. if '-' in elements[0]:
  163. start, end = map(lambda x: int(x, 16), elements[0].split('-'))
  164. major, minor = map(lambda x: int(x, 16), elements[3].split(':'))
  165. self.vmas.append(VMA(
  166. name=elements[5] if len(elements) == 6 else '',
  167. start=start,
  168. end=end,
  169. read=elements[1][0] == 'r',
  170. write=elements[1][1] == 'w',
  171. execute=elements[1][2] == 'x',
  172. private=elements[1][3] == 'p',
  173. pgoff=int(elements[2], 16),
  174. major=major,
  175. minor=minor,
  176. inode=int(elements[4], 16),
  177. stats={},
  178. ))
  179. else:
  180. param = elements[0][:-1]
  181. if param in stats:
  182. value = int(elements[1])
  183. self.vmas[-1].stats[param] = {'type': None, 'value': value}
  184. def __iter__(self):
  185. yield from self.vmas
  186. def thp_parse(vma, kpageflags, ranges, indexes, vfns, pfns, anons, heads):
  187. # Given 4 same-sized arrays representing a range within a page table backed
  188. # by THPs (vfns: virtual frame numbers, pfns: physical frame numbers, anons:
  189. # True if page is anonymous, heads: True if page is head of a THP), return a
  190. # dictionary of statistics describing the mapped THPs.
  191. stats = {
  192. 'file': {
  193. 'partial': 0,
  194. 'aligned': [0] * (PMD_ORDER + 1),
  195. 'unaligned': [0] * (PMD_ORDER + 1),
  196. },
  197. 'anon': {
  198. 'partial': 0,
  199. 'aligned': [0] * (PMD_ORDER + 1),
  200. 'unaligned': [0] * (PMD_ORDER + 1),
  201. },
  202. }
  203. for rindex, rpfn in zip(ranges[0], ranges[2]):
  204. index_next = int(rindex[0])
  205. index_end = int(rindex[1]) + 1
  206. pfn_end = int(rpfn[1]) + 1
  207. folios = indexes[index_next:index_end][heads[index_next:index_end]]
  208. # Account pages for any partially mapped THP at the front. In that case,
  209. # the first page of the range is a tail.
  210. nr = (int(folios[0]) if len(folios) else index_end) - index_next
  211. stats['anon' if anons[index_next] else 'file']['partial'] += nr
  212. # Account pages for any partially mapped THP at the back. In that case,
  213. # the next page after the range is a tail.
  214. if len(folios):
  215. flags = int(kpageflags.get(pfn_end)[0])
  216. if flags & KPF_COMPOUND_TAIL:
  217. nr = index_end - int(folios[-1])
  218. folios = folios[:-1]
  219. index_end -= nr
  220. stats['anon' if anons[index_end - 1] else 'file']['partial'] += nr
  221. # Account fully mapped THPs in the middle of the range.
  222. if len(folios):
  223. folio_nrs = np.append(np.diff(folios), np.uint64(index_end - folios[-1]))
  224. folio_orders = np.log2(folio_nrs).astype(np.uint64)
  225. for index, order in zip(folios, folio_orders):
  226. index = int(index)
  227. order = int(order)
  228. nr = 1 << order
  229. vfn = int(vfns[index])
  230. align = 'aligned' if align_forward(vfn, nr) == vfn else 'unaligned'
  231. anon = 'anon' if anons[index] else 'file'
  232. stats[anon][align][order] += nr
  233. # Account PMD-mapped THPs spearately, so filter out of the stats. There is a
  234. # race between acquiring the smaps stats and reading pagemap, where memory
  235. # could be deallocated. So clamp to zero incase it would have gone negative.
  236. anon_pmd_mapped = vma.stats['AnonHugePages']['value']
  237. file_pmd_mapped = vma.stats['ShmemPmdMapped']['value'] + \
  238. vma.stats['FilePmdMapped']['value']
  239. stats['anon']['aligned'][PMD_ORDER] = max(0, stats['anon']['aligned'][PMD_ORDER] - kbnr(anon_pmd_mapped))
  240. stats['file']['aligned'][PMD_ORDER] = max(0, stats['file']['aligned'][PMD_ORDER] - kbnr(file_pmd_mapped))
  241. rstats = {
  242. f"anon-thp-pmd-aligned-{odkb(PMD_ORDER)}kB": {'type': 'anon', 'value': anon_pmd_mapped},
  243. f"file-thp-pmd-aligned-{odkb(PMD_ORDER)}kB": {'type': 'file', 'value': file_pmd_mapped},
  244. }
  245. def flatten_sub(type, subtype, stats):
  246. param = f"{type}-thp-pte-{subtype}-{{}}kB"
  247. for od, nr in enumerate(stats[2:], 2):
  248. rstats[param.format(odkb(od))] = {'type': type, 'value': nrkb(nr)}
  249. def flatten_type(type, stats):
  250. flatten_sub(type, 'aligned', stats['aligned'])
  251. flatten_sub(type, 'unaligned', stats['unaligned'])
  252. rstats[f"{type}-thp-pte-partial"] = {'type': type, 'value': nrkb(stats['partial'])}
  253. flatten_type('anon', stats['anon'])
  254. flatten_type('file', stats['file'])
  255. return rstats
  256. def cont_parse(vma, order, ranges, anons, heads):
  257. # Given 4 same-sized arrays representing a range within a page table backed
  258. # by THPs (vfns: virtual frame numbers, pfns: physical frame numbers, anons:
  259. # True if page is anonymous, heads: True if page is head of a THP), return a
  260. # dictionary of statistics describing the contiguous blocks.
  261. nr_cont = 1 << order
  262. nr_anon = 0
  263. nr_file = 0
  264. for rindex, rvfn, rpfn in zip(*ranges):
  265. index_next = int(rindex[0])
  266. index_end = int(rindex[1]) + 1
  267. vfn_start = int(rvfn[0])
  268. pfn_start = int(rpfn[0])
  269. if align_offset(pfn_start, nr_cont) != align_offset(vfn_start, nr_cont):
  270. continue
  271. off = align_forward(vfn_start, nr_cont) - vfn_start
  272. index_next += off
  273. while index_next + nr_cont <= index_end:
  274. folio_boundary = heads[index_next+1:index_next+nr_cont].any()
  275. if not folio_boundary:
  276. if anons[index_next]:
  277. nr_anon += nr_cont
  278. else:
  279. nr_file += nr_cont
  280. index_next += nr_cont
  281. # Account blocks that are PMD-mapped spearately, so filter out of the stats.
  282. # There is a race between acquiring the smaps stats and reading pagemap,
  283. # where memory could be deallocated. So clamp to zero incase it would have
  284. # gone negative.
  285. anon_pmd_mapped = vma.stats['AnonHugePages']['value']
  286. file_pmd_mapped = vma.stats['ShmemPmdMapped']['value'] + \
  287. vma.stats['FilePmdMapped']['value']
  288. nr_anon = max(0, nr_anon - kbnr(anon_pmd_mapped))
  289. nr_file = max(0, nr_file - kbnr(file_pmd_mapped))
  290. rstats = {
  291. f"anon-cont-pmd-aligned-{nrkb(nr_cont)}kB": {'type': 'anon', 'value': anon_pmd_mapped},
  292. f"file-cont-pmd-aligned-{nrkb(nr_cont)}kB": {'type': 'file', 'value': file_pmd_mapped},
  293. }
  294. rstats[f"anon-cont-pte-aligned-{nrkb(nr_cont)}kB"] = {'type': 'anon', 'value': nrkb(nr_anon)}
  295. rstats[f"file-cont-pte-aligned-{nrkb(nr_cont)}kB"] = {'type': 'file', 'value': nrkb(nr_file)}
  296. return rstats
  297. def vma_print(vma, pid):
  298. # Prints a VMA instance in a format similar to smaps. The main difference is
  299. # that the pid is included as the first value.
  300. print("{:010d}: {:016x}-{:016x} {}{}{}{} {:08x} {:02x}:{:02x} {:08x} {}"
  301. .format(
  302. pid, vma.start, vma.end,
  303. 'r' if vma.read else '-', 'w' if vma.write else '-',
  304. 'x' if vma.execute else '-', 'p' if vma.private else 's',
  305. vma.pgoff, vma.major, vma.minor, vma.inode, vma.name
  306. ))
  307. def stats_print(stats, tot_anon, tot_file, inc_empty):
  308. # Print a statistics dictionary.
  309. label_field = 32
  310. for label, stat in stats.items():
  311. type = stat['type']
  312. value = stat['value']
  313. if value or inc_empty:
  314. pad = max(0, label_field - len(label) - 1)
  315. if type == 'anon' and tot_anon > 0:
  316. percent = f' ({value / tot_anon:3.0%})'
  317. elif type == 'file' and tot_file > 0:
  318. percent = f' ({value / tot_file:3.0%})'
  319. else:
  320. percent = ''
  321. print(f"{label}:{' ' * pad}{value:8} kB{percent}")
  322. def vma_parse(vma, pagemap, kpageflags, contorders):
  323. # Generate thp and cont statistics for a single VMA.
  324. start = vma.start >> PAGE_SHIFT
  325. end = vma.end >> PAGE_SHIFT
  326. pmes = pagemap.get(start, end - start)
  327. present = pmes & PM_PAGE_PRESENT != 0
  328. pfns = pmes & PM_PFN_MASK
  329. pfns = pfns[present]
  330. vfns = np.arange(start, end, dtype=np.uint64)
  331. vfns = vfns[present]
  332. pfn_vec = cont_ranges_all([pfns], [pfns])[0]
  333. flags = kpageflags.getv(pfn_vec)
  334. anons = flags & KPF_ANON != 0
  335. heads = flags & KPF_COMPOUND_HEAD != 0
  336. thps = flags & KPF_THP != 0
  337. vfns = vfns[thps]
  338. pfns = pfns[thps]
  339. anons = anons[thps]
  340. heads = heads[thps]
  341. indexes = np.arange(len(vfns), dtype=np.uint64)
  342. ranges = cont_ranges_all([vfns, pfns], [indexes, vfns, pfns])
  343. thpstats = thp_parse(vma, kpageflags, ranges, indexes, vfns, pfns, anons, heads)
  344. contstats = [cont_parse(vma, order, ranges, anons, heads) for order in contorders]
  345. tot_anon = vma.stats['Anonymous']['value']
  346. tot_file = vma.stats['Rss']['value'] - tot_anon
  347. return {
  348. **thpstats,
  349. **{k: v for s in contstats for k, v in s.items()}
  350. }, tot_anon, tot_file
  351. def do_main(args):
  352. pids = set()
  353. rollup = {}
  354. rollup_anon = 0
  355. rollup_file = 0
  356. if args.cgroup:
  357. strict = False
  358. for walk_info in os.walk(args.cgroup):
  359. cgroup = walk_info[0]
  360. with open(f'{cgroup}/cgroup.procs') as pidfile:
  361. for line in pidfile.readlines():
  362. pids.add(int(line.strip()))
  363. elif args.pid:
  364. strict = True
  365. pids = pids.union(args.pid)
  366. else:
  367. strict = False
  368. for pid in os.listdir('/proc'):
  369. if pid.isdigit():
  370. pids.add(int(pid))
  371. if not args.rollup:
  372. print(" PID START END PROT OFFSET DEV INODE OBJECT")
  373. for pid in pids:
  374. try:
  375. with PageMap(pid) as pagemap:
  376. with KPageFlags() as kpageflags:
  377. for vma in VMAList(pid, vma_all_stats if args.inc_smaps else vma_min_stats):
  378. if (vma.read or vma.write or vma.execute) and vma.stats['Rss']['value'] > 0:
  379. stats, vma_anon, vma_file = vma_parse(vma, pagemap, kpageflags, args.cont)
  380. else:
  381. stats = {}
  382. vma_anon = 0
  383. vma_file = 0
  384. if args.inc_smaps:
  385. stats = {**vma.stats, **stats}
  386. if args.rollup:
  387. for k, v in stats.items():
  388. if k in rollup:
  389. assert(rollup[k]['type'] == v['type'])
  390. rollup[k]['value'] += v['value']
  391. else:
  392. rollup[k] = v
  393. rollup_anon += vma_anon
  394. rollup_file += vma_file
  395. else:
  396. vma_print(vma, pid)
  397. stats_print(stats, vma_anon, vma_file, args.inc_empty)
  398. except (FileNotFoundError, ProcessLookupError, FileIOException):
  399. if strict:
  400. raise
  401. if args.rollup:
  402. stats_print(rollup, rollup_anon, rollup_file, args.inc_empty)
  403. def main():
  404. docs_width = shutil.get_terminal_size().columns
  405. docs_width -= 2
  406. docs_width = min(80, docs_width)
  407. def format(string):
  408. text = re.sub(r'\s+', ' ', string)
  409. text = re.sub(r'\s*\\n\s*', '\n', text)
  410. paras = text.split('\n')
  411. paras = [textwrap.fill(p, width=docs_width) for p in paras]
  412. return '\n'.join(paras)
  413. def formatter(prog):
  414. return argparse.RawDescriptionHelpFormatter(prog, width=docs_width)
  415. def size2order(human):
  416. units = {
  417. "K": 2**10, "M": 2**20, "G": 2**30,
  418. "k": 2**10, "m": 2**20, "g": 2**30,
  419. }
  420. unit = 1
  421. if human[-1] in units:
  422. unit = units[human[-1]]
  423. human = human[:-1]
  424. try:
  425. size = int(human)
  426. except ValueError:
  427. raise ArgException('error: --cont value must be integer size with optional KMG unit')
  428. size *= unit
  429. order = int(math.log2(size / PAGE_SIZE))
  430. if order < 1:
  431. raise ArgException('error: --cont value must be size of at least 2 pages')
  432. if (1 << order) * PAGE_SIZE != size:
  433. raise ArgException('error: --cont value must be size of power-of-2 pages')
  434. if order > PMD_ORDER:
  435. raise ArgException('error: --cont value must be less than or equal to PMD order')
  436. return order
  437. parser = argparse.ArgumentParser(formatter_class=formatter,
  438. description=format("""Prints information about how transparent huge
  439. pages are mapped, either system-wide, or for a specified
  440. process or cgroup.\\n
  441. \\n
  442. When run with --pid, the user explicitly specifies the set
  443. of pids to scan. e.g. "--pid 10 [--pid 134 ...]". When run
  444. with --cgroup, the user passes either a v1 or v2 cgroup and
  445. all pids that belong to the cgroup subtree are scanned. When
  446. run with neither --pid nor --cgroup, the full set of pids on
  447. the system is gathered from /proc and scanned as if the user
  448. had provided "--pid 1 --pid 2 ...".\\n
  449. \\n
  450. A default set of statistics is always generated for THP
  451. mappings. However, it is also possible to generate
  452. additional statistics for "contiguous block mappings" where
  453. the block size is user-defined.\\n
  454. \\n
  455. Statistics are maintained independently for anonymous and
  456. file-backed (pagecache) memory and are shown both in kB and
  457. as a percentage of either total anonymous or total
  458. file-backed memory as appropriate.\\n
  459. \\n
  460. THP Statistics\\n
  461. --------------\\n
  462. \\n
  463. Statistics are always generated for fully- and
  464. contiguously-mapped THPs whose mapping address is aligned to
  465. their size, for each <size> supported by the system.
  466. Separate counters describe THPs mapped by PTE vs those
  467. mapped by PMD. (Although note a THP can only be mapped by
  468. PMD if it is PMD-sized):\\n
  469. \\n
  470. - anon-thp-pte-aligned-<size>kB\\n
  471. - file-thp-pte-aligned-<size>kB\\n
  472. - anon-thp-pmd-aligned-<size>kB\\n
  473. - file-thp-pmd-aligned-<size>kB\\n
  474. \\n
  475. Similarly, statistics are always generated for fully- and
  476. contiguously-mapped THPs whose mapping address is *not*
  477. aligned to their size, for each <size> supported by the
  478. system. Due to the unaligned mapping, it is impossible to
  479. map by PMD, so there are only PTE counters for this case:\\n
  480. \\n
  481. - anon-thp-pte-unaligned-<size>kB\\n
  482. - file-thp-pte-unaligned-<size>kB\\n
  483. \\n
  484. Statistics are also always generated for mapped pages that
  485. belong to a THP but where the is THP is *not* fully- and
  486. contiguously- mapped. These "partial" mappings are all
  487. counted in the same counter regardless of the size of the
  488. THP that is partially mapped:\\n
  489. \\n
  490. - anon-thp-pte-partial\\n
  491. - file-thp-pte-partial\\n
  492. \\n
  493. Contiguous Block Statistics\\n
  494. ---------------------------\\n
  495. \\n
  496. An optional, additional set of statistics is generated for
  497. every contiguous block size specified with `--cont <size>`.
  498. These statistics show how much memory is mapped in
  499. contiguous blocks of <size> and also aligned to <size>. A
  500. given contiguous block must all belong to the same THP, but
  501. there is no requirement for it to be the *whole* THP.
  502. Separate counters describe contiguous blocks mapped by PTE
  503. vs those mapped by PMD:\\n
  504. \\n
  505. - anon-cont-pte-aligned-<size>kB\\n
  506. - file-cont-pte-aligned-<size>kB\\n
  507. - anon-cont-pmd-aligned-<size>kB\\n
  508. - file-cont-pmd-aligned-<size>kB\\n
  509. \\n
  510. As an example, if monitoring 64K contiguous blocks (--cont
  511. 64K), there are a number of sources that could provide such
  512. blocks: a fully- and contiguously-mapped 64K THP that is
  513. aligned to a 64K boundary would provide 1 block. A fully-
  514. and contiguously-mapped 128K THP that is aligned to at least
  515. a 64K boundary would provide 2 blocks. Or a 128K THP that
  516. maps its first 100K, but contiguously and starting at a 64K
  517. boundary would provide 1 block. A fully- and
  518. contiguously-mapped 2M THP would provide 32 blocks. There
  519. are many other possible permutations.\\n"""),
  520. epilog=format("""Requires root privilege to access pagemap and
  521. kpageflags."""))
  522. group = parser.add_mutually_exclusive_group(required=False)
  523. group.add_argument('--pid',
  524. metavar='pid', required=False, type=int, default=[], action='append',
  525. help="""Process id of the target process. Maybe issued multiple times to
  526. scan multiple processes. --pid and --cgroup are mutually exclusive.
  527. If neither are provided, all processes are scanned to provide
  528. system-wide information.""")
  529. group.add_argument('--cgroup',
  530. metavar='path', required=False,
  531. help="""Path to the target cgroup in sysfs. Iterates over every pid in
  532. the cgroup and its children. --pid and --cgroup are mutually
  533. exclusive. If neither are provided, all processes are scanned to
  534. provide system-wide information.""")
  535. parser.add_argument('--rollup',
  536. required=False, default=False, action='store_true',
  537. help="""Sum the per-vma statistics to provide a summary over the whole
  538. system, process or cgroup.""")
  539. parser.add_argument('--cont',
  540. metavar='size[KMG]', required=False, default=[], action='append',
  541. help="""Adds stats for memory that is mapped in contiguous blocks of
  542. <size> and also aligned to <size>. May be issued multiple times to
  543. track multiple sized blocks. Useful to infer e.g. arm64 contpte and
  544. hpa mappings. Size must be a power-of-2 number of pages.""")
  545. parser.add_argument('--inc-smaps',
  546. required=False, default=False, action='store_true',
  547. help="""Include all numerical, additive /proc/<pid>/smaps stats in the
  548. output.""")
  549. parser.add_argument('--inc-empty',
  550. required=False, default=False, action='store_true',
  551. help="""Show all statistics including those whose value is 0.""")
  552. parser.add_argument('--periodic',
  553. metavar='sleep_ms', required=False, type=int,
  554. help="""Run in a loop, polling every sleep_ms milliseconds.""")
  555. args = parser.parse_args()
  556. try:
  557. args.cont = [size2order(cont) for cont in args.cont]
  558. except ArgException as e:
  559. parser.print_usage()
  560. raise
  561. if args.periodic:
  562. while True:
  563. do_main(args)
  564. print()
  565. time.sleep(args.periodic / 1000)
  566. else:
  567. do_main(args)
  568. if __name__ == "__main__":
  569. try:
  570. main()
  571. except Exception as e:
  572. prog = os.path.basename(sys.argv[0])
  573. print(f'{prog}: {e}')
  574. exit(1)