1#!/usr/bin/env python3
2#
3# Copyright (C) 2022 Roman Gushchin <roman.gushchin@linux.dev>
4# Copyright (C) 2022 Meta
5
6import os
7import argparse
8import sys
9
10
11def scan_cgroups(cgroup_root):
12    cgroups = {}
13
14    for root, subdirs, _ in os.walk(cgroup_root):
15        for cgroup in subdirs:
16            path = os.path.join(root, cgroup)
17            ino = os.stat(path).st_ino
18            cgroups[ino] = path
19
20    # (memcg ino, path)
21    return cgroups
22
23
24def scan_shrinkers(shrinker_debugfs):
25    shrinkers = []
26
27    for root, subdirs, _ in os.walk(shrinker_debugfs):
28        for shrinker in subdirs:
29            count_path = os.path.join(root, shrinker, "count")
30            with open(count_path) as f:
31                for line in f.readlines():
32                    items = line.split(' ')
33                    ino = int(items[0])
34                    # (count, shrinker, memcg ino)
35                    shrinkers.append((int(items[1]), shrinker, ino))
36    return shrinkers
37
38
39def main():
40    parser = argparse.ArgumentParser(description='Display biggest shrinkers')
41    parser.add_argument('-n', '--lines', type=int, help='Number of lines to print')
42
43    args = parser.parse_args()
44
45    cgroups = scan_cgroups("/sys/fs/cgroup/")
46    shrinkers = scan_shrinkers("/sys/kernel/debug/shrinker/")
47    shrinkers = sorted(shrinkers, reverse = True, key = lambda x: x[0])
48
49    n = 0
50    for s in shrinkers:
51        count, name, ino = (s[0], s[1], s[2])
52        if count == 0:
53            break
54
55        if ino == 0 or ino == 1:
56            cg = "/"
57        else:
58            try:
59                cg = cgroups[ino]
60            except KeyError:
61                cg = "unknown (%d)" % ino
62
63        print("%-8s %-20s %s" % (count, name, cg))
64
65        n += 1
66        if args.lines and n >= args.lines:
67            break
68
69
70if __name__ == '__main__':
71    main()
72