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