1 /*
  2  * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "gc/parallel/objectStartArray.inline.hpp"
 27 #include "gc/parallel/parallelArguments.hpp"
 28 #include "gc/parallel/parallelScavengeHeap.hpp"
 29 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
 30 #include "gc/parallel/psCardTable.hpp"
 31 #include "gc/parallel/psOldGen.hpp"
 32 #include "gc/shared/cardTableBarrierSet.hpp"
 33 #include "gc/shared/gcLocker.hpp"
 34 #include "gc/shared/spaceDecorator.inline.hpp"
 35 #include "logging/log.hpp"
 36 #include "oops/oop.inline.hpp"
 37 #include "runtime/java.hpp"
 38 #include "utilities/align.hpp"
 39 
 40 PSOldGen::PSOldGen(ReservedSpace rs, size_t initial_size, size_t min_size,
 41                    size_t max_size, const char* perf_data_name, int level):
 42   _min_gen_size(min_size),
 43   _max_gen_size(max_size)
 44 {
 45   initialize(rs, initial_size, GenAlignment, perf_data_name, level);
 46 }
 47 
 48 void PSOldGen::initialize(ReservedSpace rs, size_t initial_size, size_t alignment,
 49                           const char* perf_data_name, int level) {
 50   initialize_virtual_space(rs, initial_size, alignment);
 51   initialize_work(perf_data_name, level);
 52 
 53   initialize_performance_counters(perf_data_name, level);
 54 }
 55 
 56 void PSOldGen::initialize_virtual_space(ReservedSpace rs,
 57                                         size_t initial_size,
 58                                         size_t alignment) {
 59 
 60   _virtual_space = new PSVirtualSpace(rs, alignment);
 61   if (!_virtual_space->expand_by(initial_size)) {
 62     vm_exit_during_initialization("Could not reserve enough space for "
 63                                   "object heap");
 64   }
 65 }
 66 
 67 void PSOldGen::initialize_work(const char* perf_data_name, int level) {
 68   MemRegion const reserved_mr = reserved();
 69   assert(reserved_mr.byte_size() == max_gen_size(), "invariant");
 70 
 71   // Object start stuff: for all reserved memory
 72   start_array()->initialize(reserved_mr);
 73 
 74   // Card table stuff: for all committed memory
 75   MemRegion committed_mr((HeapWord*)virtual_space()->low(),
 76                          (HeapWord*)virtual_space()->high());
 77 
 78   if (ZapUnusedHeapArea) {
 79     // Mangle newly committed space immediately rather than
 80     // waiting for the initialization of the space even though
 81     // mangling is related to spaces.  Doing it here eliminates
 82     // the need to carry along information that a complete mangling
 83     // (bottom to end) needs to be done.
 84     SpaceMangler::mangle_region(committed_mr);
 85   }
 86 
 87   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 88   PSCardTable* ct = heap->card_table();
 89   ct->resize_covered_region(committed_mr);
 90 
 91   // Verify that the start and end of this generation is the start of a card.
 92   // If this wasn't true, a single card could span more than one generation,
 93   // which would cause problems when we commit/uncommit memory, and when we
 94   // clear and dirty cards.
 95   guarantee(CardTable::is_card_aligned(reserved_mr.start()), "generation must be card aligned");
 96   // Check the heap layout documented at `class ParallelScavengeHeap`.
 97   assert(reserved_mr.end() != heap->reserved_region().end(), "invariant");
 98   guarantee(CardTable::is_card_aligned(reserved_mr.end()), "generation must be card aligned");
 99 
100   //
101   // ObjectSpace stuff
102   //
103 
104   _object_space = new MutableSpace(virtual_space()->alignment());
105   object_space()->initialize(committed_mr,
106                              SpaceDecorator::Clear,
107                              SpaceDecorator::Mangle,
108                              MutableSpace::SetupPages,
109                              &ParallelScavengeHeap::heap()->workers());
110 
111   // Update the start_array
112   start_array()->set_covered_region(committed_mr);
113 }
114 
115 void PSOldGen::initialize_performance_counters(const char* perf_data_name, int level) {
116   // Generation Counters, generation 'level', 1 subspace
117   _gen_counters = new PSGenerationCounters(perf_data_name, level, 1, min_gen_size(),
118                                            max_gen_size(), virtual_space());
119   _space_counters = new SpaceCounters(perf_data_name, 0,
120                                       virtual_space()->reserved_size(),
121                                       _object_space, _gen_counters);
122 }
123 
124 // Assume that the generation has been allocated if its
125 // reserved size is not 0.
126 bool  PSOldGen::is_allocated() {
127   return virtual_space()->reserved_size() != 0;
128 }
129 
130 size_t PSOldGen::num_iterable_blocks() const {
131   return (object_space()->used_in_bytes() + IterateBlockSize - 1) / IterateBlockSize;
132 }
133 
134 void PSOldGen::object_iterate_block(ObjectClosure* cl, size_t block_index) {
135   size_t block_word_size = IterateBlockSize / HeapWordSize;
136   assert((block_word_size % BOTConstants::card_size_in_words()) == 0,
137          "To ensure fast object_start calls");
138 
139   MutableSpace *space = object_space();
140 
141   HeapWord* begin = space->bottom() + block_index * block_word_size;
142   HeapWord* end = MIN2(space->top(), begin + block_word_size);
143 
144   // Get object starting at or reaching into this block.
145   HeapWord* start = start_array()->object_start(begin);
146   if (start < begin) {
147     start += cast_to_oop(start)->size();
148   }
149   assert(start >= begin,
150          "Object address" PTR_FORMAT " must be larger or equal to block address at " PTR_FORMAT,
151          p2i(start), p2i(begin));
152   // Iterate all objects until the end.
153   for (HeapWord* p = start; p < end; p += cast_to_oop(p)->size()) {
154     cl->do_object(cast_to_oop(p));
155   }
156 }
157 
158 bool PSOldGen::expand_for_allocate(size_t word_size) {
159   assert(word_size > 0, "allocating zero words?");
160   bool result = true;
161   {
162     MutexLocker x(PSOldGenExpand_lock);
163     // Avoid "expand storms" by rechecking available space after obtaining
164     // the lock, because another thread may have already made sufficient
165     // space available.  If insufficient space available, that will remain
166     // true until we expand, since we have the lock.  Other threads may take
167     // the space we need before we can allocate it, regardless of whether we
168     // expand.  That's okay, we'll just try expanding again.
169     if (object_space()->needs_expand(word_size)) {
170       result = expand(word_size*HeapWordSize);
171     }
172   }
173   if (GCExpandToAllocateDelayMillis > 0) {
174     os::naked_sleep(GCExpandToAllocateDelayMillis);
175   }
176   return result;
177 }
178 
179 bool PSOldGen::expand(size_t bytes) {
180   assert_lock_strong(PSOldGenExpand_lock);
181   assert_locked_or_safepoint(Heap_lock);
182   assert(bytes > 0, "precondition");
183   const size_t alignment = virtual_space()->alignment();
184   size_t aligned_bytes  = align_up(bytes, alignment);
185   size_t aligned_expand_bytes = align_up(MinHeapDeltaBytes, alignment);
186 
187   if (UseNUMA) {
188     // With NUMA we use round-robin page allocation for the old gen. Expand by at least
189     // providing a page per lgroup. Alignment is larger or equal to the page size.
190     aligned_expand_bytes = MAX2(aligned_expand_bytes, alignment * os::numa_get_groups_num());
191   }
192   if (aligned_bytes == 0) {
193     // The alignment caused the number of bytes to wrap.  A call to expand
194     // implies a best effort to expand by "bytes" but not a guarantee.  Align
195     // down to give a best effort.  This is likely the most that the generation
196     // can expand since it has some capacity to start with.
197     aligned_bytes = align_down(bytes, alignment);
198   }
199 
200   bool success = false;
201   if (aligned_expand_bytes > aligned_bytes) {
202     success = expand_by(aligned_expand_bytes);
203   }
204   if (!success) {
205     success = expand_by(aligned_bytes);
206   }
207   if (!success) {
208     success = expand_to_reserved();
209   }
210 
211   if (success && GCLocker::is_active_and_needs_gc()) {
212     log_debug(gc)("Garbage collection disabled, expanded heap instead");
213   }
214   return success;
215 }
216 
217 bool PSOldGen::expand_by(size_t bytes) {
218   assert_lock_strong(PSOldGenExpand_lock);
219   assert_locked_or_safepoint(Heap_lock);
220   assert(bytes > 0, "precondition");
221   bool result = virtual_space()->expand_by(bytes);
222   if (result) {
223     if (ZapUnusedHeapArea) {
224       // We need to mangle the newly expanded area. The memregion spans
225       // end -> new_end, we assume that top -> end is already mangled.
226       // Do the mangling before post_resize() is called because
227       // the space is available for allocation after post_resize();
228       HeapWord* const virtual_space_high = (HeapWord*) virtual_space()->high();
229       assert(object_space()->end() < virtual_space_high,
230         "Should be true before post_resize()");
231       MemRegion mangle_region(object_space()->end(), virtual_space_high);
232       // Note that the object space has not yet been updated to
233       // coincide with the new underlying virtual space.
234       SpaceMangler::mangle_region(mangle_region);
235     }
236     post_resize();
237     if (UsePerfData) {
238       _space_counters->update_capacity();
239       _gen_counters->update_all();
240     }
241   }
242 
243   if (result) {
244     size_t new_mem_size = virtual_space()->committed_size();
245     size_t old_mem_size = new_mem_size - bytes;
246     log_debug(gc)("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
247                   name(), old_mem_size/K, bytes/K, new_mem_size/K);
248   }
249 
250   return result;
251 }
252 
253 bool PSOldGen::expand_to_reserved() {
254   assert_lock_strong(PSOldGenExpand_lock);
255   assert_locked_or_safepoint(Heap_lock);
256 
257   bool result = false;
258   const size_t remaining_bytes = virtual_space()->uncommitted_size();
259   if (remaining_bytes > 0) {
260     result = expand_by(remaining_bytes);
261     DEBUG_ONLY(if (!result) log_warning(gc)("grow to reserve failed"));
262   }
263   return result;
264 }
265 
266 void PSOldGen::shrink(size_t bytes) {
267   assert_lock_strong(PSOldGenExpand_lock);
268   assert_locked_or_safepoint(Heap_lock);
269 
270   size_t size = align_down(bytes, virtual_space()->alignment());
271   if (size > 0) {
272     virtual_space()->shrink_by(bytes);
273     post_resize();
274 
275     size_t new_mem_size = virtual_space()->committed_size();
276     size_t old_mem_size = new_mem_size + bytes;
277     log_debug(gc)("Shrinking %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
278                   name(), old_mem_size/K, bytes/K, new_mem_size/K);
279   }
280 }
281 
282 void PSOldGen::complete_loaded_archive_space(MemRegion archive_space) {
283   HeapWord* cur = archive_space.start();
284   while (cur < archive_space.end()) {
285     size_t word_size = cast_to_oop(cur)->size();
286     _start_array.update_for_block(cur, cur + word_size);
287     cur += word_size;
288   }
289 }
290 
291 void PSOldGen::resize(size_t desired_free_space) {
292   const size_t alignment = virtual_space()->alignment();
293   const size_t size_before = virtual_space()->committed_size();
294   size_t new_size = used_in_bytes() + desired_free_space;
295   if (new_size < used_in_bytes()) {
296     // Overflowed the addition.
297     new_size = max_gen_size();
298   }
299   // Adjust according to our min and max
300   new_size = clamp(new_size, min_gen_size(), max_gen_size());
301 
302   new_size = align_up(new_size, alignment);
303 
304   const size_t current_size = capacity_in_bytes();
305 
306   log_trace(gc, ergo)("AdaptiveSizePolicy::old generation size: "
307     "desired free: " SIZE_FORMAT " used: " SIZE_FORMAT
308     " new size: " SIZE_FORMAT " current size " SIZE_FORMAT
309     " gen limits: " SIZE_FORMAT " / " SIZE_FORMAT,
310     desired_free_space, used_in_bytes(), new_size, current_size,
311     max_gen_size(), min_gen_size());
312 
313   if (new_size == current_size) {
314     // No change requested
315     return;
316   }
317   if (new_size > current_size) {
318     size_t change_bytes = new_size - current_size;
319     MutexLocker x(PSOldGenExpand_lock);
320     expand(change_bytes);
321   } else {
322     size_t change_bytes = current_size - new_size;
323     MutexLocker x(PSOldGenExpand_lock);
324     shrink(change_bytes);
325   }
326 
327   log_trace(gc, ergo)("AdaptiveSizePolicy::old generation size: collection: %d (" SIZE_FORMAT ") -> (" SIZE_FORMAT ") ",
328                       ParallelScavengeHeap::heap()->total_collections(),
329                       size_before,
330                       virtual_space()->committed_size());
331 }
332 
333 // NOTE! We need to be careful about resizing. During a GC, multiple
334 // allocators may be active during heap expansion. If we allow the
335 // heap resizing to become visible before we have correctly resized
336 // all heap related data structures, we may cause program failures.
337 void PSOldGen::post_resize() {
338   // First construct a memregion representing the new size
339   MemRegion new_memregion((HeapWord*)virtual_space()->low(),
340     (HeapWord*)virtual_space()->high());
341   size_t new_word_size = new_memregion.word_size();
342 
343   start_array()->set_covered_region(new_memregion);
344   ParallelScavengeHeap::heap()->card_table()->resize_covered_region(new_memregion);
345 
346   WorkerThreads* workers = Thread::current()->is_VM_thread() ?
347                       &ParallelScavengeHeap::heap()->workers() : nullptr;
348 
349   // The update of the space's end is done by this call.  As that
350   // makes the new space available for concurrent allocation, this
351   // must be the last step when expanding.
352   object_space()->initialize(new_memregion,
353                              SpaceDecorator::DontClear,
354                              SpaceDecorator::DontMangle,
355                              MutableSpace::SetupPages,
356                              workers);
357 
358   assert(new_word_size == heap_word_size(object_space()->capacity_in_bytes()),
359     "Sanity");
360 }
361 
362 void PSOldGen::print() const { print_on(tty);}
363 void PSOldGen::print_on(outputStream* st) const {
364   st->print(" %-15s", name());
365   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
366               capacity_in_bytes()/K, used_in_bytes()/K);
367   st->print_cr(" [" PTR_FORMAT ", " PTR_FORMAT ", " PTR_FORMAT ")",
368                 p2i(virtual_space()->low_boundary()),
369                 p2i(virtual_space()->high()),
370                 p2i(virtual_space()->high_boundary()));
371 
372   st->print("  object"); object_space()->print_on(st);
373 }
374 
375 void PSOldGen::update_counters() {
376   if (UsePerfData) {
377     _space_counters->update_all();
378     _gen_counters->update_all();
379   }
380 }
381 
382 void PSOldGen::verify() {
383   object_space()->verify();
384 }
385 
386 class VerifyObjectStartArrayClosure : public ObjectClosure {
387   ObjectStartArray* _start_array;
388 
389 public:
390   VerifyObjectStartArrayClosure(ObjectStartArray* start_array) :
391     _start_array(start_array) { }
392 
393   virtual void do_object(oop obj) {
394     // With compact headers, the objects can be one-word sized.
395     size_t int_off = UseCompactObjectHeaders ? MIN2((size_t)1, obj->size() - 1) : 1;
396     HeapWord* test_addr = cast_from_oop<HeapWord*>(obj) + int_off;
397     guarantee(_start_array->object_start(test_addr) == cast_from_oop<HeapWord*>(obj), "ObjectStartArray cannot find start of object");
398   }
399 };
400 
401 void PSOldGen::verify_object_start_array() {
402   VerifyObjectStartArrayClosure check(&_start_array);
403   object_iterate(&check);
404 }
405 
406 #ifndef PRODUCT
407 void PSOldGen::record_spaces_top() {
408   assert(ZapUnusedHeapArea, "Not mangling unused space");
409   object_space()->set_top_for_allocations();
410 }
411 #endif