Debian Codegraph @

rpython/memory/gc/env.py

raw symbols SCIP
1 """
2 Utilities to get environ variables and platform-specific memory-related values.
3 """
4 import os, sys, platform
5 from rpython.rlib.rarithmetic import r_uint
6 from rpython.rlib.debug import debug_print, debug_start, debug_stop
7 from rpython.rlib.rstring import assert_str0
8 from rpython.rtyper.lltypesystem import lltype, rffi
9 from rpython.rtyper.lltypesystem.lloperation import llop
10 from rpython.translator.tool.cbuild import ExternalCompilationInfo
11
12 # ____________________________________________________________
13 # Reading env vars. Supports returning ints, uints or floats,
14 # and in the first two cases accepts the suffixes B, KB, MB and GB
15 # (lower case or upper case).
16
17 def _read_float_and_factor_from_env(varname):
18 value = os.environ.get(varname)
19 if value:
20 if len(value) > 1 and value[-1] in 'bB':
21 value = value[:-1]
22 realvalue = value[:-1]
23 if value[-1] in 'kK':
24 factor = 1024
25 elif value[-1] in 'mM':
26 factor = 1024*1024
27 elif value[-1] in 'gG':
28 factor = 1024*1024*1024
29 else:
30 factor = 1
31 realvalue = value
32 try:
33 return (float(realvalue), factor)
34 except ValueError:
35 pass
36 return (0.0, 0)
37
38 def read_from_env(varname):
39 value, factor = _read_float_and_factor_from_env(varname)
40 return int(value * factor)
41
42 def read_uint_from_env(varname):
43 value, factor = _read_float_and_factor_from_env(varname)
44 return r_uint(value * factor)
45
46 def read_float_from_env(varname):
47 value, factor = _read_float_and_factor_from_env(varname)
48 if factor != 1:
49 return 0.0
50 return value
51
52
53 # ____________________________________________________________
54 # Get the total amount of RAM installed in a system.
55 # On 32-bit systems, it will try to return at most the addressable size.
56 # If unknown, it will just return the addressable size, which
57 # will be huge on 64-bit systems.
58
59 if sys.maxint == 2147483647: # 32-bit
60 if sys.platform.startswith('linux'):
61 addressable_size = float(2**32) # 4GB
62 elif sys.platform == 'win32':
63 addressable_size = float(2**31) # 2GB
64 else:
65 addressable_size = float(2**31 + 2**30) # 3GB (compromise)
66 else:
67 addressable_size = float(2**63) # 64-bit
68
69
70 def get_total_memory_linux(filename):
71 debug_start("gc-hardware")
72 result = -1.0
73 try:
74 fd = os.open(filename, os.O_RDONLY, 0644)
75 try:
76 buf = os.read(fd, 4096)
77 finally:
78 os.close(fd)
79 except OSError:
80 pass
81 else:
82 if buf.startswith('MemTotal:'):
83 start = _skipspace(buf, len('MemTotal:'))
84 stop = start
85 while stop < len(buf) and buf[stop].isdigit():
86 stop += 1
87 if start < stop:
88 result = float(buf[start:stop]) * 1024.0 # assume kB
89 if result < 0.0:
90 debug_print("get_total_memory() failed")
91 result = addressable_size
92 else:
93 debug_print("memtotal =", result)
94 if result > addressable_size:
95 result = addressable_size
96 debug_stop("gc-hardware")
97 return result
98 get_total_memory_linux2 = get_total_memory_linux3 = get_total_memory_linux
99
100 def get_total_memory_darwin(result):
101 debug_start("gc-hardware")
102 if result <= 0:
103 debug_print("get_total_memory() failed")
104 result = addressable_size
105 else:
106 debug_print("memtotal = ", result)
107 if result > addressable_size:
108 result = addressable_size
109 debug_stop("gc-hardware")
110 return result
111
112
113 if sys.platform.startswith('linux'):
114 def get_total_memory():
115 return get_total_memory_linux2('/proc/meminfo')
116
117 elif sys.platform == 'darwin':
118 def get_total_memory():
119 return get_total_memory_darwin(get_darwin_sysctl_signed('hw.memsize'))
120
121 elif 'freebsd' in sys.platform:
122 def get_total_memory():
123 return get_total_memory_darwin(get_darwin_sysctl_signed('hw.usermem'))
124
125 else:
126 def get_total_memory():
127 return addressable_size # XXX implement me for other platforms
128
129
130 # ____________________________________________________________
131 # Estimation of the nursery size, based on the L2 cache.
132
133 # ---------- Linux2 ----------
134
135 def get_L2cache_linux2():
136 arch = os.uname()[4] # machine
137 if arch.endswith('86') or arch == 'x86_64':
138 return get_L2cache_linux2_cpuinfo()
139 if arch in ('alpha', 'ppc'):
140 return get_L2cache_linux2_cpuinfo(label='L2 cache')
141 #if arch == 's390x': untested
142 # return get_L2cache_linux2_cpuinfo_s390x()
143 if arch in ('ia64', 'aarch64'):
144 return get_L2cache_linux2_system_cpu_index()
145 if arch in ('parisc', 'parisc64'):
146 return get_L2cache_linux2_cpuinfo(label='D-cache')
147 if arch in ('sparc', 'sparc64'):
148 return get_L2cache_linux2_sparc()
149 return -1
150
151 get_L2cache_linux3 = get_L2cache_linux2
152
153
154 def get_L2cache_linux2_cpuinfo(filename="/proc/cpuinfo", label='cache size'):
155 debug_start("gc-hardware")
156 L2cache = sys.maxint
157 try:
158 fd = os.open(filename, os.O_RDONLY, 0644)
159 try:
160 data = []
161 while True:
162 buf = os.read(fd, 4096)
163 if not buf:
164 break
165 data.append(buf)
166 finally:
167 os.close(fd)
168 except OSError:
169 pass
170 else:
171 data = ''.join(data)
172 linepos = 0
173 while True:
174 start = _findend(data, '\n' + label, linepos)
175 if start < 0:
176 break # done
177 linepos = _findend(data, '\n', start)
178 if linepos < 0:
179 break # no end-of-line??
180 # *** data[start:linepos] == " : 2048 KB\n"
181 start = _skipspace(data, start)
182 if data[start] != ':':
183 continue
184 # *** data[start:linepos] == ": 2048 KB\n"
185 start = _skipspace(data, start + 1)
186 # *** data[start:linepos] == "2048 KB\n"
187 end = start
188 while '0' <= data[end] <= '9':
189 end += 1
190 # *** data[start:end] == "2048"
191 if start == end:
192 continue
193 number = int(data[start:end])
194 # *** data[end:linepos] == " KB\n"
195 end = _skipspace(data, end)
196 if data[end] not in ('K', 'k'): # assume kilobytes for now
197 continue
198 number = number * 1024
199 # for now we look for the smallest of the L2 caches of the CPUs
200 if number < L2cache:
201 L2cache = number
202
203 debug_print("L2cache =", L2cache)
204 debug_stop("gc-hardware")
205
206 if L2cache < sys.maxint:
207 return L2cache
208 else:
209 # Print a top-level warning even in non-debug builds
210 llop.debug_print(lltype.Void,
211 "Warning: cannot find your CPU L2 cache size in /proc/cpuinfo")
212 return -1
213
214 def get_L2cache_linux2_cpuinfo_s390x(filename="/proc/cpuinfo", label='cache2'):
215 debug_start("gc-hardware")
216 L2cache = sys.maxint
217 try:
218 fd = os.open(filename, os.O_RDONLY, 0644)
219 try:
220 data = []
221 while True:
222 buf = os.read(fd, 4096)
223 if not buf:
224 break
225 data.append(buf)
226 finally:
227 os.close(fd)
228 except OSError:
229 pass
230 else:
231 data = ''.join(data)
232 linepos = 0
233 while True:
234 start = _findend(data, '\n' + label, linepos)
235 if start < 0:
236 break # done
237 start = _findend(data, 'size=', start)
238 if start < 0:
239 break
240 end = _findend(data, ' ', start) - 1
241 if end < 0:
242 break
243 linepos = end
244 size = data[start:end]
245 last_char = len(size)-1
246 assert 0 <= last_char < len(size)
247 if size[last_char] not in ('K', 'k'): # assume kilobytes for now
248 continue
249 number = int(size[:last_char])* 1024
250 # for now we look for the smallest of the L2 caches of the CPUs
251 if number < L2cache:
252 L2cache = number
253
254 debug_print("L2cache =", L2cache)
255 debug_stop("gc-hardware")
256
257 if L2cache < sys.maxint:
258 return L2cache
259 else:
260 # Print a top-level warning even in non-debug builds
261 llop.debug_print(lltype.Void,
262 "Warning: cannot find your CPU L2 cache size in /proc/cpuinfo")
263 return -1
264
265 def get_L2cache_linux2_sparc():
266 debug_start("gc-hardware")
267 cpu = 0
268 L2cache = sys.maxint
269 while True:
270 try:
271 fd = os.open('/sys/devices/system/cpu/cpu' + assert_str0(str(cpu))
272 + '/l2_cache_size', os.O_RDONLY, 0644)
273 try:
274 line = os.read(fd, 4096)
275 finally:
276 os.close(fd)
277 end = len(line) - 1
278 assert end > 0
279 number = int(line[:end])
280 except OSError:
281 break
282 if number < L2cache:
283 L2cache = number
284 cpu += 1
285
286 debug_print("L2cache =", L2cache)
287 debug_stop("gc-hardware")
288 if L2cache < sys.maxint:
289 return L2cache
290 else:
291 # Print a top-level warning even in non-debug builds
292 llop.debug_print(lltype.Void,
293 "Warning: cannot find your CPU L2 cache size in "
294 "/sys/devices/system/cpu/cpuX/l2_cache_size")
295 return -1
296
297 def get_L2cache_linux2_system_cpu_index():
298 debug_start("gc-hardware")
299 cpu = 0
300 L2cache = sys.maxint
301 L3cache = sys.maxint
302 while True:
303 cpudir = '/sys/devices/system/cpu/cpu' + assert_str0(str(cpu))
304 index = 0
305 while True:
306 cachedir = cpudir + '/cache/index' + assert_str0(str(index))
307 try:
308 fd = os.open(cachedir + '/level', os.O_RDONLY, 0644)
309 try:
310 level = int(os.read(fd, 4096)[:-1])
311 finally:
312 os.close(fd)
313 except OSError:
314 break
315 if level not in (2, 3):
316 index += 1
317 continue
318 try:
319 fd = os.open(cachedir + '/size', os.O_RDONLY, 0644)
320 try:
321 data = os.read(fd, 4096)
322 finally:
323 os.close(fd)
324 except OSError:
325 break
326
327 end = 0
328 while '0' <= data[end] <= '9':
329 end += 1
330 if end == 0:
331 index += 1
332 continue
333 if data[end] not in ('K', 'k'): # assume kilobytes for now
334 index += 1
335 continue
336
337 number = int(data[:end])
338 number *= 1024
339
340 if level == 2:
341 if number < L2cache:
342 L2cache = number
343 if level == 3:
344 if number < L3cache:
345 L3cache = number
346
347 index += 1
348
349 if index == 0:
350 break
351 cpu += 1
352
353 mangled = L2cache + L3cache
354 debug_print("L2cache =", mangled)
355 debug_stop("gc-hardware")
356 if mangled > 0:
357 return mangled
358 else:
359 # Print a top-level warning even in non-debug builds
360 llop.debug_print(lltype.Void,
361 "Warning: cannot find your CPU L2 & L3 cache size in "
362 "/sys/devices/system/cpu/cpuX/cache")
363 return -1
364
365
366 def _findend(data, pattern, pos):
367 pos = data.find(pattern, pos)
368 if pos < 0:
369 return -1
370 return pos + len(pattern)
371
372 def _skipspace(data, pos):
373 while data[pos] in (' ', '\t'):
374 pos += 1
375 return pos
376
377 # ---------- Darwin ----------
378
379 sysctlbyname_eci = ExternalCompilationInfo(includes=["sys/sysctl.h"])
380 sysctlbyname = rffi.llexternal('sysctlbyname',
381 [rffi.CCHARP, rffi.VOIDP, rffi.SIZE_TP,
382 rffi.VOIDP, rffi.SIZE_T],
383 rffi.INT,
384 sandboxsafe=True,
385 compilation_info=sysctlbyname_eci)
386
387 def get_darwin_sysctl_signed(sysctl_name):
388 rval_p = lltype.malloc(rffi.LONGLONGP.TO, 1, flavor='raw')
389 try:
390 len_p = lltype.malloc(rffi.SIZE_TP.TO, 1, flavor='raw')
391 try:
392 size = rffi.sizeof(rffi.LONGLONG)
393 rval_p[0] = rffi.cast(rffi.LONGLONG, 0)
394 len_p[0] = rffi.cast(rffi.SIZE_T, size)
395 # XXX a hack for llhelper not being robust-enough
396 result = sysctlbyname(sysctl_name,
397 rffi.cast(rffi.VOIDP, rval_p),
398 len_p,
399 lltype.nullptr(rffi.VOIDP.TO),
400 rffi.cast(rffi.SIZE_T, 0))
401 rval = 0
402 if (rffi.cast(lltype.Signed, result) == 0 and
403 rffi.cast(lltype.Signed, len_p[0]) == size):
404 rval = rffi.cast(lltype.Signed, rval_p[0])
405 if rffi.cast(rffi.LONGLONG, rval) != rval_p[0]:
406 rval = 0 # overflow!
407 return rval
408 finally:
409 lltype.free(len_p, flavor='raw')
410 finally:
411 lltype.free(rval_p, flavor='raw')
412
413
414 def get_L2cache_darwin():
415 """Try to estimate the best nursery size at run-time, depending
416 on the machine we are running on.
417 """
418 debug_start("gc-hardware")
419 # On Apple Silicon, `hw.l2cachesize` returns the *efficiency* cluster's
420 # L2 (e.g. 4 MB on an M-series chip) rather than the performance
421 # cluster's (16 MB and up). Apple documents per-cluster topology under
422 # `hw.perflevelN.*` and states that "lower values of N indicate
423 # higher-performance core types" - so `hw.perflevel0.l2cachesize` is
424 # the L2 for the cluster the work actually runs against. See
425 # https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_system_capabilities#3901385
426 # On Intel Macs `hw.perflevel0.*` is absent (returns 0), so this falls
427 # back to the legacy `hw.l2cachesize`.
428 L2cache = get_darwin_sysctl_signed("hw.perflevel0.l2cachesize")
429 if L2cache <= 0:
430 L2cache = get_darwin_sysctl_signed("hw.l2cachesize")
431 # `hw.l3cachesize` reports L3 on Intel Macs. On observed Apple Silicon
432 # systems this sysctl is absent and returns 0; Apple also documents
433 # `hw.perflevel0.l3cachesize` but in practice it appears unpopulated on
434 # at least some M-series chips. We keep the existing behavior (sum L2
435 # and L3, treating an absent L3 as 0) which yields the correct Intel
436 # answer and a conservative-but-not-pathological Apple Silicon answer.
437 L3cache = get_darwin_sysctl_signed("hw.l3cachesize")
438 debug_print("L2cache =", L2cache)
439 debug_print("L3cache =", L3cache)
440 debug_stop("gc-hardware")
441
442 mangled = L2cache + L3cache
443
444 if mangled > 0:
445 return mangled
446 else:
447 # Print a top-level warning even in non-debug builds
448 llop.debug_print(lltype.Void,
449 "Warning: cannot find your CPU L2 cache size with sysctl()")
450 return -1
451
452
453 # --------------------
454
455 get_L2cache = globals().get('get_L2cache_' + sys.platform,
456 lambda: -1) # implement me for other platforms
457
458 NURSERY_SIZE_UNKNOWN_CACHE = 4 * 1024 * 1024
459 # arbitrary 4M. better than default of 131k for most cases
460 # in case it didn't work
461
462 def best_nursery_size_for_L2cache(L2cache):
463 # Heuristically, the best nursery size to choose is about half
464 # of the L2 cache.
465 if L2cache > 8 * 1024 * 1024: # we don't want to have nursery estimated
466 # on L2 when L3 is present
467 return L2cache // 2
468 else:
469 return NURSERY_SIZE_UNKNOWN_CACHE
470
471 def estimate_best_nursery_size():
472 """Try to estimate the best nursery size at run-time, depending
473 on the machine we are running on. Linux code."""
474 L2cache = get_L2cache()
475 return best_nursery_size_for_L2cache(L2cache)