1 /*
   2  * Copyright (c) 2000, 2012, 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/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "gc_implementation/shared/collectorCounters.hpp"
  31 #include "gc_implementation/shared/gcTraceTime.hpp"
  32 #include "gc_implementation/shared/vmGCOperations.hpp"
  33 #include "gc_interface/collectedHeap.inline.hpp"
  34 #include "memory/compactPermGen.hpp"
  35 #include "memory/filemap.hpp"
  36 #include "memory/gcLocker.inline.hpp"
  37 #include "memory/genCollectedHeap.hpp"
  38 #include "memory/genOopClosures.inline.hpp"
  39 #include "memory/generation.inline.hpp"
  40 #include "memory/generationSpec.hpp"
  41 #include "memory/permGen.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "memory/sharedHeap.hpp"
  44 #include "memory/space.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "oops/oop.inline2.hpp"
  47 #include "runtime/aprofiler.hpp"
  48 #include "runtime/biasedLocking.hpp"
  49 #include "runtime/fprofiler.hpp"
  50 #include "runtime/handles.hpp"
  51 #include "runtime/handles.inline.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/vmThread.hpp"
  54 #include "services/memoryService.hpp"
  55 #include "services/memTracker.hpp"
  56 #include "utilities/vmError.hpp"
  57 #include "utilities/workgroup.hpp"
  58 #ifndef SERIALGC
  59 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
  60 #include "gc_implementation/concurrentMarkSweep/vmCMSOperations.hpp"
  61 #endif
  62 
  63 GenCollectedHeap* GenCollectedHeap::_gch;
  64 NOT_PRODUCT(size_t GenCollectedHeap::_skip_header_HeapWords = 0;)
  65 
  66 // The set of potentially parallel tasks in strong root scanning.
  67 enum GCH_process_strong_roots_tasks {
  68   // We probably want to parallelize both of these internally, but for now...
  69   GCH_PS_younger_gens,
  70   // Leave this one last.
  71   GCH_PS_NumElements
  72 };
  73 
  74 GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy) :
  75   SharedHeap(policy),
  76   _gen_policy(policy),
  77   _gen_process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)),
  78   _full_collections_completed(0)
  79 {
  80   if (_gen_process_strong_tasks == NULL ||
  81       !_gen_process_strong_tasks->valid()) {
  82     vm_exit_during_initialization("Failed necessary allocation.");
  83   }
  84   assert(policy != NULL, "Sanity check");
  85   _preloading_shared_classes = false;
  86 }
  87 
  88 jint GenCollectedHeap::initialize() {
  89   CollectedHeap::pre_initialize();
  90 
  91   int i;
  92   _n_gens = gen_policy()->number_of_generations();
  93 
  94   // While there are no constraints in the GC code that HeapWordSize
  95   // be any particular value, there are multiple other areas in the
  96   // system which believe this to be true (e.g. oop->object_size in some
  97   // cases incorrectly returns the size in wordSize units rather than
  98   // HeapWordSize).
  99   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
 100 
 101   // The heap must be at least as aligned as generations.
 102   size_t alignment = Generation::GenGrain;
 103 
 104   _gen_specs = gen_policy()->generations();
 105   PermanentGenerationSpec *perm_gen_spec =
 106                                 collector_policy()->permanent_generation();
 107 
 108   // Make sure the sizes are all aligned.
 109   for (i = 0; i < _n_gens; i++) {
 110     _gen_specs[i]->align(alignment);
 111   }
 112   perm_gen_spec->align(alignment);
 113 
 114   // If we are dumping the heap, then allocate a wasted block of address
 115   // space in order to push the heap to a lower address.  This extra
 116   // address range allows for other (or larger) libraries to be loaded
 117   // without them occupying the space required for the shared spaces.
 118 
 119   if (DumpSharedSpaces) {
 120     uintx reserved = 0;
 121     uintx block_size = 64*1024*1024;
 122     while (reserved < SharedDummyBlockSize) {
 123       char* dummy = os::reserve_memory(block_size);
 124       reserved += block_size;
 125     }
 126   }
 127 
 128   // Allocate space for the heap.
 129 
 130   char* heap_address;
 131   size_t total_reserved = 0;
 132   int n_covered_regions = 0;
 133   ReservedSpace heap_rs(0);
 134 
 135   heap_address = allocate(alignment, perm_gen_spec, &total_reserved,
 136                           &n_covered_regions, &heap_rs);
 137 
 138   if (UseSharedSpaces) {
 139     if (!heap_rs.is_reserved() || heap_address != heap_rs.base()) {
 140       if (heap_rs.is_reserved()) {
 141         heap_rs.release();
 142       }
 143       FileMapInfo* mapinfo = FileMapInfo::current_info();
 144       mapinfo->fail_continue("Unable to reserve shared region.");
 145       allocate(alignment, perm_gen_spec, &total_reserved, &n_covered_regions,
 146                &heap_rs);
 147     }
 148   }
 149 
 150   if (!heap_rs.is_reserved()) {
 151     vm_shutdown_during_initialization(
 152       "Could not reserve enough space for object heap");
 153     return JNI_ENOMEM;
 154   }
 155 
 156   _reserved = MemRegion((HeapWord*)heap_rs.base(),
 157                         (HeapWord*)(heap_rs.base() + heap_rs.size()));
 158 
 159   // It is important to do this in a way such that concurrent readers can't
 160   // temporarily think somethings in the heap.  (Seen this happen in asserts.)
 161   _reserved.set_word_size(0);
 162   _reserved.set_start((HeapWord*)heap_rs.base());
 163   size_t actual_heap_size = heap_rs.size() - perm_gen_spec->misc_data_size()
 164                                            - perm_gen_spec->misc_code_size();
 165   _reserved.set_end((HeapWord*)(heap_rs.base() + actual_heap_size));
 166 
 167   _rem_set = collector_policy()->create_rem_set(_reserved, n_covered_regions);
 168   set_barrier_set(rem_set()->bs());
 169 
 170   _gch = this;
 171 
 172   for (i = 0; i < _n_gens; i++) {
 173     ReservedSpace this_rs = heap_rs.first_part(_gen_specs[i]->max_size(),
 174                                               UseSharedSpaces, UseSharedSpaces);
 175     _gens[i] = _gen_specs[i]->init(this_rs, i, rem_set());
 176     // tag generations in JavaHeap
 177     MemTracker::record_virtual_memory_type((address)this_rs.base(), mtJavaHeap);
 178     heap_rs = heap_rs.last_part(_gen_specs[i]->max_size());
 179   }
 180   _perm_gen = perm_gen_spec->init(heap_rs, PermSize, rem_set());
 181   // tag PermGen
 182   MemTracker::record_virtual_memory_type((address)heap_rs.base(), mtJavaHeap);
 183 
 184   clear_incremental_collection_failed();
 185 
 186 #ifndef SERIALGC
 187   // If we are running CMS, create the collector responsible
 188   // for collecting the CMS generations.
 189   if (collector_policy()->is_concurrent_mark_sweep_policy()) {
 190     bool success = create_cms_collector();
 191     if (!success) return JNI_ENOMEM;
 192   }
 193 #endif // SERIALGC
 194 
 195   return JNI_OK;
 196 }
 197 
 198 
 199 char* GenCollectedHeap::allocate(size_t alignment,
 200                                  PermanentGenerationSpec* perm_gen_spec,
 201                                  size_t* _total_reserved,
 202                                  int* _n_covered_regions,
 203                                  ReservedSpace* heap_rs){
 204   // Now figure out the total size.
 205   size_t total_reserved = 0;
 206   int n_covered_regions = 0;
 207   const size_t pageSize = UseLargePages ?
 208       os::large_page_size() : os::vm_page_size();
 209 
 210   for (int i = 0; i < _n_gens; i++) {
 211     total_reserved = add_and_check_overflow(total_reserved, _gen_specs[i]->max_size());
 212     n_covered_regions += _gen_specs[i]->n_covered_regions();
 213   }
 214 
 215   assert(total_reserved % pageSize == 0,
 216          err_msg("Gen size; total_reserved=" SIZE_FORMAT ", pageSize="
 217                  SIZE_FORMAT, total_reserved, pageSize));
 218   total_reserved = add_and_check_overflow(total_reserved, perm_gen_spec->max_size());
 219   assert(total_reserved % pageSize == 0,
 220          err_msg("Perm size; total_reserved=" SIZE_FORMAT ", pageSize="
 221                  SIZE_FORMAT ", perm gen max=" SIZE_FORMAT, total_reserved,
 222                  pageSize, perm_gen_spec->max_size()));
 223 
 224   n_covered_regions += perm_gen_spec->n_covered_regions();
 225 
 226   // Add the size of the data area which shares the same reserved area
 227   // as the heap, but which is not actually part of the heap.
 228   size_t misc = perm_gen_spec->misc_data_size() + perm_gen_spec->misc_code_size();
 229   total_reserved = add_and_check_overflow(total_reserved, misc);
 230 
 231   if (UseLargePages) {
 232     assert(total_reserved != 0, "total_reserved cannot be 0");
 233     total_reserved = round_up_and_check_overflow(total_reserved, os::large_page_size());
 234   }
 235 
 236   // Calculate the address at which the heap must reside in order for
 237   // the shared data to be at the required address.
 238 
 239   char* heap_address;
 240   if (UseSharedSpaces) {
 241 
 242     // Calculate the address of the first word beyond the heap.
 243     FileMapInfo* mapinfo = FileMapInfo::current_info();
 244     int lr = CompactingPermGenGen::n_regions - 1;
 245     size_t capacity = align_size_up(mapinfo->space_capacity(lr), alignment);
 246     heap_address = mapinfo->region_base(lr) + capacity;
 247 
 248     // Calculate the address of the first word of the heap.
 249     heap_address -= total_reserved;
 250   } else {
 251     heap_address = NULL;  // any address will do.
 252     if (UseCompressedOops) {
 253       heap_address = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
 254       *_total_reserved = total_reserved;
 255       *_n_covered_regions = n_covered_regions;
 256       *heap_rs = ReservedHeapSpace(total_reserved, alignment,
 257                                    UseLargePages, heap_address);
 258 
 259       if (heap_address != NULL && !heap_rs->is_reserved()) {
 260         // Failed to reserve at specified address - the requested memory
 261         // region is taken already, for example, by 'java' launcher.
 262         // Try again to reserver heap higher.
 263         heap_address = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop);
 264         *heap_rs = ReservedHeapSpace(total_reserved, alignment,
 265                                      UseLargePages, heap_address);
 266 
 267         if (heap_address != NULL && !heap_rs->is_reserved()) {
 268           // Failed to reserve at specified address again - give up.
 269           heap_address = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop);
 270           assert(heap_address == NULL, "");
 271           *heap_rs = ReservedHeapSpace(total_reserved, alignment,
 272                                        UseLargePages, heap_address);
 273         }
 274       }
 275       return heap_address;
 276     }
 277   }
 278 
 279   *_total_reserved = total_reserved;
 280   *_n_covered_regions = n_covered_regions;
 281   *heap_rs = ReservedHeapSpace(total_reserved, alignment,
 282                                UseLargePages, heap_address);
 283 
 284   return heap_address;
 285 }
 286 
 287 
 288 void GenCollectedHeap::post_initialize() {
 289   SharedHeap::post_initialize();
 290   TwoGenerationCollectorPolicy *policy =
 291     (TwoGenerationCollectorPolicy *)collector_policy();
 292   guarantee(policy->is_two_generation_policy(), "Illegal policy type");
 293   DefNewGeneration* def_new_gen = (DefNewGeneration*) get_gen(0);
 294   assert(def_new_gen->kind() == Generation::DefNew ||
 295          def_new_gen->kind() == Generation::ParNew ||
 296          def_new_gen->kind() == Generation::ASParNew,
 297          "Wrong generation kind");
 298 
 299   Generation* old_gen = get_gen(1);
 300   assert(old_gen->kind() == Generation::ConcurrentMarkSweep ||
 301          old_gen->kind() == Generation::ASConcurrentMarkSweep ||
 302          old_gen->kind() == Generation::MarkSweepCompact,
 303     "Wrong generation kind");
 304 
 305   policy->initialize_size_policy(def_new_gen->eden()->capacity(),
 306                                  old_gen->capacity(),
 307                                  def_new_gen->from()->capacity());
 308   policy->initialize_gc_policy_counters();
 309 }
 310 
 311 void GenCollectedHeap::ref_processing_init() {
 312   SharedHeap::ref_processing_init();
 313   for (int i = 0; i < _n_gens; i++) {
 314     _gens[i]->ref_processor_init();
 315   }
 316 }
 317 
 318 size_t GenCollectedHeap::capacity() const {
 319   size_t res = 0;
 320   for (int i = 0; i < _n_gens; i++) {
 321     res += _gens[i]->capacity();
 322   }
 323   return res;
 324 }
 325 
 326 size_t GenCollectedHeap::used() const {
 327   size_t res = 0;
 328   for (int i = 0; i < _n_gens; i++) {
 329     res += _gens[i]->used();
 330   }
 331   return res;
 332 }
 333 
 334 // Save the "used_region" for generations level and lower,
 335 // and, if perm is true, for perm gen.
 336 void GenCollectedHeap::save_used_regions(int level, bool perm) {
 337   assert(level < _n_gens, "Illegal level parameter");
 338   for (int i = level; i >= 0; i--) {
 339     _gens[i]->save_used_region();
 340   }
 341   if (perm) {
 342     perm_gen()->save_used_region();
 343   }
 344 }
 345 
 346 size_t GenCollectedHeap::max_capacity() const {
 347   size_t res = 0;
 348   for (int i = 0; i < _n_gens; i++) {
 349     res += _gens[i]->max_capacity();
 350   }
 351   return res;
 352 }
 353 
 354 // Update the _full_collections_completed counter
 355 // at the end of a stop-world full GC.
 356 unsigned int GenCollectedHeap::update_full_collections_completed() {
 357   MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 358   assert(_full_collections_completed <= _total_full_collections,
 359          "Can't complete more collections than were started");
 360   _full_collections_completed = _total_full_collections;
 361   ml.notify_all();
 362   return _full_collections_completed;
 363 }
 364 
 365 // Update the _full_collections_completed counter, as appropriate,
 366 // at the end of a concurrent GC cycle. Note the conditional update
 367 // below to allow this method to be called by a concurrent collector
 368 // without synchronizing in any manner with the VM thread (which
 369 // may already have initiated a STW full collection "concurrently").
 370 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) {
 371   MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 372   assert((_full_collections_completed <= _total_full_collections) &&
 373          (count <= _total_full_collections),
 374          "Can't complete more collections than were started");
 375   if (count > _full_collections_completed) {
 376     _full_collections_completed = count;
 377     ml.notify_all();
 378   }
 379   return _full_collections_completed;
 380 }
 381 
 382 
 383 #ifndef PRODUCT
 384 // Override of memory state checking method in CollectedHeap:
 385 // Some collectors (CMS for example) can't have badHeapWordVal written
 386 // in the first two words of an object. (For instance , in the case of
 387 // CMS these words hold state used to synchronize between certain
 388 // (concurrent) GC steps and direct allocating mutators.)
 389 // The skip_header_HeapWords() method below, allows us to skip
 390 // over the requisite number of HeapWord's. Note that (for
 391 // generational collectors) this means that those many words are
 392 // skipped in each object, irrespective of the generation in which
 393 // that object lives. The resultant loss of precision seems to be
 394 // harmless and the pain of avoiding that imprecision appears somewhat
 395 // higher than we are prepared to pay for such rudimentary debugging
 396 // support.
 397 void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr,
 398                                                          size_t size) {
 399   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 400     // We are asked to check a size in HeapWords,
 401     // but the memory is mangled in juint words.
 402     juint* start = (juint*) (addr + skip_header_HeapWords());
 403     juint* end   = (juint*) (addr + size);
 404     for (juint* slot = start; slot < end; slot += 1) {
 405       assert(*slot == badHeapWordVal,
 406              "Found non badHeapWordValue in pre-allocation check");
 407     }
 408   }
 409 }
 410 #endif
 411 
 412 HeapWord* GenCollectedHeap::attempt_allocation(size_t size,
 413                                                bool is_tlab,
 414                                                bool first_only) {
 415   HeapWord* res;
 416   for (int i = 0; i < _n_gens; i++) {
 417     if (_gens[i]->should_allocate(size, is_tlab)) {
 418       res = _gens[i]->allocate(size, is_tlab);
 419       if (res != NULL) return res;
 420       else if (first_only) break;
 421     }
 422   }
 423   // Otherwise...
 424   return NULL;
 425 }
 426 
 427 HeapWord* GenCollectedHeap::mem_allocate(size_t size,
 428                                          bool* gc_overhead_limit_was_exceeded) {
 429   return collector_policy()->mem_allocate_work(size,
 430                                                false /* is_tlab */,
 431                                                gc_overhead_limit_was_exceeded);
 432 }
 433 
 434 bool GenCollectedHeap::must_clear_all_soft_refs() {
 435   return _gc_cause == GCCause::_last_ditch_collection;
 436 }
 437 
 438 bool GenCollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
 439   return UseConcMarkSweepGC &&
 440          ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
 441           (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent));
 442 }
 443 
 444 void GenCollectedHeap::do_collection(bool  full,
 445                                      bool   clear_all_soft_refs,
 446                                      size_t size,
 447                                      bool   is_tlab,
 448                                      int    max_level) {
 449   bool prepared_for_verification = false;
 450   ResourceMark rm;
 451   DEBUG_ONLY(Thread* my_thread = Thread::current();)
 452 
 453   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 454   assert(my_thread->is_VM_thread() ||
 455          my_thread->is_ConcurrentGC_thread(),
 456          "incorrect thread type capability");
 457   assert(Heap_lock->is_locked(),
 458          "the requesting thread should have the Heap_lock");
 459   guarantee(!is_gc_active(), "collection is not reentrant");
 460   assert(max_level < n_gens(), "sanity check");
 461 
 462   if (GC_locker::check_active_before_gc()) {
 463     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
 464   }
 465 
 466   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
 467                           collector_policy()->should_clear_all_soft_refs();
 468 
 469   ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
 470 
 471   const size_t perm_prev_used = perm_gen()->used();
 472 
 473   print_heap_before_gc();
 474 
 475   {
 476     FlagSetting fl(_is_gc_active, true);
 477 
 478     bool complete = full && (max_level == (n_gens()-1));
 479     const char* gc_cause_prefix = complete ? "Full GC" : "GC";
 480     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
 481     GCTraceTime t(GCCauseString(gc_cause_prefix, gc_cause()), PrintGCDetails, false, NULL);
 482 
 483     gc_prologue(complete);
 484     increment_total_collections(complete);
 485 
 486     size_t gch_prev_used = used();
 487 
 488     int starting_level = 0;
 489     if (full) {
 490       // Search for the oldest generation which will collect all younger
 491       // generations, and start collection loop there.
 492       for (int i = max_level; i >= 0; i--) {
 493         if (_gens[i]->full_collects_younger_generations()) {
 494           starting_level = i;
 495           break;
 496         }
 497       }
 498     }
 499 
 500     bool must_restore_marks_for_biased_locking = false;
 501 
 502     int max_level_collected = starting_level;
 503     for (int i = starting_level; i <= max_level; i++) {
 504       if (_gens[i]->should_collect(full, size, is_tlab)) {
 505         if (i == n_gens() - 1) {  // a major collection is to happen
 506           if (!complete) {
 507             // The full_collections increment was missed above.
 508             increment_total_full_collections();
 509           }
 510           pre_full_gc_dump(NULL);    // do any pre full gc dumps
 511         }
 512         // Timer for individual generations. Last argument is false: no CR
 513         // FIXME: We should try to start the timing earlier to cover more of the GC pause
 514         GCTraceTime t1(_gens[i]->short_name(), PrintGCDetails, false, NULL);
 515         TraceCollectorStats tcs(_gens[i]->counters());
 516         TraceMemoryManagerStats tmms(_gens[i]->kind(),gc_cause());
 517 
 518         size_t prev_used = _gens[i]->used();
 519         _gens[i]->stat_record()->invocations++;
 520         _gens[i]->stat_record()->accumulated_time.start();
 521 
 522         // Must be done anew before each collection because
 523         // a previous collection will do mangling and will
 524         // change top of some spaces.
 525         record_gen_tops_before_GC();
 526 
 527         if (PrintGC && Verbose) {
 528           gclog_or_tty->print("level=%d invoke=%d size=" SIZE_FORMAT,
 529                      i,
 530                      _gens[i]->stat_record()->invocations,
 531                      size*HeapWordSize);
 532         }
 533 
 534         if (VerifyBeforeGC && i >= VerifyGCLevel &&
 535             total_collections() >= VerifyGCStartAt) {
 536           HandleMark hm;  // Discard invalid handles created during verification
 537           if (!prepared_for_verification) {
 538             prepare_for_verify();
 539             prepared_for_verification = true;
 540           }
 541           gclog_or_tty->print(" VerifyBeforeGC:");
 542           Universe::verify();
 543         }
 544         COMPILER2_PRESENT(DerivedPointerTable::clear());
 545 
 546         if (!must_restore_marks_for_biased_locking &&
 547             _gens[i]->performs_in_place_marking()) {
 548           // We perform this mark word preservation work lazily
 549           // because it's only at this point that we know whether we
 550           // absolutely have to do it; we want to avoid doing it for
 551           // scavenge-only collections where it's unnecessary
 552           must_restore_marks_for_biased_locking = true;
 553           BiasedLocking::preserve_marks();
 554         }
 555 
 556         // Do collection work
 557         {
 558           // Note on ref discovery: For what appear to be historical reasons,
 559           // GCH enables and disabled (by enqueing) refs discovery.
 560           // In the future this should be moved into the generation's
 561           // collect method so that ref discovery and enqueueing concerns
 562           // are local to a generation. The collect method could return
 563           // an appropriate indication in the case that notification on
 564           // the ref lock was needed. This will make the treatment of
 565           // weak refs more uniform (and indeed remove such concerns
 566           // from GCH). XXX
 567 
 568           HandleMark hm;  // Discard invalid handles created during gc
 569           save_marks();   // save marks for all gens
 570           // We want to discover references, but not process them yet.
 571           // This mode is disabled in process_discovered_references if the
 572           // generation does some collection work, or in
 573           // enqueue_discovered_references if the generation returns
 574           // without doing any work.
 575           ReferenceProcessor* rp = _gens[i]->ref_processor();
 576           // If the discovery of ("weak") refs in this generation is
 577           // atomic wrt other collectors in this configuration, we
 578           // are guaranteed to have empty discovered ref lists.
 579           if (rp->discovery_is_atomic()) {
 580             rp->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
 581             rp->setup_policy(do_clear_all_soft_refs);
 582           } else {
 583             // collect() below will enable discovery as appropriate
 584           }
 585           _gens[i]->collect(full, do_clear_all_soft_refs, size, is_tlab);
 586           if (!rp->enqueuing_is_done()) {
 587             rp->enqueue_discovered_references();
 588           } else {
 589             rp->set_enqueuing_is_done(false);
 590           }
 591           rp->verify_no_references_recorded();
 592         }
 593         max_level_collected = i;
 594 
 595         // Determine if allocation request was met.
 596         if (size > 0) {
 597           if (!is_tlab || _gens[i]->supports_tlab_allocation()) {
 598             if (size*HeapWordSize <= _gens[i]->unsafe_max_alloc_nogc()) {
 599               size = 0;
 600             }
 601           }
 602         }
 603 
 604         COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 605 
 606         _gens[i]->stat_record()->accumulated_time.stop();
 607 
 608         update_gc_stats(i, full);
 609 
 610         if (VerifyAfterGC && i >= VerifyGCLevel &&
 611             total_collections() >= VerifyGCStartAt) {
 612           HandleMark hm;  // Discard invalid handles created during verification
 613           gclog_or_tty->print(" VerifyAfterGC:");
 614           Universe::verify();
 615         }
 616 
 617         if (PrintGCDetails) {
 618           gclog_or_tty->print(":");
 619           _gens[i]->print_heap_change(prev_used);
 620         }
 621       }
 622     }
 623 
 624     // Update "complete" boolean wrt what actually transpired --
 625     // for instance, a promotion failure could have led to
 626     // a whole heap collection.
 627     complete = complete || (max_level_collected == n_gens() - 1);
 628 
 629     if (complete) { // We did a "major" collection
 630       // FIXME: See comment at pre_full_gc_dump call
 631       post_full_gc_dump(NULL);   // do any post full gc dumps
 632     }
 633 
 634     if (PrintGCDetails) {
 635       print_heap_change(gch_prev_used);
 636 
 637       // Print perm gen info for full GC with PrintGCDetails flag.
 638       if (complete) {
 639         print_perm_heap_change(perm_prev_used);
 640       }
 641     }
 642 
 643     for (int j = max_level_collected; j >= 0; j -= 1) {
 644       // Adjust generation sizes.
 645       _gens[j]->compute_new_size();
 646     }
 647 
 648     if (complete) {
 649       // Ask the permanent generation to adjust size for full collections
 650       perm()->compute_new_size();
 651       update_full_collections_completed();
 652     }
 653 
 654     // Track memory usage and detect low memory after GC finishes
 655     MemoryService::track_memory_usage();
 656 
 657     gc_epilogue(complete);
 658 
 659     if (must_restore_marks_for_biased_locking) {
 660       BiasedLocking::restore_marks();
 661     }
 662   }
 663 
 664   AdaptiveSizePolicy* sp = gen_policy()->size_policy();
 665   AdaptiveSizePolicyOutput(sp, total_collections());
 666 
 667   print_heap_after_gc();
 668 
 669 #ifdef TRACESPINNING
 670   ParallelTaskTerminator::print_termination_counts();
 671 #endif
 672 }
 673 
 674 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
 675   return collector_policy()->satisfy_failed_allocation(size, is_tlab);
 676 }
 677 
 678 void GenCollectedHeap::set_par_threads(uint t) {
 679   SharedHeap::set_par_threads(t);
 680   _gen_process_strong_tasks->set_n_threads(t);
 681 }
 682 
 683 void GenCollectedHeap::
 684 gen_process_strong_roots(int level,
 685                          bool younger_gens_as_roots,
 686                          bool activate_scope,
 687                          bool collecting_perm_gen,
 688                          SharedHeap::ScanningOption so,
 689                          OopsInGenClosure* not_older_gens,
 690                          bool do_code_roots,
 691                          OopsInGenClosure* older_gens) {
 692   // General strong roots.
 693 
 694   if (!do_code_roots) {
 695     SharedHeap::process_strong_roots(activate_scope, collecting_perm_gen, so,
 696                                      not_older_gens, NULL, older_gens);
 697   } else {
 698     bool do_code_marking = (activate_scope || nmethod::oops_do_marking_is_active());
 699     CodeBlobToOopClosure code_roots(not_older_gens, /*do_marking=*/ do_code_marking);
 700     SharedHeap::process_strong_roots(activate_scope, collecting_perm_gen, so,
 701                                      not_older_gens, &code_roots, older_gens);
 702   }
 703 
 704   if (younger_gens_as_roots) {
 705     if (!_gen_process_strong_tasks->is_task_claimed(GCH_PS_younger_gens)) {
 706       for (int i = 0; i < level; i++) {
 707         not_older_gens->set_generation(_gens[i]);
 708         _gens[i]->oop_iterate(not_older_gens);
 709       }
 710       not_older_gens->reset_generation();
 711     }
 712   }
 713   // When collection is parallel, all threads get to cooperate to do
 714   // older-gen scanning.
 715   for (int i = level+1; i < _n_gens; i++) {
 716     older_gens->set_generation(_gens[i]);
 717     rem_set()->younger_refs_iterate(_gens[i], older_gens);
 718     older_gens->reset_generation();
 719   }
 720 
 721   _gen_process_strong_tasks->all_tasks_completed();
 722 }
 723 
 724 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure,
 725                                               CodeBlobClosure* code_roots,
 726                                               OopClosure* non_root_closure) {
 727   SharedHeap::process_weak_roots(root_closure, code_roots, non_root_closure);
 728   // "Local" "weak" refs
 729   for (int i = 0; i < _n_gens; i++) {
 730     _gens[i]->ref_processor()->weak_oops_do(root_closure);
 731   }
 732 }
 733 
 734 #define GCH_SINCE_SAVE_MARKS_ITERATE_DEFN(OopClosureType, nv_suffix)    \
 735 void GenCollectedHeap::                                                 \
 736 oop_since_save_marks_iterate(int level,                                 \
 737                              OopClosureType* cur,                       \
 738                              OopClosureType* older) {                   \
 739   _gens[level]->oop_since_save_marks_iterate##nv_suffix(cur);           \
 740   for (int i = level+1; i < n_gens(); i++) {                            \
 741     _gens[i]->oop_since_save_marks_iterate##nv_suffix(older);           \
 742   }                                                                     \
 743   perm_gen()->oop_since_save_marks_iterate##nv_suffix(older);           \
 744 }
 745 
 746 ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DEFN)
 747 
 748 #undef GCH_SINCE_SAVE_MARKS_ITERATE_DEFN
 749 
 750 bool GenCollectedHeap::no_allocs_since_save_marks(int level) {
 751   for (int i = level; i < _n_gens; i++) {
 752     if (!_gens[i]->no_allocs_since_save_marks()) return false;
 753   }
 754   return perm_gen()->no_allocs_since_save_marks();
 755 }
 756 
 757 bool GenCollectedHeap::supports_inline_contig_alloc() const {
 758   return _gens[0]->supports_inline_contig_alloc();
 759 }
 760 
 761 HeapWord** GenCollectedHeap::top_addr() const {
 762   return _gens[0]->top_addr();
 763 }
 764 
 765 HeapWord** GenCollectedHeap::end_addr() const {
 766   return _gens[0]->end_addr();
 767 }
 768 
 769 size_t GenCollectedHeap::unsafe_max_alloc() {
 770   return _gens[0]->unsafe_max_alloc_nogc();
 771 }
 772 
 773 // public collection interfaces
 774 
 775 void GenCollectedHeap::collect(GCCause::Cause cause) {
 776   if (should_do_concurrent_full_gc(cause)) {
 777 #ifndef SERIALGC
 778     // mostly concurrent full collection
 779     collect_mostly_concurrent(cause);
 780 #else  // SERIALGC
 781     ShouldNotReachHere();
 782 #endif // SERIALGC
 783   } else {
 784 #ifdef ASSERT
 785     if (cause == GCCause::_scavenge_alot) {
 786       // minor collection only
 787       collect(cause, 0);
 788     } else {
 789       // Stop-the-world full collection
 790       collect(cause, n_gens() - 1);
 791     }
 792 #else
 793     // Stop-the-world full collection
 794     collect(cause, n_gens() - 1);
 795 #endif
 796   }
 797 }
 798 
 799 void GenCollectedHeap::collect(GCCause::Cause cause, int max_level) {
 800   // The caller doesn't have the Heap_lock
 801   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
 802   MutexLocker ml(Heap_lock);
 803   collect_locked(cause, max_level);
 804 }
 805 
 806 // This interface assumes that it's being called by the
 807 // vm thread. It collects the heap assuming that the
 808 // heap lock is already held and that we are executing in
 809 // the context of the vm thread.
 810 void GenCollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
 811   assert(Thread::current()->is_VM_thread(), "Precondition#1");
 812   assert(Heap_lock->is_locked(), "Precondition#2");
 813   GCCauseSetter gcs(this, cause);
 814   switch (cause) {
 815     case GCCause::_heap_inspection:
 816     case GCCause::_heap_dump: {
 817       HandleMark hm;
 818       do_full_collection(false,         // don't clear all soft refs
 819                          n_gens() - 1);
 820       break;
 821     }
 822     default: // XXX FIX ME
 823       ShouldNotReachHere(); // Unexpected use of this function
 824   }
 825 }
 826 
 827 void GenCollectedHeap::collect_locked(GCCause::Cause cause) {
 828   // The caller has the Heap_lock
 829   assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");
 830   collect_locked(cause, n_gens() - 1);
 831 }
 832 
 833 // this is the private collection interface
 834 // The Heap_lock is expected to be held on entry.
 835 
 836 void GenCollectedHeap::collect_locked(GCCause::Cause cause, int max_level) {
 837   if (_preloading_shared_classes) {
 838     report_out_of_shared_space(SharedPermGen);
 839   }
 840   // Read the GC count while holding the Heap_lock
 841   unsigned int gc_count_before      = total_collections();
 842   unsigned int full_gc_count_before = total_full_collections();
 843   {
 844     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
 845     VM_GenCollectFull op(gc_count_before, full_gc_count_before,
 846                          cause, max_level);
 847     VMThread::execute(&op);
 848   }
 849 }
 850 
 851 #ifndef SERIALGC
 852 bool GenCollectedHeap::create_cms_collector() {
 853 
 854   assert(((_gens[1]->kind() == Generation::ConcurrentMarkSweep) ||
 855          (_gens[1]->kind() == Generation::ASConcurrentMarkSweep)) &&
 856          _perm_gen->as_gen()->kind() == Generation::ConcurrentMarkSweep,
 857          "Unexpected generation kinds");
 858   // Skip two header words in the block content verification
 859   NOT_PRODUCT(_skip_header_HeapWords = CMSCollector::skip_header_HeapWords();)
 860   CMSCollector* collector = new CMSCollector(
 861     (ConcurrentMarkSweepGeneration*)_gens[1],
 862     (ConcurrentMarkSweepGeneration*)_perm_gen->as_gen(),
 863     _rem_set->as_CardTableRS(),
 864     (ConcurrentMarkSweepPolicy*) collector_policy());
 865 
 866   if (collector == NULL || !collector->completed_initialization()) {
 867     if (collector) {
 868       delete collector;  // Be nice in embedded situation
 869     }
 870     vm_shutdown_during_initialization("Could not create CMS collector");
 871     return false;
 872   }
 873   return true;  // success
 874 }
 875 
 876 void GenCollectedHeap::collect_mostly_concurrent(GCCause::Cause cause) {
 877   assert(!Heap_lock->owned_by_self(), "Should not own Heap_lock");
 878 
 879   MutexLocker ml(Heap_lock);
 880   // Read the GC counts while holding the Heap_lock
 881   unsigned int full_gc_count_before = total_full_collections();
 882   unsigned int gc_count_before      = total_collections();
 883   {
 884     MutexUnlocker mu(Heap_lock);
 885     VM_GenCollectFullConcurrent op(gc_count_before, full_gc_count_before, cause);
 886     VMThread::execute(&op);
 887   }
 888 }
 889 #endif // SERIALGC
 890 
 891 
 892 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,
 893                                           int max_level) {
 894   int local_max_level;
 895   if (!incremental_collection_will_fail(false /* don't consult_young */) &&
 896       gc_cause() == GCCause::_gc_locker) {
 897     local_max_level = 0;
 898   } else {
 899     local_max_level = max_level;
 900   }
 901 
 902   do_collection(true                 /* full */,
 903                 clear_all_soft_refs  /* clear_all_soft_refs */,
 904                 0                    /* size */,
 905                 false                /* is_tlab */,
 906                 local_max_level      /* max_level */);
 907   // Hack XXX FIX ME !!!
 908   // A scavenge may not have been attempted, or may have
 909   // been attempted and failed, because the old gen was too full
 910   if (local_max_level == 0 && gc_cause() == GCCause::_gc_locker &&
 911       incremental_collection_will_fail(false /* don't consult_young */)) {
 912     if (PrintGCDetails) {
 913       gclog_or_tty->print_cr("GC locker: Trying a full collection "
 914                              "because scavenge failed");
 915     }
 916     // This time allow the old gen to be collected as well
 917     do_collection(true                 /* full */,
 918                   clear_all_soft_refs  /* clear_all_soft_refs */,
 919                   0                    /* size */,
 920                   false                /* is_tlab */,
 921                   n_gens() - 1         /* max_level */);
 922   }
 923 }
 924 
 925 bool GenCollectedHeap::is_in_young(oop p) {
 926   bool result = ((HeapWord*)p) < _gens[_n_gens - 1]->reserved().start();
 927   assert(result == _gens[0]->is_in_reserved(p),
 928          err_msg("incorrect test - result=%d, p=" PTR_FORMAT, result, (void*)p));
 929   return result;
 930 }
 931 
 932 // Returns "TRUE" iff "p" points into the committed areas of the heap.
 933 bool GenCollectedHeap::is_in(const void* p) const {
 934   #ifndef ASSERT
 935   guarantee(VerifyBeforeGC   ||
 936             VerifyDuringGC   ||
 937             VerifyBeforeExit ||
 938             PrintAssembly    ||
 939             tty->count() != 0 ||   // already printing
 940             VerifyAfterGC    ||
 941     VMError::fatal_error_in_progress(), "too expensive");
 942 
 943   #endif
 944   // This might be sped up with a cache of the last generation that
 945   // answered yes.
 946   for (int i = 0; i < _n_gens; i++) {
 947     if (_gens[i]->is_in(p)) return true;
 948   }
 949   if (_perm_gen->as_gen()->is_in(p)) return true;
 950   // Otherwise...
 951   return false;
 952 }
 953 
 954 #ifdef ASSERT
 955 // Don't implement this by using is_in_young().  This method is used
 956 // in some cases to check that is_in_young() is correct.
 957 bool GenCollectedHeap::is_in_partial_collection(const void* p) {
 958   assert(is_in_reserved(p) || p == NULL,
 959     "Does not work if address is non-null and outside of the heap");
 960   // The order of the generations is young (low addr), old, perm (high addr)
 961   return p < _gens[_n_gens - 2]->reserved().end() && p != NULL;
 962 }
 963 #endif
 964 
 965 void GenCollectedHeap::oop_iterate(OopClosure* cl) {
 966   for (int i = 0; i < _n_gens; i++) {
 967     _gens[i]->oop_iterate(cl);
 968   }
 969 }
 970 
 971 void GenCollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl) {
 972   for (int i = 0; i < _n_gens; i++) {
 973     _gens[i]->oop_iterate(mr, cl);
 974   }
 975 }
 976 
 977 void GenCollectedHeap::object_iterate(ObjectClosure* cl) {
 978   for (int i = 0; i < _n_gens; i++) {
 979     _gens[i]->object_iterate(cl);
 980   }
 981   perm_gen()->object_iterate(cl);
 982 }
 983 
 984 void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) {
 985   for (int i = 0; i < _n_gens; i++) {
 986     _gens[i]->safe_object_iterate(cl);
 987   }
 988   perm_gen()->safe_object_iterate(cl);
 989 }
 990 
 991 void GenCollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
 992   for (int i = 0; i < _n_gens; i++) {
 993     _gens[i]->object_iterate_since_last_GC(cl);
 994   }
 995 }
 996 
 997 Space* GenCollectedHeap::space_containing(const void* addr) const {
 998   for (int i = 0; i < _n_gens; i++) {
 999     Space* res = _gens[i]->space_containing(addr);
1000     if (res != NULL) return res;
1001   }
1002   Space* res = perm_gen()->space_containing(addr);
1003   if (res != NULL) return res;
1004   // Otherwise...
1005   assert(false, "Could not find containing space");
1006   return NULL;
1007 }
1008 
1009 
1010 HeapWord* GenCollectedHeap::block_start(const void* addr) const {
1011   assert(is_in_reserved(addr), "block_start of address outside of heap");
1012   for (int i = 0; i < _n_gens; i++) {
1013     if (_gens[i]->is_in_reserved(addr)) {
1014       assert(_gens[i]->is_in(addr),
1015              "addr should be in allocated part of generation");
1016       return _gens[i]->block_start(addr);
1017     }
1018   }
1019   if (perm_gen()->is_in_reserved(addr)) {
1020     assert(perm_gen()->is_in(addr),
1021            "addr should be in allocated part of perm gen");
1022     return perm_gen()->block_start(addr);
1023   }
1024   assert(false, "Some generation should contain the address");
1025   return NULL;
1026 }
1027 
1028 size_t GenCollectedHeap::block_size(const HeapWord* addr) const {
1029   assert(is_in_reserved(addr), "block_size of address outside of heap");
1030   for (int i = 0; i < _n_gens; i++) {
1031     if (_gens[i]->is_in_reserved(addr)) {
1032       assert(_gens[i]->is_in(addr),
1033              "addr should be in allocated part of generation");
1034       return _gens[i]->block_size(addr);
1035     }
1036   }
1037   if (perm_gen()->is_in_reserved(addr)) {
1038     assert(perm_gen()->is_in(addr),
1039            "addr should be in allocated part of perm gen");
1040     return perm_gen()->block_size(addr);
1041   }
1042   assert(false, "Some generation should contain the address");
1043   return 0;
1044 }
1045 
1046 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {
1047   assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
1048   assert(block_start(addr) == addr, "addr must be a block start");
1049   for (int i = 0; i < _n_gens; i++) {
1050     if (_gens[i]->is_in_reserved(addr)) {
1051       return _gens[i]->block_is_obj(addr);
1052     }
1053   }
1054   if (perm_gen()->is_in_reserved(addr)) {
1055     return perm_gen()->block_is_obj(addr);
1056   }
1057   assert(false, "Some generation should contain the address");
1058   return false;
1059 }
1060 
1061 bool GenCollectedHeap::supports_tlab_allocation() const {
1062   for (int i = 0; i < _n_gens; i += 1) {
1063     if (_gens[i]->supports_tlab_allocation()) {
1064       return true;
1065     }
1066   }
1067   return false;
1068 }
1069 
1070 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {
1071   size_t result = 0;
1072   for (int i = 0; i < _n_gens; i += 1) {
1073     if (_gens[i]->supports_tlab_allocation()) {
1074       result += _gens[i]->tlab_capacity();
1075     }
1076   }
1077   return result;
1078 }
1079 
1080 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {
1081   size_t result = 0;
1082   for (int i = 0; i < _n_gens; i += 1) {
1083     if (_gens[i]->supports_tlab_allocation()) {
1084       result += _gens[i]->unsafe_max_tlab_alloc();
1085     }
1086   }
1087   return result;
1088 }
1089 
1090 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t size) {
1091   bool gc_overhead_limit_was_exceeded;
1092   return collector_policy()->mem_allocate_work(size /* size */,
1093                                                true /* is_tlab */,
1094                                                &gc_overhead_limit_was_exceeded);
1095 }
1096 
1097 // Requires "*prev_ptr" to be non-NULL.  Deletes and a block of minimal size
1098 // from the list headed by "*prev_ptr".
1099 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {
1100   bool first = true;
1101   size_t min_size = 0;   // "first" makes this conceptually infinite.
1102   ScratchBlock **smallest_ptr, *smallest;
1103   ScratchBlock  *cur = *prev_ptr;
1104   while (cur) {
1105     assert(*prev_ptr == cur, "just checking");
1106     if (first || cur->num_words < min_size) {
1107       smallest_ptr = prev_ptr;
1108       smallest     = cur;
1109       min_size     = smallest->num_words;
1110       first        = false;
1111     }
1112     prev_ptr = &cur->next;
1113     cur     =  cur->next;
1114   }
1115   smallest      = *smallest_ptr;
1116   *smallest_ptr = smallest->next;
1117   return smallest;
1118 }
1119 
1120 // Sort the scratch block list headed by res into decreasing size order,
1121 // and set "res" to the result.
1122 static void sort_scratch_list(ScratchBlock*& list) {
1123   ScratchBlock* sorted = NULL;
1124   ScratchBlock* unsorted = list;
1125   while (unsorted) {
1126     ScratchBlock *smallest = removeSmallestScratch(&unsorted);
1127     smallest->next  = sorted;
1128     sorted          = smallest;
1129   }
1130   list = sorted;
1131 }
1132 
1133 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,
1134                                                size_t max_alloc_words) {
1135   ScratchBlock* res = NULL;
1136   for (int i = 0; i < _n_gens; i++) {
1137     _gens[i]->contribute_scratch(res, requestor, max_alloc_words);
1138   }
1139   sort_scratch_list(res);
1140   return res;
1141 }
1142 
1143 void GenCollectedHeap::release_scratch() {
1144   for (int i = 0; i < _n_gens; i++) {
1145     _gens[i]->reset_scratch();
1146   }
1147 }
1148 
1149 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {
1150   void do_generation(Generation* gen) {
1151     gen->prepare_for_verify();
1152   }
1153 };
1154 
1155 void GenCollectedHeap::prepare_for_verify() {
1156   ensure_parsability(false);        // no need to retire TLABs
1157   GenPrepareForVerifyClosure blk;
1158   generation_iterate(&blk, false);
1159   perm_gen()->prepare_for_verify();
1160 }
1161 
1162 
1163 void GenCollectedHeap::generation_iterate(GenClosure* cl,
1164                                           bool old_to_young) {
1165   if (old_to_young) {
1166     for (int i = _n_gens-1; i >= 0; i--) {
1167       cl->do_generation(_gens[i]);
1168     }
1169   } else {
1170     for (int i = 0; i < _n_gens; i++) {
1171       cl->do_generation(_gens[i]);
1172     }
1173   }
1174 }
1175 
1176 void GenCollectedHeap::space_iterate(SpaceClosure* cl) {
1177   for (int i = 0; i < _n_gens; i++) {
1178     _gens[i]->space_iterate(cl, true);
1179   }
1180   perm_gen()->space_iterate(cl, true);
1181 }
1182 
1183 bool GenCollectedHeap::is_maximal_no_gc() const {
1184   for (int i = 0; i < _n_gens; i++) {  // skip perm gen
1185     if (!_gens[i]->is_maximal_no_gc()) {
1186       return false;
1187     }
1188   }
1189   return true;
1190 }
1191 
1192 void GenCollectedHeap::save_marks() {
1193   for (int i = 0; i < _n_gens; i++) {
1194     _gens[i]->save_marks();
1195   }
1196   perm_gen()->save_marks();
1197 }
1198 
1199 void GenCollectedHeap::compute_new_generation_sizes(int collectedGen) {
1200   for (int i = 0; i <= collectedGen; i++) {
1201     _gens[i]->compute_new_size();
1202   }
1203 }
1204 
1205 GenCollectedHeap* GenCollectedHeap::heap() {
1206   assert(_gch != NULL, "Uninitialized access to GenCollectedHeap::heap()");
1207   assert(_gch->kind() == CollectedHeap::GenCollectedHeap, "not a generational heap");
1208   return _gch;
1209 }
1210 
1211 
1212 void GenCollectedHeap::prepare_for_compaction() {
1213   Generation* scanning_gen = _gens[_n_gens-1];
1214   // Start by compacting into same gen.
1215   CompactPoint cp(scanning_gen, NULL, NULL);
1216   while (scanning_gen != NULL) {
1217     scanning_gen->prepare_for_compaction(&cp);
1218     scanning_gen = prev_gen(scanning_gen);
1219   }
1220 }
1221 
1222 GCStats* GenCollectedHeap::gc_stats(int level) const {
1223   return _gens[level]->gc_stats();
1224 }
1225 
1226 void GenCollectedHeap::verify(bool silent, VerifyOption option /* ignored */) {
1227   if (!silent) {
1228     gclog_or_tty->print("permgen ");
1229   }
1230   perm_gen()->verify();
1231   for (int i = _n_gens-1; i >= 0; i--) {
1232     Generation* g = _gens[i];
1233     if (!silent) {
1234       gclog_or_tty->print(g->name());
1235       gclog_or_tty->print(" ");
1236     }
1237     g->verify();
1238   }
1239   if (!silent) {
1240     gclog_or_tty->print("remset ");
1241   }
1242   rem_set()->verify();
1243 }
1244 
1245 void GenCollectedHeap::print_on(outputStream* st) const {
1246   for (int i = 0; i < _n_gens; i++) {
1247     _gens[i]->print_on(st);
1248   }
1249   perm_gen()->print_on(st);
1250 }
1251 
1252 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {
1253   if (workers() != NULL) {
1254     workers()->threads_do(tc);
1255   }
1256 #ifndef SERIALGC
1257   if (UseConcMarkSweepGC) {
1258     ConcurrentMarkSweepThread::threads_do(tc);
1259   }
1260 #endif // SERIALGC
1261 }
1262 
1263 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {
1264 #ifndef SERIALGC
1265   if (UseParNewGC) {
1266     workers()->print_worker_threads_on(st);
1267   }
1268   if (UseConcMarkSweepGC) {
1269     ConcurrentMarkSweepThread::print_all_on(st);
1270   }
1271 #endif // SERIALGC
1272 }
1273 
1274 void GenCollectedHeap::print_tracing_info() const {
1275   if (TraceGen0Time) {
1276     get_gen(0)->print_summary_info();
1277   }
1278   if (TraceGen1Time) {
1279     get_gen(1)->print_summary_info();
1280   }
1281 }
1282 
1283 void GenCollectedHeap::print_heap_change(size_t prev_used) const {
1284   if (PrintGCDetails && Verbose) {
1285     gclog_or_tty->print(" "  SIZE_FORMAT
1286                         "->" SIZE_FORMAT
1287                         "("  SIZE_FORMAT ")",
1288                         prev_used, used(), capacity());
1289   } else {
1290     gclog_or_tty->print(" "  SIZE_FORMAT "K"
1291                         "->" SIZE_FORMAT "K"
1292                         "("  SIZE_FORMAT "K)",
1293                         prev_used / K, used() / K, capacity() / K);
1294   }
1295 }
1296 
1297 //New method to print perm gen info with PrintGCDetails flag
1298 void GenCollectedHeap::print_perm_heap_change(size_t perm_prev_used) const {
1299   gclog_or_tty->print(", [%s :", perm_gen()->short_name());
1300   perm_gen()->print_heap_change(perm_prev_used);
1301   gclog_or_tty->print("]");
1302 }
1303 
1304 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {
1305  private:
1306   bool _full;
1307  public:
1308   void do_generation(Generation* gen) {
1309     gen->gc_prologue(_full);
1310   }
1311   GenGCPrologueClosure(bool full) : _full(full) {};
1312 };
1313 
1314 void GenCollectedHeap::gc_prologue(bool full) {
1315   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
1316 
1317   always_do_update_barrier = false;
1318   // Fill TLAB's and such
1319   CollectedHeap::accumulate_statistics_all_tlabs();
1320   ensure_parsability(true);   // retire TLABs
1321 
1322   // Call allocation profiler
1323   AllocationProfiler::iterate_since_last_gc();
1324   // Walk generations
1325   GenGCPrologueClosure blk(full);
1326   generation_iterate(&blk, false);  // not old-to-young.
1327   perm_gen()->gc_prologue(full);
1328 };
1329 
1330 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure {
1331  private:
1332   bool _full;
1333  public:
1334   void do_generation(Generation* gen) {
1335     gen->gc_epilogue(_full);
1336   }
1337   GenGCEpilogueClosure(bool full) : _full(full) {};
1338 };
1339 
1340 void GenCollectedHeap::gc_epilogue(bool full) {
1341 #ifdef COMPILER2
1342   assert(DerivedPointerTable::is_empty(), "derived pointer present");
1343   size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr()));
1344   guarantee(actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps");
1345 #endif /* COMPILER2 */
1346 
1347   resize_all_tlabs();
1348 
1349   GenGCEpilogueClosure blk(full);
1350   generation_iterate(&blk, false);  // not old-to-young.
1351   perm_gen()->gc_epilogue(full);
1352 
1353   if (!CleanChunkPoolAsync) {
1354     Chunk::clean_chunk_pool();
1355   }
1356 
1357   always_do_update_barrier = UseConcMarkSweepGC;
1358 };
1359 
1360 #ifndef PRODUCT
1361 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure {
1362  private:
1363  public:
1364   void do_generation(Generation* gen) {
1365     gen->record_spaces_top();
1366   }
1367 };
1368 
1369 void GenCollectedHeap::record_gen_tops_before_GC() {
1370   if (ZapUnusedHeapArea) {
1371     GenGCSaveTopsBeforeGCClosure blk;
1372     generation_iterate(&blk, false);  // not old-to-young.
1373     perm_gen()->record_spaces_top();
1374   }
1375 }
1376 #endif  // not PRODUCT
1377 
1378 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {
1379  public:
1380   void do_generation(Generation* gen) {
1381     gen->ensure_parsability();
1382   }
1383 };
1384 
1385 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {
1386   CollectedHeap::ensure_parsability(retire_tlabs);
1387   GenEnsureParsabilityClosure ep_cl;
1388   generation_iterate(&ep_cl, false);
1389   perm_gen()->ensure_parsability();
1390 }
1391 
1392 oop GenCollectedHeap::handle_failed_promotion(Generation* gen,
1393                                               oop obj,
1394                                               size_t obj_size) {
1395   assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
1396   HeapWord* result = NULL;
1397 
1398   // First give each higher generation a chance to allocate the promoted object.
1399   Generation* allocator = next_gen(gen);
1400   if (allocator != NULL) {
1401     do {
1402       result = allocator->allocate(obj_size, false);
1403     } while (result == NULL && (allocator = next_gen(allocator)) != NULL);
1404   }
1405 
1406   if (result == NULL) {
1407     // Then give gen and higher generations a chance to expand and allocate the
1408     // object.
1409     do {
1410       result = gen->expand_and_allocate(obj_size, false);
1411     } while (result == NULL && (gen = next_gen(gen)) != NULL);
1412   }
1413 
1414   if (result != NULL) {
1415     Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size);
1416   }
1417   return oop(result);
1418 }
1419 
1420 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {
1421   jlong _time;   // in ms
1422   jlong _now;    // in ms
1423 
1424  public:
1425   GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { }
1426 
1427   jlong time() { return _time; }
1428 
1429   void do_generation(Generation* gen) {
1430     _time = MIN2(_time, gen->time_of_last_gc(_now));
1431   }
1432 };
1433 
1434 jlong GenCollectedHeap::millis_since_last_gc() {
1435   // We need a monotonically non-deccreasing time in ms but
1436   // os::javaTimeMillis() does not guarantee monotonicity.
1437   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
1438   GenTimeOfLastGCClosure tolgc_cl(now);
1439   // iterate over generations getting the oldest
1440   // time that a generation was collected
1441   generation_iterate(&tolgc_cl, false);
1442   tolgc_cl.do_generation(perm_gen());
1443 
1444   // javaTimeNanos() is guaranteed to be monotonically non-decreasing
1445   // provided the underlying platform provides such a time source
1446   // (and it is bug free). So we still have to guard against getting
1447   // back a time later than 'now'.
1448   jlong retVal = now - tolgc_cl.time();
1449   if (retVal < 0) {
1450     NOT_PRODUCT(warning("time warp: "INT64_FORMAT, retVal);)
1451     return 0;
1452   }
1453   return retVal;
1454 }