Created
February 19, 2022 08:09
-
-
Save pinzhenx/22212d19eb592154abe0668c7a9c959c to your computer and use it in GitHub Desktop.
How is MemAvailable calculated in Linux? Python version of the kernel calculating the memory stats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pgsize = 4 # kb | |
total_lowwmark = 0 | |
total_reserved = 0 | |
with open('/proc/zoneinfo') as zoneinfo: | |
for line in zoneinfo: | |
if 'pages free' in line: | |
next(zoneinfo) | |
low = int(next(zoneinfo).split()[1]) | |
high = int(next(zoneinfo).split()[1]) | |
total_lowwmark += low | |
if 'managed' in line: | |
managed = int(line.split()[1]) | |
if 'protection:' in line: | |
lowmem = line.strip('protection: ()\n').split(',') | |
maxlowmem = max(int(i) for i in lowmem) | |
reserved = min(managed, maxlowmem + high) | |
total_reserved += reserved | |
mmstat = {} | |
with open('/proc/meminfo') as meminfo: | |
for line in meminfo: | |
field = line.split() | |
mmstat[field[0].rstrip(':')] = int(field[1]) | |
free = mmstat['MemFree'] // pgsize | |
filecache = (mmstat['Active(file)'] + mmstat['Inactive(file)']) // pgsize | |
sreclaim = mmstat.get('KReclaimable', mmstat['SReclaimable']) // pgsize | |
available = free - total_reserved + (filecache - min(filecache // 2, total_lowwmark)) + (sreclaim - min(sreclaim // 2, total_lowwmark)) | |
available *= pgsize | |
print('mmstat =', mmstat) | |
print('total_lowwmark =', total_lowwmark) | |
print('total_reserved =', total_reserved) | |
print('sreclaim =', sreclaim) | |
print('filecache =', filecache) | |
print('available =', available) | |
assert available == mmstat['MemAvailable'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment