Debian Codegraph @

rpython/memory/gc/minimark.py

raw symbols SCIP
1 """ MiniMark GC.
2
3 Environment variables can be used to fine-tune the following parameters:
4
5 PYPY_GC_NURSERY The nursery size. Defaults to 1/2 of your cache or
6 '4M'. Small values
7 (like 1 or 1KB) are useful for debugging.
8
9 PYPY_GC_NURSERY_CLEANUP The interval at which nursery is cleaned up. Must
10 be smaller than the nursery size and bigger than the
11 biggest object we can allotate in the nursery.
12
13 PYPY_GC_MAJOR_COLLECT Major collection memory factor. Default is '1.82',
14 which means trigger a major collection when the
15 memory consumed equals 1.82 times the memory
16 really used at the end of the previous major
17 collection.
18
19 PYPY_GC_GROWTH Major collection threshold's max growth rate.
20 Default is '1.4'. Useful to collect more often
21 than normally on sudden memory growth, e.g. when
22 there is a temporary peak in memory usage.
23
24 PYPY_GC_MAX The max heap size. If coming near this limit, it
25 will first collect more often, then raise an
26 RPython MemoryError, and if that is not enough,
27 crash the program with a fatal error. Try values
28 like '1.6GB'.
29
30 PYPY_GC_MAX_DELTA The major collection threshold will never be set
31 to more than PYPY_GC_MAX_DELTA the amount really
32 used after a collection. Defaults to 1/8th of the
33 total RAM size (which is constrained to be at most
34 2/3/4GB on 32-bit systems). Try values like '200MB'.
35
36 PYPY_GC_MIN Don't collect while the memory size is below this
37 limit. Useful to avoid spending all the time in
38 the GC in very small programs. Defaults to 8
39 times the nursery.
40
41 PYPY_GC_DEBUG Enable extra checks around collections that are
42 too slow for normal use. Values are 0 (off),
43 1 (on major collections) or 2 (also on minor
44 collections).
45 """
46 # XXX Should find a way to bound the major collection threshold by the
47 # XXX total addressable size. Maybe by keeping some minimarkpage arenas
48 # XXX pre-reserved, enough for a few nursery collections? What about
49 # XXX raw-malloced memory?
50 import sys
51 from rpython.rtyper.lltypesystem import lltype, llmemory, llarena, llgroup
52 from rpython.rtyper.lltypesystem.lloperation import llop
53 from rpython.rtyper.lltypesystem.llmemory import raw_malloc_usage
54 from rpython.memory.gc.base import GCBase, MovingGCBase
55 from rpython.memory.gc import env
56 from rpython.memory.support import mangle_hash
57 from rpython.rlib.rarithmetic import ovfcheck, LONG_BIT, intmask, r_uint
58 from rpython.rlib.rarithmetic import LONG_BIT_SHIFT
59 from rpython.rlib.debug import ll_assert, debug_print, debug_start, debug_stop
60 from rpython.rlib.objectmodel import specialize
61
62
63 #
64 # Handles the objects in 2 generations:
65 #
66 # * young objects: allocated in the nursery if they are not too large, or
67 # raw-malloced otherwise. The nursery is a fixed-size memory buffer of
68 # 4MB by default. When full, we do a minor collection;
69 # the surviving objects from the nursery are moved outside, and the
70 # non-surviving raw-malloced objects are freed. All surviving objects
71 # become old.
72 #
73 # * old objects: never move again. These objects are either allocated by
74 # minimarkpage.py (if they are small), or raw-malloced (if they are not
75 # small). Collected by regular mark-n-sweep during major collections.
76 #
77
78 WORD = LONG_BIT // 8
79 NULL = llmemory.NULL
80
81 first_gcflag = 1 << (LONG_BIT//2)
82
83 # The following flag is set on objects if we need to do something to
84 # track the young pointers that it might contain. The flag is not set
85 # on young objects (unless they are large arrays, see below), and we
86 # simply assume that any young object can point to any other young object.
87 # For old and prebuilt objects, the flag is usually set, and is cleared
88 # when we write a young pointer to it. For large arrays with
89 # GCFLAG_HAS_CARDS, we rely on card marking to track where the
90 # young pointers are; the flag GCFLAG_TRACK_YOUNG_PTRS is set in this
91 # case too, to speed up the write barrier.
92 GCFLAG_TRACK_YOUNG_PTRS = first_gcflag << 0
93
94 # The following flag is set on some prebuilt objects. The flag is set
95 # unless the object is already listed in 'prebuilt_root_objects'.
96 # When a pointer is written inside an object with GCFLAG_NO_HEAP_PTRS
97 # set, the write_barrier clears the flag and adds the object to
98 # 'prebuilt_root_objects'.
99 GCFLAG_NO_HEAP_PTRS = first_gcflag << 1
100
101 # The following flag is set on surviving objects during a major collection,
102 # and on surviving raw-malloced young objects during a minor collection.
103 GCFLAG_VISITED = first_gcflag << 2
104
105 # The following flag is set on nursery objects of which we asked the id
106 # or the identityhash. It means that a space of the size of the object
107 # has already been allocated in the nonmovable part.
108 GCFLAG_HAS_SHADOW = first_gcflag << 3
109
110 # The following flag is set temporarily on some objects during a major
111 # collection. See pypy/doc/discussion/finalizer-order.txt
112 GCFLAG_FINALIZATION_ORDERING = first_gcflag << 4
113
114 # This flag is reserved for RPython.
115 GCFLAG_EXTRA = first_gcflag << 5
116
117 # The following flag is set on externally raw_malloc'ed arrays of pointers.
118 # They are allocated with some extra space in front of them for a bitfield,
119 # one bit per 'card_page_indices' indices.
120 GCFLAG_HAS_CARDS = first_gcflag << 6
121 GCFLAG_CARDS_SET = first_gcflag << 7 # <- at least one card bit is set
122 # note that GCFLAG_CARDS_SET is the most significant bit of a byte:
123 # this is required for the JIT (x86)
124
125 # another flag set only on specific objects: the ll_dummy_value from
126 # rpython.rtyper.rmodel
127 GCFLAG_DUMMY = first_gcflag << 8
128
129 _GCFLAG_FIRST_UNUSED = first_gcflag << 9 # the first unused bit
130
131
132 FORWARDSTUB = lltype.GcStruct('forwarding_stub',
133 ('forw', llmemory.Address))
134 FORWARDSTUBPTR = lltype.Ptr(FORWARDSTUB)
135 NURSARRAY = lltype.Array(llmemory.Address)
136
137 # ____________________________________________________________
138
139 class MiniMarkGC(MovingGCBase):
140 _alloc_flavor_ = "raw"
141 inline_simple_malloc = True
142 inline_simple_malloc_varsize = True
143 needs_write_barrier = True
144 prebuilt_gc_objects_are_static_roots = False
145 malloc_zero_filled = True # xxx experiment with False
146 gcflag_extra = GCFLAG_EXTRA
147 gcflag_dummy = GCFLAG_DUMMY
148
149 # All objects start with a HDR, i.e. with a field 'tid' which contains
150 # a word. This word is divided in two halves: the lower half contains
151 # the typeid, and the upper half contains various flags, as defined
152 # by GCFLAG_xxx above.
153 HDR = lltype.Struct('header', ('tid', lltype.Signed))
154 typeid_is_in_field = 'tid'
155
156 _ADDRARRAY = lltype.Array(llmemory.Address, hints={'nolength': True})
157
158
159 # During a minor collection, the objects in the nursery that are
160 # moved outside are changed in-place: their header is replaced with
161 # the value -42, and the following word is set to the address of
162 # where the object was moved. This means that all objects in the
163 # nursery need to be at least 2 words long, but objects outside the
164 # nursery don't need to.
165 minimal_size_in_nursery = (
166 llmemory.sizeof(HDR) + llmemory.sizeof(llmemory.Address))
167
168
169 TRANSLATION_PARAMS = {
170 # Automatically adjust the size of the nursery and the
171 # 'major_collection_threshold' from the environment.
172 # See docstring at the start of the file.
173 "read_from_env": True,
174
175 # The size of the nursery. Note that this is only used as a
176 # fall-back number.
177 "nursery_size": 896*1024,
178
179 # The system page size. Like malloc, we assume that it is 4K
180 # for 32-bit systems; unlike malloc, we assume that it is 8K
181 # for 64-bit systems, for consistent results.
182 "page_size": 1024*WORD,
183
184 # The size of an arena. Arenas are groups of pages allocated
185 # together.
186 "arena_size": 65536*WORD,
187
188 # The maximum size of an object allocated compactly. All objects
189 # that are larger are just allocated with raw_malloc(). Note that
190 # the size limit for being first allocated in the nursery is much
191 # larger; see below.
192 "small_request_threshold": 35*WORD,
193
194 # Full collection threshold: after a major collection, we record
195 # the total size consumed; and after every minor collection, if the
196 # total size is now more than 'major_collection_threshold' times,
197 # we trigger the next major collection.
198 "major_collection_threshold": 1.82,
199
200 # Threshold to avoid that the total heap size grows by a factor of
201 # major_collection_threshold at every collection: it can only
202 # grow at most by the following factor from one collection to the
203 # next. Used e.g. when there is a sudden, temporary peak in memory
204 # usage; this avoids that the upper bound grows too fast.
205 "growth_rate_max": 1.4,
206
207 # The number of array indices that are mapped to a single bit in
208 # write_barrier_from_array(). Must be a power of two. The default
209 # value of 128 means that card pages are 512 bytes (1024 on 64-bits)
210 # in regular arrays of pointers; more in arrays whose items are
211 # larger. A value of 0 disables card marking.
212 "card_page_indices": 128,
213
214 # Objects whose total size is at least 'large_object' bytes are
215 # allocated out of the nursery immediately, as old objects. The
216 # minimal allocated size of the nursery is 2x the following
217 # number (by default, at least 132KB on 32-bit and 264KB on 64-bit).
218 "large_object": (16384+512)*WORD,
219
220 # This is the chunk that we cleanup in the nursery. The point is
221 # to avoid having to trash all the caches just to zero the nursery,
222 # so we trade it by cleaning it bit-by-bit, as we progress through
223 # nursery. Has to fit at least one large object
224 "nursery_cleanup": 32768 * WORD,
225 }
226
227 def __init__(self, config,
228 read_from_env=False,
229 nursery_size=32*WORD,
230 nursery_cleanup=9*WORD,
231 page_size=16*WORD,
232 arena_size=64*WORD,
233 small_request_threshold=5*WORD,
234 major_collection_threshold=2.5,
235 growth_rate_max=2.5, # for tests
236 card_page_indices=0,
237 large_object=8*WORD,
238 ArenaCollectionClass=None,
239 **kwds):
240 MovingGCBase.__init__(self, config, **kwds)
241 assert small_request_threshold % WORD == 0
242 self.read_from_env = read_from_env
243 self.nursery_size = nursery_size
244 self.nursery_cleanup = nursery_cleanup
245 self.small_request_threshold = small_request_threshold
246 self.major_collection_threshold = major_collection_threshold
247 self.growth_rate_max = growth_rate_max
248 self.num_major_collects = 0
249 self.min_heap_size = 0.0
250 self.max_heap_size = 0.0
251 self.max_heap_size_already_raised = False
252 self.max_delta = float(r_uint(-1))
253 #
254 self.card_page_indices = card_page_indices
255 if self.card_page_indices > 0:
256 self.card_page_shift = 0
257 while (1 << self.card_page_shift) < self.card_page_indices:
258 self.card_page_shift += 1
259 #
260 # 'large_object' limit how big objects can be in the nursery, so
261 # it gives a lower bound on the allowed size of the nursery.
262 self.nonlarge_max = large_object - 1
263 #
264 self.nursery = NULL
265 self.nursery_free = NULL
266 self.nursery_top = NULL
267 self.nursery_real_top = NULL
268 self.debug_tiny_nursery = -1
269 self.debug_rotating_nurseries = lltype.nullptr(NURSARRAY)
270 self.extra_threshold = 0
271 #
272 # The ArenaCollection() handles the nonmovable objects allocation.
273 if ArenaCollectionClass is None:
274 from rpython.memory.gc import minimarkpage
275 ArenaCollectionClass = minimarkpage.ArenaCollection
276 self.ac = ArenaCollectionClass(arena_size, page_size,
277 small_request_threshold)
278 #
279 # Used by minor collection: a list of (mostly non-young) objects that
280 # (may) contain a pointer to a young object. Populated by
281 # the write barrier: when we clear GCFLAG_TRACK_YOUNG_PTRS, we
282 # add it to this list.
283 # Note that young array objects may (by temporary "mistake") be added
284 # to this list, but will be removed again at the start of the next
285 # minor collection.
286 self.old_objects_pointing_to_young = self.AddressStack()
287 #
288 # Similar to 'old_objects_pointing_to_young', but lists objects
289 # that have the GCFLAG_CARDS_SET bit. For large arrays. Note
290 # that it is possible for an object to be listed both in here
291 # and in 'old_objects_pointing_to_young', in which case we
292 # should just clear the cards and trace it fully, as usual.
293 # Note also that young array objects are never listed here.
294 self.old_objects_with_cards_set = self.AddressStack()
295 #
296 # A list of all prebuilt GC objects that contain pointers to the heap
297 self.prebuilt_root_objects = self.AddressStack()
298 #
299 self._init_writebarrier_logic()
300
301
302 def setup(self):
303 """Called at run-time to initialize the GC."""
304 #
305 # Hack: MovingGCBase.setup() sets up stuff related to id(), which
306 # we implement differently anyway. So directly call GCBase.setup().
307 GCBase.setup(self)
308 #
309 # Two lists of all raw_malloced objects (the objects too large)
310 self.young_rawmalloced_objects = self.null_address_dict()
311 self.old_rawmalloced_objects = self.AddressStack()
312 self.rawmalloced_total_size = r_uint(0)
313 #
314 # Two lists of all objects with finalizers. Actually they are lists
315 # of pairs (finalization_queue_nr, object). "probably young objects"
316 # are all traced and moved to the "old" list by the next minor
317 # collection.
318 self.probably_young_objects_with_finalizers = self.AddressDeque()
319 self.old_objects_with_finalizers = self.AddressDeque()
320 p = lltype.malloc(self._ADDRARRAY, 1, flavor='raw',
321 track_allocation=False)
322 self.singleaddr = llmemory.cast_ptr_to_adr(p)
323 #
324 # Two lists of all objects with destructors.
325 self.young_objects_with_destructors = self.AddressStack()
326 self.old_objects_with_destructors = self.AddressStack()
327 #
328 # Two lists of the objects with weakrefs. No weakref can be an
329 # old object weakly pointing to a young object: indeed, weakrefs
330 # are immutable so they cannot point to an object that was
331 # created after it.
332 self.young_objects_with_weakrefs = self.AddressStack()
333 self.old_objects_with_weakrefs = self.AddressStack()
334 #
335 # Support for id and identityhash: map nursery objects with
336 # GCFLAG_HAS_SHADOW to their future location at the next
337 # minor collection.
338 self.nursery_objects_shadows = self.AddressDict()
339 #
340 # Allocate a nursery. In case of auto_nursery_size, start by
341 # allocating a very small nursery, enough to do things like look
342 # up the env var, which requires the GC; and then really
343 # allocate the nursery of the final size.
344 if not self.read_from_env:
345 self.allocate_nursery()
346 else:
347 #
348 defaultsize = self.nursery_size
349 minsize = 2 * (self.nonlarge_max + 1)
350 self.nursery_size = minsize
351 self.allocate_nursery()
352 #
353 # From there on, the GC is fully initialized and the code
354 # below can use it
355 newsize = env.read_from_env('PYPY_GC_NURSERY')
356 # PYPY_GC_NURSERY=smallvalue means that minor collects occur
357 # very frequently; the extreme case is PYPY_GC_NURSERY=1, which
358 # forces a minor collect for every malloc. Useful to debug
359 # external factors, like trackgcroot or the handling of the write
360 # barrier. Implemented by still using 'minsize' for the nursery
361 # size (needed to handle mallocs just below 'large_objects') but
362 # hacking at the current nursery position in collect_and_reserve().
363 if newsize <= 0:
364 newsize = env.estimate_best_nursery_size()
365 if newsize <= 0:
366 newsize = defaultsize
367 if newsize < minsize:
368 self.debug_tiny_nursery = newsize & ~(WORD-1)
369 newsize = minsize
370
371 nurs_cleanup = env.read_from_env('PYPY_GC_NURSERY_CLEANUP')
372 if nurs_cleanup > 0:
373 self.nursery_cleanup = nurs_cleanup
374 #
375 major_coll = env.read_float_from_env('PYPY_GC_MAJOR_COLLECT')
376 if major_coll > 1.0:
377 self.major_collection_threshold = major_coll
378 #
379 growth = env.read_float_from_env('PYPY_GC_GROWTH')
380 if growth > 1.0:
381 self.growth_rate_max = growth
382 #
383 min_heap_size = env.read_uint_from_env('PYPY_GC_MIN')
384 if min_heap_size > 0:
385 self.min_heap_size = float(min_heap_size)
386 else:
387 # defaults to 8 times the nursery
388 self.min_heap_size = newsize * 8
389 #
390 max_heap_size = env.read_uint_from_env('PYPY_GC_MAX')
391 if max_heap_size > 0:
392 self.max_heap_size = float(max_heap_size)
393 #
394 max_delta = env.read_uint_from_env('PYPY_GC_MAX_DELTA')
395 if max_delta > 0:
396 self.max_delta = float(max_delta)
397 else:
398 self.max_delta = 0.125 * env.get_total_memory()
399 #
400 self.minor_collection() # to empty the nursery
401 llarena.arena_free(self.nursery)
402 self.nursery_size = newsize
403 self.allocate_nursery()
404 #
405 if self.nursery_cleanup < self.nonlarge_max + 1:
406 self.nursery_cleanup = self.nonlarge_max + 1
407 # We need exactly initial_cleanup + N*nursery_cleanup = nursery_size.
408 # We choose the value of initial_cleanup to be between 1x and 2x the
409 # value of nursery_cleanup.
410 self.initial_cleanup = self.nursery_cleanup + (
411 self.nursery_size % self.nursery_cleanup)
412 if (r_uint(self.initial_cleanup) > r_uint(self.nursery_size) or
413 self.debug_tiny_nursery >= 0):
414 self.initial_cleanup = self.nursery_size
415
416 def _nursery_memory_size(self):
417 extra = self.nonlarge_max + 1
418 return self.nursery_size + extra
419
420 def _alloc_nursery(self):
421 # the start of the nursery: we actually allocate a bit more for
422 # the nursery than really needed, to simplify pointer arithmetic
423 # in malloc_fixedsize_clear(). The few extra pages are never used
424 # anyway so it doesn't even count.
425 nursery = llarena.arena_malloc(self._nursery_memory_size(), 2)
426 if not nursery:
427 raise MemoryError("cannot allocate nursery")
428 return nursery
429
430 def allocate_nursery(self):
431 debug_start("gc-set-nursery-size")
432 debug_print("nursery size:", self.nursery_size)
433 self.nursery = self._alloc_nursery()
434 # the current position in the nursery:
435 self.nursery_free = self.nursery
436 # the end of the nursery:
437 self.nursery_top = self.nursery + self.nursery_size
438 self.nursery_real_top = self.nursery_top
439 # initialize the threshold
440 self.min_heap_size = max(self.min_heap_size, self.nursery_size *
441 self.major_collection_threshold)
442 # the following two values are usually equal, but during raw mallocs
443 # of arrays, next_major_collection_threshold is decremented to make
444 # the next major collection arrive earlier.
445 # See translator/c/test/test_newgc, test_nongc_attached_to_gc
446 self.next_major_collection_initial = self.min_heap_size
447 self.next_major_collection_threshold = self.min_heap_size
448 self.set_major_threshold_from(0.0)
449 ll_assert(self.extra_threshold == 0, "extra_threshold set too early")
450 self.initial_cleanup = self.nursery_size
451 debug_stop("gc-set-nursery-size")
452
453
454 def set_major_threshold_from(self, threshold, reserving_size=0):
455 # Set the next_major_collection_threshold.
456 threshold_max = (self.next_major_collection_initial *
457 self.growth_rate_max)
458 if threshold > threshold_max:
459 threshold = threshold_max
460 #
461 threshold += reserving_size
462 if threshold < self.min_heap_size:
463 threshold = self.min_heap_size
464 #
465 if self.max_heap_size > 0.0 and threshold > self.max_heap_size:
466 threshold = self.max_heap_size
467 bounded = True
468 else:
469 bounded = False
470 #
471 self.next_major_collection_initial = threshold
472 self.next_major_collection_threshold = threshold
473 return bounded
474
475
476 def post_setup(self):
477 # set up extra stuff for PYPY_GC_DEBUG.
478 MovingGCBase.post_setup(self)
479 if self.DEBUG and llarena.has_protect:
480 # gc debug mode: allocate 23 nurseries instead of just 1,
481 # and use them alternatively, while mprotect()ing the unused
482 # ones to detect invalid access.
483 debug_start("gc-debug")
484 self.debug_rotating_nurseries = lltype.malloc(
485 NURSARRAY, 22, flavor='raw', track_allocation=False)
486 i = 0
487 while i < 22:
488 nurs = self._alloc_nursery()
489 llarena.arena_protect(nurs, self._nursery_memory_size(), True)
490 self.debug_rotating_nurseries[i] = nurs
491 i += 1
492 debug_print("allocated", len(self.debug_rotating_nurseries),
493 "extra nurseries")
494 debug_stop("gc-debug")
495
496 def debug_rotate_nursery(self):
497 if self.debug_rotating_nurseries:
498 debug_start("gc-debug")
499 oldnurs = self.nursery
500 llarena.arena_protect(oldnurs, self._nursery_memory_size(), True)
501 #
502 newnurs = self.debug_rotating_nurseries[0]
503 i = 0
504 while i < len(self.debug_rotating_nurseries) - 1:
505 self.debug_rotating_nurseries[i] = (
506 self.debug_rotating_nurseries[i + 1])
507 i += 1
508 self.debug_rotating_nurseries[i] = oldnurs
509 #
510 llarena.arena_protect(newnurs, self._nursery_memory_size(), False)
511 self.nursery = newnurs
512 self.nursery_top = self.nursery + self.initial_cleanup
513 self.nursery_real_top = self.nursery + self.nursery_size
514 debug_print("switching from nursery", oldnurs,
515 "to nursery", self.nursery,
516 "size", self.nursery_size)
517 debug_stop("gc-debug")
518
519
520 def malloc_fixedsize_clear(self, typeid, size,
521 needs_finalizer=False,
522 is_finalizer_light=False,
523 contains_weakptr=False):
524 size_gc_header = self.gcheaderbuilder.size_gc_header
525 totalsize = size_gc_header + size
526 rawtotalsize = raw_malloc_usage(totalsize)
527 #
528 # If the object needs a finalizer, ask for a rawmalloc.
529 # The following check should be constant-folded.
530 if needs_finalizer and not is_finalizer_light:
531 # old-style finalizers only!
532 ll_assert(not contains_weakptr,
533 "'needs_finalizer' and 'contains_weakptr' both specified")
534 obj = self.external_malloc(typeid, 0, alloc_young=False)
535 res = llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
536 self.register_finalizer(-1, res)
537 return res
538 #
539 # If totalsize is greater than nonlarge_max (which should never be
540 # the case in practice), ask for a rawmalloc. The following check
541 # should be constant-folded.
542 if rawtotalsize > self.nonlarge_max:
543 ll_assert(not contains_weakptr,
544 "'contains_weakptr' specified for a large object")
545 obj = self.external_malloc(typeid, 0, alloc_young=True)
546 #
547 else:
548 # If totalsize is smaller than minimal_size_in_nursery, round it
549 # up. The following check should also be constant-folded.
550 min_size = raw_malloc_usage(self.minimal_size_in_nursery)
551 if rawtotalsize < min_size:
552 totalsize = rawtotalsize = min_size
553 #
554 # Get the memory from the nursery. If there is not enough space
555 # there, do a collect first.
556 result = self.nursery_free
557 self.nursery_free = result + totalsize
558 if self.nursery_free > self.nursery_top:
559 result = self.collect_and_reserve(result, totalsize)
560 #
561 # Build the object.
562 llarena.arena_reserve(result, totalsize)
563 obj = result + size_gc_header
564 self.init_gc_object(result, typeid, flags=0)
565 #
566 # If it is a weakref or has a lightweight destructor, record it
567 # (checks constant-folded).
568 if needs_finalizer:
569 self.young_objects_with_destructors.append(obj)
570 if contains_weakptr:
571 self.young_objects_with_weakrefs.append(obj)
572 return llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
573
574
575 def malloc_varsize_clear(self, typeid, length, size, itemsize,
576 offset_to_length):
577 size_gc_header = self.gcheaderbuilder.size_gc_header
578 nonvarsize = size_gc_header + size
579 #
580 # Compute the maximal length that makes the object still
581 # below 'nonlarge_max'. All the following logic is usually
582 # constant-folded because self.nonlarge_max, size and itemsize
583 # are all constants (the arguments are constant due to
584 # inlining).
585 maxsize = self.nonlarge_max - raw_malloc_usage(nonvarsize)
586 if maxsize < 0:
587 toobig = r_uint(0) # the nonvarsize alone is too big
588 elif raw_malloc_usage(itemsize):
589 toobig = r_uint(maxsize // raw_malloc_usage(itemsize)) + 1
590 else:
591 toobig = r_uint(sys.maxint) + 1
592
593 if r_uint(length) >= r_uint(toobig):
594 #
595 # If the total size of the object would be larger than
596 # 'nonlarge_max', then allocate it externally. We also
597 # go there if 'length' is actually negative.
598 obj = self.external_malloc(typeid, length, alloc_young=True)
599 #
600 else:
601 # With the above checks we know now that totalsize cannot be more
602 # than 'nonlarge_max'; in particular, the + and * cannot overflow.
603 totalsize = nonvarsize + itemsize * length
604 totalsize = llarena.round_up_for_allocation(totalsize)
605 #
606 # 'totalsize' should contain at least the GC header and
607 # the length word, so it should never be smaller than
608 # 'minimal_size_in_nursery'
609 ll_assert(raw_malloc_usage(totalsize) >=
610 raw_malloc_usage(self.minimal_size_in_nursery),
611 "malloc_varsize_clear(): totalsize < minimalsize")
612 #
613 # Get the memory from the nursery. If there is not enough space
614 # there, do a collect first.
615 result = self.nursery_free
616 self.nursery_free = result + totalsize
617 if self.nursery_free > self.nursery_top:
618 result = self.collect_and_reserve(result, totalsize)
619 #
620 # Build the object.
621 llarena.arena_reserve(result, totalsize)
622 self.init_gc_object(result, typeid, flags=0)
623 #
624 # Set the length and return the object.
625 obj = result + size_gc_header
626 (obj + offset_to_length).signed[0] = length
627 #
628 return llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
629
630
631 def malloc_fixed_or_varsize_nonmovable(self, typeid, length):
632 # length==0 for fixedsize
633 obj = self.external_malloc(typeid, length, alloc_young=True)
634 return llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
635
636
637 def collect(self, gen=1):
638 """Do a minor (gen=0) or major (gen>0) collection."""
639 self.minor_collection()
640 if gen > 0:
641 self.major_collection()
642
643 def move_nursery_top(self, totalsize):
644 size = self.nursery_cleanup
645 ll_assert(self.nursery_real_top - self.nursery_top >= size,
646 "nursery_cleanup not a divisor of nursery_size - initial_cleanup")
647 ll_assert(llmemory.raw_malloc_usage(totalsize) <= size,
648 "totalsize > nursery_cleanup")
649 llarena.arena_reset(self.nursery_top, size, 2)
650 self.nursery_top += size
651 move_nursery_top._always_inline_ = True
652
653 def collect_and_reserve(self, prev_result, totalsize):
654 """To call when nursery_free overflows nursery_top.
655 First check if the nursery_top is the real top, otherwise we
656 can just move the top of one cleanup and continue
657
658 Do a minor collection, and possibly also a major collection,
659 and finally reserve 'totalsize' bytes at the start of the
660 now-empty nursery.
661 """
662 if self.nursery_top < self.nursery_real_top:
663 self.move_nursery_top(totalsize)
664 return prev_result
665 self.minor_collection()
666 #
667 if self.get_total_memory_used() > self.next_major_collection_threshold:
668 self.major_collection()
669 #
670 # The nursery might not be empty now, because of
671 # execute_finalizers(). If it is almost full again,
672 # we need to fix it with another call to minor_collection().
673 if self.nursery_free + totalsize > self.nursery_top:
674 #
675 if self.nursery_free + totalsize > self.nursery_real_top:
676 self.minor_collection()
677 # then the nursery is empty
678 else:
679 # we just need to clean up a bit more of the nursery
680 self.move_nursery_top(totalsize)
681 #
682 result = self.nursery_free
683 self.nursery_free = result + totalsize
684 ll_assert(self.nursery_free <= self.nursery_top, "nursery overflow")
685 #
686 if self.debug_tiny_nursery >= 0: # for debugging
687 if self.nursery_top - self.nursery_free > self.debug_tiny_nursery:
688 self.nursery_free = self.nursery_top - self.debug_tiny_nursery
689 #
690 return result
691 collect_and_reserve._dont_inline_ = True
692
693
694 # XXX kill alloc_young and make it always True
695 def external_malloc(self, typeid, length, alloc_young):
696 """Allocate a large object using the ArenaCollection or
697 raw_malloc(), possibly as an object with card marking enabled,
698 if it has gc pointers in its var-sized part. 'length' should be
699 specified as 0 if the object is not varsized. The returned
700 object is fully initialized and zero-filled."""
701 #
702 # Here we really need a valid 'typeid', not 0 (as the JIT might
703 # try to send us if there is still a bug).
704 ll_assert(bool(self.combine(typeid, 0)),
705 "external_malloc: typeid == 0")
706 #
707 # Compute the total size, carefully checking for overflows.
708 size_gc_header = self.gcheaderbuilder.size_gc_header
709 nonvarsize = size_gc_header + self.fixed_size(typeid)
710 if length == 0:
711 # this includes the case of fixed-size objects, for which we
712 # should not even ask for the varsize_item_sizes().
713 totalsize = nonvarsize
714 elif length > 0:
715 # var-sized allocation with at least one item
716 itemsize = self.varsize_item_sizes(typeid)
717 try:
718 varsize = ovfcheck(itemsize * length)
719 totalsize = ovfcheck(nonvarsize + varsize)
720 except OverflowError:
721 raise MemoryError
722 else:
723 # negative length! This likely comes from an overflow
724 # earlier. We will just raise MemoryError here.
725 raise MemoryError
726 #
727 # If somebody calls this function a lot, we must eventually
728 # force a full collection.
729 if (float(self.get_total_memory_used()) + raw_malloc_usage(totalsize) >
730 self.next_major_collection_threshold):
731 self.minor_collection()
732 self.major_collection(raw_malloc_usage(totalsize))
733 #
734 # Check if the object would fit in the ArenaCollection.
735 # Also, an object allocated from ArenaCollection must be old.
736 if (raw_malloc_usage(totalsize) <= self.small_request_threshold
737 and not alloc_young):
738 #
739 # Yes. Round up 'totalsize' (it cannot overflow and it
740 # must remain <= self.small_request_threshold.)
741 totalsize = llarena.round_up_for_allocation(totalsize)
742 ll_assert(raw_malloc_usage(totalsize) <=
743 self.small_request_threshold,
744 "rounding up made totalsize > small_request_threshold")
745 #
746 # Allocate from the ArenaCollection and clear the memory returned.
747 result = self.ac.malloc(totalsize)
748 llmemory.raw_memclear(result, totalsize)
749 #
750 extra_flags = GCFLAG_TRACK_YOUNG_PTRS
751 #
752 else:
753 # No, so proceed to allocate it externally with raw_malloc().
754 # Check if we need to introduce the card marker bits area.
755 if (self.card_page_indices <= 0 # <- this check is constant-folded
756 or not self.has_gcptr_in_varsize(typeid) or
757 raw_malloc_usage(totalsize) <= self.nonlarge_max):
758 #
759 # In these cases, we don't want a card marker bits area.
760 # This case also includes all fixed-size objects.
761 cardheadersize = 0
762 extra_flags = 0
763 #
764 else:
765 # Reserve N extra words containing card bits before the object.
766 extra_words = self.card_marking_words_for_length(length)
767 cardheadersize = WORD * extra_words
768 extra_flags = GCFLAG_HAS_CARDS | GCFLAG_TRACK_YOUNG_PTRS
769 # if 'alloc_young', then we also immediately set
770 # GCFLAG_CARDS_SET, but without adding the object to
771 # 'old_objects_with_cards_set'. In this way it should
772 # never be added to that list as long as it is young.
773 if alloc_young:
774 extra_flags |= GCFLAG_CARDS_SET
775 #
776 # Detect very rare cases of overflows
777 if raw_malloc_usage(totalsize) > (sys.maxint - (WORD-1)
778 - cardheadersize):
779 raise MemoryError("rare case of overflow")
780 #
781 # Now we know that the following computations cannot overflow.
782 # Note that round_up_for_allocation() is also needed to get the
783 # correct number added to 'rawmalloced_total_size'.
784 allocsize = (cardheadersize + raw_malloc_usage(
785 llarena.round_up_for_allocation(totalsize)))
786 #
787 # Allocate the object using arena_malloc(), which we assume here
788 # is just the same as raw_malloc(), but allows the extra
789 # flexibility of saying that we have extra words in the header.
790 # The memory returned is cleared by a raw_memclear().
791 arena = llarena.arena_malloc(allocsize, 2)
792 if not arena:
793 raise MemoryError("cannot allocate large object")
794 #
795 # Reserve the card mark bits as a list of single bytes
796 # (the loop is empty in C).
797 i = 0
798 while i < cardheadersize:
799 llarena.arena_reserve(arena + i, llmemory.sizeof(lltype.Char))
800 i += 1
801 #
802 # Reserve the actual object. (This is also a no-op in C).
803 result = arena + cardheadersize
804 llarena.arena_reserve(result, totalsize)
805 #
806 # Record the newly allocated object and its full malloced size.
807 # The object is young or old depending on the argument.
808 self.rawmalloced_total_size += r_uint(allocsize)
809 if alloc_young:
810 if not self.young_rawmalloced_objects:
811 self.young_rawmalloced_objects = self.AddressDict()
812 self.young_rawmalloced_objects.add(result + size_gc_header)
813 else:
814 self.old_rawmalloced_objects.append(result + size_gc_header)
815 extra_flags |= GCFLAG_TRACK_YOUNG_PTRS
816 #
817 # Common code to fill the header and length of the object.
818 self.init_gc_object(result, typeid, extra_flags)
819 if self.is_varsize(typeid):
820 offset_to_length = self.varsize_offset_to_length(typeid)
821 (result + size_gc_header + offset_to_length).signed[0] = length
822 return result + size_gc_header
823
824
825 # ----------
826 # Other functions in the GC API
827
828 def set_max_heap_size(self, size):
829 self.max_heap_size = float(size)
830 if self.max_heap_size > 0.0:
831 if self.max_heap_size < self.next_major_collection_initial:
832 self.next_major_collection_initial = self.max_heap_size
833 if self.max_heap_size < self.next_major_collection_threshold:
834 self.next_major_collection_threshold = self.max_heap_size
835
836 def raw_malloc_memory_pressure(self, sizehint, adr):
837 self.next_major_collection_threshold -= sizehint
838 if self.next_major_collection_threshold < 0:
839 # cannot trigger a full collection now, but we can ensure
840 # that one will occur very soon
841 self.nursery_top = self.nursery_real_top
842 self.nursery_free = self.nursery_real_top
843
844 def can_optimize_clean_setarrayitems(self):
845 if self.card_page_indices > 0:
846 return False
847 return MovingGCBase.can_optimize_clean_setarrayitems(self)
848
849 def can_move(self, obj):
850 """Overrides the parent can_move()."""
851 return self.is_in_nursery(obj)
852
853
854 def shrink_array(self, obj, smallerlength):
855 #
856 # Only objects in the nursery can be "resized". Resizing them
857 # means recording that they have a smaller size, so that when
858 # moved out of the nursery, they will consume less memory.
859 # In particular, an array with GCFLAG_HAS_CARDS is never resized.
860 # Also, a nursery object with GCFLAG_HAS_SHADOW is not resized
861 # either, as this would potentially loose part of the memory in
862 # the already-allocated shadow.
863 if not self.is_in_nursery(obj):
864 return False
865 if self.header(obj).tid & GCFLAG_HAS_SHADOW:
866 return False
867 #
868 size_gc_header = self.gcheaderbuilder.size_gc_header
869 typeid = self.get_type_id(obj)
870 totalsmallersize = (
871 size_gc_header + self.fixed_size(typeid) +
872 self.varsize_item_sizes(typeid) * smallerlength)
873 llarena.arena_shrink_obj(obj - size_gc_header, totalsmallersize)
874 #
875 offset_to_length = self.varsize_offset_to_length(typeid)
876 (obj + offset_to_length).signed[0] = smallerlength
877 return True
878
879
880 # ----------
881 # Simple helpers
882
883 def get_type_id(self, obj):
884 tid = self.header(obj).tid
885 return llop.extract_ushort(llgroup.HALFWORD, tid)
886
887 def combine(self, typeid16, flags):
888 return llop.combine_ushort(lltype.Signed, typeid16, flags)
889
890 def init_gc_object(self, addr, typeid16, flags=0):
891 # The default 'flags' is zero. The flags GCFLAG_NO_xxx_PTRS
892 # have been chosen to allow 'flags' to be zero in the common
893 # case (hence the 'NO' in their name).
894 hdr = llmemory.cast_adr_to_ptr(addr, lltype.Ptr(self.HDR))
895 hdr.tid = self.combine(typeid16, flags)
896
897 def init_gc_object_immortal(self, addr, typeid16, flags=0):
898 # For prebuilt GC objects, the flags must contain
899 # GCFLAG_NO_xxx_PTRS, at least initially.
900 flags |= GCFLAG_NO_HEAP_PTRS | GCFLAG_TRACK_YOUNG_PTRS
901 self.init_gc_object(addr, typeid16, flags)
902
903 def is_in_nursery(self, addr):
904 ll_assert(llmemory.cast_adr_to_int(addr) & 1 == 0,
905 "odd-valued (i.e. tagged) pointer unexpected here")
906 return self.nursery <= addr < self.nursery_real_top
907
908 def appears_to_be_young(self, addr):
909 # "is a valid addr to a young object?"
910 # but it's ok to occasionally return True accidentally.
911 # Maybe the best implementation would be a bloom filter
912 # of some kind instead of the dictionary lookup that is
913 # sometimes done below. But the expected common answer
914 # is "Yes" because addr points to the nursery, so it may
915 # not be useful to optimize the other case too much.
916 #
917 # First, if 'addr' appears to be a pointer to some place within
918 # the nursery, return True
919 if not self.translated_to_c:
920 # When non-translated, filter out tagged pointers explicitly.
921 # When translated, it may occasionally give a wrong answer
922 # of True if 'addr' is a tagged pointer with just the wrong value.
923 if not self.is_valid_gc_object(addr):
924 return False
925
926 if self.nursery <= addr < self.nursery_real_top:
927 return True # addr is in the nursery
928 #
929 # Else, it may be in the set 'young_rawmalloced_objects'
930 return (bool(self.young_rawmalloced_objects) and
931 self.young_rawmalloced_objects.contains(addr))
932 appears_to_be_young._always_inline_ = True
933
934 def debug_is_old_object(self, addr):
935 return (self.is_valid_gc_object(addr)
936 and not self.appears_to_be_young(addr))
937
938 def is_forwarded(self, obj):
939 """Returns True if the nursery obj is marked as forwarded.
940 Implemented a bit obscurely by checking an unrelated flag
941 that can never be set on a young object -- except if tid == -42.
942 """
943 assert self.is_in_nursery(obj)
944 tid = self.header(obj).tid
945 result = (tid & GCFLAG_FINALIZATION_ORDERING != 0)
946 if result:
947 ll_assert(tid == -42, "bogus header for young obj")
948 else:
949 ll_assert(bool(tid), "bogus header (1)")
950 ll_assert(tid & -_GCFLAG_FIRST_UNUSED == 0, "bogus header (2)")
951 return result
952
953 def get_forwarding_address(self, obj):
954 return llmemory.cast_adr_to_ptr(obj, FORWARDSTUBPTR).forw
955
956 def get_possibly_forwarded_type_id(self, obj):
957 if self.is_in_nursery(obj) and self.is_forwarded(obj):
958 obj = self.get_forwarding_address(obj)
959 return self.get_type_id(obj)
960
961 def get_total_memory_used(self):
962 """Return the total memory used, not counting any object in the
963 nursery: only objects in the ArenaCollection or raw-malloced.
964 """
965 return self.ac.total_memory_used + self.rawmalloced_total_size
966
967 def card_marking_words_for_length(self, length):
968 # --- Unoptimized version:
969 #num_bits = ((length-1) >> self.card_page_shift) + 1
970 #return (num_bits + (LONG_BIT - 1)) >> LONG_BIT_SHIFT
971 # --- Optimized version:
972 return intmask(
973 ((r_uint(length) + r_uint((LONG_BIT << self.card_page_shift) - 1)) >>
974 (self.card_page_shift + LONG_BIT_SHIFT)))
975
976 def card_marking_bytes_for_length(self, length):
977 # --- Unoptimized version:
978 #num_bits = ((length-1) >> self.card_page_shift) + 1
979 #return (num_bits + 7) >> 3
980 # --- Optimized version:
981 return intmask(
982 ((r_uint(length) + r_uint((8 << self.card_page_shift) - 1)) >>
983 (self.card_page_shift + 3)))
984
985 def debug_check_consistency(self):
986 if self.DEBUG:
987 ll_assert(not self.young_rawmalloced_objects,
988 "young raw-malloced objects in a major collection")
989 ll_assert(not self.young_objects_with_weakrefs.non_empty(),
990 "young objects with weakrefs in a major collection")
991 MovingGCBase.debug_check_consistency(self)
992
993 def debug_check_object(self, obj):
994 # after a minor or major collection, no object should be in the nursery
995 ll_assert(not self.is_in_nursery(obj),
996 "object in nursery after collection")
997 # similarily, all objects should have this flag, except if they
998 # don't have any GC pointer
999 typeid = self.get_type_id(obj)
1000 if self.has_gcptr(typeid):
1001 ll_assert(self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS != 0,
1002 "missing GCFLAG_TRACK_YOUNG_PTRS")
1003 # the GCFLAG_VISITED should not be set between collections
1004 ll_assert(self.header(obj).tid & GCFLAG_VISITED == 0,
1005 "unexpected GCFLAG_VISITED")
1006 # the GCFLAG_FINALIZATION_ORDERING should not be set between coll.
1007 ll_assert(self.header(obj).tid & GCFLAG_FINALIZATION_ORDERING == 0,
1008 "unexpected GCFLAG_FINALIZATION_ORDERING")
1009 # the GCFLAG_CARDS_SET should not be set between collections
1010 ll_assert(self.header(obj).tid & GCFLAG_CARDS_SET == 0,
1011 "unexpected GCFLAG_CARDS_SET")
1012 # if the GCFLAG_HAS_CARDS is set, check that all bits are zero now
1013 if self.header(obj).tid & GCFLAG_HAS_CARDS:
1014 if self.card_page_indices <= 0:
1015 ll_assert(False, "GCFLAG_HAS_CARDS but not using card marking")
1016 return
1017 typeid = self.get_type_id(obj)
1018 ll_assert(self.has_gcptr_in_varsize(typeid),
1019 "GCFLAG_HAS_CARDS but not has_gcptr_in_varsize")
1020 ll_assert(self.header(obj).tid & GCFLAG_NO_HEAP_PTRS == 0,
1021 "GCFLAG_HAS_CARDS && GCFLAG_NO_HEAP_PTRS")
1022 offset_to_length = self.varsize_offset_to_length(typeid)
1023 length = (obj + offset_to_length).signed[0]
1024 extra_words = self.card_marking_words_for_length(length)
1025 #
1026 size_gc_header = self.gcheaderbuilder.size_gc_header
1027 p = llarena.getfakearenaaddress(obj - size_gc_header)
1028 i = extra_words * WORD
1029 while i > 0:
1030 p -= 1
1031 ll_assert(p.char[0] == '\x00',
1032 "the card marker bits are not cleared")
1033 i -= 1
1034
1035 # ----------
1036 # Write barrier
1037
1038 # for the JIT: a minimal description of the write_barrier() method
1039 # (the JIT assumes it is of the shape
1040 # "if addr_struct.int0 & JIT_WB_IF_FLAG: remember_young_pointer()")
1041 JIT_WB_IF_FLAG = GCFLAG_TRACK_YOUNG_PTRS
1042
1043 # for the JIT to generate custom code corresponding to the array
1044 # write barrier for the simplest case of cards. If JIT_CARDS_SET
1045 # is already set on an object, it will execute code like this:
1046 # MOV eax, index
1047 # SHR eax, JIT_WB_CARD_PAGE_SHIFT
1048 # XOR eax, -8
1049 # BTS [object], eax
1050 if TRANSLATION_PARAMS['card_page_indices'] > 0:
1051 JIT_WB_CARDS_SET = GCFLAG_CARDS_SET
1052 JIT_WB_CARD_PAGE_SHIFT = 1
1053 while ((1 << JIT_WB_CARD_PAGE_SHIFT) !=
1054 TRANSLATION_PARAMS['card_page_indices']):
1055 JIT_WB_CARD_PAGE_SHIFT += 1
1056
1057 @classmethod
1058 def JIT_max_size_of_young_obj(cls):
1059 return cls.TRANSLATION_PARAMS['large_object']
1060
1061 @classmethod
1062 def JIT_minimal_size_in_nursery(cls):
1063 return cls.minimal_size_in_nursery
1064
1065 def write_barrier(self, addr_struct):
1066 if self.header(addr_struct).tid & GCFLAG_TRACK_YOUNG_PTRS:
1067 self.remember_young_pointer(addr_struct)
1068
1069 def write_barrier_from_array(self, addr_array, index):
1070 if self.header(addr_array).tid & GCFLAG_TRACK_YOUNG_PTRS:
1071 if self.card_page_indices > 0: # <- constant-folded
1072 self.remember_young_pointer_from_array2(addr_array, index)
1073 else:
1074 self.remember_young_pointer(addr_array)
1075
1076 def _init_writebarrier_logic(self):
1077 DEBUG = self.DEBUG
1078 # The purpose of attaching remember_young_pointer to the instance
1079 # instead of keeping it as a regular method is to
1080 # make the code in write_barrier() marginally smaller
1081 # (which is important because it is inlined *everywhere*).
1082 def remember_young_pointer(addr_struct):
1083 # 'addr_struct' is the address of the object in which we write.
1084 # We know that 'addr_struct' has GCFLAG_TRACK_YOUNG_PTRS so far.
1085 #
1086 if DEBUG: # note: PYPY_GC_DEBUG=1 does not enable this
1087 ll_assert(self.debug_is_old_object(addr_struct) or
1088 self.header(addr_struct).tid & GCFLAG_HAS_CARDS != 0,
1089 "young object with GCFLAG_TRACK_YOUNG_PTRS and no cards")
1090 #
1091 # We need to remove the flag GCFLAG_TRACK_YOUNG_PTRS and add
1092 # the object to the list 'old_objects_pointing_to_young'.
1093 # We know that 'addr_struct' cannot be in the nursery,
1094 # because nursery objects never have the flag
1095 # GCFLAG_TRACK_YOUNG_PTRS to start with. Note that in
1096 # theory we don't need to do that if the pointer that we're
1097 # writing into the object isn't pointing to a young object.
1098 # However, it isn't really a win, because then sometimes
1099 # we're going to call this function a lot of times for the
1100 # same object; moreover we'd need to pass the 'newvalue' as
1101 # an argument here. The JIT has always called a
1102 # 'newvalue'-less version, too.
1103 self.old_objects_pointing_to_young.append(addr_struct)
1104 objhdr = self.header(addr_struct)
1105 objhdr.tid &= ~GCFLAG_TRACK_YOUNG_PTRS
1106 #
1107 # Second part: if 'addr_struct' is actually a prebuilt GC
1108 # object and it's the first time we see a write to it, we
1109 # add it to the list 'prebuilt_root_objects'.
1110 if objhdr.tid & GCFLAG_NO_HEAP_PTRS:
1111 objhdr.tid &= ~GCFLAG_NO_HEAP_PTRS
1112 self.prebuilt_root_objects.append(addr_struct)
1113
1114 remember_young_pointer._dont_inline_ = True
1115 self.remember_young_pointer = remember_young_pointer
1116 #
1117 if self.card_page_indices > 0:
1118 self._init_writebarrier_with_card_marker()
1119
1120
1121 def _init_writebarrier_with_card_marker(self):
1122 DEBUG = self.DEBUG
1123 def remember_young_pointer_from_array2(addr_array, index):
1124 # 'addr_array' is the address of the object in which we write,
1125 # which must have an array part; 'index' is the index of the
1126 # item that is (or contains) the pointer that we write.
1127 # We know that 'addr_array' has GCFLAG_TRACK_YOUNG_PTRS so far.
1128 #
1129 objhdr = self.header(addr_array)
1130 if objhdr.tid & GCFLAG_HAS_CARDS == 0:
1131 #
1132 if DEBUG: # note: PYPY_GC_DEBUG=1 does not enable this
1133 ll_assert(self.debug_is_old_object(addr_array),
1134 "young array with no card but GCFLAG_TRACK_YOUNG_PTRS")
1135 #
1136 # no cards, use default logic. Mostly copied from above.
1137 self.old_objects_pointing_to_young.append(addr_array)
1138 objhdr.tid &= ~GCFLAG_TRACK_YOUNG_PTRS
1139 if objhdr.tid & GCFLAG_NO_HEAP_PTRS:
1140 objhdr.tid &= ~GCFLAG_NO_HEAP_PTRS
1141 self.prebuilt_root_objects.append(addr_array)
1142 return
1143 #
1144 # 'addr_array' is a raw_malloc'ed array with card markers
1145 # in front. Compute the index of the bit to set:
1146 bitindex = index >> self.card_page_shift
1147 byteindex = bitindex >> 3
1148 bitmask = 1 << (bitindex & 7)
1149 #
1150 # If the bit is already set, leave now.
1151 addr_byte = self.get_card(addr_array, byteindex)
1152 byte = ord(addr_byte.char[0])
1153 if byte & bitmask:
1154 return
1155 #
1156 # We set the flag (even if the newly written address does not
1157 # actually point to the nursery, which seems to be ok -- actually
1158 # it seems more important that remember_young_pointer_from_array2()
1159 # does not take 3 arguments).
1160 addr_byte.char[0] = chr(byte | bitmask)
1161 #
1162 if objhdr.tid & GCFLAG_CARDS_SET == 0:
1163 self.old_objects_with_cards_set.append(addr_array)
1164 objhdr.tid |= GCFLAG_CARDS_SET
1165
1166 remember_young_pointer_from_array2._dont_inline_ = True
1167 assert self.card_page_indices > 0
1168 self.remember_young_pointer_from_array2 = (
1169 remember_young_pointer_from_array2)
1170
1171 def jit_remember_young_pointer_from_array(addr_array):
1172 # minimal version of the above, with just one argument,
1173 # called by the JIT when GCFLAG_TRACK_YOUNG_PTRS is set
1174 # but GCFLAG_CARDS_SET is cleared. This tries to set
1175 # GCFLAG_CARDS_SET if possible; otherwise, it falls back
1176 # to remember_young_pointer().
1177 objhdr = self.header(addr_array)
1178 if objhdr.tid & GCFLAG_HAS_CARDS:
1179 self.old_objects_with_cards_set.append(addr_array)
1180 objhdr.tid |= GCFLAG_CARDS_SET
1181 else:
1182 self.remember_young_pointer(addr_array)
1183
1184 self.jit_remember_young_pointer_from_array = (
1185 jit_remember_young_pointer_from_array)
1186
1187 def get_card(self, obj, byteindex):
1188 size_gc_header = self.gcheaderbuilder.size_gc_header
1189 addr_byte = obj - size_gc_header
1190 return llarena.getfakearenaaddress(addr_byte) + (~byteindex)
1191
1192
1193 def writebarrier_before_copy(self, source_addr, dest_addr,
1194 source_start, dest_start, length):
1195 """ This has the same effect as calling writebarrier over
1196 each element in dest copied from source, except it might reset
1197 one of the following flags a bit too eagerly, which means we'll have
1198 a bit more objects to track, but being on the safe side.
1199 """
1200 source_hdr = self.header(source_addr)
1201 dest_hdr = self.header(dest_addr)
1202 if dest_hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
1203 return True
1204 # ^^^ a fast path of write-barrier
1205 #
1206 if source_hdr.tid & GCFLAG_HAS_CARDS != 0:
1207 #
1208 if source_hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
1209 # The source object may have random young pointers.
1210 # Return False to mean "do it manually in ll_arraycopy".
1211 return False
1212 #
1213 if source_hdr.tid & GCFLAG_CARDS_SET == 0:
1214 # The source object has no young pointers at all. Done.
1215 return True
1216 #
1217 if dest_hdr.tid & GCFLAG_HAS_CARDS == 0:
1218 # The dest object doesn't have cards. Do it manually.
1219 return False
1220 #
1221 if source_start != 0 or dest_start != 0:
1222 # Misaligned. Do it manually.
1223 return False
1224 #
1225 self.manually_copy_card_bits(source_addr, dest_addr, length)
1226 return True
1227 #
1228 if source_hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
1229 # there might be in source a pointer to a young object
1230 self.old_objects_pointing_to_young.append(dest_addr)
1231 dest_hdr.tid &= ~GCFLAG_TRACK_YOUNG_PTRS
1232 #
1233 if dest_hdr.tid & GCFLAG_NO_HEAP_PTRS:
1234 if source_hdr.tid & GCFLAG_NO_HEAP_PTRS == 0:
1235 dest_hdr.tid &= ~GCFLAG_NO_HEAP_PTRS
1236 self.prebuilt_root_objects.append(dest_addr)
1237 return True
1238
1239 def writebarrier_before_move(self, array_addr):
1240 """If 'array_addr' uses cards, then this has the same effect as
1241 a call to the generic writebarrier, effectively generalizing the
1242 cards to "any item may be young".
1243 """
1244 if self.card_page_indices <= 0: # check constant-folded
1245 return # no cards, nothing to do
1246 #
1247 array_hdr = self.header(array_addr)
1248 if array_hdr.tid & GCFLAG_CARDS_SET != 0:
1249 self.write_barrier(array_addr)
1250
1251 def manually_copy_card_bits(self, source_addr, dest_addr, length):
1252 # manually copy the individual card marks from source to dest
1253 assert self.card_page_indices > 0
1254 bytes = self.card_marking_bytes_for_length(length)
1255 #
1256 anybyte = 0
1257 i = 0
1258 while i < bytes:
1259 addr_srcbyte = self.get_card(source_addr, i)
1260 addr_dstbyte = self.get_card(dest_addr, i)
1261 byte = ord(addr_srcbyte.char[0])
1262 anybyte |= byte
1263 addr_dstbyte.char[0] = chr(ord(addr_dstbyte.char[0]) | byte)
1264 i += 1
1265 #
1266 if anybyte:
1267 dest_hdr = self.header(dest_addr)
1268 if dest_hdr.tid & GCFLAG_CARDS_SET == 0:
1269 self.old_objects_with_cards_set.append(dest_addr)
1270 dest_hdr.tid |= GCFLAG_CARDS_SET
1271
1272 def register_finalizer(self, fq_index, gcobj):
1273 from rpython.rtyper.lltypesystem import rffi
1274 obj = llmemory.cast_ptr_to_adr(gcobj)
1275 fq_index = rffi.cast(llmemory.Address, fq_index)
1276 self.probably_young_objects_with_finalizers.append(obj)
1277 self.probably_young_objects_with_finalizers.append(fq_index)
1278
1279 # ----------
1280 # Nursery collection
1281
1282 def minor_collection(self):
1283 """Perform a minor collection: find the objects from the nursery
1284 that remain alive and move them out."""
1285 #
1286 debug_start("gc-minor")
1287 #
1288 # Before everything else, remove from 'old_objects_pointing_to_young'
1289 # the young arrays.
1290 if self.young_rawmalloced_objects:
1291 self.remove_young_arrays_from_old_objects_pointing_to_young()
1292 #
1293 # First, find the roots that point to young objects. All nursery
1294 # objects found are copied out of the nursery, and the occasional
1295 # young raw-malloced object is flagged with GCFLAG_VISITED.
1296 # Note that during this step, we ignore references to further
1297 # young objects; only objects directly referenced by roots
1298 # are copied out or flagged. They are also added to the list
1299 # 'old_objects_pointing_to_young'.
1300 self.collect_roots_in_nursery()
1301 #
1302 # visit the "probably young" objects with finalizers. They
1303 # always all survive.
1304 if self.probably_young_objects_with_finalizers.non_empty():
1305 self.deal_with_young_objects_with_finalizers()
1306 #
1307 while True:
1308 # If we are using card marking, do a partial trace of the arrays
1309 # that are flagged with GCFLAG_CARDS_SET.
1310 if self.card_page_indices > 0:
1311 self.collect_cardrefs_to_nursery()
1312 #
1313 # Now trace objects from 'old_objects_pointing_to_young'.
1314 # All nursery objects they reference are copied out of the
1315 # nursery, and again added to 'old_objects_pointing_to_young'.
1316 # All young raw-malloced object found are flagged GCFLAG_VISITED.
1317 # We proceed until 'old_objects_pointing_to_young' is empty.
1318 self.collect_oldrefs_to_nursery()
1319 #
1320 # We have to loop back if collect_oldrefs_to_nursery caused
1321 # new objects to show up in old_objects_with_cards_set
1322 if self.card_page_indices > 0:
1323 if self.old_objects_with_cards_set.non_empty():
1324 continue
1325 break
1326 #
1327 # Now all live nursery objects should be out. Update the young
1328 # weakrefs' targets.
1329 if self.young_objects_with_weakrefs.non_empty():
1330 self.invalidate_young_weakrefs()
1331 if self.young_objects_with_destructors.non_empty():
1332 self.deal_with_young_objects_with_destructors()
1333 #
1334 # Clear this mapping.
1335 if self.nursery_objects_shadows.length() > 0:
1336 self.nursery_objects_shadows.clear()
1337 #
1338 # Walk the list of young raw-malloced objects, and either free
1339 # them or make them old.
1340 if self.young_rawmalloced_objects:
1341 self.free_young_rawmalloced_objects()
1342 #
1343 # All live nursery objects are out, and the rest dies. Fill
1344 # the nursery up to the cleanup point with zeros
1345 llarena.arena_reset(self.nursery, self.nursery_size, 0)
1346 llarena.arena_reset(self.nursery, self.initial_cleanup, 2)
1347 self.debug_rotate_nursery()
1348 self.nursery_free = self.nursery
1349 self.nursery_top = self.nursery + self.initial_cleanup
1350 self.nursery_real_top = self.nursery + self.nursery_size
1351 #
1352 debug_print("minor collect, total memory used:",
1353 self.get_total_memory_used())
1354 if self.DEBUG >= 2:
1355 self.debug_check_consistency() # expensive!
1356 debug_stop("gc-minor")
1357
1358
1359 def collect_roots_in_nursery(self):
1360 # we don't need to trace prebuilt GcStructs during a minor collect:
1361 # if a prebuilt GcStruct contains a pointer to a young object,
1362 # then the write_barrier must have ensured that the prebuilt
1363 # GcStruct is in the list self.old_objects_pointing_to_young.
1364 debug_start("gc-minor-walkroots")
1365 self.root_walker.walk_roots(
1366 MiniMarkGC._trace_drag_out1, # stack roots
1367 MiniMarkGC._trace_drag_out1, # static in prebuilt non-gc
1368 None, # static in prebuilt gc
1369 is_minor=True)
1370 debug_stop("gc-minor-walkroots")
1371
1372 def collect_cardrefs_to_nursery(self):
1373 size_gc_header = self.gcheaderbuilder.size_gc_header
1374 oldlist = self.old_objects_with_cards_set
1375 while oldlist.non_empty():
1376 obj = oldlist.pop()
1377 #
1378 # Remove the GCFLAG_CARDS_SET flag.
1379 ll_assert(self.header(obj).tid & GCFLAG_CARDS_SET != 0,
1380 "!GCFLAG_CARDS_SET but object in 'old_objects_with_cards_set'")
1381 self.header(obj).tid &= ~GCFLAG_CARDS_SET
1382 #
1383 # Get the number of card marker bytes in the header.
1384 typeid = self.get_type_id(obj)
1385 offset_to_length = self.varsize_offset_to_length(typeid)
1386 length = (obj + offset_to_length).signed[0]
1387 bytes = self.card_marking_bytes_for_length(length)
1388 p = llarena.getfakearenaaddress(obj - size_gc_header)
1389 #
1390 # If the object doesn't have GCFLAG_TRACK_YOUNG_PTRS, then it
1391 # means that it is in 'old_objects_pointing_to_young' and
1392 # will be fully traced by collect_oldrefs_to_nursery() just
1393 # afterwards.
1394 if self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
1395 #
1396 # In that case, we just have to reset all card bits.
1397 while bytes > 0:
1398 p -= 1
1399 p.char[0] = '\x00'
1400 bytes -= 1
1401 #
1402 else:
1403 # Walk the bytes encoding the card marker bits, and for
1404 # each bit set, call trace_and_drag_out_of_nursery_partial().
1405 interval_start = 0
1406 while bytes > 0:
1407 p -= 1
1408 cardbyte = ord(p.char[0])
1409 p.char[0] = '\x00' # reset the bits
1410 bytes -= 1
1411 next_byte_start = interval_start + 8*self.card_page_indices
1412 #
1413 while cardbyte != 0:
1414 interval_stop = interval_start + self.card_page_indices
1415 #
1416 if cardbyte & 1:
1417 if interval_stop > length:
1418 interval_stop = length
1419 #--- the sanity check below almost always
1420 #--- passes, except in situations like
1421 #--- test_writebarrier_before_copy_manually\
1422 # _copy_card_bits
1423 #ll_assert(cardbyte <= 1 and bytes == 0,
1424 # "premature end of object")
1425 ll_assert(bytes == 0, "premature end of object")
1426 if interval_stop <= interval_start:
1427 break
1428 self.trace_and_drag_out_of_nursery_partial(
1429 obj, interval_start, interval_stop)
1430 #
1431 interval_start = interval_stop
1432 cardbyte >>= 1
1433 interval_start = next_byte_start
1434
1435
1436 def collect_oldrefs_to_nursery(self):
1437 # Follow the old_objects_pointing_to_young list and move the
1438 # young objects they point to out of the nursery.
1439 oldlist = self.old_objects_pointing_to_young
1440 while oldlist.non_empty():
1441 obj = oldlist.pop()
1442 #
1443 # Check that the flags are correct: we must not have
1444 # GCFLAG_TRACK_YOUNG_PTRS so far.
1445 ll_assert(self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS == 0,
1446 "old_objects_pointing_to_young contains obj with "
1447 "GCFLAG_TRACK_YOUNG_PTRS")
1448 #
1449 # Add the flag GCFLAG_TRACK_YOUNG_PTRS. All live objects should
1450 # have this flag set after a nursery collection.
1451 self.header(obj).tid |= GCFLAG_TRACK_YOUNG_PTRS
1452 #
1453 # Trace the 'obj' to replace pointers to nursery with pointers
1454 # outside the nursery, possibly forcing nursery objects out
1455 # and adding them to 'old_objects_pointing_to_young' as well.
1456 self.trace_and_drag_out_of_nursery(obj)
1457
1458 def trace_and_drag_out_of_nursery(self, obj):
1459 """obj must not be in the nursery. This copies all the
1460 young objects it references out of the nursery.
1461 """
1462 self.trace(obj, self.make_callback('_trace_drag_out'), self, None)
1463
1464 def trace_and_drag_out_of_nursery_partial(self, obj, start, stop):
1465 """Like trace_and_drag_out_of_nursery(), but limited to the array
1466 indices in range(start, stop).
1467 """
1468 ll_assert(start < stop, "empty or negative range "
1469 "in trace_and_drag_out_of_nursery_partial()")
1470 #print 'trace_partial:', start, stop, '\t', obj
1471 self.trace_partial(obj, start, stop,
1472 self.make_callback('_trace_drag_out'), self, None)
1473
1474
1475 def _trace_drag_out1(self, root):
1476 self._trace_drag_out(root, None)
1477
1478 def _trace_drag_out(self, root, ignored):
1479 obj = root.address[0]
1480 #print '_trace_drag_out(%x: %r)' % (hash(obj.ptr._obj), obj)
1481 #
1482 # If 'obj' is not in the nursery, nothing to change -- expect
1483 # that we must set GCFLAG_VISITED on young raw-malloced objects.
1484 if not self.is_in_nursery(obj):
1485 # cache usage trade-off: I think that it is a better idea to
1486 # check if 'obj' is in young_rawmalloced_objects with an access
1487 # to this (small) dictionary, rather than risk a lot of cache
1488 # misses by reading a flag in the header of all the 'objs' that
1489 # arrive here.
1490 if (bool(self.young_rawmalloced_objects)
1491 and self.young_rawmalloced_objects.contains(obj)):
1492 self._visit_young_rawmalloced_object(obj)
1493 return
1494 #
1495 size_gc_header = self.gcheaderbuilder.size_gc_header
1496 if self.header(obj).tid & GCFLAG_HAS_SHADOW == 0:
1497 #
1498 # Common case: 'obj' was not already forwarded (otherwise
1499 # tid == -42, containing all flags), and it doesn't have the
1500 # HAS_SHADOW flag either. We must move it out of the nursery,
1501 # into a new nonmovable location.
1502 totalsize = size_gc_header + self.get_size(obj)
1503 newhdr = self._malloc_out_of_nursery(totalsize)
1504 #
1505 elif self.is_forwarded(obj):
1506 #
1507 # 'obj' was already forwarded. Change the original reference
1508 # to point to its forwarding address, and we're done.
1509 root.address[0] = self.get_forwarding_address(obj)
1510 return
1511 #
1512 else:
1513 # First visit to an object that has already a shadow.
1514 newobj = self.nursery_objects_shadows.get(obj)
1515 ll_assert(newobj != NULL, "GCFLAG_HAS_SHADOW but no shadow found")
1516 newhdr = newobj - size_gc_header
1517 #
1518 # Remove the flag GCFLAG_HAS_SHADOW, so that it doesn't get
1519 # copied to the shadow itself.
1520 self.header(obj).tid &= ~GCFLAG_HAS_SHADOW
1521 #
1522 totalsize = size_gc_header + self.get_size(obj)
1523 #
1524 # Copy it. Note that references to other objects in the
1525 # nursery are kept unchanged in this step.
1526 llmemory.raw_memcopy(obj - size_gc_header, newhdr, totalsize)
1527 #
1528 # Set the old object's tid to -42 (containing all flags) and
1529 # replace the old object's content with the target address.
1530 # A bit of no-ops to convince llarena that we are changing
1531 # the layout, in non-translated versions.
1532 typeid = self.get_type_id(obj)
1533 obj = llarena.getfakearenaaddress(obj)
1534 llarena.arena_reset(obj - size_gc_header, totalsize, 0)
1535 llarena.arena_reserve(obj - size_gc_header,
1536 size_gc_header + llmemory.sizeof(FORWARDSTUB))
1537 self.header(obj).tid = -42
1538 newobj = newhdr + size_gc_header
1539 llmemory.cast_adr_to_ptr(obj, FORWARDSTUBPTR).forw = newobj
1540 #
1541 # Change the original pointer to this object.
1542 root.address[0] = newobj
1543 #
1544 # Add the newobj to the list 'old_objects_pointing_to_young',
1545 # because it can contain further pointers to other young objects.
1546 # We will fix such references to point to the copy of the young
1547 # objects when we walk 'old_objects_pointing_to_young'.
1548 if self.has_gcptr(typeid):
1549 # we only have to do it if we have any gcptrs
1550 self.old_objects_pointing_to_young.append(newobj)
1551 _trace_drag_out._always_inline_ = True
1552
1553 def _visit_young_rawmalloced_object(self, obj):
1554 # 'obj' points to a young, raw-malloced object.
1555 # Any young rawmalloced object never seen by the code here
1556 # will end up without GCFLAG_VISITED, and be freed at the
1557 # end of the current minor collection. Note that there was
1558 # a bug in which dying young arrays with card marks would
1559 # still be scanned before being freed, keeping a lot of
1560 # objects unnecessarily alive.
1561 hdr = self.header(obj)
1562 if hdr.tid & GCFLAG_VISITED:
1563 return
1564 hdr.tid |= GCFLAG_VISITED
1565 #
1566 # we just made 'obj' old, so we need to add it to the correct lists
1567 added_somewhere = False
1568 #
1569 if hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
1570 self.old_objects_pointing_to_young.append(obj)
1571 added_somewhere = True
1572 #
1573 if hdr.tid & GCFLAG_HAS_CARDS != 0:
1574 ll_assert(hdr.tid & GCFLAG_CARDS_SET != 0,
1575 "young array: GCFLAG_HAS_CARDS without GCFLAG_CARDS_SET")
1576 self.old_objects_with_cards_set.append(obj)
1577 added_somewhere = True
1578 #
1579 ll_assert(added_somewhere, "wrong flag combination on young array")
1580
1581
1582 def _malloc_out_of_nursery(self, totalsize):
1583 """Allocate non-movable memory for an object of the given
1584 'totalsize' that lives so far in the nursery."""
1585 if raw_malloc_usage(totalsize) <= self.small_request_threshold:
1586 # most common path
1587 return self.ac.malloc(totalsize)
1588 else:
1589 # for nursery objects that are not small
1590 return self._malloc_out_of_nursery_nonsmall(totalsize)
1591 _malloc_out_of_nursery._always_inline_ = True
1592
1593 def _malloc_out_of_nursery_nonsmall(self, totalsize):
1594 # 'totalsize' should be aligned.
1595 ll_assert(raw_malloc_usage(totalsize) & (WORD-1) == 0,
1596 "misaligned totalsize in _malloc_out_of_nursery_nonsmall")
1597 #
1598 arena = llarena.arena_malloc(raw_malloc_usage(totalsize), False)
1599 if not arena:
1600 raise MemoryError("cannot allocate object")
1601 llarena.arena_reserve(arena, totalsize)
1602 #
1603 size_gc_header = self.gcheaderbuilder.size_gc_header
1604 self.rawmalloced_total_size += r_uint(raw_malloc_usage(totalsize))
1605 self.old_rawmalloced_objects.append(arena + size_gc_header)
1606 return arena
1607
1608 def free_young_rawmalloced_objects(self):
1609 self.young_rawmalloced_objects.foreach(
1610 self._free_young_rawmalloced_obj, None)
1611 self.young_rawmalloced_objects.delete()
1612 self.young_rawmalloced_objects = self.null_address_dict()
1613
1614 def _free_young_rawmalloced_obj(self, obj, ignored1, ignored2):
1615 # If 'obj' has GCFLAG_VISITED, it was seen by _trace_drag_out
1616 # and survives. Otherwise, it dies.
1617 self.free_rawmalloced_object_if_unvisited(obj)
1618
1619 def remove_young_arrays_from_old_objects_pointing_to_young(self):
1620 old = self.old_objects_pointing_to_young
1621 new = self.AddressStack()
1622 while old.non_empty():
1623 obj = old.pop()
1624 if not self.young_rawmalloced_objects.contains(obj):
1625 new.append(obj)
1626 # an extra copy, to avoid assignments to
1627 # 'self.old_objects_pointing_to_young'
1628 while new.non_empty():
1629 old.append(new.pop())
1630 new.delete()
1631
1632 # ----------
1633 # Full collection
1634
1635 def major_collection(self, reserving_size=0):
1636 """Do a major collection. Only for when the nursery is empty."""
1637 #
1638 debug_start("gc-collect")
1639 debug_print()
1640 debug_print(".----------- Full collection ------------------")
1641 debug_print("| used before collection:")
1642 debug_print("| in ArenaCollection: ",
1643 self.ac.total_memory_used, "bytes")
1644 debug_print("| raw_malloced: ",
1645 self.rawmalloced_total_size, "bytes")
1646 #
1647 # Debugging checks
1648 ll_assert(self.nursery_free == self.nursery,
1649 "nursery not empty in major_collection()")
1650 self.debug_check_consistency()
1651 #
1652 # Note that a major collection is non-moving. The goal is only to
1653 # find and free some of the objects allocated by the ArenaCollection.
1654 # We first visit all objects and toggle the flag GCFLAG_VISITED on
1655 # them, starting from the roots.
1656 self.objects_to_trace = self.AddressStack()
1657 self.collect_roots()
1658 self.visit_all_objects()
1659 #
1660 # Finalizer support: adds the flag GCFLAG_VISITED to all objects
1661 # with a finalizer and all objects reachable from there (and also
1662 # moves some objects from 'objects_with_finalizers' to
1663 # 'run_finalizers').
1664 self.kept_alive_by_finalizer = r_uint(0)
1665 if self.old_objects_with_finalizers.non_empty():
1666 self.deal_with_objects_with_finalizers()
1667 #
1668 self.objects_to_trace.delete()
1669 #
1670 # Weakref support: clear the weak pointers to dying objects
1671 if self.old_objects_with_weakrefs.non_empty():
1672 self.invalidate_old_weakrefs()
1673 if self.old_objects_with_destructors.non_empty():
1674 self.deal_with_old_objects_with_destructors()
1675
1676 #
1677 # Walk all rawmalloced objects and free the ones that don't
1678 # have the GCFLAG_VISITED flag.
1679 self.free_unvisited_rawmalloc_objects()
1680 #
1681 # Ask the ArenaCollection to visit all objects. Free the ones
1682 # that have not been visited above, and reset GCFLAG_VISITED on
1683 # the others.
1684 self.ac.mass_free(self._free_if_unvisited)
1685 #
1686 # We also need to reset the GCFLAG_VISITED on prebuilt GC objects.
1687 self.prebuilt_root_objects.foreach(self._reset_gcflag_visited, None)
1688 #
1689 self.debug_check_consistency()
1690 #
1691 self.num_major_collects += 1
1692 debug_print("| used after collection:")
1693 debug_print("| in ArenaCollection: ",
1694 self.ac.total_memory_used, "bytes")
1695 debug_print("| raw_malloced: ",
1696 self.rawmalloced_total_size, "bytes")
1697 debug_print("| number of major collects: ",
1698 self.num_major_collects)
1699 debug_print("`----------------------------------------------")
1700 debug_stop("gc-collect")
1701 #
1702 # Set the threshold for the next major collection to be when we
1703 # have allocated 'major_collection_threshold' times more than
1704 # we currently have -- but no more than 'max_delta' more than
1705 # we currently have.
1706 total_memory_used = float(self.get_total_memory_used())
1707 total_memory_used -= float(self.kept_alive_by_finalizer)
1708 if total_memory_used < 0:
1709 total_memory_used = 0
1710 bounded = self.set_major_threshold_from(
1711 min(total_memory_used * self.major_collection_threshold,
1712 total_memory_used + self.max_delta),
1713 reserving_size)
1714 #
1715 # Max heap size: gives an upper bound on the threshold. If we
1716 # already have at least this much allocated, raise MemoryError.
1717 if bounded and (float(self.get_total_memory_used()) + reserving_size >=
1718 self.next_major_collection_initial):
1719 #
1720 # First raise MemoryError, giving the program a chance to
1721 # quit cleanly. It might still allocate in the nursery,
1722 # which might eventually be emptied, triggering another
1723 # major collect and (possibly) reaching here again with an
1724 # even higher memory consumption. To prevent it, if it's
1725 # the second time we are here, then abort the program.
1726 if self.max_heap_size_already_raised:
1727 llop.debug_fatalerror(lltype.Void,
1728 "Using too much memory, aborting")
1729 self.max_heap_size_already_raised = True
1730 raise MemoryError
1731 #
1732 # At the end, we can execute the finalizers of the objects
1733 # listed in 'run_finalizers'. Note that this will typically do
1734 # more allocations.
1735 self.execute_finalizers()
1736
1737
1738 def _free_if_unvisited(self, hdr):
1739 size_gc_header = self.gcheaderbuilder.size_gc_header
1740 obj = hdr + size_gc_header
1741 if self.header(obj).tid & GCFLAG_VISITED:
1742 self.header(obj).tid &= ~GCFLAG_VISITED
1743 return False # survives
1744 return True # dies
1745
1746 def _reset_gcflag_visited(self, obj, ignored):
1747 self.header(obj).tid &= ~GCFLAG_VISITED
1748
1749 def free_rawmalloced_object_if_unvisited(self, obj):
1750 if self.header(obj).tid & GCFLAG_VISITED:
1751 self.header(obj).tid &= ~GCFLAG_VISITED # survives
1752 self.old_rawmalloced_objects.append(obj)
1753 else:
1754 size_gc_header = self.gcheaderbuilder.size_gc_header
1755 totalsize = size_gc_header + self.get_size(obj)
1756 allocsize = raw_malloc_usage(totalsize)
1757 arena = llarena.getfakearenaaddress(obj - size_gc_header)
1758 #
1759 # Must also include the card marker area, if any
1760 if (self.card_page_indices > 0 # <- this is constant-folded
1761 and self.header(obj).tid & GCFLAG_HAS_CARDS):
1762 #
1763 # Get the length and compute the number of extra bytes
1764 typeid = self.get_type_id(obj)
1765 ll_assert(self.has_gcptr_in_varsize(typeid),
1766 "GCFLAG_HAS_CARDS but not has_gcptr_in_varsize")
1767 offset_to_length = self.varsize_offset_to_length(typeid)
1768 length = (obj + offset_to_length).signed[0]
1769 extra_words = self.card_marking_words_for_length(length)
1770 arena -= extra_words * WORD
1771 allocsize += extra_words * WORD
1772 #
1773 llarena.arena_free(arena)
1774 self.rawmalloced_total_size -= r_uint(allocsize)
1775
1776 def free_unvisited_rawmalloc_objects(self):
1777 list = self.old_rawmalloced_objects
1778 self.old_rawmalloced_objects = self.AddressStack()
1779 #
1780 while list.non_empty():
1781 self.free_rawmalloced_object_if_unvisited(list.pop())
1782 #
1783 list.delete()
1784
1785
1786 def collect_roots(self):
1787 # Collect all roots. Starts from all the objects
1788 # from 'prebuilt_root_objects'.
1789 self.prebuilt_root_objects.foreach(self._collect_obj,
1790 self.objects_to_trace)
1791 #
1792 # Add the roots from the other sources.
1793 self.root_walker.walk_roots(
1794 MiniMarkGC._collect_ref_stk, # stack roots
1795 MiniMarkGC._collect_ref_stk, # static in prebuilt non-gc structures
1796 None) # we don't need the static in all prebuilt gc objects
1797 #
1798 # If we are in an inner collection caused by a call to a finalizer,
1799 # the 'run_finalizers' objects also need to be kept alive.
1800 self.enum_pending_finalizers(self._collect_obj,
1801 self.objects_to_trace)
1802
1803 def enumerate_all_roots(self, callback, arg):
1804 self.prebuilt_root_objects.foreach(callback, arg)
1805 MovingGCBase.enumerate_all_roots(self, callback, arg)
1806 enumerate_all_roots._annspecialcase_ = 'specialize:arg(1)'
1807
1808 def enum_live_with_finalizers(self, callback, arg):
1809 self.probably_young_objects_with_finalizers.foreach(callback, arg, 2)
1810 self.old_objects_with_finalizers.foreach(callback, arg, 2)
1811 enum_live_with_finalizers._annspecialcase_ = 'specialize:arg(1)'
1812
1813 @staticmethod
1814 def _collect_obj(obj, objects_to_trace):
1815 objects_to_trace.append(obj)
1816
1817 def _collect_ref_stk(self, root):
1818 obj = root.address[0]
1819 llop.debug_nonnull_pointer(lltype.Void, obj)
1820 self.objects_to_trace.append(obj)
1821
1822 def _collect_ref_rec(self, root, ignored):
1823 self.objects_to_trace.append(root.address[0])
1824
1825 def visit_all_objects(self):
1826 pending = self.objects_to_trace
1827 while pending.non_empty():
1828 obj = pending.pop()
1829 self.visit(obj)
1830
1831 def visit(self, obj):
1832 #
1833 # 'obj' is a live object. Check GCFLAG_VISITED to know if we
1834 # have already seen it before.
1835 #
1836 # Moreover, we can ignore prebuilt objects with GCFLAG_NO_HEAP_PTRS.
1837 # If they have this flag set, then they cannot point to heap
1838 # objects, so ignoring them is fine. If they don't have this
1839 # flag set, then the object should be in 'prebuilt_root_objects',
1840 # and the GCFLAG_VISITED will be reset at the end of the
1841 # collection.
1842 hdr = self.header(obj)
1843 if hdr.tid & (GCFLAG_VISITED | GCFLAG_NO_HEAP_PTRS):
1844 return
1845 #
1846 # It's the first time. We set the flag.
1847 hdr.tid |= GCFLAG_VISITED
1848 if not self.has_gcptr(llop.extract_ushort(llgroup.HALFWORD, hdr.tid)):
1849 return
1850 #
1851 # Trace the content of the object and put all objects it references
1852 # into the 'objects_to_trace' list.
1853 self.trace(obj, self.make_callback('_collect_ref_rec'), self, None)
1854
1855
1856 # ----------
1857 # id() and identityhash() support
1858
1859 def _allocate_shadow(self, obj):
1860 size_gc_header = self.gcheaderbuilder.size_gc_header
1861 size = self.get_size(obj)
1862 shadowhdr = self._malloc_out_of_nursery(size_gc_header +
1863 size)
1864 # Initialize the shadow enough to be considered a
1865 # valid gc object. If the original object stays
1866 # alive at the next minor collection, it will anyway
1867 # be copied over the shadow and overwrite the
1868 # following fields. But if the object dies, then
1869 # the shadow will stay around and only be freed at
1870 # the next major collection, at which point we want
1871 # it to look valid (but ready to be freed).
1872 shadow = shadowhdr + size_gc_header
1873 self.header(shadow).tid = self.header(obj).tid
1874 typeid = self.get_type_id(obj)
1875 if self.is_varsize(typeid):
1876 lenofs = self.varsize_offset_to_length(typeid)
1877 (shadow + lenofs).signed[0] = (obj + lenofs).signed[0]
1878 #
1879 self.header(obj).tid |= GCFLAG_HAS_SHADOW
1880 self.nursery_objects_shadows.setitem(obj, shadow)
1881 return shadow
1882
1883 def _find_shadow(self, obj):
1884 #
1885 # The object is not a tagged pointer, and it is still in the
1886 # nursery. Find or allocate a "shadow" object, which is
1887 # where the object will be moved by the next minor
1888 # collection
1889 if self.header(obj).tid & GCFLAG_HAS_SHADOW:
1890 shadow = self.nursery_objects_shadows.get(obj)
1891 ll_assert(shadow != NULL,
1892 "GCFLAG_HAS_SHADOW but no shadow found")
1893 else:
1894 shadow = self._allocate_shadow(obj)
1895 #
1896 # The answer is the address of the shadow.
1897 return shadow
1898 _find_shadow._dont_inline_ = True
1899
1900 def id_or_identityhash(self, gcobj):
1901 """Implement the common logic of id() and identityhash()
1902 of an object, given as a GCREF.
1903 """
1904 obj = llmemory.cast_ptr_to_adr(gcobj)
1905 if self.is_valid_gc_object(obj):
1906 if self.is_in_nursery(obj):
1907 obj = self._find_shadow(obj)
1908 return llmemory.cast_adr_to_int(obj)
1909 id_or_identityhash._always_inline_ = True
1910
1911 def id(self, gcobj):
1912 return self.id_or_identityhash(gcobj)
1913
1914 def identityhash(self, gcobj):
1915 return mangle_hash(self.id_or_identityhash(gcobj))
1916
1917 # ----------
1918 # Finalizers
1919
1920 def deal_with_young_objects_with_destructors(self):
1921 """We can reasonably assume that destructors don't do
1922 anything fancy and *just* call them. Among other things
1923 they won't resurrect objects
1924 """
1925 while self.young_objects_with_destructors.non_empty():
1926 obj = self.young_objects_with_destructors.pop()
1927 if not self.is_forwarded(obj):
1928 self.call_destructor(obj)
1929 else:
1930 obj = self.get_forwarding_address(obj)
1931 self.old_objects_with_destructors.append(obj)
1932
1933 def deal_with_old_objects_with_destructors(self):
1934 """We can reasonably assume that destructors don't do
1935 anything fancy and *just* call them. Among other things
1936 they won't resurrect objects
1937 """
1938 new_objects = self.AddressStack()
1939 while self.old_objects_with_destructors.non_empty():
1940 obj = self.old_objects_with_destructors.pop()
1941 if self.header(obj).tid & GCFLAG_VISITED:
1942 # surviving
1943 new_objects.append(obj)
1944 else:
1945 # dying
1946 self.call_destructor(obj)
1947 self.old_objects_with_destructors.delete()
1948 self.old_objects_with_destructors = new_objects
1949
1950 def deal_with_young_objects_with_finalizers(self):
1951 while self.probably_young_objects_with_finalizers.non_empty():
1952 obj = self.probably_young_objects_with_finalizers.popleft()
1953 fq_nr = self.probably_young_objects_with_finalizers.popleft()
1954 self.singleaddr.address[0] = obj
1955 self._trace_drag_out1(self.singleaddr)
1956 obj = self.singleaddr.address[0]
1957 self.old_objects_with_finalizers.append(obj)
1958 self.old_objects_with_finalizers.append(fq_nr)
1959
1960 def deal_with_objects_with_finalizers(self):
1961 # Walk over list of objects with finalizers.
1962 # If it is not surviving, add it to the list of to-be-called
1963 # finalizers and make it survive, to make the finalizer runnable.
1964 # We try to run the finalizers in a "reasonable" order, like
1965 # CPython does. The details of this algorithm are in
1966 # pypy/doc/discussion/finalizer-order.txt.
1967 new_with_finalizer = self.AddressDeque()
1968 marked = self.AddressDeque()
1969 pending = self.AddressStack()
1970 self.tmpstack = self.AddressStack()
1971 while self.old_objects_with_finalizers.non_empty():
1972 x = self.old_objects_with_finalizers.popleft()
1973 fq_nr = self.old_objects_with_finalizers.popleft()
1974 ll_assert(self._finalization_state(x) != 1,
1975 "bad finalization state 1")
1976 if self.header(x).tid & GCFLAG_VISITED:
1977 new_with_finalizer.append(x)
1978 new_with_finalizer.append(fq_nr)
1979 continue
1980 marked.append(x)
1981 marked.append(fq_nr)
1982 pending.append(x)
1983 while pending.non_empty():
1984 y = pending.pop()
1985 state = self._finalization_state(y)
1986 if state == 0:
1987 self._bump_finalization_state_from_0_to_1(y)
1988 self.trace(y, self._append_if_nonnull, pending, None)
1989 elif state == 2:
1990 self._recursively_bump_finalization_state_from_2_to_3(y)
1991 self._recursively_bump_finalization_state_from_1_to_2(x)
1992
1993 while marked.non_empty():
1994 x = marked.popleft()
1995 fq_nr = marked.popleft()
1996 state = self._finalization_state(x)
1997 ll_assert(state >= 2, "unexpected finalization state < 2")
1998 if state == 2:
1999 from rpython.rtyper.lltypesystem import rffi
2000 fq_index = rffi.cast(lltype.Signed, fq_nr)
2001 self.mark_finalizer_to_run(fq_index, x)
2002 # we must also fix the state from 2 to 3 here, otherwise
2003 # we leave the GCFLAG_FINALIZATION_ORDERING bit behind
2004 # which will confuse the next collection
2005 self._recursively_bump_finalization_state_from_2_to_3(x)
2006 else:
2007 new_with_finalizer.append(x)
2008 new_with_finalizer.append(fq_nr)
2009
2010 self.tmpstack.delete()
2011 pending.delete()
2012 marked.delete()
2013 self.old_objects_with_finalizers.delete()
2014 self.old_objects_with_finalizers = new_with_finalizer
2015
2016 def _append_if_nonnull(pointer, stack, ignored):
2017 stack.append(pointer.address[0])
2018 _append_if_nonnull = staticmethod(_append_if_nonnull)
2019
2020 def _finalization_state(self, obj):
2021 tid = self.header(obj).tid
2022 if tid & GCFLAG_VISITED:
2023 if tid & GCFLAG_FINALIZATION_ORDERING:
2024 return 2
2025 else:
2026 return 3
2027 else:
2028 if tid & GCFLAG_FINALIZATION_ORDERING:
2029 return 1
2030 else:
2031 return 0
2032
2033 def _bump_finalization_state_from_0_to_1(self, obj):
2034 ll_assert(self._finalization_state(obj) == 0,
2035 "unexpected finalization state != 0")
2036 size_gc_header = self.gcheaderbuilder.size_gc_header
2037 totalsize = size_gc_header + self.get_size(obj)
2038 hdr = self.header(obj)
2039 hdr.tid |= GCFLAG_FINALIZATION_ORDERING
2040 self.kept_alive_by_finalizer += raw_malloc_usage(totalsize)
2041
2042 def _recursively_bump_finalization_state_from_2_to_3(self, obj):
2043 ll_assert(self._finalization_state(obj) == 2,
2044 "unexpected finalization state != 2")
2045 pending = self.tmpstack
2046 ll_assert(not pending.non_empty(), "tmpstack not empty")
2047 pending.append(obj)
2048 while pending.non_empty():
2049 y = pending.pop()
2050 hdr = self.header(y)
2051 if hdr.tid & GCFLAG_FINALIZATION_ORDERING: # state 2 ?
2052 hdr.tid &= ~GCFLAG_FINALIZATION_ORDERING # change to state 3
2053 self.trace(y, self._append_if_nonnull, pending, None)
2054
2055 def _recursively_bump_finalization_state_from_1_to_2(self, obj):
2056 # recursively convert objects from state 1 to state 2.
2057 # The call to visit_all_objects() will add the GCFLAG_VISITED
2058 # recursively.
2059 self.objects_to_trace.append(obj)
2060 self.visit_all_objects()
2061
2062
2063 # ----------
2064 # Weakrefs
2065
2066 # The code relies on the fact that no weakref can be an old object
2067 # weakly pointing to a young object. Indeed, weakrefs are immutable
2068 # so they cannot point to an object that was created after it.
2069 # Thanks to this, during a minor collection, we don't have to fix
2070 # or clear the address stored in old weakrefs.
2071 def invalidate_young_weakrefs(self):
2072 """Called during a nursery collection."""
2073 # walk over the list of objects that contain weakrefs and are in the
2074 # nursery. if the object it references survives then update the
2075 # weakref; otherwise invalidate the weakref
2076 while self.young_objects_with_weakrefs.non_empty():
2077 obj = self.young_objects_with_weakrefs.pop()
2078 if not self.is_forwarded(obj):
2079 continue # weakref itself dies
2080 obj = self.get_forwarding_address(obj)
2081 offset = self.weakpointer_offset(self.get_type_id(obj))
2082 pointing_to = (obj + offset).address[0]
2083 if self.is_in_nursery(pointing_to):
2084 if self.is_forwarded(pointing_to):
2085 (obj + offset).address[0] = self.get_forwarding_address(
2086 pointing_to)
2087 else:
2088 (obj + offset).address[0] = llmemory.NULL
2089 continue # no need to remember this weakref any longer
2090 #
2091 elif (bool(self.young_rawmalloced_objects) and
2092 self.young_rawmalloced_objects.contains(pointing_to)):
2093 # young weakref to a young raw-malloced object
2094 if self.header(pointing_to).tid & GCFLAG_VISITED:
2095 pass # survives, but does not move
2096 else:
2097 (obj + offset).address[0] = llmemory.NULL
2098 continue # no need to remember this weakref any longer
2099 #
2100 elif self.header(pointing_to).tid & GCFLAG_NO_HEAP_PTRS:
2101 # see test_weakref_to_prebuilt: it's not useful to put
2102 # weakrefs into 'old_objects_with_weakrefs' if they point
2103 # to a prebuilt object (they are immortal). If moreover
2104 # the 'pointing_to' prebuilt object still has the
2105 # GCFLAG_NO_HEAP_PTRS flag, then it's even wrong, because
2106 # 'pointing_to' will not get the GCFLAG_VISITED during
2107 # the next major collection. Solve this by not registering
2108 # the weakref into 'old_objects_with_weakrefs'.
2109 continue
2110 #
2111 self.old_objects_with_weakrefs.append(obj)
2112
2113 def invalidate_old_weakrefs(self):
2114 """Called during a major collection."""
2115 # walk over list of objects that contain weakrefs
2116 # if the object it references does not survive, invalidate the weakref
2117 new_with_weakref = self.AddressStack()
2118 while self.old_objects_with_weakrefs.non_empty():
2119 obj = self.old_objects_with_weakrefs.pop()
2120 if self.header(obj).tid & GCFLAG_VISITED == 0:
2121 continue # weakref itself dies
2122 offset = self.weakpointer_offset(self.get_type_id(obj))
2123 pointing_to = (obj + offset).address[0]
2124 ll_assert((self.header(pointing_to).tid & GCFLAG_NO_HEAP_PTRS)
2125 == 0, "registered old weakref should not "
2126 "point to a NO_HEAP_PTRS obj")
2127 if self.header(pointing_to).tid & GCFLAG_VISITED:
2128 new_with_weakref.append(obj)
2129 else:
2130 (obj + offset).address[0] = llmemory.NULL
2131 self.old_objects_with_weakrefs.delete()
2132 self.old_objects_with_weakrefs = new_with_weakref