1 /*
  2  * Copyright (c) 2001, 2022, 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 "classfile/classLoaderData.hpp"
 27 #include "classfile/vmClasses.hpp"
 28 #include "gc/shared/allocTracer.hpp"
 29 #include "gc/shared/barrierSet.hpp"
 30 #include "gc/shared/collectedHeap.hpp"
 31 #include "gc/shared/collectedHeap.inline.hpp"
 32 #include "gc/shared/gcLocker.inline.hpp"
 33 #include "gc/shared/gcHeapSummary.hpp"
 34 #include "gc/shared/stringdedup/stringDedup.hpp"
 35 #include "gc/shared/gcTrace.hpp"
 36 #include "gc/shared/gcTraceTime.inline.hpp"
 37 #include "gc/shared/gcVMOperations.hpp"
 38 #include "gc/shared/gcWhen.hpp"
 39 #include "gc/shared/gc_globals.hpp"
 40 #include "gc/shared/memAllocator.hpp"
 41 #include "gc/shared/tlab_globals.hpp"
 42 #include "logging/log.hpp"
 43 #include "logging/logStream.hpp"
 44 #include "memory/classLoaderMetaspace.hpp"
 45 #include "memory/metaspaceUtils.hpp"
 46 #include "memory/resourceArea.hpp"
 47 #include "memory/universe.hpp"
 48 #include "oops/instanceMirrorKlass.hpp"
 49 #include "oops/oop.inline.hpp"
 50 #include "runtime/handles.inline.hpp"
 51 #include "runtime/init.hpp"
 52 #include "runtime/javaThread.hpp"
 53 #include "runtime/perfData.hpp"
 54 #include "runtime/threadSMR.hpp"
 55 #include "runtime/vmThread.hpp"
 56 #include "services/heapDumper.hpp"
 57 #include "utilities/align.hpp"
 58 #include "utilities/copy.hpp"
 59 #include "utilities/events.hpp"
 60 
 61 class ClassLoaderData;
 62 
 63 size_t CollectedHeap::_lab_alignment_reserve = ~(size_t)0;
 64 Klass* CollectedHeap::_filler_object_klass = NULL;
 65 size_t CollectedHeap::_filler_array_max_size = 0;
 66 size_t CollectedHeap::_stack_chunk_max_size = 0;
 67 
 68 class GCMessage : public FormatBuffer<1024> {
 69  public:
 70   bool is_before;
 71 };
 72 
 73 template <>
 74 void EventLogBase<GCMessage>::print(outputStream* st, GCMessage& m) {
 75   st->print_cr("GC heap %s", m.is_before ? "before" : "after");
 76   st->print_raw(m);
 77 }
 78 
 79 class GCHeapLog : public EventLogBase<GCMessage> {
 80  private:
 81   void log_heap(CollectedHeap* heap, bool before);
 82 
 83  public:
 84   GCHeapLog() : EventLogBase<GCMessage>("GC Heap History", "gc") {}
 85 
 86   void log_heap_before(CollectedHeap* heap) {
 87     log_heap(heap, true);
 88   }
 89   void log_heap_after(CollectedHeap* heap) {
 90     log_heap(heap, false);
 91   }
 92 };
 93 
 94 void GCHeapLog::log_heap(CollectedHeap* heap, bool before) {
 95   if (!should_log()) {
 96     return;
 97   }
 98 
 99   double timestamp = fetch_timestamp();
100   MutexLocker ml(&_mutex, Mutex::_no_safepoint_check_flag);
101   int index = compute_log_index();
102   _records[index].thread = NULL; // Its the GC thread so it's not that interesting.
103   _records[index].timestamp = timestamp;
104   _records[index].data.is_before = before;
105   stringStream st(_records[index].data.buffer(), _records[index].data.size());
106 
107   st.print_cr("{Heap %s GC invocations=%u (full %u):",
108                  before ? "before" : "after",
109                  heap->total_collections(),
110                  heap->total_full_collections());
111 
112   heap->print_on(&st);
113   st.print_cr("}");
114 }
115 
116 ParallelObjectIterator::ParallelObjectIterator(uint thread_num) :
117   _impl(Universe::heap()->parallel_object_iterator(thread_num))
118 {}
119 
120 ParallelObjectIterator::~ParallelObjectIterator() {
121   delete _impl;
122 }
123 
124 void ParallelObjectIterator::object_iterate(ObjectClosure* cl, uint worker_id) {
125   _impl->object_iterate(cl, worker_id);
126 }
127 
128 size_t CollectedHeap::unused() const {
129   MutexLocker ml(Heap_lock);
130   return capacity() - used();
131 }
132 
133 VirtualSpaceSummary CollectedHeap::create_heap_space_summary() {
134   size_t capacity_in_words = capacity() / HeapWordSize;
135 
136   return VirtualSpaceSummary(
137     _reserved.start(), _reserved.start() + capacity_in_words, _reserved.end());
138 }
139 
140 GCHeapSummary CollectedHeap::create_heap_summary() {
141   VirtualSpaceSummary heap_space = create_heap_space_summary();
142   return GCHeapSummary(heap_space, used());
143 }
144 
145 MetaspaceSummary CollectedHeap::create_metaspace_summary() {
146   const MetaspaceChunkFreeListSummary& ms_chunk_free_list_summary =
147     MetaspaceUtils::chunk_free_list_summary(Metaspace::NonClassType);
148   const MetaspaceChunkFreeListSummary& class_chunk_free_list_summary =
149     MetaspaceUtils::chunk_free_list_summary(Metaspace::ClassType);
150   return MetaspaceSummary(MetaspaceGC::capacity_until_GC(),
151                           MetaspaceUtils::get_combined_statistics(),
152                           ms_chunk_free_list_summary, class_chunk_free_list_summary);
153 }
154 
155 void CollectedHeap::print_heap_before_gc() {
156   LogTarget(Debug, gc, heap) lt;
157   if (lt.is_enabled()) {
158     LogStream ls(lt);
159     ls.print_cr("Heap before GC invocations=%u (full %u):", total_collections(), total_full_collections());
160     ResourceMark rm;
161     print_on(&ls);
162   }
163 
164   if (_gc_heap_log != NULL) {
165     _gc_heap_log->log_heap_before(this);
166   }
167 }
168 
169 void CollectedHeap::print_heap_after_gc() {
170   LogTarget(Debug, gc, heap) lt;
171   if (lt.is_enabled()) {
172     LogStream ls(lt);
173     ls.print_cr("Heap after GC invocations=%u (full %u):", total_collections(), total_full_collections());
174     ResourceMark rm;
175     print_on(&ls);
176   }
177 
178   if (_gc_heap_log != NULL) {
179     _gc_heap_log->log_heap_after(this);
180   }
181 }
182 
183 void CollectedHeap::print() const { print_on(tty); }
184 
185 void CollectedHeap::print_on_error(outputStream* st) const {
186   st->print_cr("Heap:");
187   print_extended_on(st);
188   st->cr();
189 
190   BarrierSet* bs = BarrierSet::barrier_set();
191   if (bs != NULL) {
192     bs->print_on(st);
193   }
194 }
195 
196 void CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
197   const GCHeapSummary& heap_summary = create_heap_summary();
198   gc_tracer->report_gc_heap_summary(when, heap_summary);
199 
200   const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
201   gc_tracer->report_metaspace_summary(when, metaspace_summary);
202 }
203 
204 void CollectedHeap::trace_heap_before_gc(const GCTracer* gc_tracer) {
205   trace_heap(GCWhen::BeforeGC, gc_tracer);
206 }
207 
208 void CollectedHeap::trace_heap_after_gc(const GCTracer* gc_tracer) {
209   trace_heap(GCWhen::AfterGC, gc_tracer);
210 }
211 
212 // Default implementation, for collectors that don't support the feature.
213 bool CollectedHeap::supports_concurrent_gc_breakpoints() const {
214   return false;
215 }
216 
217 bool CollectedHeap::is_oop(oop object) const {
218   if (!is_object_aligned(object)) {
219     return false;
220   }
221 
222   if (!is_in(object)) {
223     return false;
224   }
225 
226   return true;
227 }
228 
229 // Memory state functions.
230 
231 
232 CollectedHeap::CollectedHeap() :
233   _capacity_at_last_gc(0),
234   _used_at_last_gc(0),
235   _is_gc_active(false),
236   _last_whole_heap_examined_time_ns(os::javaTimeNanos()),
237   _total_collections(0),
238   _total_full_collections(0),
239   _gc_cause(GCCause::_no_gc),
240   _gc_lastcause(GCCause::_no_gc)
241 {
242   // If the minimum object size is greater than MinObjAlignment, we can
243   // end up with a shard at the end of the buffer that's smaller than
244   // the smallest object.  We can't allow that because the buffer must
245   // look like it's full of objects when we retire it, so we make
246   // sure we have enough space for a filler int array object.
247   size_t min_size = min_dummy_object_size();
248   _lab_alignment_reserve = min_size > (size_t)MinObjAlignment ? align_object_size(min_size) : 0;
249 
250   const size_t max_len = size_t(arrayOopDesc::max_array_length(T_INT));
251   const size_t elements_per_word = HeapWordSize / sizeof(jint);
252   int header_size_in_bytes = arrayOopDesc::base_offset_in_bytes(T_INT);
253   assert(header_size_in_bytes % sizeof(jint) == 0, "must be aligned to int");
254   int header_size_in_ints = header_size_in_bytes / sizeof(jint);
255   _filler_array_max_size = align_object_size((header_size_in_ints + max_len) / elements_per_word);
256 
257   NOT_PRODUCT(_promotion_failure_alot_count = 0;)
258   NOT_PRODUCT(_promotion_failure_alot_gc_number = 0;)
259 
260   if (UsePerfData) {
261     EXCEPTION_MARK;
262 
263     // create the gc cause jvmstat counters
264     _perf_gc_cause = PerfDataManager::create_string_variable(SUN_GC, "cause",
265                              80, GCCause::to_string(_gc_cause), CHECK);
266 
267     _perf_gc_lastcause =
268                 PerfDataManager::create_string_variable(SUN_GC, "lastCause",
269                              80, GCCause::to_string(_gc_lastcause), CHECK);
270   }
271 
272   // Create the ring log
273   if (LogEvents) {
274     _gc_heap_log = new GCHeapLog();
275   } else {
276     _gc_heap_log = NULL;
277   }
278 }
279 
280 // This interface assumes that it's being called by the
281 // vm thread. It collects the heap assuming that the
282 // heap lock is already held and that we are executing in
283 // the context of the vm thread.
284 void CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
285   Thread* thread = Thread::current();
286   assert(thread->is_VM_thread(), "Precondition#1");
287   assert(Heap_lock->is_locked(), "Precondition#2");
288   GCCauseSetter gcs(this, cause);
289   switch (cause) {
290     case GCCause::_codecache_GC_threshold:
291     case GCCause::_heap_inspection:
292     case GCCause::_heap_dump:
293     case GCCause::_metadata_GC_threshold : {
294       HandleMark hm(thread);
295       do_full_collection(false);        // don't clear all soft refs
296       break;
297     }
298     case GCCause::_archive_time_gc:
299     case GCCause::_metadata_GC_clear_soft_refs: {
300       HandleMark hm(thread);
301       do_full_collection(true);         // do clear all soft refs
302       break;
303     }
304     default:
305       ShouldNotReachHere(); // Unexpected use of this function
306   }
307 }
308 
309 MetaWord* CollectedHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
310                                                             size_t word_size,
311                                                             Metaspace::MetadataType mdtype) {
312   uint loop_count = 0;
313   uint gc_count = 0;
314   uint full_gc_count = 0;
315 
316   assert(!Heap_lock->owned_by_self(), "Should not be holding the Heap_lock");
317 
318   do {
319     MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
320     if (result != NULL) {
321       return result;
322     }
323 
324     if (GCLocker::is_active_and_needs_gc()) {
325       // If the GCLocker is active, just expand and allocate.
326       // If that does not succeed, wait if this thread is not
327       // in a critical section itself.
328       result = loader_data->metaspace_non_null()->expand_and_allocate(word_size, mdtype);
329       if (result != NULL) {
330         return result;
331       }
332       JavaThread* jthr = JavaThread::current();
333       if (!jthr->in_critical()) {
334         // Wait for JNI critical section to be exited
335         GCLocker::stall_until_clear();
336         // The GC invoked by the last thread leaving the critical
337         // section will be a young collection and a full collection
338         // is (currently) needed for unloading classes so continue
339         // to the next iteration to get a full GC.
340         continue;
341       } else {
342         if (CheckJNICalls) {
343           fatal("Possible deadlock due to allocating while"
344                 " in jni critical section");
345         }
346         return NULL;
347       }
348     }
349 
350     {  // Need lock to get self consistent gc_count's
351       MutexLocker ml(Heap_lock);
352       gc_count      = Universe::heap()->total_collections();
353       full_gc_count = Universe::heap()->total_full_collections();
354     }
355 
356     // Generate a VM operation
357     VM_CollectForMetadataAllocation op(loader_data,
358                                        word_size,
359                                        mdtype,
360                                        gc_count,
361                                        full_gc_count,
362                                        GCCause::_metadata_GC_threshold);
363     VMThread::execute(&op);
364 
365     // If GC was locked out, try again. Check before checking success because the
366     // prologue could have succeeded and the GC still have been locked out.
367     if (op.gc_locked()) {
368       continue;
369     }
370 
371     if (op.prologue_succeeded()) {
372       return op.result();
373     }
374     loop_count++;
375     if ((QueuedAllocationWarningCount > 0) &&
376         (loop_count % QueuedAllocationWarningCount == 0)) {
377       log_warning(gc, ergo)("satisfy_failed_metadata_allocation() retries %d times,"
378                             " size=" SIZE_FORMAT, loop_count, word_size);
379     }
380   } while (true);  // Until a GC is done
381 }
382 
383 MemoryUsage CollectedHeap::memory_usage() {
384   return MemoryUsage(InitialHeapSize, used(), capacity(), max_capacity());
385 }
386 
387 void CollectedHeap::set_gc_cause(GCCause::Cause v) {
388   if (UsePerfData) {
389     _gc_lastcause = _gc_cause;
390     _perf_gc_lastcause->set_value(GCCause::to_string(_gc_lastcause));
391     _perf_gc_cause->set_value(GCCause::to_string(v));
392   }
393   _gc_cause = v;
394 }
395 
396 #ifndef PRODUCT
397 void CollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr, size_t size) {
398   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
399     // please note mismatch between size (in 32/64 bit words), and ju_addr that always point to a 32 bit word
400     for (juint* ju_addr = reinterpret_cast<juint*>(addr); ju_addr < reinterpret_cast<juint*>(addr + size); ++ju_addr) {
401       assert(*ju_addr == badHeapWordVal, "Found non badHeapWordValue in pre-allocation check");
402     }
403   }
404 }
405 #endif // PRODUCT
406 
407 size_t CollectedHeap::max_tlab_size() const {
408   // TLABs can't be bigger than we can fill with a int[Integer.MAX_VALUE].
409   // This restriction could be removed by enabling filling with multiple arrays.
410   // If we compute that the reasonable way as
411   //    header_size + ((sizeof(jint) * max_jint) / HeapWordSize)
412   // we'll overflow on the multiply, so we do the divide first.
413   // We actually lose a little by dividing first,
414   // but that just makes the TLAB  somewhat smaller than the biggest array,
415   // which is fine, since we'll be able to fill that.
416   int header_size_in_bytes = typeArrayOopDesc::base_offset_in_bytes(T_INT);
417   assert(header_size_in_bytes % sizeof(jint) == 0, "header size must align to int");
418   size_t max_int_size = header_size_in_bytes / HeapWordSize +
419               sizeof(jint) *
420               ((juint) max_jint / (size_t) HeapWordSize);
421   return align_down(max_int_size, MinObjAlignment);
422 }
423 
424 size_t CollectedHeap::filler_array_min_size() {
425   int aligned_header_size_words = align_up(arrayOopDesc::base_offset_in_bytes(T_INT), HeapWordSize) / HeapWordSize;
426   return align_object_size(aligned_header_size_words); // align to MinObjAlignment
427 }
428 
429 void CollectedHeap::zap_filler_array_with(HeapWord* start, size_t words, juint value) {
430   int payload_start = align_up(arrayOopDesc::base_offset_in_bytes(T_INT), HeapWordSize) / HeapWordSize;
431   Copy::fill_to_words(start + payload_start,
432                       words - payload_start, value);
433 }
434 
435 #ifdef ASSERT
436 void CollectedHeap::fill_args_check(HeapWord* start, size_t words)
437 {
438   assert(words >= min_fill_size(), "too small to fill");
439   assert(is_object_aligned(words), "unaligned size");
440 }
441 
442 void CollectedHeap::zap_filler_array(HeapWord* start, size_t words, bool zap)
443 {
444   if (ZapFillerObjects && zap) {
445     zap_filler_array_with(start, words, 0XDEAFBABE);
446   }
447 }
448 #endif // ASSERT
449 
450 void
451 CollectedHeap::fill_with_array(HeapWord* start, size_t words, bool zap)
452 {
453   assert(words >= filler_array_min_size(), "too small for an array");
454   assert(words <= filler_array_max_size(), "too big for a single object");
455 
456   const size_t payload_size_bytes = words * HeapWordSize - arrayOopDesc::base_offset_in_bytes(T_INT);
457   assert(payload_size_bytes % sizeof(jint) == 0, "must be int aligned");
458   const size_t len = payload_size_bytes / sizeof(jint);
459   assert((int)len >= 0, "size too large " SIZE_FORMAT " becomes %d", words, (int)len);
460 
461   ObjArrayAllocator allocator(Universe::fillerArrayKlassObj(), words, (int)len, /* do_zero */ false);
462   allocator.initialize(start);
463   if (DumpSharedSpaces) {
464     // This array is written into the CDS archive. Make sure it
465     // has deterministic contents.
466     zap_filler_array_with(start, words, 0);
467   } else {
468     DEBUG_ONLY(zap_filler_array(start, words, zap);)
469   }
470 }
471 
472 void
473 CollectedHeap::fill_with_object_impl(HeapWord* start, size_t words, bool zap)
474 {
475   assert(words <= filler_array_max_size(), "too big for a single object");
476 
477   if (words >= filler_array_min_size()) {
478     fill_with_array(start, words, zap);
479   } else if (words > 0) {
480     assert(words == min_fill_size(), "unaligned size");
481     ObjAllocator allocator(CollectedHeap::filler_object_klass(), words);
482     allocator.initialize(start);
483   }
484 }
485 
486 void CollectedHeap::fill_with_object(HeapWord* start, size_t words, bool zap)
487 {
488   DEBUG_ONLY(fill_args_check(start, words);)
489   HandleMark hm(Thread::current());  // Free handles before leaving.
490   fill_with_object_impl(start, words, zap);
491 }
492 
493 void CollectedHeap::fill_with_objects(HeapWord* start, size_t words, bool zap)
494 {
495   DEBUG_ONLY(fill_args_check(start, words);)
496   HandleMark hm(Thread::current());  // Free handles before leaving.
497 
498   // Multiple objects may be required depending on the filler array maximum size. Fill
499   // the range up to that with objects that are filler_array_max_size sized. The
500   // remainder is filled with a single object.
501   const size_t min = min_fill_size();
502   const size_t max = filler_array_max_size();
503   while (words > max) {
504     const size_t cur = (words - max) >= min ? max : max - min;
505     fill_with_array(start, cur, zap);
506     start += cur;
507     words -= cur;
508   }
509 
510   fill_with_object_impl(start, words, zap);
511 }
512 
513 void CollectedHeap::fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) {
514   CollectedHeap::fill_with_object(start, end, zap);
515 }
516 
517 HeapWord* CollectedHeap::allocate_new_tlab(size_t min_size,
518                                            size_t requested_size,
519                                            size_t* actual_size) {
520   guarantee(false, "thread-local allocation buffers not supported");
521   return NULL;
522 }
523 
524 void CollectedHeap::ensure_parsability(bool retire_tlabs) {
525   assert(SafepointSynchronize::is_at_safepoint() || !is_init_completed(),
526          "Should only be called at a safepoint or at start-up");
527 
528   ThreadLocalAllocStats stats;
529 
530   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next();) {
531     BarrierSet::barrier_set()->make_parsable(thread);
532     if (UseTLAB) {
533       if (retire_tlabs) {
534         thread->tlab().retire(&stats);
535       } else {
536         thread->tlab().make_parsable();
537       }
538     }
539   }
540 
541   stats.publish();
542 }
543 
544 void CollectedHeap::resize_all_tlabs() {
545   assert(SafepointSynchronize::is_at_safepoint() || !is_init_completed(),
546          "Should only resize tlabs at safepoint");
547 
548   if (UseTLAB && ResizeTLAB) {
549     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
550       thread->tlab().resize();
551     }
552   }
553 }
554 
555 jlong CollectedHeap::millis_since_last_whole_heap_examined() {
556   return (os::javaTimeNanos() - _last_whole_heap_examined_time_ns) / NANOSECS_PER_MILLISEC;
557 }
558 
559 void CollectedHeap::record_whole_heap_examined_timestamp() {
560   _last_whole_heap_examined_time_ns = os::javaTimeNanos();
561 }
562 
563 void CollectedHeap::full_gc_dump(GCTimer* timer, bool before) {
564   assert(timer != NULL, "timer is null");
565   if ((HeapDumpBeforeFullGC && before) || (HeapDumpAfterFullGC && !before)) {
566     GCTraceTime(Info, gc) tm(before ? "Heap Dump (before full gc)" : "Heap Dump (after full gc)", timer);
567     HeapDumper::dump_heap();
568   }
569 
570   LogTarget(Trace, gc, classhisto) lt;
571   if (lt.is_enabled()) {
572     GCTraceTime(Trace, gc, classhisto) tm(before ? "Class Histogram (before full gc)" : "Class Histogram (after full gc)", timer);
573     ResourceMark rm;
574     LogStream ls(lt);
575     VM_GC_HeapInspection inspector(&ls, false /* ! full gc */);
576     inspector.doit();
577   }
578 }
579 
580 void CollectedHeap::pre_full_gc_dump(GCTimer* timer) {
581   full_gc_dump(timer, true);
582 }
583 
584 void CollectedHeap::post_full_gc_dump(GCTimer* timer) {
585   full_gc_dump(timer, false);
586 }
587 
588 void CollectedHeap::initialize_reserved_region(const ReservedHeapSpace& rs) {
589   // It is important to do this in a way such that concurrent readers can't
590   // temporarily think something is in the heap.  (Seen this happen in asserts.)
591   _reserved.set_word_size(0);
592   _reserved.set_start((HeapWord*)rs.base());
593   _reserved.set_end((HeapWord*)rs.end());
594 }
595 
596 void CollectedHeap::post_initialize() {
597   StringDedup::initialize();
598   initialize_serviceability();
599 }
600 
601 #ifndef PRODUCT
602 
603 bool CollectedHeap::promotion_should_fail(volatile size_t* count) {
604   // Access to count is not atomic; the value does not have to be exact.
605   if (PromotionFailureALot) {
606     const size_t gc_num = total_collections();
607     const size_t elapsed_gcs = gc_num - _promotion_failure_alot_gc_number;
608     if (elapsed_gcs >= PromotionFailureALotInterval) {
609       // Test for unsigned arithmetic wrap-around.
610       if (++*count >= PromotionFailureALotCount) {
611         *count = 0;
612         return true;
613       }
614     }
615   }
616   return false;
617 }
618 
619 bool CollectedHeap::promotion_should_fail() {
620   return promotion_should_fail(&_promotion_failure_alot_count);
621 }
622 
623 void CollectedHeap::reset_promotion_should_fail(volatile size_t* count) {
624   if (PromotionFailureALot) {
625     _promotion_failure_alot_gc_number = total_collections();
626     *count = 0;
627   }
628 }
629 
630 void CollectedHeap::reset_promotion_should_fail() {
631   reset_promotion_should_fail(&_promotion_failure_alot_count);
632 }
633 
634 #endif  // #ifndef PRODUCT
635 
636 bool CollectedHeap::supports_object_pinning() const {
637   return false;
638 }
639 
640 oop CollectedHeap::pin_object(JavaThread* thread, oop obj) {
641   ShouldNotReachHere();
642   return NULL;
643 }
644 
645 void CollectedHeap::unpin_object(JavaThread* thread, oop obj) {
646   ShouldNotReachHere();
647 }
648 
649 bool CollectedHeap::is_archived_object(oop object) const {
650   return false;
651 }
652 
653 uint32_t CollectedHeap::hash_oop(oop obj) const {
654   const uintptr_t addr = cast_from_oop<uintptr_t>(obj);
655   return static_cast<uint32_t>(addr >> LogMinObjAlignment);
656 }
657 
658 // It's the caller's responsibility to ensure glitch-freedom
659 // (if required).
660 void CollectedHeap::update_capacity_and_used_at_gc() {
661   _capacity_at_last_gc = capacity();
662   _used_at_last_gc     = used();
663 }