Debian Codegraph @

rpython/memory/gc/minimarkpage.py

raw symbols SCIP
1 import sys
2 from rpython.rtyper.lltypesystem import lltype, llmemory, llarena, rffi
3 from rpython.rlib.rarithmetic import LONG_BIT, r_uint
4 from rpython.rlib.objectmodel import we_are_translated
5 from rpython.rlib.debug import ll_assert, fatalerror
6
7 WORD = LONG_BIT // 8
8 NULL = llmemory.NULL
9 WORD_POWER_2 = {32: 2, 64: 3}[LONG_BIT]
10 assert 1 << WORD_POWER_2 == WORD
11
12 # Terminology: the memory is subdivided into "arenas" containing "pages".
13 # A page contains a number of allocated objects, called "blocks".
14
15 # The actual allocation occurs in whole arenas, which are then subdivided
16 # into pages. For each arena we allocate one of the following structures:
17
18 ARENA_PTR = lltype.Ptr(lltype.ForwardReference())
19 ARENA = lltype.Struct('ArenaReference',
20 # -- The address of the arena, as returned by malloc()
21 ('base', llmemory.Address),
22 # -- The number of free and the total number of pages in the arena
23 ('nfreepages', lltype.Signed),
24 ('totalpages', lltype.Signed),
25 # -- A chained list of free pages in the arena. Ends with NULL.
26 ('freepages', llmemory.Address),
27 # -- A linked list of arenas. See below.
28 ('nextarena', ARENA_PTR),
29 )
30 ARENA_PTR.TO.become(ARENA)
31 ARENA_NULL = lltype.nullptr(ARENA)
32
33 # The idea is that when we need a free page, we take it from the arena
34 # which currently has the *lowest* number of free pages. This allows
35 # arenas with a lot of free pages to eventually become entirely free, at
36 # which point they are returned to the OS. If an arena has a total of
37 # 64 pages, then we have 64 global lists, arenas_lists[0] to
38 # arenas_lists[63], such that arenas_lists[i] contains exactly those
39 # arenas that have 'nfreepages == i'. We allocate pages out of the
40 # arena in 'current_arena'; when it is exhausted we pick another arena
41 # with the smallest value for nfreepages (but > 0).
42
43 # ____________________________________________________________
44 #
45 # Each page in an arena can be:
46 #
47 # - uninitialized: never touched so far.
48 #
49 # - allocated: contains some objects (all of the same size). Starts with a
50 # PAGE_HEADER. The page is on the chained list of pages that still have
51 # room for objects of that size, unless it is completely full.
52 #
53 # - free: used to be partially full, and is now free again. The page is
54 # on the chained list of free pages 'freepages' from its arena.
55
56 # Each allocated page contains blocks of a given size, which can again be in
57 # one of three states: allocated, free, or uninitialized. The uninitialized
58 # blocks (initially all of them) are at the tail of the page.
59
60 PAGE_PTR = lltype.Ptr(lltype.ForwardReference())
61 PAGE_HEADER = lltype.Struct('PageHeader',
62 # -- The following pointer makes a chained list of pages. For non-full
63 # pages, it is a chained list of pages having the same size class,
64 # rooted in 'page_for_size[size_class]'. For full pages, it is a
65 # different chained list rooted in 'full_page_for_size[size_class]'.
66 # For free pages, it is the list 'freepages' in the arena header.
67 ('nextpage', PAGE_PTR),
68 # -- The arena this page is part of.
69 ('arena', ARENA_PTR),
70 # -- The number of free blocks. The numbers of uninitialized and
71 # allocated blocks can be deduced from the context if needed.
72 ('nfree', lltype.Signed),
73 # -- The chained list of free blocks. It ends as a pointer to the
74 # first uninitialized block (pointing to data that is uninitialized,
75 # or to the end of the page).
76 ('freeblock', llmemory.Address),
77 # -- The structure above is 4 words, which is a good value:
78 # '(1024-4) % N' is zero or very small for various small N's,
79 # i.e. there is not much wasted space.
80 )
81 PAGE_PTR.TO.become(PAGE_HEADER)
82 PAGE_NULL = lltype.nullptr(PAGE_HEADER)
83
84 # ----------
85
86
87 class ArenaCollection(object):
88 _alloc_flavor_ = "raw"
89
90 def __init__(self, arena_size, page_size, small_request_threshold):
91 # 'small_request_threshold' is the largest size that we
92 # can ask with self.malloc().
93 self.arena_size = arena_size
94 self.page_size = page_size
95 self.small_request_threshold = small_request_threshold
96 self.arenas_count = 0
97 #
98 # 'pageaddr_for_size': for each size N between WORD and
99 # small_request_threshold (included), contains either NULL or
100 # a pointer to a page that has room for at least one more
101 # allocation of the given size.
102 length = small_request_threshold / WORD + 1
103 self.page_for_size = self._new_page_ptr_list(length)
104 self.full_page_for_size = self._new_page_ptr_list(length)
105 self.old_page_for_size = self._new_page_ptr_list(length)
106 self.old_full_page_for_size = self._new_page_ptr_list(length)
107 self.nblocks_for_size = lltype.malloc(rffi.CArray(lltype.Signed),
108 length, flavor='raw',
109 immortal=True)
110 self.hdrsize = llmemory.raw_malloc_usage(llmemory.sizeof(PAGE_HEADER))
111 assert page_size > self.hdrsize
112 self.nblocks_for_size[0] = 0 # unused
113 for i in range(1, length):
114 self.nblocks_for_size[i] = (page_size - self.hdrsize) // (WORD * i)
115 #
116 self.max_pages_per_arena = arena_size // page_size
117 self.arenas_lists = lltype.malloc(rffi.CArray(ARENA_PTR),
118 self.max_pages_per_arena,
119 flavor='raw', zero=True,
120 immortal=True)
121 # this is used in mass_free() only
122 self.old_arenas_lists = lltype.malloc(rffi.CArray(ARENA_PTR),
123 self.max_pages_per_arena,
124 flavor='raw', zero=True,
125 immortal=True)
126 #
127 # the arena currently consumed; it must have at least one page
128 # available, or be NULL. The arena object that we point to is
129 # not in any 'arenas_lists'. We will consume all its pages before
130 # we choose a next arena, even if there is a major collection
131 # in-between.
132 self.current_arena = ARENA_NULL
133 #
134 # guarantee that 'arenas_lists[1:min_empty_nfreepages]' are all empty
135 self.min_empty_nfreepages = self.max_pages_per_arena
136 #
137 # part of current_arena might still contain uninitialized pages
138 self.num_uninitialized_pages = 0
139 #
140 # the total memory used, counting every block in use, without
141 # the additional bookkeeping stuff.
142 self.total_memory_used = r_uint(0)
143 self.peak_memory_used = r_uint(0)
144 self.total_memory_alloced = r_uint(0)
145 self.peak_memory_alloced = r_uint(0)
146
147
148 def _new_page_ptr_list(self, length):
149 return lltype.malloc(rffi.CArray(PAGE_PTR), length,
150 flavor='raw', zero=True,
151 immortal=True)
152
153
154 def malloc(self, size):
155 """Allocate a block from a page in an arena."""
156 nsize = llmemory.raw_malloc_usage(size)
157 ll_assert(nsize > 0, "malloc: size is null or negative")
158 ll_assert(nsize <= self.small_request_threshold,"malloc: size too big")
159 ll_assert((nsize & (WORD-1)) == 0, "malloc: size is not aligned")
160 self.total_memory_used += r_uint(nsize)
161 #
162 # Get the page to use from the size
163 size_class = nsize >> WORD_POWER_2
164 page = self.page_for_size[size_class]
165 if page == PAGE_NULL:
166 page = self.allocate_new_page(size_class)
167 #
168 # The result is simply 'page.freeblock'
169 result = page.freeblock
170 if page.nfree > 0:
171 #
172 # The 'result' was part of the chained list; read the next.
173 page.nfree -= 1
174 freeblock = result.address[0]
175 llarena.arena_reset(result,
176 llmemory.sizeof(llmemory.Address),
177 0)
178 #
179 else:
180 # The 'result' is part of the uninitialized blocks.
181 freeblock = result + nsize
182 #
183 page.freeblock = freeblock
184 #
185 pageaddr = llarena.getfakearenaaddress(llmemory.cast_ptr_to_adr(page))
186 if freeblock - pageaddr > self.page_size - nsize:
187 # This was the last free block, so unlink the page from the
188 # chained list and put it in the 'full_page_for_size' list.
189 self.page_for_size[size_class] = page.nextpage
190 page.nextpage = self.full_page_for_size[size_class]
191 self.full_page_for_size[size_class] = page
192 #
193 llarena.arena_reserve(result, _dummy_size(size))
194 return result
195
196
197 def allocate_new_page(self, size_class):
198 """Allocate and return a new page for the given size_class."""
199 #
200 # Allocate a new arena if needed.
201 if self.current_arena == ARENA_NULL:
202 self.allocate_new_arena()
203 #
204 # The result is simply 'current_arena.freepages'.
205 arena = self.current_arena
206 result = arena.freepages
207 if arena.nfreepages > 0:
208 #
209 # The 'result' was part of the chained list; read the next.
210 arena.nfreepages -= 1
211 freepages = result.address[0]
212 llarena.arena_reset(result,
213 llmemory.sizeof(llmemory.Address),
214 0)
215 #
216 else:
217 # The 'result' is part of the uninitialized pages.
218 ll_assert(self.num_uninitialized_pages > 0,
219 "fully allocated arena found in self.current_arena")
220 self.num_uninitialized_pages -= 1
221 if self.num_uninitialized_pages > 0:
222 freepages = result + self.page_size
223 else:
224 freepages = NULL
225 #
226 arena.freepages = freepages
227 if freepages == NULL:
228 # This was the last page, so put the arena away into
229 # arenas_lists[0].
230 ll_assert(arena.nfreepages == 0,
231 "freepages == NULL but nfreepages > 0")
232 arena.nextarena = self.arenas_lists[0]
233 self.arenas_lists[0] = arena
234 self.current_arena = ARENA_NULL
235 #
236 # Initialize the fields of the resulting page
237 llarena.arena_reserve(result, llmemory.sizeof(PAGE_HEADER))
238 page = llmemory.cast_adr_to_ptr(result, PAGE_PTR)
239 page.arena = arena
240 page.nfree = 0
241 page.freeblock = result + self.hdrsize
242 page.nextpage = PAGE_NULL
243 ll_assert(self.page_for_size[size_class] == PAGE_NULL,
244 "allocate_new_page() called but a page is already waiting")
245 self.page_for_size[size_class] = page
246 return page
247
248
249 def _all_arenas(self):
250 """For testing. Enumerates all arenas."""
251 if self.current_arena:
252 yield self.current_arena
253 for arena in self.arenas_lists:
254 while arena:
255 yield arena
256 arena = arena.nextarena
257
258
259 def _pick_next_arena(self):
260 # Pick an arena from 'arenas_lists[i]', with i as small as possible
261 # but > 0. Use caching with 'min_empty_nfreepages', which guarantees
262 # that 'arenas_lists[1:min_empty_nfreepages]' are all empty.
263 i = self.min_empty_nfreepages
264 while i < self.max_pages_per_arena:
265 #
266 if self.arenas_lists[i] != ARENA_NULL:
267 #
268 # Found it.
269 self.current_arena = self.arenas_lists[i]
270 self.arenas_lists[i] = self.current_arena.nextarena
271 return True
272 #
273 i += 1
274 self.min_empty_nfreepages = i
275 return False
276
277
278 def allocate_new_arena(self):
279 """Loads in self.current_arena the arena to allocate from next."""
280 #
281 if self._pick_next_arena():
282 return
283 #
284 # Maybe we are incrementally collecting, in which case an arena
285 # could have more free pages thrown into it than arenas_lists[]
286 # accounts for. Rehash and retry.
287 self._rehash_arenas_lists()
288 if self._pick_next_arena():
289 return
290 #
291 # No more arena with any free page. We must allocate a new arena.
292 if not we_are_translated():
293 for a in self._all_arenas():
294 assert a.nfreepages == 0
295 #
296 # 'arena_base' points to the start of malloced memory; it might not
297 # be a page-aligned address
298 arena_base = llarena.arena_malloc(self.arena_size, False)
299 self.total_memory_alloced += self.arena_size
300 self.peak_memory_alloced = max(self.total_memory_alloced,
301 self.peak_memory_alloced)
302
303 if not arena_base:
304 out_of_memory("out of memory: couldn't allocate the next arena")
305 arena_end = arena_base + self.arena_size
306 #
307 # 'firstpage' points to the first unused page
308 firstpage = start_of_page(arena_base + self.page_size - 1,
309 self.page_size)
310 # 'npages' is the number of full pages just allocated
311 npages = (arena_end - firstpage) // self.page_size
312 #
313 # Allocate an ARENA object and initialize it
314 arena = lltype.malloc(ARENA, flavor='raw', track_allocation=False)
315 arena.base = arena_base
316 arena.nfreepages = 0 # they are all uninitialized pages
317 arena.totalpages = npages
318 arena.freepages = firstpage
319 self.num_uninitialized_pages = npages
320 self.current_arena = arena
321 self.arenas_count += 1
322 #
323 allocate_new_arena._dont_inline_ = True
324
325
326 def mass_free_prepare(self):
327 """Prepare calls to mass_free_incremental(): moves the chained lists
328 into 'self.old_xxx'.
329 """
330 self.peak_memory_used = max(self.peak_memory_used,
331 self.total_memory_used)
332 #
333 size_class = self.small_request_threshold >> WORD_POWER_2
334 self.size_class_with_old_pages = size_class
335 #
336 while size_class >= 1:
337 self.old_page_for_size[size_class] = (
338 self.page_for_size[size_class])
339 self.old_full_page_for_size[size_class] = (
340 self.full_page_for_size[size_class])
341 self.page_for_size[size_class] = PAGE_NULL
342 self.full_page_for_size[size_class] = PAGE_NULL
343 size_class -= 1
344
345
346 def mass_free_incremental(self, ok_to_free_func, max_pages):
347 """For each object, if ok_to_free_func(obj) returns True, then free
348 the object. This returns True if complete, or False if the limit
349 'max_pages' is reached.
350 """
351 size_class = self.size_class_with_old_pages
352 #
353 while size_class >= 1:
354 #
355 # Walk the pages in 'page_for_size[size_class]' and
356 # 'full_page_for_size[size_class]' and free some objects.
357 # Pages completely freed are added to 'page.arena.freepages',
358 # and become available for reuse by any size class. Pages
359 # not completely freed are re-chained either in
360 # 'full_page_for_size[]' or 'page_for_size[]'.
361 max_pages = self.mass_free_in_pages(size_class, ok_to_free_func,
362 max_pages)
363 if max_pages <= 0:
364 self.size_class_with_old_pages = size_class
365 return False
366 #
367 size_class -= 1
368 #
369 if size_class >= 0:
370 self._rehash_arenas_lists()
371 self.size_class_with_old_pages = -1
372 #
373 return True
374
375
376 def mass_free(self, ok_to_free_func):
377 """For each object, if ok_to_free_func(obj) returns True, then free
378 the object.
379 """
380 self.mass_free_prepare()
381 #
382 res = self.mass_free_incremental(ok_to_free_func, sys.maxint)
383 ll_assert(res, "non-incremental mass_free_in_pages() returned False")
384
385
386 def _rehash_arenas_lists(self):
387 #
388 # Rehash arenas into the correct arenas_lists[i]. If
389 # 'self.current_arena' contains an arena too, it remains there.
390 (self.old_arenas_lists, self.arenas_lists) = (
391 self.arenas_lists, self.old_arenas_lists)
392 #
393 i = 0
394 while i < self.max_pages_per_arena:
395 self.arenas_lists[i] = ARENA_NULL
396 i += 1
397 #
398 i = 0
399 while i < self.max_pages_per_arena:
400 arena = self.old_arenas_lists[i]
401 while arena != ARENA_NULL:
402 nextarena = arena.nextarena
403 #
404 if arena.nfreepages == arena.totalpages:
405 #
406 # The whole arena is empty. Free it.
407 llarena.arena_reset(arena.base, self.arena_size, 4)
408 llarena.arena_free(arena.base)
409 self.total_memory_alloced -= self.arena_size
410 lltype.free(arena, flavor='raw', track_allocation=False)
411 self.arenas_count -= 1
412 #
413 else:
414 # Insert 'arena' in the correct arenas_lists[n]
415 n = arena.nfreepages
416 ll_assert(n < self.max_pages_per_arena,
417 "totalpages != nfreepages >= max_pages_per_arena")
418 arena.nextarena = self.arenas_lists[n]
419 self.arenas_lists[n] = arena
420 #
421 arena = nextarena
422 i += 1
423 #
424 self.min_empty_nfreepages = 1
425
426
427 def mass_free_in_pages(self, size_class, ok_to_free_func, max_pages):
428 nblocks = self.nblocks_for_size[size_class]
429 block_size = size_class * WORD
430 remaining_partial_pages = self.page_for_size[size_class]
431 remaining_full_pages = self.full_page_for_size[size_class]
432 #
433 step = 0
434 while step < 2:
435 if step == 0:
436 page = self.old_full_page_for_size[size_class]
437 self.old_full_page_for_size[size_class] = PAGE_NULL
438 else:
439 page = self.old_page_for_size[size_class]
440 self.old_page_for_size[size_class] = PAGE_NULL
441 #
442 while page != PAGE_NULL:
443 #
444 # Collect the page.
445 surviving = self.walk_page(page, block_size, ok_to_free_func)
446 nextpage = page.nextpage
447 #
448 if surviving == nblocks:
449 #
450 # The page is still full. Re-insert it in the
451 # 'remaining_full_pages' chained list.
452 ll_assert(step == 0,
453 "A non-full page became full while freeing")
454 page.nextpage = remaining_full_pages
455 remaining_full_pages = page
456 #
457 elif surviving > 0:
458 #
459 # There is at least 1 object surviving. Re-insert
460 # the page in the 'remaining_partial_pages' chained list.
461 page.nextpage = remaining_partial_pages
462 remaining_partial_pages = page
463 #
464 else:
465 # No object survives; free the page.
466 self.free_page(page)
467
468 #
469 max_pages -= 1
470 if max_pages <= 0:
471 # End of the incremental step: store back the unprocessed
472 # pages into self.old_xxx and return early
473 if step == 0:
474 self.old_full_page_for_size[size_class] = nextpage
475 else:
476 self.old_page_for_size[size_class] = nextpage
477 step = 99 # stop
478 break
479
480 page = nextpage
481 #
482 else:
483 step += 1
484 #
485 self.page_for_size[size_class] = remaining_partial_pages
486 self.full_page_for_size[size_class] = remaining_full_pages
487 return max_pages
488
489
490 def free_page(self, page):
491 """Free a whole page."""
492 #
493 # Insert the freed page in the arena's 'freepages' list.
494 # If nfreepages == totalpages, then it will be freed at the
495 # end of mass_free().
496 arena = page.arena
497 arena.nfreepages += 1
498 pageaddr = llmemory.cast_ptr_to_adr(page)
499 pageaddr = llarena.getfakearenaaddress(pageaddr)
500 llarena.arena_reset(pageaddr, self.page_size, 0)
501 llarena.arena_reserve(pageaddr, llmemory.sizeof(llmemory.Address))
502 pageaddr.address[0] = arena.freepages
503 arena.freepages = pageaddr
504
505
506 def walk_page(self, page, block_size, ok_to_free_func):
507 """Walk over all objects in a page, and ask ok_to_free_func()."""
508 #
509 # 'freeblock' is the next free block
510 freeblock = page.freeblock
511 #
512 # 'prevfreeblockat' is the address of where 'freeblock' was read from.
513 prevfreeblockat = lltype.direct_fieldptr(page, 'freeblock')
514 prevfreeblockat = llmemory.cast_ptr_to_adr(prevfreeblockat)
515 #
516 obj = llarena.getfakearenaaddress(llmemory.cast_ptr_to_adr(page))
517 obj += self.hdrsize
518 surviving = 0 # initially
519 freed = 0
520 skip_free_blocks = page.nfree
521 #
522 while True:
523 #
524 if obj == freeblock:
525 #
526 if skip_free_blocks == 0:
527 #
528 # 'obj' points to the first uninitialized block,
529 # or to the end of the page if there are none.
530 break
531 #
532 # 'obj' points to a free block. It means that
533 # 'prevfreeblockat.address[0]' does not need to be updated.
534 # Just read the next free block from 'obj.address[0]'.
535 skip_free_blocks -= 1
536 prevfreeblockat = obj
537 freeblock = obj.address[0]
538 #
539 else:
540 # 'obj' points to a valid object.
541 ll_assert(freeblock > obj,
542 "freeblocks are linked out of order")
543 #
544 if ok_to_free_func(obj):
545 #
546 # The object should die.
547 llarena.arena_reset(obj, _dummy_size(block_size), 0)
548 llarena.arena_reserve(obj,
549 llmemory.sizeof(llmemory.Address))
550 # Insert 'obj' in the linked list of free blocks.
551 prevfreeblockat.address[0] = obj
552 prevfreeblockat = obj
553 obj.address[0] = freeblock
554 #
555 # Update the number of free objects in the page.
556 page.nfree += 1
557 freed += 1
558 #
559 else:
560 # The object survives.
561 surviving += 1
562 #
563 obj += block_size
564 #
565 # Update the global total size of objects.
566 self.total_memory_used -= r_uint(freed * block_size)
567 #
568 # Return the number of surviving objects.
569 return surviving
570
571
572 def _nuninitialized(self, page, size_class):
573 # Helper for debugging: count the number of uninitialized blocks
574 freeblock = page.freeblock
575 for i in range(page.nfree):
576 freeblock = freeblock.address[0]
577 assert freeblock != NULL
578 pageaddr = llarena.getfakearenaaddress(llmemory.cast_ptr_to_adr(page))
579 num_initialized_blocks, rem = divmod(
580 freeblock - pageaddr - self.hdrsize, size_class * WORD)
581 assert rem == 0, "page size_class misspecified?"
582 nblocks = self.nblocks_for_size[size_class]
583 return nblocks - num_initialized_blocks
584
585
586 # ____________________________________________________________
587 # Helpers to go from a pointer to the start of its page
588
589 def start_of_page(addr, page_size):
590 """Return the address of the start of the page that contains 'addr'."""
591 if we_are_translated():
592 offset = llmemory.cast_adr_to_int(addr) % page_size
593 return addr - offset
594 else:
595 return _start_of_page_untranslated(addr, page_size)
596
597 def _start_of_page_untranslated(addr, page_size):
598 assert isinstance(addr, llarena.fakearenaaddress)
599 shift = WORD # for testing, we assume that the whole arena is not
600 # on a page boundary
601 ofs = ((addr.offset - shift) // page_size) * page_size + shift
602 return llarena.fakearenaaddress(addr.arena, ofs)
603
604 def _dummy_size(size):
605 if we_are_translated():
606 return size
607 if isinstance(size, int):
608 size = llmemory.sizeof(lltype.Char) * size
609 return size
610
611 def out_of_memory(errmsg):
612 """Signal a fatal out-of-memory error and abort. For situations where
613 it is hard to write and test code that would handle a MemoryError
614 exception gracefully.
615 """
616 fatalerror(errmsg)