Debian Codegraph @

rpython/memory/gc/incminimark.py

raw symbols SCIP
1 """Incremental version of the 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_DEBUG If set to non-zero, will fill nursery with garbage,
10 to help debugging.
11
12 PYPY_GC_INCREMENT_STEP The size of memory marked during the marking step.
13 Default is size of nursery * 2. If you mark it too high
14 your GC is not incremental at all. The minimum is set
15 to size that survives minor collection * 1.5 so we
16 reclaim anything all the time.
17
18 PYPY_GC_MAJOR_COLLECT Major collection memory factor. Default is '1.82',
19 which means trigger a major collection when the
20 memory consumed equals 1.82 times the memory
21 really used at the end of the previous major
22 collection.
23
24 PYPY_GC_GROWTH Major collection threshold's max growth rate.
25 Default is '1.4'. Useful to collect more often
26 than normally on sudden memory growth, e.g. when
27 there is a temporary peak in memory usage.
28
29 PYPY_GC_MAX The max heap size. If coming near this limit, it
30 will first collect more often, then raise an
31 RPython MemoryError, and if that is not enough,
32 crash the program with a fatal error. Try values
33 like '1.6GB'.
34
35 PYPY_GC_MAX_DELTA The major collection threshold will never be set
36 to more than PYPY_GC_MAX_DELTA the amount really
37 used after a collection. Defaults to 1/8th of the
38 total RAM size (which is constrained to be at most
39 2/3/4GB on 32-bit systems). Try values like '200MB'.
40
41 PYPY_GC_MIN Don't collect while the memory size is below this
42 limit. Useful to avoid spending all the time in
43 the GC in very small programs. Defaults to 8
44 times the nursery.
45
46 PYPY_GC_DEBUG Enable extra checks around collections that are
47 too slow for normal use. Values are 0 (off),
48 1 (on major collections) or 2 (also on minor
49 collections).
50
51 PYPY_GC_MAX_PINNED The maximal number of pinned objects at any point
52 in time. Defaults to a conservative value depending
53 on nursery size and maximum object size inside the
54 nursery. Useful for debugging by setting it to 0.
55 """
56 # XXX Should find a way to bound the major collection threshold by the
57 # XXX total addressable size. Maybe by keeping some minimarkpage arenas
58 # XXX pre-reserved, enough for a few nursery collections? What about
59 # XXX raw-malloced memory?
60
61 # XXX try merging old_objects_pointing_to_pinned into
62 # XXX old_objects_pointing_to_young (IRC 2014-10-22, fijal and gregor_w)
63 import sys
64 import os
65 import time
66 from rpython.rtyper.lltypesystem import lltype, llmemory, llarena, llgroup
67 from rpython.rtyper.lltypesystem.lloperation import llop
68 from rpython.rtyper.lltypesystem.llmemory import raw_malloc_usage
69 from rpython.memory.gc.base import GCBase, MovingGCBase
70 from rpython.memory.gc import env
71 from rpython.memory.support import mangle_hash
72 from rpython.rlib.rarithmetic import ovfcheck, LONG_BIT, intmask, r_uint
73 from rpython.rlib.rarithmetic import LONG_BIT_SHIFT
74 from rpython.rlib.debug import ll_assert, debug_print, debug_start, debug_stop
75 from rpython.rlib.objectmodel import specialize, always_inline, we_are_translated
76 from rpython.rlib import rgc, unroll
77 from rpython.memory.gc.minimarkpage import out_of_memory
78
79 #
80 # Handles the objects in 2 generations:
81 #
82 # * young objects: allocated in the nursery if they are not too large, or
83 # raw-malloced otherwise. The nursery is a fixed-size memory buffer of
84 # 4MB by default. When full, we do a minor collection;
85 # - surviving objects from the nursery are moved outside and become old,
86 # - non-surviving raw-malloced objects are freed,
87 # - and pinned objects are kept at their place inside the nursery and stay
88 # young.
89 #
90 # * old objects: never move again. These objects are either allocated by
91 # minimarkpage.py (if they are small), or raw-malloced (if they are not
92 # small). Collected by regular mark-n-sweep during major collections.
93 #
94
95 WORD = LONG_BIT // 8
96
97 first_gcflag = 1 << (LONG_BIT//2)
98
99 # The following flag is set on objects if we need to do something to
100 # track the young pointers that it might contain. The flag is not set
101 # on young objects (unless they are large arrays, see below), and we
102 # simply assume that any young object can point to any other young object.
103 # For old and prebuilt objects, the flag is usually set, and is cleared
104 # when we write any pointer to it. For large arrays with
105 # GCFLAG_HAS_CARDS, we rely on card marking to track where the
106 # young pointers are; the flag GCFLAG_TRACK_YOUNG_PTRS is set in this
107 # case too, to speed up the write barrier.
108 GCFLAG_TRACK_YOUNG_PTRS = first_gcflag << 0
109
110 # The following flag is set on some prebuilt objects. The flag is set
111 # unless the object is already listed in 'prebuilt_root_objects'.
112 # When a pointer is written inside an object with GCFLAG_NO_HEAP_PTRS
113 # set, the write_barrier clears the flag and adds the object to
114 # 'prebuilt_root_objects'.
115 GCFLAG_NO_HEAP_PTRS = first_gcflag << 1
116
117 # The following flag is set on surviving objects during a major collection.
118 GCFLAG_VISITED = first_gcflag << 2
119
120 # The following flag is set on nursery objects of which we asked the id
121 # or the identityhash. It means that a space of the size of the object
122 # has already been allocated in the nonmovable part.
123 GCFLAG_HAS_SHADOW = first_gcflag << 3
124
125 # The following flag is set temporarily on some objects during a major
126 # collection. See pypy/doc/discussion/finalizer-order.txt
127 GCFLAG_FINALIZATION_ORDERING = first_gcflag << 4
128
129 # This flag is reserved for RPython.
130 GCFLAG_EXTRA = first_gcflag << 5
131
132 # The following flag is set on externally raw_malloc'ed arrays of pointers.
133 # They are allocated with some extra space in front of them for a bitfield,
134 # one bit per 'card_page_indices' indices.
135 GCFLAG_HAS_CARDS = first_gcflag << 6
136 GCFLAG_CARDS_SET = first_gcflag << 7 # <- at least one card bit is set
137 # note that GCFLAG_CARDS_SET is the most significant bit of a byte:
138 # this is required for the JIT (x86)
139
140 # The following flag is set on surviving raw-malloced young objects during
141 # a minor collection.
142 GCFLAG_VISITED_RMY = first_gcflag << 8
143
144 # The following flag is set on nursery objects to keep them in the nursery.
145 # This means that a young object with this flag is not moved out
146 # of the nursery during a minor collection. See pin()/unpin() for further
147 # details.
148 GCFLAG_PINNED = first_gcflag << 9
149
150 # The following flag is set only on objects outside the nursery
151 # (i.e. old objects). Therefore we can reuse GCFLAG_PINNED as it is used for
152 # the same feature (object pinning) and GCFLAG_PINNED is only used on nursery
153 # objects.
154 # If this flag is set, the flagged object is already an element of
155 # 'old_objects_pointing_to_pinned' and doesn't have to be added again.
156 GCFLAG_PINNED_OBJECT_PARENT_KNOWN = GCFLAG_PINNED
157
158 # record that ignore_finalizer() has been called
159 GCFLAG_IGNORE_FINALIZER = first_gcflag << 10
160
161 # shadow objects can have its memory initialized when it is created.
162 # It does not need an additional copy in trace out
163 GCFLAG_SHADOW_INITIALIZED = first_gcflag << 11
164
165 # another flag set only on specific objects: the ll_dummy_value from
166 # rpython.rtyper.rmodel
167 GCFLAG_DUMMY = first_gcflag << 12
168
169 _GCFLAG_FIRST_UNUSED = first_gcflag << 13 # the first unused bit
170
171 flagnames_and_values = unroll.unrolling_iterable([
172 (name, value) for name, value in globals().items()
173 if name.startswith("GCFLAG_")])
174
175 # States for the incremental GC
176
177 # The scanning phase, next step call will scan the current roots
178 # This state must complete in a single step
179 STATE_SCANNING = 0
180
181 # The marking phase. We walk the list 'objects_to_trace' of all gray objects
182 # and mark all of the things they point to gray. This step lasts until there
183 # are no more gray objects. ('objects_to_trace' never contains pinned objs.)
184 STATE_MARKING = 1
185
186 # here we kill all the unvisited objects
187 STATE_SWEEPING = 2
188
189 # here we call all the finalizers
190 STATE_FINALIZING = 3
191
192 GC_STATES = ['SCANNING', 'MARKING', 'SWEEPING', 'FINALIZING']
193
194
195 FORWARDSTUB = lltype.GcStruct('forwarding_stub',
196 ('forw', llmemory.Address))
197 FORWARDSTUBPTR = lltype.Ptr(FORWARDSTUB)
198 NURSARRAY = lltype.Array(llmemory.Address)
199
200 # ____________________________________________________________
201
202
203
204 class IncrementalMiniMarkGC(MovingGCBase):
205 _alloc_flavor_ = "raw"
206 inline_simple_malloc = True
207 inline_simple_malloc_varsize = True
208 needs_write_barrier = True
209 prebuilt_gc_objects_are_static_roots = False
210 can_usually_pin_objects = True
211 malloc_zero_filled = False
212 gcflag_extra = GCFLAG_EXTRA
213 gcflag_dummy = GCFLAG_DUMMY
214
215 # All objects start with a HDR, i.e. with a field 'tid' which contains
216 # a word. This word is divided in two halves: the lower half contains
217 # the typeid, and the upper half contains various flags, as defined
218 # by GCFLAG_xxx above.
219 HDR = lltype.Struct('header', ('tid', lltype.Signed))
220 typeid_is_in_field = 'tid'
221
222 # During a minor collection, the objects in the nursery that are
223 # moved outside are changed in-place: their header is replaced with
224 # the value -42, and the following word is set to the address of
225 # where the object was moved. This means that all objects in the
226 # nursery need to be at least 2 words long, but objects outside the
227 # nursery don't need to.
228 minimal_size_in_nursery = (
229 llmemory.sizeof(HDR) + llmemory.sizeof(llmemory.Address))
230
231
232 TRANSLATION_PARAMS = {
233 # Automatically adjust the size of the nursery and the
234 # 'major_collection_threshold' from the environment.
235 # See docstring at the start of the file.
236 "read_from_env": True,
237
238 # The size of the nursery. Note that this is only used as a
239 # fall-back number.
240 "nursery_size": 896*1024,
241
242 # The system page size. Like malloc, we assume that it is 4K
243 # for 32-bit systems; unlike malloc, we assume that it is 8K
244 # for 64-bit systems, for consistent results.
245 "page_size": 1024*WORD,
246
247 # The size of an arena. Arenas are groups of pages allocated
248 # together.
249 "arena_size": 65536*WORD,
250
251 # The maximum size of an object allocated compactly. All objects
252 # that are larger are just allocated with raw_malloc(). Note that
253 # the size limit for being first allocated in the nursery is much
254 # larger; see below.
255 "small_request_threshold": 35*WORD,
256
257 # Full collection threshold: after a major collection, we record
258 # the total size consumed; and after every minor collection, if the
259 # total size is now more than 'major_collection_threshold' times,
260 # we trigger the next major collection.
261 "major_collection_threshold": 1.82,
262
263 # Threshold to avoid that the total heap size grows by a factor of
264 # major_collection_threshold at every collection: it can only
265 # grow at most by the following factor from one collection to the
266 # next. Used e.g. when there is a sudden, temporary peak in memory
267 # usage; this avoids that the upper bound grows too fast.
268 "growth_rate_max": 1.4,
269
270 # The number of array indices that are mapped to a single bit in
271 # write_barrier_from_array(). Must be a power of two. The default
272 # value of 128 means that card pages are 512 bytes (1024 on 64-bits)
273 # in regular arrays of pointers; more in arrays whose items are
274 # larger. A value of 0 disables card marking.
275 "card_page_indices": 128,
276
277 # Objects whose total size is at least 'large_object' bytes are
278 # allocated out of the nursery immediately, as old objects. The
279 # minimal allocated size of the nursery is 2x the following
280 # number (by default, at least 132KB on 32-bit and 264KB on 64-bit).
281 "large_object": (16384+512)*WORD,
282 }
283
284 def __init__(self, config,
285 read_from_env=False,
286 nursery_size=32*WORD,
287 nursery_cleanup=9*WORD,
288 page_size=16*WORD,
289 arena_size=64*WORD,
290 small_request_threshold=5*WORD,
291 major_collection_threshold=2.5,
292 growth_rate_max=2.5, # for tests
293 card_page_indices=0,
294 large_object=8*WORD,
295 ArenaCollectionClass=None,
296 **kwds):
297 "NOT_RPYTHON"
298 MovingGCBase.__init__(self, config, **kwds)
299 assert small_request_threshold % WORD == 0
300 self.read_from_env = read_from_env
301 self.nursery_size = nursery_size
302
303 self.small_request_threshold = small_request_threshold
304 self.major_collection_threshold = major_collection_threshold
305 self.growth_rate_max = growth_rate_max
306 self.num_major_collects = 0
307 self.min_heap_size = 0.0
308 self.max_heap_size = 0.0
309 self.max_heap_size_already_raised = False
310 self.max_delta = float(r_uint(-1))
311 self.max_number_of_pinned_objects = 0 # computed later
312 #
313 self.card_page_indices = card_page_indices
314 if self.card_page_indices > 0:
315 self.card_page_shift = 0
316 while (1 << self.card_page_shift) < self.card_page_indices:
317 self.card_page_shift += 1
318 #
319 # 'large_object' limit how big objects can be in the nursery, so
320 # it gives a lower bound on the allowed size of the nursery.
321 self.nonlarge_max = large_object - 1
322 #
323 self.nursery = llmemory.NULL
324 self.nursery_free = llmemory.NULL
325 self.nursery_top = llmemory.NULL
326 self.debug_tiny_nursery = -1
327 self.debug_rotating_nurseries = lltype.nullptr(NURSARRAY)
328 self.extra_threshold = 0
329 #
330 # The ArenaCollection() handles the nonmovable objects allocation.
331 if ArenaCollectionClass is None:
332 from rpython.memory.gc import minimarkpage
333 ArenaCollectionClass = minimarkpage.ArenaCollection
334 self.ac = ArenaCollectionClass(arena_size, page_size,
335 small_request_threshold)
336 #
337 # Used by minor collection: a list of (mostly non-young) objects that
338 # (may) contain a pointer to a young object. Populated by
339 # the write barrier: when we clear GCFLAG_TRACK_YOUNG_PTRS, we
340 # add it to this list.
341 # Note that young array objects may (by temporary "mistake") be added
342 # to this list, but will be removed again at the start of the next
343 # minor collection.
344 self.old_objects_pointing_to_young = self.AddressStack()
345 #
346 # Similar to 'old_objects_pointing_to_young', but lists objects
347 # that have the GCFLAG_CARDS_SET bit. For large arrays. Note
348 # that it is possible for an object to be listed both in here
349 # and in 'old_objects_pointing_to_young', in which case we
350 # should just clear the cards and trace it fully, as usual.
351 # Note also that young array objects are never listed here.
352 self.old_objects_with_cards_set = self.AddressStack()
353 #
354 # A list of all prebuilt GC objects that contain pointers to the heap
355 self.prebuilt_root_objects = self.AddressStack()
356 #
357 self._init_writebarrier_logic()
358 #
359 # The size of all the objects turned from 'young' to 'old'
360 # since we started the last major collection cycle. This is
361 # used to track progress of the incremental GC: normally, we
362 # run one major GC step after each minor collection, but if a
363 # lot of objects are made old, we need run two or more steps.
364 # Otherwise the risk is that we create old objects faster than
365 # we're collecting them. The 'threshold' is incremented after
366 # each major GC step at a fixed rate; the idea is that as long
367 # as 'size_objects_made_old > threshold_objects_made_old' then
368 # we must do more major GC steps. See major_collection_step()
369 # for more details.
370 self.size_objects_made_old = r_uint(0)
371 self.threshold_objects_made_old = r_uint(0)
372
373
374 def setup(self):
375 """Called at run-time to initialize the GC."""
376 #
377 # Hack: MovingGCBase.setup() sets up stuff related to id(), which
378 # we implement differently anyway. So directly call GCBase.setup().
379 GCBase.setup(self)
380 #
381 # Two lists of all raw_malloced objects (the objects too large)
382 self.young_rawmalloced_objects = self.null_address_dict()
383 self.old_rawmalloced_objects = self.AddressStack()
384 self.raw_malloc_might_sweep = self.AddressStack()
385 self.rawmalloced_total_size = r_uint(0)
386 self.rawmalloced_peak_size = r_uint(0)
387 self.total_gc_time = 0.0
388
389 self.gc_state = STATE_SCANNING
390
391 # if the GC is disabled, it runs only minor collections; major
392 # collections need to be manually triggered by explicitly calling
393 # collect()
394 self.enabled = True
395 #
396 # Two lists of all objects with finalizers. Actually they are lists
397 # of pairs (finalization_queue_nr, object). "probably young objects"
398 # are all traced and moved to the "old" list by the next minor
399 # collection.
400 self.probably_young_objects_with_finalizers = self.AddressDeque()
401 self.old_objects_with_finalizers = self.AddressDeque()
402 p = lltype.malloc(self._ADDRARRAY, 1, flavor='raw',
403 track_allocation=False)
404 self.singleaddr = llmemory.cast_ptr_to_adr(p)
405 #
406 # Two lists of all objects with destructors.
407 self.young_objects_with_destructors = self.AddressStack()
408 self.old_objects_with_destructors = self.AddressStack()
409 #
410 # Two lists of the objects with weakrefs. No weakref can be an
411 # old object weakly pointing to a young object: indeed, weakrefs
412 # are immutable so they cannot point to an object that was
413 # created after it.
414 self.young_objects_with_weakrefs = self.AddressStack()
415 self.old_objects_with_weakrefs = self.AddressStack()
416 #
417 # Support for id and identityhash: map nursery objects with
418 # GCFLAG_HAS_SHADOW to their future location at the next
419 # minor collection.
420 self.nursery_objects_shadows = self.AddressDict()
421 #
422 # A sorted deque containing addresses of pinned objects.
423 # This collection is used to make sure we don't overwrite pinned objects.
424 # Each minor collection creates a new deque containing the active pinned
425 # objects. The addresses are used to set the next 'nursery_top'.
426 self.nursery_barriers = self.AddressDeque()
427 #
428 # Counter tracking how many pinned objects currently reside inside
429 # the nursery.
430 self.pinned_objects_in_nursery = 0
431 #
432 # This flag is set if the previous minor collection found at least
433 # one pinned object alive.
434 self.any_pinned_object_kept = False
435 #
436 # Keeps track of old objects pointing to pinned objects. These objects
437 # must be traced every minor collection. Without tracing them the
438 # referenced pinned object wouldn't be visited and therefore collected.
439 self.old_objects_pointing_to_pinned = self.AddressStack()
440 self.updated_old_objects_pointing_to_pinned = False
441 #
442 # Allocate a nursery. In case of auto_nursery_size, start by
443 # allocating a very small nursery, enough to do things like look
444 # up the env var, which requires the GC; and then really
445 # allocate the nursery of the final size.
446 if not self.read_from_env:
447 self.allocate_nursery()
448 self.gc_increment_step = self.nursery_size * 4
449 self.gc_nursery_debug = False
450 else:
451 #
452 defaultsize = self.nursery_size
453 minsize = 2 * (self.nonlarge_max + 1)
454 self.nursery_size = minsize
455 self.allocate_nursery()
456 #
457 # From there on, the GC is fully initialized and the code
458 # below can use it
459 newsize = env.read_from_env('PYPY_GC_NURSERY')
460 # PYPY_GC_NURSERY=smallvalue means that minor collects occur
461 # very frequently; the extreme case is PYPY_GC_NURSERY=1, which
462 # forces a minor collect for every malloc. Useful to debug
463 # external factors, like trackgcroot or the handling of the write
464 # barrier. Implemented by still using 'minsize' for the nursery
465 # size (needed to handle mallocs just below 'large_objects') but
466 # hacking at the current nursery position in collect_and_reserve().
467 if newsize <= 0:
468 newsize = env.estimate_best_nursery_size()
469 if newsize <= 0:
470 newsize = defaultsize
471 if newsize < minsize:
472 self.debug_tiny_nursery = newsize & ~(WORD-1)
473 newsize = minsize
474 #
475 major_coll = env.read_float_from_env('PYPY_GC_MAJOR_COLLECT')
476 if major_coll > 1.0:
477 self.major_collection_threshold = major_coll
478 #
479 growth = env.read_float_from_env('PYPY_GC_GROWTH')
480 if growth > 1.0:
481 self.growth_rate_max = growth
482 #
483 min_heap_size = env.read_uint_from_env('PYPY_GC_MIN')
484 if min_heap_size > 0:
485 self.min_heap_size = float(min_heap_size)
486 else:
487 # defaults to 8 times the nursery
488 self.min_heap_size = newsize * 8
489 #
490 max_heap_size = env.read_uint_from_env('PYPY_GC_MAX')
491 if max_heap_size > 0:
492 self.max_heap_size = float(max_heap_size)
493 #
494 max_delta = env.read_uint_from_env('PYPY_GC_MAX_DELTA')
495 if max_delta > 0:
496 self.max_delta = float(max_delta)
497 else:
498 self.max_delta = 0.125 * env.get_total_memory()
499
500 gc_increment_step = env.read_uint_from_env('PYPY_GC_INCREMENT_STEP')
501 if gc_increment_step > 0:
502 self.gc_increment_step = gc_increment_step
503 else:
504 self.gc_increment_step = newsize * 4
505 #
506 nursery_debug = env.read_uint_from_env('PYPY_GC_NURSERY_DEBUG')
507 if nursery_debug > 0:
508 self.gc_nursery_debug = True
509 else:
510 self.gc_nursery_debug = False
511 self._minor_collection() # to empty the nursery
512 llarena.arena_free(self.nursery)
513 self.nursery_size = newsize
514 self.allocate_nursery()
515 #
516 env_max_number_of_pinned_objects = os.environ.get('PYPY_GC_MAX_PINNED')
517 if env_max_number_of_pinned_objects:
518 try:
519 env_max_number_of_pinned_objects = int(env_max_number_of_pinned_objects)
520 except ValueError:
521 env_max_number_of_pinned_objects = 0
522 #
523 if env_max_number_of_pinned_objects >= 0: # 0 allows to disable pinning completely
524 self.max_number_of_pinned_objects = env_max_number_of_pinned_objects
525 else:
526 # Estimate this number conservatively
527 bigobj = self.nonlarge_max + 1
528 self.max_number_of_pinned_objects = self.nursery_size / (bigobj * 2)
529
530 def enable(self):
531 self.enabled = True
532
533 def disable(self):
534 self.enabled = False
535
536 def isenabled(self):
537 return self.enabled
538
539 def _nursery_memory_size(self):
540 extra = self.nonlarge_max + 1
541 return self.nursery_size + extra
542
543 def _alloc_nursery(self):
544 # the start of the nursery: we actually allocate a bit more for
545 # the nursery than really needed, to simplify pointer arithmetic
546 # in malloc_fixedsize(). The few extra pages are never used
547 # anyway so it doesn't even count.
548 nursery = llarena.arena_malloc(self._nursery_memory_size(), 0)
549 if not nursery:
550 out_of_memory("cannot allocate nursery")
551 return nursery
552
553 def allocate_nursery(self):
554 debug_start("gc-set-nursery-size")
555 debug_print("nursery size:", self.nursery_size)
556 self.nursery = self._alloc_nursery()
557 # the current position in the nursery:
558 self.nursery_free = self.nursery
559 # the end of the nursery:
560 self.nursery_top = self.nursery + self.nursery_size
561 # initialize the threshold
562 self.min_heap_size = max(self.min_heap_size, self.nursery_size *
563 self.major_collection_threshold)
564 # the following two values are usually equal, but during raw mallocs
565 # with memory pressure accounting, next_major_collection_threshold
566 # is decremented to make the next major collection arrive earlier.
567 # See translator/c/test/test_newgc, test_nongc_attached_to_gc
568 self.next_major_collection_initial = self.min_heap_size
569 self.next_major_collection_threshold = self.min_heap_size
570 self.set_major_threshold_from(0.0)
571 ll_assert(self.extra_threshold == 0, "extra_threshold set too early")
572 debug_stop("gc-set-nursery-size")
573
574
575 def set_major_threshold_from(self, threshold, reserving_size=0):
576 # Set the next_major_collection_threshold.
577 threshold_max = (self.next_major_collection_initial *
578 self.growth_rate_max)
579 if threshold > threshold_max:
580 threshold = threshold_max
581 #
582 threshold += reserving_size
583 if threshold < self.min_heap_size:
584 threshold = self.min_heap_size
585 #
586 if self.max_heap_size > 0.0 and threshold > self.max_heap_size:
587 threshold = self.max_heap_size
588 bounded = True
589 else:
590 bounded = False
591 #
592 self.next_major_collection_initial = threshold
593 self.next_major_collection_threshold = threshold
594 return bounded
595
596
597 def post_setup(self):
598 # set up extra stuff for PYPY_GC_DEBUG.
599 MovingGCBase.post_setup(self)
600 if self.DEBUG and llarena.has_protect:
601 # gc debug mode: allocate 7 nurseries instead of just 1,
602 # and use them alternatively, while mprotect()ing the unused
603 # ones to detect invalid access.
604 debug_start("gc-debug")
605 self.debug_rotating_nurseries = lltype.malloc(
606 NURSARRAY, 6, flavor='raw', track_allocation=False)
607 i = 0
608 while i < 6:
609 nurs = self._alloc_nursery()
610 llarena.arena_protect(nurs, self._nursery_memory_size(), True)
611 self.debug_rotating_nurseries[i] = nurs
612 i += 1
613 debug_print("allocated", len(self.debug_rotating_nurseries),
614 "extra nurseries")
615 debug_stop("gc-debug")
616
617 def debug_rotate_nursery(self):
618 if self.debug_rotating_nurseries:
619 debug_start("gc-debug")
620 oldnurs = self.nursery
621 llarena.arena_protect(oldnurs, self._nursery_memory_size(), True)
622 #
623 newnurs = self.debug_rotating_nurseries[0]
624 i = 0
625 while i < len(self.debug_rotating_nurseries) - 1:
626 self.debug_rotating_nurseries[i] = (
627 self.debug_rotating_nurseries[i + 1])
628 i += 1
629 self.debug_rotating_nurseries[i] = oldnurs
630 #
631 llarena.arena_protect(newnurs, self._nursery_memory_size(), False)
632 self.nursery = newnurs
633 self.nursery_top = self.nursery + self.nursery_size
634 debug_print("switching from nursery", oldnurs,
635 "to nursery", self.nursery,
636 "size", self.nursery_size)
637 debug_stop("gc-debug")
638
639
640 def malloc_fixedsize(self, typeid, size,
641 needs_finalizer=False,
642 is_finalizer_light=False,
643 contains_weakptr=False):
644 size_gc_header = self.gcheaderbuilder.size_gc_header
645 totalsize = size_gc_header + size
646 rawtotalsize = raw_malloc_usage(totalsize)
647 #
648 # If the object needs a finalizer, ask for a rawmalloc.
649 # The following check should be constant-folded.
650 if needs_finalizer and not is_finalizer_light:
651 # old-style finalizers only!
652 ll_assert(not contains_weakptr,
653 "'needs_finalizer' and 'contains_weakptr' both specified")
654 obj = self.external_malloc(typeid, 0, alloc_young=False)
655 res = llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
656 self.register_finalizer(-1, res)
657 return res
658 #
659 # If totalsize is greater than nonlarge_max (which should never be
660 # the case in practice), ask for a rawmalloc. The following check
661 # should be constant-folded.
662 if rawtotalsize > self.nonlarge_max:
663 ll_assert(not contains_weakptr,
664 "'contains_weakptr' specified for a large object")
665 obj = self.external_malloc(typeid, 0, alloc_young=True)
666 #
667 else:
668 # If totalsize is smaller than minimal_size_in_nursery, round it
669 # up. The following check should also be constant-folded.
670 min_size = raw_malloc_usage(self.minimal_size_in_nursery)
671 if rawtotalsize < min_size:
672 totalsize = rawtotalsize = min_size
673 #
674 # Get the memory from the nursery. If there is not enough space
675 # there, do a collect first.
676 result = self.nursery_free
677 ll_assert(result != llmemory.NULL, "uninitialized nursery")
678 self.nursery_free = new_free = self._bump_pointer(result, totalsize)
679 if new_free > self.nursery_top:
680 result = self.collect_and_reserve(totalsize)
681 #
682 # Build the object.
683 llarena.arena_reserve(result, totalsize)
684 obj = result + size_gc_header
685 self.init_gc_object(result, typeid, flags=0)
686 #
687 # If it is a weakref or has a lightweight destructor, record it
688 # (checks constant-folded).
689 if needs_finalizer:
690 self.young_objects_with_destructors.append(obj)
691 if contains_weakptr:
692 self.young_objects_with_weakrefs.append(obj)
693 return llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
694
695
696 def malloc_varsize(self, typeid, length, size, itemsize,
697 offset_to_length):
698 size_gc_header = self.gcheaderbuilder.size_gc_header
699 nonvarsize = size_gc_header + size
700 #
701 # Compute the maximal length that makes the object still
702 # below 'nonlarge_max'. All the following logic is usually
703 # constant-folded because self.nonlarge_max, size and itemsize
704 # are all constants (the arguments are constant due to
705 # inlining).
706 maxsize = self.nonlarge_max - raw_malloc_usage(nonvarsize)
707 if maxsize < 0:
708 toobig = r_uint(0) # the nonvarsize alone is too big
709 elif raw_malloc_usage(itemsize):
710 toobig = r_uint(maxsize // raw_malloc_usage(itemsize)) + 1
711 else:
712 toobig = r_uint(sys.maxint) + 1
713
714 if r_uint(length) >= r_uint(toobig):
715 #
716 # If the total size of the object would be larger than
717 # 'nonlarge_max', then allocate it externally. We also
718 # go there if 'length' is actually negative.
719 obj = self.external_malloc(typeid, length, alloc_young=True)
720 #
721 else:
722 # With the above checks we know now that totalsize cannot be more
723 # than 'nonlarge_max'; in particular, the + and * cannot overflow.
724 totalsize = nonvarsize + itemsize * length
725 totalsize = llarena.round_up_for_allocation(totalsize)
726 #
727 # 'totalsize' should contain at least the GC header and
728 # the length word, so it should never be smaller than
729 # 'minimal_size_in_nursery'
730 ll_assert(raw_malloc_usage(totalsize) >=
731 raw_malloc_usage(self.minimal_size_in_nursery),
732 "malloc_varsize(): totalsize < minimalsize")
733 #
734 # Get the memory from the nursery. If there is not enough space
735 # there, do a collect first.
736 result = self.nursery_free
737 new_free = self._bump_pointer(result, totalsize)
738 self.nursery_free = new_free
739 if new_free > self.nursery_top:
740 result = self.collect_and_reserve(totalsize)
741 #
742 # Build the object.
743 llarena.arena_reserve(result, totalsize)
744 self.init_gc_object(result, typeid, flags=0)
745 #
746 # Set the length and return the object.
747 obj = result + size_gc_header
748 (obj + offset_to_length).signed[0] = length
749 #
750 return llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
751
752 @always_inline
753 def _bump_pointer(self, result, totalsize):
754 ll_assert(result != llmemory.NULL, "uninitialized nursery")
755 if not we_are_translated():
756 # grumble grumble, there is a weird heuristic in
757 # fakearenaaddress.__add__ which gets confused if
758 # self.nursery_top is a pinned object. so for direct tests, do
759 # the right thing directly
760 bytes = llmemory.raw_malloc_usage(totalsize)
761 return result.arena.getaddr(result.offset + bytes)
762 else:
763 return result + totalsize
764
765 def malloc_fixed_or_varsize_nonmovable(self, typeid, length):
766 # length==0 for fixedsize
767 obj = self.external_malloc(typeid, length, alloc_young=True)
768 return llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
769
770 def move_out_of_nursery(self, obj):
771 # called twice, it should return the same shadow object,
772 # and not creating another shadow object. As a safety feature,
773 # when called on a non-nursery object, do nothing.
774 if not self.is_in_nursery(obj):
775 return obj
776 shadow = self._find_shadow(obj)
777 if (self.header(obj).tid & GCFLAG_SHADOW_INITIALIZED) == 0:
778 self.header(obj).tid |= GCFLAG_SHADOW_INITIALIZED
779 totalsize = self.get_size(obj)
780 llmemory.raw_memcopy(obj, shadow, totalsize)
781 return shadow
782
783 def collect(self, gen=2):
784 """Do a minor (gen=0), start a major (gen=1), or do a full
785 major (gen>=2) collection."""
786 if gen < 0:
787 # Dangerous! this makes no progress on the major GC cycle.
788 # If called too often, the memory usage will keep increasing,
789 # because we'll never completely fill the nursery (and so
790 # never run anything about the major collection).
791 self._minor_collection()
792 elif gen == 0:
793 # This runs a minor collection. This is basically what occurs
794 # when the nursery is full. If a major collection is in
795 # progress, it also runs one more step of it. It might also
796 # decide to start a major collection just now, depending on
797 # current memory pressure.
798 self.minor_collection_with_major_progress(force_enabled=True)
799 elif gen == 1:
800 # This is like gen == 0, but if no major collection is running,
801 # then it forces one to start now.
802 self.minor_collection_with_major_progress(force_enabled=True)
803 if self.gc_state == STATE_SCANNING:
804 self.major_collection_step()
805 else:
806 # This does a complete minor and major collection.
807 self.minor_and_major_collection()
808 self.rrc_invoke_callback()
809
810 def collect_step(self):
811 """
812 Do a single major collection step. Return True when the major collection
813 is completed.
814
815 This is meant to be used together with gc.disable(), to have a
816 fine-grained control on when the GC runs.
817 """
818 old_state = self.gc_state
819 self._minor_collection()
820 self.major_collection_step()
821 self.rrc_invoke_callback()
822 return rgc._encode_states(old_state, self.gc_state)
823
824 def minor_collection_with_major_progress(self, extrasize=0,
825 force_enabled=False):
826 """Do a minor collection. Then, if the GC is enabled and there
827 is already a major GC in progress, run at least one major collection
828 step. If there is no major GC but the threshold is reached, start a
829 major GC.
830 """
831 self._minor_collection()
832 if not self.enabled and not force_enabled:
833 return
834
835 # If the gc_state is STATE_SCANNING, we're not in the middle
836 # of an incremental major collection. In that case, wait
837 # until there is too much garbage before starting the next
838 # major collection. But if we are in the middle of an
839 # incremental major collection, then always do (at least) one
840 # step now.
841 #
842 # Within a major collection cycle, every call to
843 # major_collection_step() increments
844 # 'threshold_objects_made_old' by nursery_size/2.
845
846 if self.gc_state != STATE_SCANNING or self.threshold_reached(extrasize):
847 self.major_collection_step(extrasize)
848
849 # See documentation in major_collection_step() for target invariants
850 while self.gc_state != STATE_SCANNING: # target (A1)
851 threshold = self.threshold_objects_made_old
852 if threshold >= r_uint(extrasize):
853 threshold -= r_uint(extrasize) # (*)
854 if self.size_objects_made_old <= threshold: # target (A2)
855 break
856 # Note that target (A2) is tweaked by (*); see
857 # test_gc_set_max_heap_size in translator/c, test_newgc.py
858
859 self._minor_collection()
860 self.major_collection_step(extrasize)
861
862 self.rrc_invoke_callback()
863
864
865 def collect_and_reserve(self, totalsize):
866 """To call when nursery_free overflows nursery_top.
867 First check if pinned objects are in front of nursery_top. If so,
868 jump over the pinned object and try again to reserve totalsize.
869 Otherwise do a minor collection, and possibly some steps of a
870 major collection, and finally reserve totalsize bytes.
871 """
872
873 minor_collection_count = 0
874 while True:
875 self.nursery_free = llmemory.NULL # debug: don't use me
876 # note: no "raise MemoryError" between here and the next time
877 # we initialize nursery_free!
878
879 if self.nursery_barriers.non_empty():
880 # Pinned object in front of nursery_top. Try reserving totalsize
881 # by jumping into the next, yet unused, area inside the
882 # nursery. "Next area" in this case is the space between the
883 # pinned object in front of nusery_top and the pinned object
884 # after that. Graphically explained:
885 #
886 # |- allocating totalsize failed in this area
887 # | |- nursery_top
888 # | | |- pinned object in front of nursery_top,
889 # v v v jump over this
890 # +---------+--------+--------+--------+-----------+ }
891 # | used | pinned | empty | pinned | empty | }- nursery
892 # +---------+--------+--------+--------+-----------+ }
893 # ^- try reserving totalsize in here next
894 #
895 # All pinned objects are represented by entries in
896 # nursery_barriers (see minor_collection). The last entry is
897 # always the end of the nursery. Therefore if nursery_barriers
898 # contains only one element, we jump over a pinned object and
899 # the "next area" (the space where we will try to allocate
900 # totalsize) starts at the end of the pinned object and ends at
901 # nursery's end.
902 #
903 # find the size of the pinned object after nursery_top
904 size_gc_header = self.gcheaderbuilder.size_gc_header
905 pinned_obj_size = size_gc_header + self.get_size(
906 self.nursery_top + size_gc_header)
907 #
908 # update used nursery space to allocate objects
909 self.nursery_free = self.nursery_top + pinned_obj_size
910 self.nursery_top = self.nursery_barriers.popleft()
911 else:
912 minor_collection_count += 1
913 if minor_collection_count == 1:
914 self.minor_collection_with_major_progress()
915 else:
916 # Nursery too full again. This is likely because of
917 # execute_finalizers() or rrc_invoke_callback().
918 # we need to fix it with another call to minor_collection()
919 # ---this time only the minor part so that we are sure that
920 # the nursery is empty (apart from pinned objects).
921 #
922 # Note that this still works with the counters:
923 # 'size_objects_made_old' will be increased by
924 # the _minor_collection() below. We don't
925 # immediately restore the target invariant that
926 # 'size_objects_made_old <= threshold_objects_made_old'.
927 # But we will do it in the next call to
928 # minor_collection_with_major_progress().
929 #
930 ll_assert(minor_collection_count == 2,
931 "Calling minor_collection() twice is not "
932 "enough. Too many pinned objects?")
933 self._minor_collection()
934 #
935 # Tried to do something about nursery_free overflowing
936 # nursery_top before this point. Try to reserve totalsize now.
937 # If this succeeds break out of loop.
938 result = self.nursery_free
939 new_free = self._bump_pointer(result, totalsize)
940 if new_free <= self.nursery_top:
941 self.nursery_free = new_free
942 ll_assert(self.nursery_free <= self.nursery_top, "nursery overflow")
943 break
944 #
945 #
946 if self.debug_tiny_nursery >= 0: # for debugging
947 if self.nursery_top - self.nursery_free > self.debug_tiny_nursery:
948 self.nursery_free = self.nursery_top - self.debug_tiny_nursery
949 #
950 return result
951 collect_and_reserve._dont_inline_ = True
952
953
954 # XXX kill alloc_young and make it always True
955 def external_malloc(self, typeid, length, alloc_young):
956 """Allocate a large object using the ArenaCollection or
957 raw_malloc(), possibly as an object with card marking enabled,
958 if it has gc pointers in its var-sized part. 'length' should be
959 specified as 0 if the object is not varsized. The returned
960 object is fully initialized, but not zero-filled."""
961 #
962 # Here we really need a valid 'typeid', not 0 (as the JIT might
963 # try to send us if there is still a bug).
964 ll_assert(bool(self.combine(typeid, 0)),
965 "external_malloc: typeid == 0")
966 #
967 # Compute the total size, carefully checking for overflows.
968 size_gc_header = self.gcheaderbuilder.size_gc_header
969 nonvarsize = size_gc_header + self.fixed_size(typeid)
970 if length == 0:
971 # this includes the case of fixed-size objects, for which we
972 # should not even ask for the varsize_item_sizes().
973 totalsize = nonvarsize
974 elif length > 0:
975 # var-sized allocation with at least one item
976 itemsize = self.varsize_item_sizes(typeid)
977 try:
978 varsize = ovfcheck(itemsize * length)
979 totalsize = ovfcheck(nonvarsize + varsize)
980 except OverflowError:
981 raise MemoryError
982 else:
983 # negative length! This likely comes from an overflow
984 # earlier. We will just raise MemoryError here.
985 raise MemoryError
986 #
987 # If somebody calls this function a lot, we must eventually
988 # force a collection. We use threshold_reached(), which might
989 # be true now but become false at some point after a few calls
990 # to major_collection_step(). If there is really no memory,
991 # then when the major collection finishes it will raise
992 # MemoryError.
993 if self.threshold_reached(raw_malloc_usage(totalsize)):
994 self.minor_collection_with_major_progress(
995 raw_malloc_usage(totalsize) + self.nursery_size // 2)
996 #
997 # Check if the object would fit in the ArenaCollection.
998 # Also, an object allocated from ArenaCollection must be old.
999 if (raw_malloc_usage(totalsize) <= self.small_request_threshold
1000 and not alloc_young):
1001 #
1002 # Yes. Round up 'totalsize' (it cannot overflow and it
1003 # must remain <= self.small_request_threshold.)
1004 totalsize = llarena.round_up_for_allocation(totalsize)
1005 ll_assert(raw_malloc_usage(totalsize) <=
1006 self.small_request_threshold,
1007 "rounding up made totalsize > small_request_threshold")
1008 #
1009 # Allocate from the ArenaCollection. Don't clear it.
1010 result = self.ac.malloc(totalsize)
1011 #
1012 extra_flags = GCFLAG_TRACK_YOUNG_PTRS
1013 #
1014 else:
1015 # No, so proceed to allocate it externally with raw_malloc().
1016 # Check if we need to introduce the card marker bits area.
1017 if (self.card_page_indices <= 0 # <- this check is constant-folded
1018 or not self.has_gcptr_in_varsize(typeid) or
1019 raw_malloc_usage(totalsize) <= self.nonlarge_max):
1020 #
1021 # In these cases, we don't want a card marker bits area.
1022 # This case also includes all fixed-size objects.
1023 cardheadersize = 0
1024 extra_flags = 0
1025 #
1026 else:
1027 # Reserve N extra words containing card bits before the object.
1028 extra_words = self.card_marking_words_for_length(length)
1029 cardheadersize = WORD * extra_words
1030 extra_flags = GCFLAG_HAS_CARDS | GCFLAG_TRACK_YOUNG_PTRS
1031 # if 'alloc_young', then we also immediately set
1032 # GCFLAG_CARDS_SET, but without adding the object to
1033 # 'old_objects_with_cards_set'. In this way it should
1034 # never be added to that list as long as it is young.
1035 if alloc_young:
1036 extra_flags |= GCFLAG_CARDS_SET
1037 #
1038 # Detect very rare cases of overflows
1039 if raw_malloc_usage(totalsize) > (sys.maxint - (WORD-1)
1040 - cardheadersize):
1041 raise MemoryError("rare case of overflow")
1042 #
1043 # Now we know that the following computations cannot overflow.
1044 # Note that round_up_for_allocation() is also needed to get the
1045 # correct number added to 'rawmalloced_total_size'.
1046 allocsize = (cardheadersize + raw_malloc_usage(
1047 llarena.round_up_for_allocation(totalsize)))
1048 #
1049 # Allocate the object using arena_malloc(), which we assume here
1050 # is just the same as raw_malloc(), but allows the extra
1051 # flexibility of saying that we have extra words in the header.
1052 # The memory returned is not cleared.
1053 arena = llarena.arena_malloc(allocsize, 0)
1054 if not arena:
1055 raise MemoryError("cannot allocate large object")
1056 #
1057 # Reserve the card mark bits as a list of single bytes,
1058 # and clear these bytes.
1059 i = 0
1060 while i < cardheadersize:
1061 p = arena + i
1062 llarena.arena_reserve(p, llmemory.sizeof(lltype.Char))
1063 p.char[0] = '\x00'
1064 i += 1
1065 #
1066 # Reserve the actual object. (This is a no-op in C).
1067 result = arena + cardheadersize
1068 llarena.arena_reserve(result, totalsize)
1069 #
1070 # Record the newly allocated object and its full malloced size.
1071 # The object is young or old depending on the argument.
1072 self.rawmalloced_total_size += r_uint(allocsize)
1073 self.rawmalloced_peak_size = max(self.rawmalloced_total_size,
1074 self.rawmalloced_peak_size)
1075 if alloc_young:
1076 if not self.young_rawmalloced_objects:
1077 self.young_rawmalloced_objects = self.AddressDict()
1078 self.young_rawmalloced_objects.add(result + size_gc_header)
1079 else:
1080 self.old_rawmalloced_objects.append(result + size_gc_header)
1081 extra_flags |= GCFLAG_TRACK_YOUNG_PTRS
1082 #
1083 # Common code to fill the header and length of the object.
1084 self.init_gc_object(result, typeid, extra_flags)
1085 if self.is_varsize(typeid):
1086 offset_to_length = self.varsize_offset_to_length(typeid)
1087 (result + size_gc_header + offset_to_length).signed[0] = length
1088 return result + size_gc_header
1089
1090
1091 # ----------
1092 # Other functions in the GC API
1093
1094 def set_max_heap_size(self, size):
1095 self.max_heap_size = float(size)
1096 if self.max_heap_size > 0.0:
1097 if self.max_heap_size < self.next_major_collection_initial:
1098 self.next_major_collection_initial = self.max_heap_size
1099 if self.max_heap_size < self.next_major_collection_threshold:
1100 self.next_major_collection_threshold = self.max_heap_size
1101
1102 def raw_malloc_memory_pressure(self, sizehint, adr):
1103 # Decrement by 'sizehint' plus a very little bit extra. This
1104 # is needed e.g. for _rawffi, which may allocate a lot of tiny
1105 # arrays.
1106 self.next_major_collection_threshold -= (sizehint + 2 * WORD)
1107 if self.next_major_collection_threshold < 0:
1108 # cannot trigger a full collection now, but we can ensure
1109 # that one will occur very soon
1110 self.nursery_free = self.nursery_top
1111
1112 def can_optimize_clean_setarrayitems(self):
1113 if self.card_page_indices > 0:
1114 return False
1115 return MovingGCBase.can_optimize_clean_setarrayitems(self)
1116
1117 def can_move(self, obj):
1118 """Overrides the parent can_move()."""
1119 return self.is_in_nursery(obj)
1120
1121 def pin(self, obj):
1122 if self.pinned_objects_in_nursery >= self.max_number_of_pinned_objects:
1123 return False
1124 if not self.is_in_nursery(obj):
1125 # old objects are already non-moving, therefore pinning
1126 # makes no sense. If you run into this case, you maybe forgot
1127 # to check can_move(obj).
1128 return False
1129 if self._is_pinned(obj):
1130 # already pinned, we do not allow to pin it again.
1131 # Reason: It would be possible that the first caller unpins
1132 # while the second caller thinks it's still pinned.
1133 return False
1134 #
1135 obj_type_id = self.get_type_id(obj)
1136 if self.cannot_pin(obj_type_id):
1137 # objects containing GC pointers can't be pinned. If we would add
1138 # it, we would have to track all pinned objects and trace them
1139 # every minor collection to make sure the referenced object are
1140 # kept alive. Right now this is not a use case that's needed.
1141 # The check above also tests for being a less common kind of
1142 # object: a weakref, or one with any kind of finalizer.
1143 return False
1144 #
1145 self.header(obj).tid |= GCFLAG_PINNED
1146 self.pinned_objects_in_nursery += 1
1147 return True
1148
1149
1150 def unpin(self, obj):
1151 ll_assert(self._is_pinned(obj),
1152 "unpin: object is already not pinned")
1153 #
1154 self.header(obj).tid &= ~GCFLAG_PINNED
1155 self.pinned_objects_in_nursery -= 1
1156
1157 def _is_pinned(self, obj):
1158 return (self.header(obj).tid & GCFLAG_PINNED) != 0
1159
1160 def shrink_array(self, obj, smallerlength):
1161 #
1162 # Only objects in the nursery can be "resized". Resizing them
1163 # means recording that they have a smaller size, so that when
1164 # moved out of the nursery, they will consume less memory.
1165 # In particular, an array with GCFLAG_HAS_CARDS is never resized.
1166 # Also, a nursery object with GCFLAG_HAS_SHADOW is not resized
1167 # either, as this would potentially loose part of the memory in
1168 # the already-allocated shadow.
1169 if not self.is_in_nursery(obj):
1170 return False
1171 if self.header(obj).tid & GCFLAG_HAS_SHADOW:
1172 return False
1173 #
1174 size_gc_header = self.gcheaderbuilder.size_gc_header
1175 typeid = self.get_type_id(obj)
1176 totalsmallersize = (
1177 size_gc_header + self.fixed_size(typeid) +
1178 self.varsize_item_sizes(typeid) * smallerlength)
1179 llarena.arena_shrink_obj(obj - size_gc_header, totalsmallersize)
1180 #
1181 offset_to_length = self.varsize_offset_to_length(typeid)
1182 (obj + offset_to_length).signed[0] = smallerlength
1183 return True
1184
1185 # ----------
1186 # Simple helpers
1187
1188 def get_type_id(self, obj):
1189 tid = self.header(obj).tid
1190 return llop.extract_ushort(llgroup.HALFWORD, tid)
1191
1192 def combine(self, typeid16, flags):
1193 return llop.combine_ushort(lltype.Signed, typeid16, flags)
1194
1195 def init_gc_object(self, addr, typeid16, flags=0):
1196 # The default 'flags' is zero. The flags GCFLAG_NO_xxx_PTRS
1197 # have been chosen to allow 'flags' to be zero in the common
1198 # case (hence the 'NO' in their name).
1199 hdr = llmemory.cast_adr_to_ptr(addr, lltype.Ptr(self.HDR))
1200 hdr.tid = self.combine(typeid16, flags)
1201
1202 def init_gc_object_immortal(self, addr, typeid16, flags=0):
1203 # For prebuilt GC objects, the flags must contain
1204 # GCFLAG_NO_xxx_PTRS, at least initially.
1205 flags |= GCFLAG_NO_HEAP_PTRS | GCFLAG_TRACK_YOUNG_PTRS
1206 self.init_gc_object(addr, typeid16, flags)
1207
1208 def is_in_nursery(self, addr):
1209 ll_assert(llmemory.cast_adr_to_int(addr) & 1 == 0,
1210 "odd-valued (i.e. tagged) pointer unexpected here")
1211 return self.nursery <= addr < self.nursery + self.nursery_size
1212
1213 def is_young_object(self, addr):
1214 # Check if the object at 'addr' is young.
1215 if not self.is_valid_gc_object(addr):
1216 return False # filter out tagged pointers explicitly.
1217 if self.is_in_nursery(addr):
1218 return True # addr is in the nursery
1219 # Else, it may be in the set 'young_rawmalloced_objects'
1220 return (bool(self.young_rawmalloced_objects) and
1221 self.young_rawmalloced_objects.contains(addr))
1222
1223 def _debug_print_flags(self, addr):
1224 if self.is_in_nursery(addr):
1225 print "in nursery"
1226 tid = self.header(addr).tid
1227 for name, value in flagnames_and_values:
1228 if tid & value:
1229 print name
1230
1231 def debug_is_old_object(self, addr):
1232 return (self.is_valid_gc_object(addr)
1233 and not self.is_young_object(addr))
1234
1235 def is_forwarded(self, obj):
1236 """Returns True if the nursery obj is marked as forwarded.
1237 Implemented a bit obscurely by checking an unrelated flag
1238 that can never be set on a young object -- except if tid == -42.
1239 """
1240 ll_assert(self.is_in_nursery(obj),
1241 "Can't forward an object outside the nursery.")
1242 tid = self.header(obj).tid
1243 result = (tid & GCFLAG_FINALIZATION_ORDERING != 0)
1244 if result:
1245 ll_assert(tid == -42, "bogus header for young obj")
1246 else:
1247 ll_assert(bool(tid), "bogus header (1)")
1248 ll_assert(tid & -_GCFLAG_FIRST_UNUSED == 0, "bogus header (2)")
1249 return result
1250
1251 def get_forwarding_address(self, obj):
1252 return llmemory.cast_adr_to_ptr(obj, FORWARDSTUBPTR).forw
1253
1254 def get_possibly_forwarded_type_id(self, obj):
1255 if self.is_in_nursery(obj) and self.is_forwarded(obj):
1256 obj = self.get_forwarding_address(obj)
1257 return self.get_type_id(obj)
1258
1259 def get_possibly_forwarded_tid(self, obj):
1260 if self.is_in_nursery(obj) and self.is_forwarded(obj):
1261 obj = self.get_forwarding_address(obj)
1262 return self.header(obj).tid
1263
1264 def get_total_memory_used(self):
1265 """Return the total memory used, not counting any object in the
1266 nursery: only objects in the ArenaCollection or raw-malloced.
1267 """
1268 return self.ac.total_memory_used + self.rawmalloced_total_size
1269
1270 def get_total_memory_alloced(self):
1271 """ Return the total memory allocated
1272 """
1273 return self.ac.total_memory_alloced + self.rawmalloced_total_size
1274
1275 def get_peak_memory_alloced(self):
1276 """ Return the peak memory ever allocated. The peaks
1277 can be at different times, but we just don't worry for now
1278 """
1279 return self.ac.peak_memory_alloced + self.rawmalloced_peak_size
1280
1281 def get_peak_memory_used(self):
1282 """ Return the peak memory GC felt ever responsible for
1283 """
1284 mem_allocated = max(self.ac.peak_memory_used,
1285 self.ac.total_memory_used)
1286 return mem_allocated + self.rawmalloced_peak_size
1287
1288 def threshold_reached(self, extra=0):
1289 return (self.next_major_collection_threshold -
1290 float(self.get_total_memory_used())) < float(extra)
1291
1292 def card_marking_words_for_length(self, length):
1293 # --- Unoptimized version:
1294 #num_bits = ((length-1) >> self.card_page_shift) + 1
1295 #return (num_bits + (LONG_BIT - 1)) >> LONG_BIT_SHIFT
1296 # --- Optimized version:
1297 return intmask(
1298 ((r_uint(length) + r_uint((LONG_BIT << self.card_page_shift) - 1)) >>
1299 (self.card_page_shift + LONG_BIT_SHIFT)))
1300
1301 def card_marking_bytes_for_length(self, length):
1302 # --- Unoptimized version:
1303 #num_bits = ((length-1) >> self.card_page_shift) + 1
1304 #return (num_bits + 7) >> 3
1305 # --- Optimized version:
1306 return intmask(
1307 ((r_uint(length) + r_uint((8 << self.card_page_shift) - 1)) >>
1308 (self.card_page_shift + 3)))
1309
1310 def debug_check_consistency(self):
1311 if self.DEBUG:
1312 ll_assert(not self.young_rawmalloced_objects,
1313 "young raw-malloced objects in a major collection")
1314 ll_assert(not self.young_objects_with_weakrefs.non_empty(),
1315 "young objects with weakrefs in a major collection")
1316
1317 if self.raw_malloc_might_sweep.non_empty():
1318 ll_assert(self.gc_state == STATE_SWEEPING,
1319 "raw_malloc_might_sweep must be empty outside SWEEPING")
1320
1321 if self.gc_state == STATE_MARKING:
1322 self.objects_to_trace.foreach(self._check_not_in_nursery, None)
1323 self.more_objects_to_trace.foreach(self._check_not_in_nursery,
1324 None)
1325 self._debug_objects_to_trace_dict1 = \
1326 self.objects_to_trace.stack2dict()
1327 self._debug_objects_to_trace_dict2 = \
1328 self.more_objects_to_trace.stack2dict()
1329 self._debug_objects_to_trace_dict3 = \
1330 self.prebuilt_root_objects.stack2dict()
1331 MovingGCBase.debug_check_consistency(self)
1332 self._debug_objects_to_trace_dict3.delete()
1333 self._debug_objects_to_trace_dict2.delete()
1334 self._debug_objects_to_trace_dict1.delete()
1335 else:
1336 MovingGCBase.debug_check_consistency(self)
1337
1338 def _check_not_in_nursery(self, obj, ignore):
1339 ll_assert(not self.is_in_nursery(obj),
1340 "'objects_to_trace' contains a nursery object")
1341
1342 def debug_check_object(self, obj):
1343 # We are after a minor collection, and possibly after a major
1344 # collection step. No object should be in the nursery (except
1345 # pinned ones)
1346 if not self._is_pinned(obj):
1347 ll_assert(not self.is_in_nursery(obj),
1348 "object in nursery after collection")
1349 ll_assert(self.header(obj).tid & GCFLAG_VISITED_RMY == 0,
1350 "GCFLAG_VISITED_RMY after collection")
1351 ll_assert(self.header(obj).tid & GCFLAG_PINNED == 0,
1352 "GCFLAG_PINNED outside the nursery after collection")
1353 else:
1354 ll_assert(self.is_in_nursery(obj),
1355 "pinned object not in nursery")
1356
1357 if self.gc_state == STATE_SCANNING:
1358 self._debug_check_object_scanning(obj)
1359 elif self.gc_state == STATE_MARKING:
1360 self._debug_check_object_marking(obj)
1361 elif self.gc_state == STATE_SWEEPING:
1362 self._debug_check_object_sweeping(obj)
1363 elif self.gc_state == STATE_FINALIZING:
1364 self._debug_check_object_finalizing(obj)
1365 else:
1366 ll_assert(False, "unknown gc_state value")
1367
1368 def _debug_check_object_marking(self, obj):
1369 if self.header(obj).tid & GCFLAG_VISITED != 0:
1370 # A black object. Should NEVER point to a white object.
1371 self.trace(obj, self.make_callback('_debug_check_not_white'), self, None)
1372 # During marking, all visited (black) objects should always have
1373 # the GCFLAG_TRACK_YOUNG_PTRS flag set, for the write barrier to
1374 # trigger --- at least if they contain any gc ptr. We are just
1375 # after a minor or major collection here, so we can't see the
1376 # object state VISITED & ~WRITE_BARRIER.
1377 typeid = self.get_type_id(obj)
1378 if self.has_gcptr(typeid):
1379 ll_assert(self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS != 0,
1380 "black object without GCFLAG_TRACK_YOUNG_PTRS")
1381
1382 def _debug_check_not_white(self, root, ignored):
1383 obj = root.address[0]
1384 if self.header(obj).tid & GCFLAG_VISITED != 0:
1385 pass # black -> black
1386 elif (self._debug_objects_to_trace_dict1.contains(obj) or
1387 self._debug_objects_to_trace_dict2.contains(obj) or
1388 self._debug_objects_to_trace_dict3.contains(obj)):
1389 pass # black -> gray
1390 elif self.header(obj).tid & GCFLAG_NO_HEAP_PTRS != 0:
1391 pass # black -> white-but-prebuilt-so-dont-care
1392 elif self._is_pinned(obj):
1393 # black -> pinned: the pinned object is a white one as
1394 # every minor collection visits them and takes care of
1395 # visiting pinned objects.
1396 # XXX (groggi) double check with fijal/armin
1397 pass # black -> pinned
1398 else:
1399 ll_assert(False, "black -> white pointer found")
1400
1401 def _debug_check_object_sweeping(self, obj):
1402 # We see only reachable objects here. They all start as VISITED
1403 # but this flag is progressively removed in the sweeping phase.
1404
1405 # All objects should have this flag, except if they
1406 # don't have any GC pointer or are pinned objects
1407 typeid = self.get_type_id(obj)
1408 if self.has_gcptr(typeid) and not self._is_pinned(obj):
1409 ll_assert(self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS != 0,
1410 "missing GCFLAG_TRACK_YOUNG_PTRS")
1411 # the GCFLAG_FINALIZATION_ORDERING should not be set between coll.
1412 ll_assert(self.header(obj).tid & GCFLAG_FINALIZATION_ORDERING == 0,
1413 "unexpected GCFLAG_FINALIZATION_ORDERING")
1414 # the GCFLAG_CARDS_SET should not be set between collections
1415 ll_assert(self.header(obj).tid & GCFLAG_CARDS_SET == 0,
1416 "unexpected GCFLAG_CARDS_SET")
1417 if self.header(obj).tid & GCFLAG_NO_HEAP_PTRS:
1418 ll_assert(bool(self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS),
1419 "GCFLAG_NO_HEAP_PTRS is set, but GCFLAG_TRACK_YOUNG_PTRS isn't!")
1420 # if the GCFLAG_HAS_CARDS is set, check that all bits are zero now
1421 if self.header(obj).tid & GCFLAG_HAS_CARDS:
1422 if self.card_page_indices <= 0:
1423 ll_assert(False, "GCFLAG_HAS_CARDS but not using card marking")
1424 return
1425 typeid = self.get_type_id(obj)
1426 ll_assert(self.has_gcptr_in_varsize(typeid),
1427 "GCFLAG_HAS_CARDS but not has_gcptr_in_varsize")
1428 ll_assert(self.header(obj).tid & GCFLAG_NO_HEAP_PTRS == 0,
1429 "GCFLAG_HAS_CARDS && GCFLAG_NO_HEAP_PTRS")
1430 offset_to_length = self.varsize_offset_to_length(typeid)
1431 length = (obj + offset_to_length).signed[0]
1432 extra_words = self.card_marking_words_for_length(length)
1433 #
1434 size_gc_header = self.gcheaderbuilder.size_gc_header
1435 p = llarena.getfakearenaaddress(obj - size_gc_header)
1436 i = extra_words * WORD
1437 while i > 0:
1438 p -= 1
1439 ll_assert(p.char[0] == '\x00',
1440 "the card marker bits are not cleared")
1441 i -= 1
1442
1443 def _debug_check_object_finalizing(self, obj):
1444 # Same invariants as STATE_SCANNING.
1445 self._debug_check_object_scanning(obj)
1446
1447 def _debug_check_object_scanning(self, obj):
1448 # This check is called before scanning starts.
1449 # Scanning is done in a single step.
1450 # the GCFLAG_VISITED should not be set between collections
1451 ll_assert(self.header(obj).tid & GCFLAG_VISITED == 0,
1452 "unexpected GCFLAG_VISITED")
1453
1454 # All other invariants from the sweeping phase should still be
1455 # satisfied.
1456 self._debug_check_object_sweeping(obj)
1457
1458
1459 # ----------
1460 # Write barrier
1461
1462 # for the JIT: a minimal description of the write_barrier() method
1463 # (the JIT assumes it is of the shape
1464 # "if addr_struct.int0 & JIT_WB_IF_FLAG: remember_young_pointer()")
1465 JIT_WB_IF_FLAG = GCFLAG_TRACK_YOUNG_PTRS
1466
1467 # for the JIT to generate custom code corresponding to the array
1468 # write barrier for the simplest case of cards. If JIT_CARDS_SET
1469 # is already set on an object, it will execute code like this:
1470 # MOV eax, index
1471 # SHR eax, JIT_WB_CARD_PAGE_SHIFT
1472 # XOR eax, -8
1473 # BTS [object], eax
1474 if TRANSLATION_PARAMS['card_page_indices'] > 0:
1475 JIT_WB_CARDS_SET = GCFLAG_CARDS_SET
1476 JIT_WB_CARD_PAGE_SHIFT = 1
1477 while ((1 << JIT_WB_CARD_PAGE_SHIFT) !=
1478 TRANSLATION_PARAMS['card_page_indices']):
1479 JIT_WB_CARD_PAGE_SHIFT += 1
1480
1481 @classmethod
1482 def JIT_max_size_of_young_obj(cls):
1483 return cls.TRANSLATION_PARAMS['large_object']
1484
1485 @classmethod
1486 def JIT_minimal_size_in_nursery(cls):
1487 return cls.minimal_size_in_nursery
1488
1489 def write_barrier(self, addr_struct):
1490 # see OP_GC_BIT in translator/c/gc.py
1491 if llop.gc_bit(lltype.Signed, self.header(addr_struct),
1492 GCFLAG_TRACK_YOUNG_PTRS):
1493 self.remember_young_pointer(addr_struct)
1494
1495 def write_barrier_from_array(self, addr_array, index):
1496 if llop.gc_bit(lltype.Signed, self.header(addr_array),
1497 GCFLAG_TRACK_YOUNG_PTRS):
1498 if self.card_page_indices > 0:
1499 self.remember_young_pointer_from_array2(addr_array, index)
1500 else:
1501 self.remember_young_pointer(addr_array)
1502
1503 @always_inline
1504 def _remember_young_pointer_inlined(self, addr):
1505 #
1506 # We need to remove the flag GCFLAG_TRACK_YOUNG_PTRS and add
1507 # the object to the list 'old_objects_pointing_to_young'.
1508 # We know that 'addr' cannot be in the nursery,
1509 # because nursery objects never have the flag
1510 # GCFLAG_TRACK_YOUNG_PTRS to start with. Note that in
1511 # theory we don't need to do that if the pointer that we're
1512 # writing into the object isn't pointing to a young object.
1513 # However, it isn't really a win, because then sometimes
1514 # we're going to call this function a lot of times for the
1515 # same object; moreover we'd need to pass the 'newvalue' as
1516 # an argument here. The JIT has always called a
1517 # 'newvalue'-less version, too. Moreover, the incremental
1518 # GC nowadays relies on this fact.
1519 self.old_objects_pointing_to_young.append(addr)
1520 objhdr = self.header(addr)
1521 tid = objhdr.tid
1522 tid &= ~GCFLAG_TRACK_YOUNG_PTRS
1523 #
1524 # Second part: if 'addr' is actually a prebuilt GC
1525 # object and it's the first time we see a write to it, we
1526 # add it to the list 'prebuilt_root_objects'.
1527 if tid & GCFLAG_NO_HEAP_PTRS:
1528 tid &= ~GCFLAG_NO_HEAP_PTRS
1529 self.prebuilt_root_objects.append(addr)
1530 objhdr.tid = tid
1531
1532 def _init_writebarrier_logic(self):
1533 DEBUG = self.DEBUG
1534 # The purpose of attaching remember_young_pointer to the instance
1535 # instead of keeping it as a regular method is to
1536 # make the code in write_barrier() marginally smaller
1537 # (which is important because it is inlined *everywhere*).
1538 def remember_young_pointer(addr_struct):
1539 # 'addr_struct' is the address of the object in which we write.
1540 # We know that 'addr_struct' has GCFLAG_TRACK_YOUNG_PTRS so far.
1541 #
1542 if DEBUG: # note: PYPY_GC_DEBUG=1 does not enable this
1543 ll_assert(self.debug_is_old_object(addr_struct) or
1544 self.header(addr_struct).tid & GCFLAG_HAS_CARDS != 0,
1545 "young object with GCFLAG_TRACK_YOUNG_PTRS and no cards")
1546 self._remember_young_pointer_inlined(addr_struct)
1547
1548 remember_young_pointer._dont_inline_ = True
1549 self.remember_young_pointer = remember_young_pointer
1550 #
1551 if self.card_page_indices > 0:
1552 self._init_writebarrier_with_card_marker()
1553
1554
1555 def _init_writebarrier_with_card_marker(self):
1556 DEBUG = self.DEBUG
1557 def remember_young_pointer_from_array2(addr_array, index):
1558 # 'addr_array' is the address of the object in which we write,
1559 # which must have an array part; 'index' is the index of the
1560 # item that is (or contains) the pointer that we write.
1561 # We know that 'addr_array' has GCFLAG_TRACK_YOUNG_PTRS so far.
1562 #
1563 objhdr = self.header(addr_array)
1564 if objhdr.tid & GCFLAG_HAS_CARDS == 0:
1565 #
1566 if DEBUG: # note: PYPY_GC_DEBUG=1 does not enable this
1567 ll_assert(self.debug_is_old_object(addr_array),
1568 "young array with no card but GCFLAG_TRACK_YOUNG_PTRS")
1569 #
1570 # no cards, use default logic
1571 self._remember_young_pointer_inlined(addr_array)
1572 return
1573 #
1574 # 'addr_array' is a raw_malloc'ed array with card markers
1575 # in front. Compute the index of the bit to set:
1576 bitindex = index >> self.card_page_shift
1577 byteindex = bitindex >> 3
1578 bitmask = 1 << (bitindex & 7)
1579 #
1580 # If the bit is already set, leave now.
1581 addr_byte = self.get_card(addr_array, byteindex)
1582 byte = ord(addr_byte.char[0])
1583 if byte & bitmask:
1584 return
1585 #
1586 # We set the flag even if the newly written address does not
1587 # actually point to the nursery. this is for two reasons:
1588 # - during the marking phase it's a correctness question. we rely
1589 # on the write barrier to find out which black objects have been
1590 # mutated and need to be rescanned at some point during the
1591 # marking phase.
1592 # - it's cheaper to call remember_young_pointer_from_array2 if it
1593 # does not take 3 arguments
1594 addr_byte.char[0] = chr(byte | bitmask)
1595 #
1596 if objhdr.tid & GCFLAG_CARDS_SET == 0:
1597 self.old_objects_with_cards_set.append(addr_array)
1598 objhdr.tid |= GCFLAG_CARDS_SET
1599
1600 remember_young_pointer_from_array2._dont_inline_ = True
1601 ll_assert(self.card_page_indices > 0,
1602 "non-positive card_page_indices")
1603 self.remember_young_pointer_from_array2 = (
1604 remember_young_pointer_from_array2)
1605
1606 def jit_remember_young_pointer_from_array(addr_array):
1607 # minimal version of the above, with just one argument,
1608 # called by the JIT when GCFLAG_TRACK_YOUNG_PTRS is set
1609 # but GCFLAG_CARDS_SET is cleared. This tries to set
1610 # GCFLAG_CARDS_SET if possible; otherwise, it falls back
1611 # to remember_young_pointer().
1612 objhdr = self.header(addr_array)
1613 if objhdr.tid & GCFLAG_HAS_CARDS:
1614 self.old_objects_with_cards_set.append(addr_array)
1615 objhdr.tid |= GCFLAG_CARDS_SET
1616 else:
1617 self.remember_young_pointer(addr_array)
1618
1619 self.jit_remember_young_pointer_from_array = (
1620 jit_remember_young_pointer_from_array)
1621
1622 def get_card(self, obj, byteindex):
1623 size_gc_header = self.gcheaderbuilder.size_gc_header
1624 addr_byte = obj - size_gc_header
1625 return llarena.getfakearenaaddress(addr_byte) + (~byteindex)
1626
1627
1628 def writebarrier_before_copy(self, source_addr, dest_addr,
1629 source_start, dest_start, length):
1630 """ This has the same effect as calling writebarrier over
1631 each element in dest copied from source, except it might reset
1632 one of the following flags a bit too eagerly, which means we'll have
1633 a bit more objects to track, but being on the safe side.
1634 """
1635 # obscuuuure. The flag 'updated_old_objects_pointing_to_pinned'
1636 # is set to True when 'old_objects_pointing_to_pinned' is modified.
1637 # Here, when it was modified, then we do a write_barrier() on
1638 # all items in that list (there should only be a small number,
1639 # so we don't care). The goal is that the logic that follows below
1640 # works as expected...
1641 if self.updated_old_objects_pointing_to_pinned:
1642 self.old_objects_pointing_to_pinned.foreach(
1643 self._wb_old_object_pointing_to_pinned, None)
1644 self.updated_old_objects_pointing_to_pinned = False
1645 #
1646 source_hdr = self.header(source_addr)
1647 dest_hdr = self.header(dest_addr)
1648 if dest_hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
1649 return True
1650 # ^^^ a fast path of write-barrier
1651 #
1652 if (self.card_page_indices > 0 and # check constant-folded
1653 source_hdr.tid & GCFLAG_HAS_CARDS != 0):
1654 #
1655 if source_hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
1656 # The source object may have random young pointers.
1657 # Return False to mean "do it manually in ll_arraycopy".
1658 return False
1659 #
1660 if dest_hdr.tid & GCFLAG_HAS_CARDS == 0:
1661 # The dest object doesn't have cards. Do it manually.
1662 return False
1663 ll_assert(dest_hdr.tid & GCFLAG_NO_HEAP_PTRS == 0,
1664 "prebuilt object with cards is not supported")
1665 #
1666 if source_hdr.tid & GCFLAG_CARDS_SET == 0:
1667 # The source object has no young pointers at all. Basically we
1668 # are done.
1669 # But, somewhat obscurely, we need to still set
1670 # GCFLAG_CARDS_SET on dest_hdr if we're in the marking phase,
1671 # without actually marking any cards. the reason for this is
1672 # the whole array needs to be turned gray and rescanned if it's
1673 # currently black, which happens at the end of
1674 # collect_cardrefs_to_nursery
1675 if self.gc_state == STATE_MARKING:
1676 if dest_hdr.tid & GCFLAG_CARDS_SET == 0:
1677 self.old_objects_with_cards_set.append(dest_addr)
1678 dest_hdr.tid |= GCFLAG_CARDS_SET
1679 return True
1680 #
1681 if source_start != 0 or dest_start != 0:
1682 # Misaligned. Do it manually.
1683 return False
1684 #
1685 self.manually_copy_card_bits(source_addr, dest_addr, length)
1686 return True
1687 # NB: if we are marking, we must not inspect the state of the
1688 # GCFLAG_TRACK_YOUNG_PTRS of source_addr here, because in the marking
1689 # phase we rely on the write barrier to also turn black objects back
1690 # into gray ones. see also the end of collect_cardrefs_to_nursery
1691 if source_hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0 or self.gc_state == STATE_MARKING:
1692 # there might be in source a pointer to a young object
1693 self._remember_young_pointer_inlined(dest_addr)
1694 #
1695 if dest_hdr.tid & GCFLAG_NO_HEAP_PTRS:
1696 if source_hdr.tid & GCFLAG_NO_HEAP_PTRS == 0:
1697 dest_hdr.tid &= ~GCFLAG_NO_HEAP_PTRS
1698 self.prebuilt_root_objects.append(dest_addr)
1699 return True
1700
1701 def writebarrier_before_move(self, array_addr):
1702 """If 'array_addr' uses cards, then this has the same effect as
1703 a call to the generic writebarrier, effectively generalizing the
1704 cards to "any item may be young".
1705 """
1706 if self.card_page_indices <= 0: # check constant-folded
1707 return # no cards, nothing to do
1708 #
1709 array_hdr = self.header(array_addr)
1710 if array_hdr.tid & GCFLAG_CARDS_SET != 0:
1711 self.write_barrier(array_addr)
1712
1713 def manually_copy_card_bits(self, source_addr, dest_addr, length):
1714 # manually copy the individual card marks from source to dest
1715 ll_assert(self.card_page_indices > 0,
1716 "non-positive card_page_indices")
1717 bytes = self.card_marking_bytes_for_length(length)
1718 #
1719 anybyte = 0
1720 i = 0
1721 while i < bytes:
1722 addr_srcbyte = self.get_card(source_addr, i)
1723 addr_dstbyte = self.get_card(dest_addr, i)
1724 byte = ord(addr_srcbyte.char[0])
1725 anybyte |= byte
1726 addr_dstbyte.char[0] = chr(ord(addr_dstbyte.char[0]) | byte)
1727 i += 1
1728 #
1729 if anybyte:
1730 dest_hdr = self.header(dest_addr)
1731 if dest_hdr.tid & GCFLAG_CARDS_SET == 0:
1732 self.old_objects_with_cards_set.append(dest_addr)
1733 dest_hdr.tid |= GCFLAG_CARDS_SET
1734
1735 def _wb_old_object_pointing_to_pinned(self, obj, ignore):
1736 self.write_barrier(obj)
1737
1738 def record_pinned_object_with_shadow(self, obj, new_shadow_object_dict):
1739 # checks if the pinned object has a shadow and if so add it to the
1740 # dict of shadows.
1741 obj = obj + self.gcheaderbuilder.size_gc_header
1742 shadow = self.nursery_objects_shadows.get(obj)
1743 if shadow != llmemory.NULL:
1744 if self.gc_state == STATE_MARKING:
1745 # if were in the marking phase, we need to make sure the shadow
1746 # stays alive by marking it black.
1747 self.header(shadow).tid |= GCFLAG_VISITED
1748 # this is only safe because pinned objects cannot themselves hold
1749 # references (otherwise we would have to mark the object gray
1750 # instead and add it to more_objects_to_trace)
1751 typeid = self.get_type_id(obj)
1752 ll_assert(not self.has_gcptr(typeid), "pinned object with gcptrs not supported")
1753 new_shadow_object_dict.setitem(obj, shadow)
1754
1755 def register_finalizer(self, fq_index, gcobj):
1756 from rpython.rtyper.lltypesystem import rffi
1757 obj = llmemory.cast_ptr_to_adr(gcobj)
1758 fq_index = rffi.cast(llmemory.Address, fq_index)
1759 self.probably_young_objects_with_finalizers.append(obj)
1760 self.probably_young_objects_with_finalizers.append(fq_index)
1761
1762 # ----------
1763 # Nursery collection
1764
1765 def _minor_collection(self):
1766 """Perform a minor collection: find the objects from the nursery
1767 that remain alive and move them out."""
1768 #
1769 start = time.time()
1770 debug_start("gc-minor")
1771 #
1772 # All nursery barriers are invalid from this point on. They
1773 # are evaluated anew as part of the minor collection.
1774 self.nursery_barriers.delete()
1775 #
1776 # Keeps track of surviving pinned objects. See also '_trace_drag_out()'
1777 # where this stack is filled. Pinning an object only prevents it from
1778 # being moved, not from being collected if it is not reachable anymore.
1779 self.surviving_pinned_objects = self.AddressStack()
1780 # The following counter keeps track of alive and pinned young objects
1781 # inside the nursery. We reset it here and increase it in
1782 # '_trace_drag_out()'.
1783 any_pinned_object_from_earlier = self.any_pinned_object_kept
1784 self.pinned_objects_in_nursery = 0
1785 self.any_pinned_object_kept = False
1786 #
1787 # Before everything else, remove from 'old_objects_pointing_to_young'
1788 # the young arrays.
1789 if self.young_rawmalloced_objects:
1790 self.remove_young_arrays_from_old_objects_pointing_to_young()
1791 #
1792 # A special step in the STATE_MARKING phase.
1793 if self.gc_state == STATE_MARKING:
1794 # Copy the 'old_objects_pointing_to_young' list so far to
1795 # 'more_objects_to_trace'. Turn black objects back to gray.
1796 # This is because these are precisely the old objects that
1797 # have been modified and need rescanning.
1798 self.old_objects_pointing_to_young.foreach(
1799 self._add_to_more_objects_to_trace_if_black, None)
1800 # Old black objects pointing to pinned objects that may no
1801 # longer be pinned now: careful,
1802 # _visit_old_objects_pointing_to_pinned() will move the
1803 # previously-pinned object, and that creates a white object.
1804 # We prevent the "black->white" situation by forcing the
1805 # old black object to become gray again.
1806 self.old_objects_pointing_to_pinned.foreach(
1807 self._add_to_more_objects_to_trace_if_black, None)
1808 #
1809 # First, find the roots that point to young objects. All nursery
1810 # objects found are copied out of the nursery, and the occasional
1811 # young raw-malloced object is flagged with GCFLAG_VISITED_RMY.
1812 # Note that during this step, we ignore references to further
1813 # young objects; only objects directly referenced by roots
1814 # are copied out or flagged. They are also added to the list
1815 # 'old_objects_pointing_to_young'.
1816 self.nursery_surviving_size = 0
1817 self.collect_roots_in_nursery(any_pinned_object_from_earlier)
1818 #
1819 # visit all objects that are known for pointing to pinned
1820 # objects. This way we populate 'surviving_pinned_objects'
1821 # with pinned object that are (only) visible from an old
1822 # object.
1823 # Additionally we create a new list as it may be that an old object
1824 # no longer points to a pinned one. Such old objects won't be added
1825 # again to 'old_objects_pointing_to_pinned'.
1826 if self.old_objects_pointing_to_pinned.non_empty():
1827 current_old_objects_pointing_to_pinned = \
1828 self.old_objects_pointing_to_pinned
1829 self.old_objects_pointing_to_pinned = self.AddressStack()
1830 current_old_objects_pointing_to_pinned.foreach(
1831 self._visit_old_objects_pointing_to_pinned, None)
1832 current_old_objects_pointing_to_pinned.delete()
1833 #
1834 # visit the P list from rawrefcount, if enabled.
1835 if self.rrc_enabled:
1836 self.rrc_minor_collection_trace()
1837 #
1838 # visit the "probably young" objects with finalizers. They
1839 # all survive, except if IGNORE_FINALIZER is set.
1840 if self.probably_young_objects_with_finalizers.non_empty():
1841 self.deal_with_young_objects_with_finalizers()
1842 #
1843 while True:
1844 # If we are using card marking, do a partial trace of the arrays
1845 # that are flagged with GCFLAG_CARDS_SET.
1846 if self.card_page_indices > 0:
1847 self.collect_cardrefs_to_nursery()
1848 #
1849 # Now trace objects from 'old_objects_pointing_to_young'.
1850 # All nursery objects they reference are copied out of the
1851 # nursery, and again added to 'old_objects_pointing_to_young'.
1852 # All young raw-malloced object found are flagged
1853 # GCFLAG_VISITED_RMY.
1854 # We proceed until 'old_objects_pointing_to_young' is empty.
1855 self.collect_oldrefs_to_nursery()
1856 #
1857 # We have to loop back if collect_oldrefs_to_nursery caused
1858 # new objects to show up in old_objects_with_cards_set
1859 if self.card_page_indices > 0:
1860 if self.old_objects_with_cards_set.non_empty():
1861 continue
1862 break
1863 #
1864 # Now all live nursery objects should be out. Update the young
1865 # weakrefs' targets.
1866 if self.young_objects_with_weakrefs.non_empty():
1867 self.invalidate_young_weakrefs()
1868 if self.young_objects_with_destructors.non_empty():
1869 self.deal_with_young_objects_with_destructors()
1870 #
1871 # Clear this mapping. Without pinned objects we just clear the dict
1872 # as all objects in the nursery are dragged out of the nursery and, if
1873 # needed, into their shadow. However, if we have pinned objects we have
1874 # to check if those pinned object have a shadow and keep a dictionary
1875 # filled with shadow information for them as they stay in the nursery.
1876 if self.nursery_objects_shadows.length() > 0:
1877 if self.surviving_pinned_objects.non_empty():
1878 new_shadows = self.AddressDict()
1879 self.surviving_pinned_objects.foreach(
1880 self.record_pinned_object_with_shadow, new_shadows)
1881 self.nursery_objects_shadows.delete()
1882 self.nursery_objects_shadows = new_shadows
1883 else:
1884 self.nursery_objects_shadows.clear()
1885 #
1886 # visit the P and O lists from rawrefcount, if enabled.
1887 if self.rrc_enabled:
1888 self.rrc_minor_collection_free()
1889 #
1890 # Walk the list of young raw-malloced objects, and either free
1891 # them or make them old.
1892 if self.young_rawmalloced_objects:
1893 self.free_young_rawmalloced_objects()
1894 #
1895 # All live nursery objects are out of the nursery or pinned inside
1896 # the nursery. Create nursery barriers to protect the pinned objects,
1897 # fill the rest of the nursery with zeros and reset the current nursery
1898 # pointer.
1899 size_gc_header = self.gcheaderbuilder.size_gc_header
1900 nursery_barriers = self.AddressDeque()
1901 prev = self.nursery
1902 self.surviving_pinned_objects.sort()
1903 ll_assert(
1904 self.pinned_objects_in_nursery == \
1905 self.surviving_pinned_objects.length(),
1906 "pinned_objects_in_nursery != surviving_pinned_objects.length()")
1907 while self.surviving_pinned_objects.non_empty():
1908 #
1909 cur = self.surviving_pinned_objects.pop()
1910 ll_assert(
1911 cur >= prev, "pinned objects encountered in backwards order")
1912 #
1913 # clear the arena between the last pinned object (or arena start)
1914 # and the pinned object
1915 free_range_size = llarena.getfakearenaaddress(cur) - prev
1916 if self.gc_nursery_debug:
1917 llarena.arena_reset(prev, free_range_size, 3)
1918 else:
1919 llarena.arena_reset(prev, free_range_size, 0)
1920 #
1921 # clean up object's flags
1922 obj = cur + size_gc_header
1923 self.header(obj).tid &= ~GCFLAG_VISITED
1924 #
1925 # create a new nursery barrier for the pinned object
1926 nursery_barriers.append(cur)
1927 #
1928 # update 'prev' to the end of the 'cur' object
1929 prev = prev + free_range_size + \
1930 (size_gc_header + self.get_size(obj))
1931 #
1932 # reset everything after the last pinned object till the end of the arena
1933 if self.gc_nursery_debug:
1934 llarena.arena_reset(prev, self.nursery + self.nursery_size - prev, 3)
1935 if not nursery_barriers.non_empty(): # no pinned objects
1936 self.debug_rotate_nursery()
1937 else:
1938 llarena.arena_reset(prev, self.nursery + self.nursery_size - prev, 0)
1939 #
1940 # always add the end of the nursery to the list
1941 nursery_barriers.append(self.nursery + self.nursery_size)
1942 #
1943 self.nursery_barriers = nursery_barriers
1944 self.surviving_pinned_objects.delete()
1945 #
1946 self.nursery_free = self.nursery
1947 self.nursery_top = self.nursery_barriers.popleft()
1948 #
1949 # clear GCFLAG_PINNED_OBJECT_PARENT_KNOWN from all parents in the list.
1950 self.old_objects_pointing_to_pinned.foreach(
1951 self._reset_flag_old_objects_pointing_to_pinned, None)
1952 #
1953 # Accounting: 'nursery_surviving_size' is the size of objects
1954 # from the nursery that we just moved out.
1955 self.size_objects_made_old += r_uint(self.nursery_surviving_size)
1956 #
1957 total_memory_used = self.get_total_memory_used()
1958 debug_print("minor collect, total memory used:", total_memory_used)
1959 debug_print("number of pinned objects:",
1960 self.pinned_objects_in_nursery)
1961 debug_print("total size of surviving objects:", self.nursery_surviving_size)
1962 if self.DEBUG >= 2:
1963 self.debug_check_consistency() # expensive!
1964 #
1965 self.root_walker.finished_minor_collection()
1966 #
1967 duration = time.time() - start
1968 self.total_gc_time += duration
1969 debug_print("time taken:", duration)
1970 debug_stop("gc-minor")
1971 self.hooks.fire_gc_minor(
1972 duration=duration,
1973 total_memory_used=total_memory_used,
1974 pinned_objects=self.pinned_objects_in_nursery)
1975
1976 def _reset_flag_old_objects_pointing_to_pinned(self, obj, ignore):
1977 ll_assert(self.header(obj).tid & GCFLAG_PINNED_OBJECT_PARENT_KNOWN != 0,
1978 "!GCFLAG_PINNED_OBJECT_PARENT_KNOWN, but requested to reset.")
1979 self.header(obj).tid &= ~GCFLAG_PINNED_OBJECT_PARENT_KNOWN
1980
1981 def _visit_old_objects_pointing_to_pinned(self, obj, ignore):
1982 self.trace(obj, self.make_callback('_trace_drag_out'), self, obj)
1983
1984 def collect_roots_in_nursery(self, any_pinned_object_from_earlier):
1985 # we don't need to trace prebuilt GcStructs during a minor collect:
1986 # if a prebuilt GcStruct contains a pointer to a young object,
1987 # then the write_barrier must have ensured that the prebuilt
1988 # GcStruct is in the list self.old_objects_pointing_to_young.
1989 debug_start("gc-minor-walkroots")
1990 if self.gc_state == STATE_MARKING:
1991 callback = IncrementalMiniMarkGC._trace_drag_out1_marking_phase
1992 else:
1993 callback = IncrementalMiniMarkGC._trace_drag_out1
1994 #
1995 # Note a subtlety: if the nursery contains pinned objects "from
1996 # earlier", i.e. created earlier than the previous minor
1997 # collection, then we can't use the "is_minor=True" optimization.
1998 # We really need to walk the complete stack to be sure we still
1999 # see them.
2000 use_jit_frame_stoppers = not any_pinned_object_from_earlier
2001 #
2002 self.root_walker.walk_roots(
2003 callback, # stack roots
2004 callback, # static in prebuilt non-gc
2005 None, # static in prebuilt gc
2006 is_minor=use_jit_frame_stoppers)
2007 debug_stop("gc-minor-walkroots")
2008
2009 def collect_cardrefs_to_nursery(self):
2010 size_gc_header = self.gcheaderbuilder.size_gc_header
2011 oldlist = self.old_objects_with_cards_set
2012 while oldlist.non_empty():
2013 obj = oldlist.pop()
2014 #
2015 # Remove the GCFLAG_CARDS_SET flag.
2016 ll_assert(self.header(obj).tid & GCFLAG_HAS_CARDS != 0,
2017 "!GCFLAG_HAS_CARDS but object in 'old_objects_with_cards_set'")
2018 ll_assert(self.header(obj).tid & GCFLAG_CARDS_SET != 0,
2019 "!GCFLAG_CARDS_SET but object in 'old_objects_with_cards_set'")
2020 self.header(obj).tid &= ~GCFLAG_CARDS_SET
2021 #
2022 # Get the number of card marker bytes in the header.
2023 typeid = self.get_type_id(obj)
2024 offset_to_length = self.varsize_offset_to_length(typeid)
2025 length = (obj + offset_to_length).signed[0]
2026 bytes = self.card_marking_bytes_for_length(length)
2027 p = llarena.getfakearenaaddress(obj - size_gc_header)
2028 #
2029 # If the object doesn't have GCFLAG_TRACK_YOUNG_PTRS, then it
2030 # means that it is in 'old_objects_pointing_to_young' and
2031 # will be fully traced by collect_oldrefs_to_nursery() just
2032 # afterwards.
2033 if self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
2034 #
2035 # In that case, we just have to reset all card bits.
2036 while bytes > 0:
2037 p -= 1
2038 p.char[0] = '\x00'
2039 bytes -= 1
2040 #
2041 else:
2042 # Walk the bytes encoding the card marker bits, and for
2043 # each bit set, call trace_and_drag_out_of_nursery_partial().
2044 interval_start = 0
2045 while bytes > 0:
2046 p -= 1
2047 cardbyte = ord(p.char[0])
2048 p.char[0] = '\x00' # reset the bits
2049 bytes -= 1
2050 next_byte_start = interval_start + 8*self.card_page_indices
2051 #
2052 while cardbyte != 0:
2053 interval_stop = interval_start + self.card_page_indices
2054 #
2055 if cardbyte & 1:
2056 if interval_stop > length:
2057 interval_stop = length
2058 #--- the sanity check below almost always
2059 #--- passes, except in situations like
2060 #--- test_writebarrier_before_copy_manually\
2061 # _copy_card_bits
2062 #ll_assert(cardbyte <= 1 and bytes == 0,
2063 # "premature end of object")
2064 ll_assert(bytes == 0, "premature end of object")
2065 if interval_stop <= interval_start:
2066 break
2067 self.trace_and_drag_out_of_nursery_partial(
2068 obj, interval_start, interval_stop)
2069 #
2070 interval_start = interval_stop
2071 cardbyte >>= 1
2072 interval_start = next_byte_start
2073 #
2074 # If we're incrementally marking right now, sorry, we also
2075 # need to add the object to 'more_objects_to_trace' and have
2076 # it fully traced once at the end of the current marking phase.
2077 ll_assert(not self.is_in_nursery(obj),
2078 "expected nursery obj in collect_cardrefs_to_nursery")
2079 if self.gc_state == STATE_MARKING:
2080 # XXX do we *need* to unconditionally do that? or is it
2081 # enough to do it if GCFLAG_VISITED is not set?
2082 self.header(obj).tid &= ~GCFLAG_VISITED
2083 self.more_objects_to_trace.append(obj)
2084
2085
2086 def collect_oldrefs_to_nursery(self):
2087 # Follow the old_objects_pointing_to_young list and move the
2088 # young objects they point to out of the nursery.
2089 oldlist = self.old_objects_pointing_to_young
2090 while oldlist.non_empty():
2091 obj = oldlist.pop()
2092 #
2093 # Check that the flags are correct: we must not have
2094 # GCFLAG_TRACK_YOUNG_PTRS so far.
2095 ll_assert(self.header(obj).tid & GCFLAG_TRACK_YOUNG_PTRS == 0,
2096 "old_objects_pointing_to_young contains obj with "
2097 "GCFLAG_TRACK_YOUNG_PTRS")
2098 #
2099 # Add the flag GCFLAG_TRACK_YOUNG_PTRS. All live objects should
2100 # have this flag set after a nursery collection.
2101 self.header(obj).tid |= GCFLAG_TRACK_YOUNG_PTRS
2102 #
2103 # Trace the 'obj' to replace pointers to nursery with pointers
2104 # outside the nursery, possibly forcing nursery objects out
2105 # and adding them to 'old_objects_pointing_to_young' as well.
2106 self.trace_and_drag_out_of_nursery(obj)
2107
2108 def trace_and_drag_out_of_nursery(self, obj):
2109 """obj must not be in the nursery. This copies all the
2110 young objects it references out of the nursery.
2111 """
2112 self.trace(obj, self.make_callback('_trace_drag_out'), self, obj)
2113
2114 def trace_and_drag_out_of_nursery_partial(self, obj, start, stop):
2115 """Like trace_and_drag_out_of_nursery(), but limited to the array
2116 indices in range(start, stop).
2117 """
2118 ll_assert(start < stop, "empty or negative range "
2119 "in trace_and_drag_out_of_nursery_partial()")
2120 #print 'trace_partial:', start, stop, '\t', obj
2121 self.trace_partial(obj, start, stop,
2122 self.make_callback('_trace_drag_out'), self, obj)
2123
2124
2125 def _trace_drag_out1(self, root):
2126 self._trace_drag_out(root, llmemory.NULL)
2127
2128 def _trace_drag_out1_marking_phase(self, root):
2129 self._trace_drag_out(root, llmemory.NULL)
2130 #
2131 # We are in the MARKING state: we must also record this object
2132 # if it was young. Don't bother with old objects in general,
2133 # as they are anyway added to 'more_objects_to_trace' if they
2134 # are modified (see _add_to_more_objects_to_trace). But we do
2135 # need to record the not-visited-yet (white) old objects. So
2136 # as a conservative approximation, we need to add the object to
2137 # the list if and only if it doesn't have GCFLAG_VISITED yet.
2138 #
2139 # Additionally, ignore pinned objects.
2140 #
2141 obj = root.address[0]
2142 if (self.header(obj).tid & (GCFLAG_VISITED | GCFLAG_PINNED)) == 0:
2143 self.more_objects_to_trace.append(obj)
2144
2145 def _trace_drag_out(self, root, parent):
2146 obj = root.address[0]
2147 #print '_trace_drag_out(%x: %r)' % (hash(obj.ptr._obj), obj)
2148 #
2149 # If 'obj' is not in the nursery, nothing to change -- expect
2150 # that we must set GCFLAG_VISITED_RMY on young raw-malloced objects.
2151 if not self.is_in_nursery(obj):
2152 # cache usage trade-off: I think that it is a better idea to
2153 # check if 'obj' is in young_rawmalloced_objects with an access
2154 # to this (small) dictionary, rather than risk a lot of cache
2155 # misses by reading a flag in the header of all the 'objs' that
2156 # arrive here.
2157 if (bool(self.young_rawmalloced_objects)
2158 and self.young_rawmalloced_objects.contains(obj)):
2159 self._visit_young_rawmalloced_object(obj)
2160 return
2161 # copy the contents of the object? usually yes, but not for some
2162 # shadow objects
2163 copy = True
2164 add_gcflag_visited = False
2165 #
2166 size_gc_header = self.gcheaderbuilder.size_gc_header
2167 if self.header(obj).tid & (GCFLAG_HAS_SHADOW | GCFLAG_PINNED) == 0:
2168 #
2169 # Common case: 'obj' was not already forwarded (otherwise
2170 # tid == -42, containing all flags), and it doesn't have the
2171 # HAS_SHADOW flag either. We must move it out of the nursery,
2172 # into a new nonmovable location.
2173 totalsize = size_gc_header + self.get_size(obj)
2174 self.nursery_surviving_size += raw_malloc_usage(totalsize)
2175 newhdr = self._malloc_out_of_nursery(totalsize)
2176 #
2177 elif self.is_forwarded(obj):
2178 #
2179 # 'obj' was already forwarded. Change the original reference
2180 # to point to its forwarding address, and we're done.
2181 root.address[0] = self.get_forwarding_address(obj)
2182 return
2183 #
2184 elif self._is_pinned(obj):
2185 hdr = self.header(obj)
2186 #
2187 # track parent of pinned object specially. This mus be done before
2188 # checking for GCFLAG_VISITED: it may be that the same pinned object
2189 # is reachable from multiple sources (e.g. two old objects pointing
2190 # to the same pinned object). In such a case we need all parents
2191 # of the pinned object in the list. Otherwise he pinned object could
2192 # become dead and be removed just because the first parent of it
2193 # is dead and collected.
2194 if parent != llmemory.NULL and \
2195 not self.header(parent).tid & GCFLAG_PINNED_OBJECT_PARENT_KNOWN:
2196 #
2197 self.old_objects_pointing_to_pinned.append(parent)
2198 self.updated_old_objects_pointing_to_pinned = True
2199 self.header(parent).tid |= GCFLAG_PINNED_OBJECT_PARENT_KNOWN
2200 #
2201 if hdr.tid & GCFLAG_VISITED:
2202 return
2203 #
2204 hdr.tid |= GCFLAG_VISITED
2205 #
2206 self.surviving_pinned_objects.append(
2207 llarena.getfakearenaaddress(obj - size_gc_header))
2208 self.pinned_objects_in_nursery += 1
2209 self.any_pinned_object_kept = True
2210 return
2211 else:
2212 # First visit to an object that has already a shadow.
2213 newobj = self.nursery_objects_shadows.get(obj)
2214 ll_assert(newobj != llmemory.NULL, "GCFLAG_HAS_SHADOW but no shadow found")
2215 if self.header(newobj).tid & GCFLAG_VISITED:
2216 # if the shadow is black, we must make sure that it remains
2217 # black after we did the copy. by default, the memcopy will
2218 # overwrite the flags with the ones that old obj has. if we
2219 # don't do that, then the copy can be collected if we're
2220 # currently in sweeping phase. see test_pin_id_bug.
2221 add_gcflag_visited = True
2222 newhdr = newobj - size_gc_header
2223 #
2224 # The flags GCFLAG_HAS_SHADOW and GCFLAG_SHADOW_INITIALIZED
2225 # have no meaning in non-nursery objects. We don't need to
2226 # remove them explicitly here before doing the copy.
2227 tid = self.header(obj).tid
2228 if (tid & GCFLAG_SHADOW_INITIALIZED) != 0:
2229 copy = False
2230 #
2231 totalsize = size_gc_header + self.get_size(obj)
2232 self.nursery_surviving_size += raw_malloc_usage(totalsize)
2233 #
2234 # Copy it. Note that references to other objects in the
2235 # nursery are kept unchanged in this step.
2236 if copy:
2237 llmemory.raw_memcopy(obj - size_gc_header, newhdr, totalsize)
2238 #
2239 # Set the old object's tid to -42 (containing all flags) and
2240 # replace the old object's content with the target address.
2241 # A bit of no-ops to convince llarena that we are changing
2242 # the layout, in non-translated versions.
2243 typeid = self.get_type_id(obj)
2244 obj = llarena.getfakearenaaddress(obj)
2245 llarena.arena_reset(obj - size_gc_header, totalsize, 0)
2246 llarena.arena_reserve(obj - size_gc_header,
2247 size_gc_header + llmemory.sizeof(FORWARDSTUB))
2248 self.header(obj).tid = -42
2249 newobj = newhdr + size_gc_header
2250 llmemory.cast_adr_to_ptr(obj, FORWARDSTUBPTR).forw = newobj
2251 #
2252 # Change the original pointer to this object.
2253 root.address[0] = newobj
2254 #
2255 # Add the newobj to the list 'old_objects_pointing_to_young',
2256 # because it can contain further pointers to other young objects.
2257 # We will fix such references to point to the copy of the young
2258 # objects when we walk 'old_objects_pointing_to_young'.
2259 if self.has_gcptr(typeid):
2260 # we only have to do it if we have any gcptrs
2261 self.old_objects_pointing_to_young.append(newobj)
2262 if add_gcflag_visited:
2263 self.header(newobj).tid |= GCFLAG_VISITED
2264
2265 _trace_drag_out._always_inline_ = True
2266
2267 def _visit_young_rawmalloced_object(self, obj):
2268 # 'obj' points to a young, raw-malloced object.
2269 # Any young rawmalloced object never seen by the code here
2270 # will end up without GCFLAG_VISITED_RMY, and be freed at the
2271 # end of the current minor collection. Note that there was
2272 # a bug in which dying young arrays with card marks would
2273 # still be scanned before being freed, keeping a lot of
2274 # objects unnecessarily alive.
2275 hdr = self.header(obj)
2276 if hdr.tid & GCFLAG_VISITED_RMY:
2277 return
2278 hdr.tid |= GCFLAG_VISITED_RMY
2279 #
2280 # Accounting
2281 size_gc_header = self.gcheaderbuilder.size_gc_header
2282 size = size_gc_header + self.get_size(obj)
2283 self.size_objects_made_old += r_uint(raw_malloc_usage(size))
2284 #
2285 # we just made 'obj' old, so we need to add it to the correct lists
2286 added_somewhere = False
2287 #
2288 if hdr.tid & GCFLAG_TRACK_YOUNG_PTRS == 0:
2289 self.old_objects_pointing_to_young.append(obj)
2290 added_somewhere = True
2291 #
2292 if hdr.tid & GCFLAG_HAS_CARDS != 0:
2293 ll_assert(hdr.tid & GCFLAG_CARDS_SET != 0,
2294 "young array: GCFLAG_HAS_CARDS without GCFLAG_CARDS_SET")
2295 self.old_objects_with_cards_set.append(obj)
2296 added_somewhere = True
2297 #
2298 ll_assert(added_somewhere, "wrong flag combination on young array")
2299
2300
2301 def _malloc_out_of_nursery(self, totalsize):
2302 """Allocate non-movable memory for an object of the given
2303 'totalsize' that lives so far in the nursery."""
2304 if (r_uint(raw_malloc_usage(totalsize)) <=
2305 r_uint(self.small_request_threshold)):
2306 # most common path
2307 return self.ac.malloc(totalsize)
2308 else:
2309 # for nursery objects that are not small
2310 return self._malloc_out_of_nursery_nonsmall(totalsize)
2311 _malloc_out_of_nursery._always_inline_ = True
2312
2313 def _malloc_out_of_nursery_nonsmall(self, totalsize):
2314 if r_uint(raw_malloc_usage(totalsize)) > r_uint(self.nursery_size):
2315 out_of_memory("memory corruption: bad size for object in the "
2316 "nursery")
2317 # 'totalsize' should be aligned.
2318 ll_assert(raw_malloc_usage(totalsize) & (WORD-1) == 0,
2319 "misaligned totalsize in _malloc_out_of_nursery_nonsmall")
2320 #
2321 arena = llarena.arena_malloc(raw_malloc_usage(totalsize), False)
2322 if not arena:
2323 out_of_memory("out of memory: couldn't allocate a few KB more")
2324 llarena.arena_reserve(arena, totalsize)
2325 #
2326 size_gc_header = self.gcheaderbuilder.size_gc_header
2327 self.rawmalloced_total_size += r_uint(raw_malloc_usage(totalsize))
2328 self.rawmalloced_peak_size = max(self.rawmalloced_total_size,
2329 self.rawmalloced_peak_size)
2330 self.old_rawmalloced_objects.append(arena + size_gc_header)
2331 return arena
2332
2333 def free_young_rawmalloced_objects(self):
2334 self.young_rawmalloced_objects.foreach(
2335 self._free_young_rawmalloced_obj, None)
2336 self.young_rawmalloced_objects.delete()
2337 self.young_rawmalloced_objects = self.null_address_dict()
2338
2339 def _free_young_rawmalloced_obj(self, obj, ignored1, ignored2):
2340 # If 'obj' has GCFLAG_VISITED_RMY, it was seen by _trace_drag_out
2341 # and survives. Otherwise, it dies.
2342 self.free_rawmalloced_object_if_unvisited(obj, GCFLAG_VISITED_RMY)
2343
2344 def remove_young_arrays_from_old_objects_pointing_to_young(self):
2345 old = self.old_objects_pointing_to_young
2346 new = self.AddressStack()
2347 while old.non_empty():
2348 obj = old.pop()
2349 if not self.young_rawmalloced_objects.contains(obj):
2350 new.append(obj)
2351 # an extra copy, to avoid assignments to
2352 # 'self.old_objects_pointing_to_young'
2353 while new.non_empty():
2354 old.append(new.pop())
2355 new.delete()
2356
2357 def _add_to_more_objects_to_trace(self, obj, ignored):
2358 ll_assert(not self.is_in_nursery(obj), "unexpected nursery obj here")
2359 self.header(obj).tid &= ~GCFLAG_VISITED
2360 self.more_objects_to_trace.append(obj)
2361
2362 def _add_to_more_objects_to_trace_if_black(self, obj, ignored):
2363 if self.header(obj).tid & GCFLAG_VISITED:
2364 self._add_to_more_objects_to_trace(obj, ignored)
2365
2366 def minor_and_major_collection(self):
2367 # First, finish the current major gc, if there is one in progress.
2368 # This is a no-op if the gc_state is already STATE_SCANNING.
2369 self.gc_step_until(STATE_SCANNING)
2370 #
2371 # Then do a complete collection again.
2372 self.gc_step_until(STATE_MARKING)
2373 self.gc_step_until(STATE_SCANNING)
2374
2375 def gc_step_until(self, state):
2376 while self.gc_state != state:
2377 self._minor_collection()
2378 self.major_collection_step()
2379
2380 debug_gc_step_until = gc_step_until # xxx
2381
2382 def debug_gc_step(self, n=1):
2383 while n > 0:
2384 self._minor_collection()
2385 self.major_collection_step()
2386 n -= 1
2387
2388 # Note - minor collections seem fast enough so that one
2389 # is done before every major collection step
2390 def major_collection_step(self, reserving_size=0):
2391 start = time.time()
2392 debug_start("gc-collect-step")
2393 oldstate = self.gc_state
2394 debug_print("starting gc state: ", GC_STATES[self.gc_state])
2395 # Debugging checks
2396 if self.pinned_objects_in_nursery == 0:
2397 ll_assert(self.nursery_free == self.nursery,
2398 "nursery not empty in major_collection_step()")
2399 else:
2400 # XXX try to add some similar check to the above one for the case
2401 # that the nursery still contains some pinned objects (groggi)
2402 pass
2403 self.debug_check_consistency()
2404
2405 #
2406 # 'threshold_objects_made_old', is used inside comparisons
2407 # with 'size_objects_made_old' to know when we must do
2408 # several major GC steps (i.e. several consecutive calls
2409 # to the present function). Here is the target that
2410 # we try to aim to: either (A1) or (A2)
2411 #
2412 # (A1) gc_state == STATE_SCANNING (i.e. major GC cycle ended)
2413 # (A2) size_objects_made_old <= threshold_objects_made_old
2414 #
2415 # Every call to major_collection_step() adds nursery_size//2
2416 # to 'threshold_objects_made_old'.
2417 # In the common case, this is larger than the size of all
2418 # objects that survive a minor collection. After a few
2419 # minor collections (each followed by one call to
2420 # major_collection_step()) the threshold is much higher than
2421 # the 'size_objects_made_old', making the target invariant (A2)
2422 # true by a large margin.
2423 #
2424 # However there are less common cases:
2425 #
2426 # * if more than half of the nursery consistently survives:
2427 # then we need two calls to major_collection_step() after
2428 # some minor collection;
2429 #
2430 # * or if we're allocating a large number of bytes in
2431 # external_malloc() and some of them survive the following
2432 # minor collection. In that case, more than two major
2433 # collection steps must be done immediately, until we
2434 # restore the target invariant (A2).
2435 #
2436 self.threshold_objects_made_old += r_uint(self.nursery_size // 2)
2437
2438
2439 if self.gc_state == STATE_SCANNING:
2440 # starting a major GC cycle: reset these two counters
2441 self.size_objects_made_old = r_uint(0)
2442 self.threshold_objects_made_old = r_uint(self.nursery_size // 2)
2443
2444 self.objects_to_trace = self.AddressStack()
2445 self.collect_roots()
2446 self.gc_state = STATE_MARKING
2447 self.more_objects_to_trace = self.AddressStack()
2448 #END SCANNING
2449 elif self.gc_state == STATE_MARKING:
2450 debug_print("number of objects to mark",
2451 self.objects_to_trace.length(),
2452 "plus",
2453 self.more_objects_to_trace.length())
2454 estimate = self.gc_increment_step
2455 estimate_from_nursery = self.nursery_surviving_size * 2
2456 if estimate_from_nursery > estimate:
2457 estimate = estimate_from_nursery
2458 estimate = intmask(estimate)
2459 remaining = self.visit_all_objects_step(estimate)
2460 #
2461 if remaining >= estimate // 2:
2462 if self.more_objects_to_trace.non_empty():
2463 # We consumed less than 1/2 of our step's time, and
2464 # there are more objects added during the marking steps
2465 # of this major collection. Visit them all now.
2466 # The idea is to ensure termination at the cost of some
2467 # incrementality, in theory.
2468 swap = self.objects_to_trace
2469 self.objects_to_trace = self.more_objects_to_trace
2470 self.more_objects_to_trace = swap
2471 self.visit_all_objects()
2472
2473 # XXX A simplifying assumption that should be checked,
2474 # finalizers/weak references are rare and short which means that
2475 # they do not need a separate state and do not need to be
2476 # made incremental.
2477 # For now, the same applies to rawrefcount'ed objects.
2478 if (not self.objects_to_trace.non_empty() and
2479 not self.more_objects_to_trace.non_empty()):
2480 #
2481 # First, 'prebuilt_root_objects' might have grown since
2482 # we scanned it in collect_roots() (rare case). Rescan.
2483 self.collect_nonstack_roots()
2484 self.visit_all_objects()
2485 #
2486 if self.rrc_enabled:
2487 self.rrc_major_collection_trace()
2488 #
2489 ll_assert(not (self.probably_young_objects_with_finalizers
2490 .non_empty()),
2491 "probably_young_objects_with_finalizers should be empty")
2492 self.kept_alive_by_finalizer = r_uint(0)
2493 if self.old_objects_with_finalizers.non_empty():
2494 self.deal_with_objects_with_finalizers()
2495 elif self.old_objects_with_weakrefs.non_empty():
2496 # Weakref support: clear the weak pointers to dying objects
2497 # (if we call deal_with_objects_with_finalizers(), it will
2498 # invoke invalidate_old_weakrefs() itself directly)
2499 self.invalidate_old_weakrefs()
2500
2501 ll_assert(not self.objects_to_trace.non_empty(),
2502 "objects_to_trace should be empty")
2503 ll_assert(not self.more_objects_to_trace.non_empty(),
2504 "more_objects_to_trace should be empty")
2505 self.objects_to_trace.delete()
2506 self.more_objects_to_trace.delete()
2507
2508 #
2509 # Destructors
2510 if self.old_objects_with_destructors.non_empty():
2511 self.deal_with_old_objects_with_destructors()
2512 # objects_to_trace processed fully, can move on to sweeping
2513 self.ac.mass_free_prepare()
2514 self.start_free_rawmalloc_objects()
2515 #
2516 # get rid of objects pointing to pinned objects that were not
2517 # visited
2518 if self.old_objects_pointing_to_pinned.non_empty():
2519 new_old_objects_pointing_to_pinned = self.AddressStack()
2520 self.old_objects_pointing_to_pinned.foreach(
2521 self._sweep_old_objects_pointing_to_pinned,
2522 new_old_objects_pointing_to_pinned)
2523 self.old_objects_pointing_to_pinned.delete()
2524 self.old_objects_pointing_to_pinned = \
2525 new_old_objects_pointing_to_pinned
2526 self.updated_old_objects_pointing_to_pinned = True
2527 #
2528 if self.rrc_enabled:
2529 self.rrc_major_collection_free()
2530 #
2531 self.stat_ac_arenas_count = self.ac.arenas_count
2532 self.stat_rawmalloced_total_size = self.rawmalloced_total_size
2533 self.gc_state = STATE_SWEEPING
2534 #END MARKING
2535 elif self.gc_state == STATE_SWEEPING:
2536 #
2537 if self.raw_malloc_might_sweep.non_empty():
2538 # Walk all rawmalloced objects and free the ones that don't
2539 # have the GCFLAG_VISITED flag. Visit at most 'limit' objects.
2540 # This limit is conservatively high enough to guarantee that
2541 # a total object size of at least '3 * nursery_size' bytes
2542 # is processed.
2543 limit = 3 * self.nursery_size // self.small_request_threshold
2544 nobjects = self.free_unvisited_rawmalloc_objects_step(limit)
2545 debug_print("freeing raw objects:", limit-nobjects,
2546 "freed, limit was", limit)
2547 done = False # the 2nd half below must still be done
2548 else:
2549 # Ask the ArenaCollection to visit a fraction of the objects.
2550 # Free the ones that have not been visited above, and reset
2551 # GCFLAG_VISITED on the others. Visit at most '3 *
2552 # nursery_size' bytes.
2553 limit = 3 * self.nursery_size // self.ac.page_size
2554 done = self.ac.mass_free_incremental(self._free_if_unvisited,
2555 limit)
2556 status = done and "No more pages left." or "More to do."
2557 debug_print("freeing GC objects, up to", limit, "pages.", status)
2558 # XXX tweak the limits above
2559 #
2560 if done:
2561 self.num_major_collects += 1
2562 #
2563 # We also need to reset the GCFLAG_VISITED on prebuilt GC objects.
2564 self.prebuilt_root_objects.foreach(self._reset_gcflag_visited, None)
2565 #
2566 # Set the threshold for the next major collection to be when we
2567 # have allocated 'major_collection_threshold' times more than
2568 # we currently have -- but no more than 'max_delta' more than
2569 # we currently have.
2570 total_memory_used = float(self.get_total_memory_used())
2571 total_memory_used -= float(self.kept_alive_by_finalizer)
2572 if total_memory_used < 0:
2573 total_memory_used = 0
2574 bounded = self.set_major_threshold_from(
2575 min(total_memory_used * self.major_collection_threshold,
2576 total_memory_used + self.max_delta),
2577 reserving_size)
2578 #
2579 # Print statistics
2580 debug_start("gc-collect-done")
2581 debug_print("arenas: ",
2582 self.stat_ac_arenas_count, " => ",
2583 self.ac.arenas_count)
2584 debug_print("bytes used in arenas: ",
2585 self.ac.total_memory_used)
2586 debug_print("bytes raw-malloced: ",
2587 self.stat_rawmalloced_total_size, " => ",
2588 self.rawmalloced_total_size)
2589 debug_print("next major collection threshold: ",
2590 self.next_major_collection_threshold)
2591 debug_stop("gc-collect-done")
2592 self.hooks.fire_gc_collect(
2593 num_major_collects=self.num_major_collects,
2594 arenas_count_before=self.stat_ac_arenas_count,
2595 arenas_count_after=self.ac.arenas_count,
2596 arenas_bytes=self.ac.total_memory_used,
2597 rawmalloc_bytes_before=self.stat_rawmalloced_total_size,
2598 rawmalloc_bytes_after=self.rawmalloced_total_size,
2599 pinned_objects = self.pinned_objects_in_nursery)
2600 #
2601 # Max heap size: gives an upper bound on the threshold. If we
2602 # already have at least this much allocated, raise MemoryError.
2603 if bounded and self.threshold_reached(reserving_size):
2604 #
2605 # First raise MemoryError, giving the program a chance to
2606 # quit cleanly. It might still allocate in the nursery,
2607 # which might eventually be emptied, triggering another
2608 # major collect and (possibly) reaching here again with an
2609 # even higher memory consumption. To prevent it, if it's
2610 # the second time we are here, then abort the program.
2611 if self.max_heap_size_already_raised:
2612 out_of_memory("using too much memory, aborting")
2613 self.max_heap_size_already_raised = True
2614 self.gc_state = STATE_SCANNING
2615 raise MemoryError
2616
2617 self.gc_state = STATE_FINALIZING
2618 # FINALIZING not yet incrementalised
2619 # but it seems safe to allow mutator to run after sweeping and
2620 # before finalizers are called. This is because run_finalizers
2621 # is a different list to objects_with_finalizers.
2622 # END SWEEPING
2623 elif self.gc_state == STATE_FINALIZING:
2624 # XXX This is considered rare,
2625 # so should we make the calling incremental? or leave as is
2626
2627 # Must be ready to start another scan
2628 # just in case finalizer calls collect again.
2629 self.gc_state = STATE_SCANNING
2630
2631 self.execute_finalizers()
2632 #END FINALIZING
2633 else:
2634 ll_assert(False, "bogus gc_state")
2635
2636 debug_print("stopping, now in gc state: ", GC_STATES[self.gc_state])
2637 duration = time.time() - start
2638 self.total_gc_time += duration
2639 debug_print("time taken: ", duration)
2640 debug_stop("gc-collect-step")
2641 self.hooks.fire_gc_collect_step(
2642 duration=duration,
2643 oldstate=oldstate,
2644 newstate=self.gc_state)
2645
2646 def _sweep_old_objects_pointing_to_pinned(self, obj, new_list):
2647 if self.header(obj).tid & GCFLAG_VISITED:
2648 new_list.append(obj)
2649
2650 def _free_if_unvisited(self, hdr):
2651 size_gc_header = self.gcheaderbuilder.size_gc_header
2652 obj = hdr + size_gc_header
2653 if self.header(obj).tid & GCFLAG_VISITED:
2654 self.header(obj).tid &= ~GCFLAG_VISITED
2655 return False # survives
2656 return True # dies
2657
2658 def _reset_gcflag_visited(self, obj, ignored):
2659 self.header(obj).tid &= ~GCFLAG_VISITED
2660
2661 def free_rawmalloced_object_if_unvisited(self, obj, check_flag):
2662 if self.header(obj).tid & check_flag:
2663 self.header(obj).tid &= ~check_flag # survives
2664 self.old_rawmalloced_objects.append(obj)
2665 else:
2666 size_gc_header = self.gcheaderbuilder.size_gc_header
2667 totalsize = size_gc_header + self.get_size(obj)
2668 allocsize = raw_malloc_usage(totalsize)
2669 arena = llarena.getfakearenaaddress(obj - size_gc_header)
2670 #
2671 # Must also include the card marker area, if any
2672 if (self.card_page_indices > 0 # <- this is constant-folded
2673 and self.header(obj).tid & GCFLAG_HAS_CARDS):
2674 #
2675 # Get the length and compute the number of extra bytes
2676 typeid = self.get_type_id(obj)
2677 ll_assert(self.has_gcptr_in_varsize(typeid),
2678 "GCFLAG_HAS_CARDS but not has_gcptr_in_varsize")
2679 offset_to_length = self.varsize_offset_to_length(typeid)
2680 length = (obj + offset_to_length).signed[0]
2681 extra_words = self.card_marking_words_for_length(length)
2682 arena -= extra_words * WORD
2683 allocsize += extra_words * WORD
2684 #
2685 llarena.arena_free(arena)
2686 self.rawmalloced_total_size -= r_uint(allocsize)
2687
2688 def start_free_rawmalloc_objects(self):
2689 ll_assert(not self.raw_malloc_might_sweep.non_empty(),
2690 "raw_malloc_might_sweep must be empty")
2691 swap = self.raw_malloc_might_sweep
2692 self.raw_malloc_might_sweep = self.old_rawmalloced_objects
2693 self.old_rawmalloced_objects = swap
2694
2695 # Returns true when finished processing objects
2696 def free_unvisited_rawmalloc_objects_step(self, nobjects):
2697 while self.raw_malloc_might_sweep.non_empty() and nobjects > 0:
2698 obj = self.raw_malloc_might_sweep.pop()
2699 self.free_rawmalloced_object_if_unvisited(obj, GCFLAG_VISITED)
2700 nobjects -= 1
2701
2702 return nobjects
2703
2704
2705 def collect_nonstack_roots(self):
2706 # Non-stack roots: first, the objects from 'prebuilt_root_objects'
2707 self.prebuilt_root_objects.foreach(self._collect_obj, None)
2708 #
2709 # Add the roots from static prebuilt non-gc structures
2710 self.root_walker.walk_roots(
2711 None,
2712 IncrementalMiniMarkGC._collect_ref_stk,
2713 None) # we don't need the static in all prebuilt gc objects
2714 #
2715 # If we are in an inner collection caused by a call to a finalizer,
2716 # the 'run_finalizers' objects also need to be kept alive.
2717 self.enum_pending_finalizers(self._collect_obj, None)
2718
2719 def collect_roots(self):
2720 # Collect all roots. Starts from the non-stack roots.
2721 self.collect_nonstack_roots()
2722 #
2723 # Add the stack roots.
2724 self.root_walker.walk_roots(
2725 IncrementalMiniMarkGC._collect_ref_stk, # stack roots
2726 None,
2727 None)
2728
2729 def enumerate_all_roots(self, callback, arg):
2730 self.prebuilt_root_objects.foreach(callback, arg)
2731 MovingGCBase.enumerate_all_roots(self, callback, arg)
2732 enumerate_all_roots._annspecialcase_ = 'specialize:arg(1)'
2733
2734 def enum_live_with_finalizers(self, callback, arg):
2735 self.probably_young_objects_with_finalizers.foreach(callback, arg, 2)
2736 self.old_objects_with_finalizers.foreach(callback, arg, 2)
2737 enum_live_with_finalizers._annspecialcase_ = 'specialize:arg(1)'
2738
2739 def _collect_obj(self, obj, ignored):
2740 # Ignore pinned objects, which are the ones still in the nursery here.
2741 # Cache effects: don't read any flag out of 'obj' at this point.
2742 # But only checking if it is in the nursery or not is fine.
2743 llop.debug_nonnull_pointer(lltype.Void, obj)
2744 if not self.is_in_nursery(obj):
2745 self.objects_to_trace.append(obj)
2746 else:
2747 # A pinned object can be found here. Such an object is handled
2748 # by minor collections and shouldn't be specially handled by
2749 # major collections. Therefore we only add non-pinned objects
2750 # to the 'objects_to_trace' list.
2751 ll_assert(self._is_pinned(obj),
2752 "non-pinned nursery obj in _collect_obj")
2753 _collect_obj._always_inline_ = True
2754
2755 def _collect_ref_stk(self, root):
2756 self._collect_obj(root.address[0], None)
2757
2758 def _collect_ref_rec(self, root, ignored):
2759 self._collect_obj(root.address[0], None)
2760
2761 def visit_all_objects(self):
2762 while self.objects_to_trace.non_empty():
2763 self.visit_all_objects_step(sys.maxint)
2764
2765 TEST_VISIT_SINGLE_STEP = False # for tests
2766
2767 def visit_all_objects_step(self, size_to_track):
2768 # Objects can be added to pending by visit
2769 pending = self.objects_to_trace
2770 while pending.non_empty():
2771 obj = pending.pop()
2772 size_to_track -= self.visit(obj)
2773 if size_to_track < 0 or self.TEST_VISIT_SINGLE_STEP:
2774 return 0
2775 return size_to_track
2776
2777 def visit(self, obj):
2778 #
2779 # 'obj' is a live object. Check GCFLAG_VISITED to know if we
2780 # have already seen it before.
2781 #
2782 # Moreover, we can ignore prebuilt objects with GCFLAG_NO_HEAP_PTRS.
2783 # If they have this flag set, then they cannot point to heap
2784 # objects, so ignoring them is fine. If they don't have this
2785 # flag set, then the object should be in 'prebuilt_root_objects',
2786 # and the GCFLAG_VISITED will be reset at the end of the
2787 # collection.
2788 # We shouldn't see an object with GCFLAG_PINNED here (the pinned
2789 # objects are never added to 'objects_to_trace'). The same-valued
2790 # flag GCFLAG_PINNED_OBJECT_PARENT_KNOWN is used during minor
2791 # collections and shouldn't be set here either.
2792 #
2793 hdr = self.header(obj)
2794 ll_assert((hdr.tid & GCFLAG_PINNED) == 0,
2795 "pinned object in 'objects_to_trace'")
2796 ll_assert(not self.is_in_nursery(obj),
2797 "nursery object in 'objects_to_trace'")
2798 if hdr.tid & (GCFLAG_VISITED | GCFLAG_NO_HEAP_PTRS):
2799 return 0
2800 #
2801 # It's the first time. We set the flag VISITED. The trick is
2802 # to also set TRACK_YOUNG_PTRS here, for the write barrier.
2803 hdr.tid |= GCFLAG_VISITED | GCFLAG_TRACK_YOUNG_PTRS
2804
2805 if self.has_gcptr(llop.extract_ushort(llgroup.HALFWORD, hdr.tid)):
2806 #
2807 # Trace the content of the object and put all objects it references
2808 # into the 'objects_to_trace' list.
2809 self.trace(obj, self.make_callback('_collect_ref_rec'), self, None)
2810
2811 size_gc_header = self.gcheaderbuilder.size_gc_header
2812 totalsize = size_gc_header + self.get_size(obj)
2813 return raw_malloc_usage(totalsize)
2814
2815 # ----------
2816 # id() and identityhash() support
2817
2818 def _allocate_shadow(self, obj):
2819 size_gc_header = self.gcheaderbuilder.size_gc_header
2820 size = self.get_size(obj)
2821 shadowhdr = self._malloc_out_of_nursery(size_gc_header +
2822 size)
2823 # Initialize the shadow enough to be considered a
2824 # valid gc object. If the original object stays
2825 # alive at the next minor collection, it will anyway
2826 # be copied over the shadow and overwrite the
2827 # following fields. But if the object dies, then
2828 # the shadow will stay around and only be freed at
2829 # the next major collection, at which point we want
2830 # it to look valid (but ready to be freed).
2831 shadow = shadowhdr + size_gc_header
2832 # XXX is it correct that the full tid (including the flags) is copied?
2833 # what about if obj has GCFLAG_PINNED set, won't that mean that the
2834 # shadow gets GCFLAG_PINNED_OBJECT_PARENT_KNOWN set (which are the same
2835 # value)? maybe it doesn't matter at the moment because pinned objects
2836 # cannot have gcptrs
2837 self.header(shadow).tid = self.header(obj).tid
2838 typeid = self.get_type_id(obj)
2839 if self.is_varsize(typeid):
2840 lenofs = self.varsize_offset_to_length(typeid)
2841 (shadow + lenofs).signed[0] = (obj + lenofs).signed[0]
2842 #
2843 self.header(obj).tid |= GCFLAG_HAS_SHADOW
2844 self.nursery_objects_shadows.setitem(obj, shadow)
2845 return shadow
2846
2847 def _find_shadow(self, obj):
2848 #
2849 # The object is not a tagged pointer, and it is still in the
2850 # nursery. Find or allocate a "shadow" object, which is
2851 # where the object will be moved by the next minor
2852 # collection
2853 if self.header(obj).tid & GCFLAG_HAS_SHADOW:
2854 shadow = self.nursery_objects_shadows.get(obj)
2855 ll_assert(shadow != llmemory.NULL,
2856 "GCFLAG_HAS_SHADOW but no shadow found")
2857 else:
2858 shadow = self._allocate_shadow(obj)
2859 #
2860 # The answer is the address of the shadow.
2861 return shadow
2862 _find_shadow._dont_inline_ = True
2863
2864 def id_or_identityhash(self, gcobj):
2865 """Implement the common logic of id() and identityhash()
2866 of an object, given as a GCREF.
2867 """
2868 obj = llmemory.cast_ptr_to_adr(gcobj)
2869 if self.is_valid_gc_object(obj):
2870 if self.is_in_nursery(obj):
2871 obj = self._find_shadow(obj)
2872 return llmemory.cast_adr_to_int(obj)
2873 id_or_identityhash._always_inline_ = True
2874
2875 def id(self, gcobj):
2876 return self.id_or_identityhash(gcobj)
2877
2878 def identityhash(self, gcobj):
2879 return mangle_hash(self.id_or_identityhash(gcobj))
2880
2881 # ----------
2882 # Finalizers
2883
2884 def deal_with_young_objects_with_destructors(self):
2885 """We can reasonably assume that destructors don't do
2886 anything fancy and *just* call them. Among other things
2887 they won't resurrect objects
2888 """
2889 while self.young_objects_with_destructors.non_empty():
2890 obj = self.young_objects_with_destructors.pop()
2891 if not self.is_forwarded(obj):
2892 self.call_destructor(obj)
2893 else:
2894 obj = self.get_forwarding_address(obj)
2895 self.old_objects_with_destructors.append(obj)
2896
2897 def deal_with_old_objects_with_destructors(self):
2898 """We can reasonably assume that destructors don't do
2899 anything fancy and *just* call them. Among other things
2900 they won't resurrect objects
2901 """
2902 new_objects = self.AddressStack()
2903 while self.old_objects_with_destructors.non_empty():
2904 obj = self.old_objects_with_destructors.pop()
2905 if self.header(obj).tid & GCFLAG_VISITED:
2906 # surviving
2907 new_objects.append(obj)
2908 else:
2909 # dying
2910 self.call_destructor(obj)
2911 self.old_objects_with_destructors.delete()
2912 self.old_objects_with_destructors = new_objects
2913
2914 def deal_with_young_objects_with_finalizers(self):
2915 while self.probably_young_objects_with_finalizers.non_empty():
2916 obj = self.probably_young_objects_with_finalizers.popleft()
2917 fq_nr = self.probably_young_objects_with_finalizers.popleft()
2918 if self.get_possibly_forwarded_tid(obj) & GCFLAG_IGNORE_FINALIZER:
2919 continue
2920 self.singleaddr.address[0] = obj
2921 self._trace_drag_out1(self.singleaddr)
2922 obj = self.singleaddr.address[0]
2923 self.old_objects_with_finalizers.append(obj)
2924 self.old_objects_with_finalizers.append(fq_nr)
2925
2926 def deal_with_objects_with_finalizers(self):
2927 # Walk over list of objects with finalizers.
2928 # If it is not surviving, add it to the list of to-be-called
2929 # finalizers and make it survive, to make the finalizer runnable.
2930 # We try to run the finalizers in a "reasonable" order, like
2931 # CPython does. The details of this algorithm are in
2932 # pypy/doc/discussion/finalizer-order.txt.
2933 new_with_finalizer = self.AddressDeque()
2934 marked = self.AddressDeque()
2935 pending = self.AddressStack()
2936 self.tmpstack = self.AddressStack()
2937 while self.old_objects_with_finalizers.non_empty():
2938 x = self.old_objects_with_finalizers.popleft()
2939 fq_nr = self.old_objects_with_finalizers.popleft()
2940 ll_assert(self._finalization_state(x) != 1,
2941 "bad finalization state 1")
2942 if self.header(x).tid & GCFLAG_IGNORE_FINALIZER:
2943 continue
2944 if self.header(x).tid & GCFLAG_VISITED:
2945 new_with_finalizer.append(x)
2946 new_with_finalizer.append(fq_nr)
2947 continue
2948 marked.append(x)
2949 marked.append(fq_nr)
2950 pending.append(x)
2951 while pending.non_empty():
2952 y = pending.pop()
2953 state = self._finalization_state(y)
2954 if state == 0:
2955 self._bump_finalization_state_from_0_to_1(y)
2956 self.trace(y, self._append_if_nonnull, pending, None)
2957 elif state == 2:
2958 self._recursively_bump_finalization_state_from_2_to_3(y)
2959 self._recursively_bump_finalization_state_from_1_to_2(x)
2960
2961 # Clear the weak pointers to dying objects. Also clears them if
2962 # they point to objects which have the GCFLAG_FINALIZATION_ORDERING
2963 # bit set here. These are objects which will be added to
2964 # run_finalizers().
2965 self.invalidate_old_weakrefs()
2966
2967 while marked.non_empty():
2968 x = marked.popleft()
2969 fq_nr = marked.popleft()
2970 state = self._finalization_state(x)
2971 ll_assert(state >= 2, "unexpected finalization state < 2")
2972 if state == 2:
2973 from rpython.rtyper.lltypesystem import rffi
2974 fq_index = rffi.cast(lltype.Signed, fq_nr)
2975 self.mark_finalizer_to_run(fq_index, x)
2976 # we must also fix the state from 2 to 3 here, otherwise
2977 # we leave the GCFLAG_FINALIZATION_ORDERING bit behind
2978 # which will confuse the next collection
2979 self._recursively_bump_finalization_state_from_2_to_3(x)
2980 else:
2981 new_with_finalizer.append(x)
2982 new_with_finalizer.append(fq_nr)
2983
2984 self.tmpstack.delete()
2985 pending.delete()
2986 marked.delete()
2987 self.old_objects_with_finalizers.delete()
2988 self.old_objects_with_finalizers = new_with_finalizer
2989
2990 def _append_if_nonnull(pointer, stack, ignored):
2991 stack.append(pointer.address[0])
2992 _append_if_nonnull = staticmethod(_append_if_nonnull)
2993
2994 def _finalization_state(self, obj):
2995 tid = self.header(obj).tid
2996 if tid & GCFLAG_VISITED:
2997 if tid & GCFLAG_FINALIZATION_ORDERING:
2998 return 2
2999 else:
3000 return 3
3001 else:
3002 if tid & GCFLAG_FINALIZATION_ORDERING:
3003 return 1
3004 else:
3005 return 0
3006
3007 def _bump_finalization_state_from_0_to_1(self, obj):
3008 ll_assert(self._finalization_state(obj) == 0,
3009 "unexpected finalization state != 0")
3010 size_gc_header = self.gcheaderbuilder.size_gc_header
3011 totalsize = size_gc_header + self.get_size(obj)
3012 hdr = self.header(obj)
3013 hdr.tid |= GCFLAG_FINALIZATION_ORDERING
3014 # A bit hackish, but we will not count these objects as "alive"
3015 # for the purpose of computing when the next major GC should
3016 # occur. This is done for issue #2590: without this, if we
3017 # allocate mostly objects with finalizers, the
3018 # next_major_collection_threshold grows forever and actual
3019 # memory usage is not bounded.
3020 self.kept_alive_by_finalizer += raw_malloc_usage(totalsize)
3021
3022 def _recursively_bump_finalization_state_from_2_to_3(self, obj):
3023 ll_assert(self._finalization_state(obj) == 2,
3024 "unexpected finalization state != 2")
3025 pending = self.tmpstack
3026 ll_assert(not pending.non_empty(), "tmpstack not empty")
3027 pending.append(obj)
3028 while pending.non_empty():
3029 y = pending.pop()
3030 hdr = self.header(y)
3031 if hdr.tid & GCFLAG_FINALIZATION_ORDERING: # state 2 ?
3032 hdr.tid &= ~GCFLAG_FINALIZATION_ORDERING # change to state 3
3033 self.trace(y, self._append_if_nonnull, pending, None)
3034
3035 def _recursively_bump_finalization_state_from_1_to_2(self, obj):
3036 # recursively convert objects from state 1 to state 2.
3037 # The call to visit_all_objects() will add the GCFLAG_VISITED
3038 # recursively.
3039 ll_assert(not self.is_in_nursery(obj), "pinned finalizer object??")
3040 self.objects_to_trace.append(obj)
3041 self.visit_all_objects()
3042
3043 def ignore_finalizer(self, obj):
3044 self.header(obj).tid |= GCFLAG_IGNORE_FINALIZER
3045
3046
3047 # ----------
3048 # Weakrefs
3049
3050 # XXX (groggi): weakref pointing to pinned object not supported.
3051 # XXX (groggi): missing asserts/checks for the missing feature.
3052
3053 # The code relies on the fact that no weakref can be an old object
3054 # weakly pointing to a young object. Indeed, weakrefs are immutable
3055 # so they cannot point to an object that was created after it.
3056 # Thanks to this, during a minor collection, we don't have to fix
3057 # or clear the address stored in old weakrefs.
3058 def invalidate_young_weakrefs(self):
3059 """Called during a nursery collection."""
3060 # walk over the list of objects that contain weakrefs and are in the
3061 # nursery. if the object it references survives then update the
3062 # weakref; otherwise invalidate the weakref
3063 while self.young_objects_with_weakrefs.non_empty():
3064 obj = self.young_objects_with_weakrefs.pop()
3065 if not self.is_forwarded(obj):
3066 continue # weakref itself dies
3067 obj = self.get_forwarding_address(obj)
3068 offset = self.weakpointer_offset(self.get_type_id(obj))
3069 pointing_to = (obj + offset).address[0]
3070 if self.is_in_nursery(pointing_to):
3071 if self.is_forwarded(pointing_to):
3072 (obj + offset).address[0] = self.get_forwarding_address(
3073 pointing_to)
3074 else:
3075 # If the target is pinned, then we reach this point too.
3076 # It means that a hypothetical RPython interpreter that
3077 # would let you take a weakref to a pinned object (strange
3078 # thing not possible at all in PyPy) might see these
3079 # weakrefs marked as dead too early.
3080 (obj + offset).address[0] = llmemory.NULL
3081 continue # no need to remember this weakref any longer
3082 #
3083 elif (bool(self.young_rawmalloced_objects) and
3084 self.young_rawmalloced_objects.contains(pointing_to)):
3085 # young weakref to a young raw-malloced object
3086 if self.header(pointing_to).tid & GCFLAG_VISITED_RMY:
3087 pass # survives, but does not move
3088 else:
3089 (obj + offset).address[0] = llmemory.NULL
3090 continue # no need to remember this weakref any longer
3091 #
3092 elif self.header(pointing_to).tid & GCFLAG_NO_HEAP_PTRS:
3093 # see test_weakref_to_prebuilt: it's not useful to put
3094 # weakrefs into 'old_objects_with_weakrefs' if they point
3095 # to a prebuilt object (they are immortal). If moreover
3096 # the 'pointing_to' prebuilt object still has the
3097 # GCFLAG_NO_HEAP_PTRS flag, then it's even wrong, because
3098 # 'pointing_to' will not get the GCFLAG_VISITED during
3099 # the next major collection. Solve this by not registering
3100 # the weakref into 'old_objects_with_weakrefs'.
3101 continue
3102 #
3103 self.old_objects_with_weakrefs.append(obj)
3104
3105 def invalidate_old_weakrefs(self):
3106 """Called during a major collection."""
3107 # walk over list of objects that contain weakrefs
3108 # if the object it references does not survive, invalidate the weakref
3109 new_with_weakref = self.AddressStack()
3110 while self.old_objects_with_weakrefs.non_empty():
3111 obj = self.old_objects_with_weakrefs.pop()
3112 if self.header(obj).tid & GCFLAG_VISITED == 0:
3113 continue # weakref itself dies
3114 offset = self.weakpointer_offset(self.get_type_id(obj))
3115 pointing_to = (obj + offset).address[0]
3116 ll_assert((self.header(pointing_to).tid & GCFLAG_NO_HEAP_PTRS)
3117 == 0, "registered old weakref should not "
3118 "point to a NO_HEAP_PTRS obj")
3119 tid = self.header(pointing_to).tid
3120 if ((tid & (GCFLAG_VISITED | GCFLAG_FINALIZATION_ORDERING)) ==
3121 GCFLAG_VISITED):
3122 new_with_weakref.append(obj)
3123 else:
3124 (obj + offset).address[0] = llmemory.NULL
3125 self.old_objects_with_weakrefs.delete()
3126 self.old_objects_with_weakrefs = new_with_weakref
3127
3128 def get_stats(self, stats_no):
3129 from rpython.memory.gc import inspector
3130
3131 if stats_no == rgc.TOTAL_MEMORY:
3132 return intmask(self.get_total_memory_used() + self.nursery_size)
3133 elif stats_no == rgc.PEAK_MEMORY:
3134 return intmask(self.get_peak_memory_used() + self.nursery_size)
3135 elif stats_no == rgc.PEAK_ALLOCATED_MEMORY:
3136 return intmask(self.get_peak_memory_alloced() + self.nursery_size)
3137 elif stats_no == rgc.TOTAL_ALLOCATED_MEMORY:
3138 return intmask(self.get_total_memory_alloced() + self.nursery_size)
3139 elif stats_no == rgc.TOTAL_MEMORY_PRESSURE:
3140 return inspector.count_memory_pressure(self)
3141 elif stats_no == rgc.TOTAL_ARENA_MEMORY:
3142 return intmask(self.ac.total_memory_used)
3143 elif stats_no == rgc.TOTAL_RAWMALLOCED_MEMORY:
3144 return intmask(self.rawmalloced_total_size)
3145 elif stats_no == rgc.PEAK_RAWMALLOCED_MEMORY:
3146 return intmask(self.rawmalloced_peak_size)
3147 elif stats_no == rgc.PEAK_ARENA_MEMORY:
3148 return intmask(max(self.ac.peak_memory_used,
3149 self.ac.total_memory_used))
3150 elif stats_no == rgc.NURSERY_SIZE:
3151 return intmask(self.nursery_size)
3152 elif stats_no == rgc.TOTAL_GC_TIME:
3153 return int(self.total_gc_time * 1000)
3154 return 0
3155
3156
3157 # ----------
3158 # RawRefCount
3159
3160 rrc_enabled = False
3161
3162 _ADDRARRAY = lltype.Array(llmemory.Address, hints={'nolength': True})
3163 PYOBJ_HDR = lltype.Struct('GCHdr_PyObject',
3164 ('ob_refcnt', lltype.Signed),
3165 ('ob_pypy_link', lltype.Signed))
3166 PYOBJ_HDR_PTR = lltype.Ptr(PYOBJ_HDR)
3167 RAWREFCOUNT_DEALLOC_TRIGGER = lltype.Ptr(lltype.FuncType([], lltype.Void))
3168
3169 def _pyobj(self, pyobjaddr):
3170 return llmemory.cast_adr_to_ptr(pyobjaddr, self.PYOBJ_HDR_PTR)
3171
3172 def rawrefcount_init(self, dealloc_trigger_callback):
3173 # see pypy/doc/discussion/rawrefcount.rst
3174 if not self.rrc_enabled:
3175 self.rrc_p_list_young = self.AddressStack()
3176 self.rrc_p_list_old = self.AddressStack()
3177 self.rrc_o_list_young = self.AddressStack()
3178 self.rrc_o_list_old = self.AddressStack()
3179 self.rrc_p_dict = self.AddressDict() # non-nursery keys only
3180 self.rrc_p_dict_nurs = self.AddressDict() # nursery keys only
3181 self.rrc_dealloc_trigger_callback = dealloc_trigger_callback
3182 self.rrc_dealloc_pending = self.AddressStack()
3183 self.rrc_enabled = True
3184
3185 def check_no_more_rawrefcount_state(self):
3186 "NOT_RPYTHON: for tests"
3187 assert self.rrc_p_list_young.length() == 0
3188 assert self.rrc_p_list_old .length() == 0
3189 assert self.rrc_o_list_young.length() == 0
3190 assert self.rrc_o_list_old .length() == 0
3191 def check_value_is_null(key, value, ignore):
3192 assert value == llmemory.NULL
3193 self.rrc_p_dict.foreach(check_value_is_null, None)
3194 self.rrc_p_dict_nurs.foreach(check_value_is_null, None)
3195
3196 def rawrefcount_create_link_pypy(self, gcobj, pyobject):
3197 ll_assert(self.rrc_enabled, "rawrefcount.init not called")
3198 obj = llmemory.cast_ptr_to_adr(gcobj)
3199 objint = llmemory.cast_adr_to_int(obj, "symbolic")
3200 self._pyobj(pyobject).ob_pypy_link = objint
3201 #
3202 lst = self.rrc_p_list_young
3203 if self.is_in_nursery(obj):
3204 dct = self.rrc_p_dict_nurs
3205 else:
3206 dct = self.rrc_p_dict
3207 if not self.is_young_object(obj):
3208 lst = self.rrc_p_list_old
3209 lst.append(pyobject)
3210 dct.setitem(obj, pyobject)
3211
3212 def rawrefcount_create_link_pyobj(self, gcobj, pyobject):
3213 ll_assert(self.rrc_enabled, "rawrefcount.init not called")
3214 obj = llmemory.cast_ptr_to_adr(gcobj)
3215 if self.is_young_object(obj):
3216 self.rrc_o_list_young.append(pyobject)
3217 else:
3218 self.rrc_o_list_old.append(pyobject)
3219 objint = llmemory.cast_adr_to_int(obj, "symbolic")
3220 self._pyobj(pyobject).ob_pypy_link = objint
3221 # there is no rrc_o_dict
3222
3223 def rawrefcount_mark_deallocating(self, gcobj, pyobject):
3224 ll_assert(self.rrc_enabled, "rawrefcount.init not called")
3225 obj = llmemory.cast_ptr_to_adr(gcobj) # should be a prebuilt obj
3226 objint = llmemory.cast_adr_to_int(obj, "symbolic")
3227 self._pyobj(pyobject).ob_pypy_link = objint
3228
3229 def rawrefcount_from_obj(self, gcobj):
3230 obj = llmemory.cast_ptr_to_adr(gcobj)
3231 if self.is_in_nursery(obj):
3232 dct = self.rrc_p_dict_nurs
3233 else:
3234 dct = self.rrc_p_dict
3235 return dct.get(obj)
3236
3237 def rawrefcount_to_obj(self, pyobject):
3238 obj = llmemory.cast_int_to_adr(self._pyobj(pyobject).ob_pypy_link)
3239 return llmemory.cast_adr_to_ptr(obj, llmemory.GCREF)
3240
3241 def rawrefcount_next_dead(self):
3242 if self.rrc_enabled:
3243 if self.rrc_dealloc_pending.non_empty():
3244 return self.rrc_dealloc_pending.pop()
3245 return llmemory.NULL
3246
3247
3248 def rrc_invoke_callback(self):
3249 if self.rrc_enabled and self.rrc_dealloc_pending.non_empty():
3250 self.rrc_dealloc_trigger_callback()
3251
3252 def rrc_minor_collection_trace(self):
3253 length_estimate = self.rrc_p_dict_nurs.length()
3254 self.rrc_p_dict_nurs.delete()
3255 self.rrc_p_dict_nurs = self.AddressDict(length_estimate)
3256 self.rrc_p_list_young.foreach(self._rrc_minor_trace,
3257 self.singleaddr)
3258
3259 def _rrc_minor_trace(self, pyobject, singleaddr):
3260 from rpython.rlib.rawrefcount import REFCNT_FROM_PYPY
3261 from rpython.rlib.rawrefcount import REFCNT_FROM_PYPY_LIGHT
3262 #
3263 rc = self._pyobj(pyobject).ob_refcnt
3264 if rc == REFCNT_FROM_PYPY or rc == REFCNT_FROM_PYPY_LIGHT:
3265 pass # the corresponding object may die
3266 else:
3267 # force the corresponding object to be alive
3268 intobj = self._pyobj(pyobject).ob_pypy_link
3269 singleaddr.address[0] = llmemory.cast_int_to_adr(intobj)
3270 self._trace_drag_out1(singleaddr)
3271
3272 def rrc_minor_collection_free(self):
3273 ll_assert(self.rrc_p_dict_nurs.length() == 0, "p_dict_nurs not empty 1")
3274 lst = self.rrc_p_list_young
3275 while lst.non_empty():
3276 self._rrc_minor_free(lst.pop(), self.rrc_p_list_old,
3277 self.rrc_p_dict)
3278 lst = self.rrc_o_list_young
3279 no_o_dict = self.null_address_dict()
3280 while lst.non_empty():
3281 self._rrc_minor_free(lst.pop(), self.rrc_o_list_old,
3282 no_o_dict)
3283
3284 def _rrc_minor_free(self, pyobject, surviving_list, surviving_dict):
3285 intobj = self._pyobj(pyobject).ob_pypy_link
3286 obj = llmemory.cast_int_to_adr(intobj)
3287 if self.is_in_nursery(obj):
3288 if self.is_forwarded(obj):
3289 # Common case: survives and moves
3290 obj = self.get_forwarding_address(obj)
3291 intobj = llmemory.cast_adr_to_int(obj, "symbolic")
3292 self._pyobj(pyobject).ob_pypy_link = intobj
3293 surviving = True
3294 if surviving_dict:
3295 # Surviving nursery object: was originally in
3296 # rrc_p_dict_nurs and now must be put into rrc_p_dict
3297 surviving_dict.setitem(obj, pyobject)
3298 else:
3299 surviving = False
3300 elif (bool(self.young_rawmalloced_objects) and
3301 self.young_rawmalloced_objects.contains(obj)):
3302 # young rawrefcount to a young raw-malloced object
3303 if self.header(obj).tid & GCFLAG_VISITED_RMY:
3304 surviving = True # survives, but does not move
3305 else:
3306 surviving = False
3307 if surviving_dict:
3308 # Dying young large object: was in rrc_p_dict,
3309 # must be deleted
3310 surviving_dict.setitem(obj, llmemory.NULL)
3311 else:
3312 ll_assert(False, "rrc_X_list_young contains non-young obj")
3313 return
3314 #
3315 if surviving:
3316 surviving_list.append(pyobject)
3317 else:
3318 self._rrc_free(pyobject)
3319
3320 def _rrc_free(self, pyobject):
3321 from rpython.rlib.rawrefcount import REFCNT_FROM_PYPY
3322 from rpython.rlib.rawrefcount import REFCNT_FROM_PYPY_LIGHT
3323 #
3324 rc = self._pyobj(pyobject).ob_refcnt
3325 if rc >= REFCNT_FROM_PYPY_LIGHT:
3326 rc -= REFCNT_FROM_PYPY_LIGHT
3327 if rc == 0:
3328 lltype.free(self._pyobj(pyobject), flavor='raw')
3329 else:
3330 # can only occur if LIGHT is used in create_link_pyobj()
3331 self._pyobj(pyobject).ob_refcnt = rc
3332 self._pyobj(pyobject).ob_pypy_link = 0
3333 else:
3334 ll_assert(rc >= REFCNT_FROM_PYPY, "refcount underflow?")
3335 ll_assert(rc < int(REFCNT_FROM_PYPY_LIGHT * 0.99),
3336 "refcount underflow from REFCNT_FROM_PYPY_LIGHT?")
3337 rc -= REFCNT_FROM_PYPY
3338 self._pyobj(pyobject).ob_pypy_link = 0
3339 if rc == 0:
3340 self.rrc_dealloc_pending.append(pyobject)
3341 # an object with refcnt == 0 cannot stay around waiting
3342 # for its deallocator to be called. Some code (lxml)
3343 # expects that tp_dealloc is called immediately when
3344 # the refcnt drops to 0. If it isn't, we get some
3345 # uncleared raw pointer that can still be used to access
3346 # the object; but (PyObject *)raw_pointer is then bogus
3347 # because after a Py_INCREF()/Py_DECREF() on it, its
3348 # tp_dealloc is also called!
3349 rc = 1
3350 self._pyobj(pyobject).ob_refcnt = rc
3351 _rrc_free._always_inline_ = True
3352
3353 def rrc_major_collection_trace(self):
3354 self.rrc_p_list_old.foreach(self._rrc_major_trace, None)
3355
3356 def _rrc_major_trace(self, pyobject, ignore):
3357 from rpython.rlib.rawrefcount import REFCNT_FROM_PYPY
3358 from rpython.rlib.rawrefcount import REFCNT_FROM_PYPY_LIGHT
3359 #
3360 rc = self._pyobj(pyobject).ob_refcnt
3361 if rc == REFCNT_FROM_PYPY or rc == REFCNT_FROM_PYPY_LIGHT:
3362 pass # the corresponding object may die
3363 else:
3364 # force the corresponding object to be alive
3365 intobj = self._pyobj(pyobject).ob_pypy_link
3366 obj = llmemory.cast_int_to_adr(intobj)
3367 self.objects_to_trace.append(obj)
3368 # XXX ouch, isn't it enough to call visit_all_objects from
3369 # rrc_major_collection_trace? and shouldn't we check what color the
3370 # object has first? we only need to trace non-black objects after
3371 # all
3372 self.visit_all_objects()
3373
3374 def rrc_major_collection_free(self):
3375 ll_assert(self.rrc_p_dict_nurs.length() == 0, "p_dict_nurs not empty 2")
3376 length_estimate = self.rrc_p_dict.length()
3377 self.rrc_p_dict.delete()
3378 self.rrc_p_dict = new_p_dict = self.AddressDict(length_estimate)
3379 new_p_list = self.AddressStack()
3380 while self.rrc_p_list_old.non_empty():
3381 self._rrc_major_free(self.rrc_p_list_old.pop(), new_p_list,
3382 new_p_dict)
3383 self.rrc_p_list_old.delete()
3384 self.rrc_p_list_old = new_p_list
3385 #
3386 new_o_list = self.AddressStack()
3387 no_o_dict = self.null_address_dict()
3388 while self.rrc_o_list_old.non_empty():
3389 self._rrc_major_free(self.rrc_o_list_old.pop(), new_o_list,
3390 no_o_dict)
3391 self.rrc_o_list_old.delete()
3392 self.rrc_o_list_old = new_o_list
3393
3394 def _rrc_major_free(self, pyobject, surviving_list, surviving_dict):
3395 # The pyobject survives if the corresponding obj survives.
3396 # This is true if the obj has one of the following two flags:
3397 # * GCFLAG_VISITED: was seen during tracing
3398 # * GCFLAG_NO_HEAP_PTRS: immortal object never traced (so far)
3399 intobj = self._pyobj(pyobject).ob_pypy_link
3400 obj = llmemory.cast_int_to_adr(intobj)
3401 if self.header(obj).tid & (GCFLAG_VISITED | GCFLAG_NO_HEAP_PTRS):
3402 surviving_list.append(pyobject)
3403 if surviving_dict:
3404 surviving_dict.insertclean(obj, pyobject)
3405 else:
3406 self._rrc_free(pyobject)