src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp

Mon, 28 Jul 2008 15:30:23 -0700

author
jmasa
date
Mon, 28 Jul 2008 15:30:23 -0700
changeset 704
850fdf70db2b
parent 672
1fdb98a17101
parent 701
2214b226b7f0
child 809
a4b729f5b611
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright 2005-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 #include "incls/_precompiled.incl"
    26 #include "incls/_psParallelCompact.cpp.incl"
    28 #include <math.h>
    30 // All sizes are in HeapWords.
    31 const size_t ParallelCompactData::Log2ChunkSize  = 9; // 512 words
    32 const size_t ParallelCompactData::ChunkSize      = (size_t)1 << Log2ChunkSize;
    33 const size_t ParallelCompactData::ChunkSizeBytes = ChunkSize << LogHeapWordSize;
    34 const size_t ParallelCompactData::ChunkSizeOffsetMask = ChunkSize - 1;
    35 const size_t ParallelCompactData::ChunkAddrOffsetMask = ChunkSizeBytes - 1;
    36 const size_t ParallelCompactData::ChunkAddrMask  = ~ChunkAddrOffsetMask;
    38 // 32-bit:  128 words covers 4 bitmap words
    39 // 64-bit:  128 words covers 2 bitmap words
    40 const size_t ParallelCompactData::Log2BlockSize   = 7; // 128 words
    41 const size_t ParallelCompactData::BlockSize       = (size_t)1 << Log2BlockSize;
    42 const size_t ParallelCompactData::BlockOffsetMask = BlockSize - 1;
    43 const size_t ParallelCompactData::BlockMask       = ~BlockOffsetMask;
    45 const size_t ParallelCompactData::BlocksPerChunk = ChunkSize / BlockSize;
    47 const ParallelCompactData::ChunkData::chunk_sz_t
    48 ParallelCompactData::ChunkData::dc_shift = 27;
    50 const ParallelCompactData::ChunkData::chunk_sz_t
    51 ParallelCompactData::ChunkData::dc_mask = ~0U << dc_shift;
    53 const ParallelCompactData::ChunkData::chunk_sz_t
    54 ParallelCompactData::ChunkData::dc_one = 0x1U << dc_shift;
    56 const ParallelCompactData::ChunkData::chunk_sz_t
    57 ParallelCompactData::ChunkData::los_mask = ~dc_mask;
    59 const ParallelCompactData::ChunkData::chunk_sz_t
    60 ParallelCompactData::ChunkData::dc_claimed = 0x8U << dc_shift;
    62 const ParallelCompactData::ChunkData::chunk_sz_t
    63 ParallelCompactData::ChunkData::dc_completed = 0xcU << dc_shift;
    65 #ifdef ASSERT
    66 short   ParallelCompactData::BlockData::_cur_phase = 0;
    67 #endif
    69 SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
    70 bool      PSParallelCompact::_print_phases = false;
    72 ReferenceProcessor* PSParallelCompact::_ref_processor = NULL;
    73 klassOop            PSParallelCompact::_updated_int_array_klass_obj = NULL;
    75 double PSParallelCompact::_dwl_mean;
    76 double PSParallelCompact::_dwl_std_dev;
    77 double PSParallelCompact::_dwl_first_term;
    78 double PSParallelCompact::_dwl_adjustment;
    79 #ifdef  ASSERT
    80 bool   PSParallelCompact::_dwl_initialized = false;
    81 #endif  // #ifdef ASSERT
    83 #ifdef VALIDATE_MARK_SWEEP
    84 GrowableArray<void*>*   PSParallelCompact::_root_refs_stack = NULL;
    85 GrowableArray<oop> *    PSParallelCompact::_live_oops = NULL;
    86 GrowableArray<oop> *    PSParallelCompact::_live_oops_moved_to = NULL;
    87 GrowableArray<size_t>*  PSParallelCompact::_live_oops_size = NULL;
    88 size_t                  PSParallelCompact::_live_oops_index = 0;
    89 size_t                  PSParallelCompact::_live_oops_index_at_perm = 0;
    90 GrowableArray<void*>*   PSParallelCompact::_other_refs_stack = NULL;
    91 GrowableArray<void*>*   PSParallelCompact::_adjusted_pointers = NULL;
    92 bool                    PSParallelCompact::_pointer_tracking = false;
    93 bool                    PSParallelCompact::_root_tracking = true;
    95 GrowableArray<HeapWord*>* PSParallelCompact::_cur_gc_live_oops = NULL;
    96 GrowableArray<HeapWord*>* PSParallelCompact::_cur_gc_live_oops_moved_to = NULL;
    97 GrowableArray<size_t>   * PSParallelCompact::_cur_gc_live_oops_size = NULL;
    98 GrowableArray<HeapWord*>* PSParallelCompact::_last_gc_live_oops = NULL;
    99 GrowableArray<HeapWord*>* PSParallelCompact::_last_gc_live_oops_moved_to = NULL;
   100 GrowableArray<size_t>   * PSParallelCompact::_last_gc_live_oops_size = NULL;
   101 #endif
   103 // XXX beg - verification code; only works while we also mark in object headers
   104 static void
   105 verify_mark_bitmap(ParMarkBitMap& _mark_bitmap)
   106 {
   107   ParallelScavengeHeap* heap = PSParallelCompact::gc_heap();
   109   PSPermGen* perm_gen = heap->perm_gen();
   110   PSOldGen* old_gen = heap->old_gen();
   111   PSYoungGen* young_gen = heap->young_gen();
   113   MutableSpace* perm_space = perm_gen->object_space();
   114   MutableSpace* old_space = old_gen->object_space();
   115   MutableSpace* eden_space = young_gen->eden_space();
   116   MutableSpace* from_space = young_gen->from_space();
   117   MutableSpace* to_space = young_gen->to_space();
   119   // 'from_space' here is the survivor space at the lower address.
   120   if (to_space->bottom() < from_space->bottom()) {
   121     from_space = to_space;
   122     to_space = young_gen->from_space();
   123   }
   125   HeapWord* boundaries[12];
   126   unsigned int bidx = 0;
   127   const unsigned int bidx_max = sizeof(boundaries) / sizeof(boundaries[0]);
   129   boundaries[0] = perm_space->bottom();
   130   boundaries[1] = perm_space->top();
   131   boundaries[2] = old_space->bottom();
   132   boundaries[3] = old_space->top();
   133   boundaries[4] = eden_space->bottom();
   134   boundaries[5] = eden_space->top();
   135   boundaries[6] = from_space->bottom();
   136   boundaries[7] = from_space->top();
   137   boundaries[8] = to_space->bottom();
   138   boundaries[9] = to_space->top();
   139   boundaries[10] = to_space->end();
   140   boundaries[11] = to_space->end();
   142   BitMap::idx_t beg_bit = 0;
   143   BitMap::idx_t end_bit;
   144   BitMap::idx_t tmp_bit;
   145   const BitMap::idx_t last_bit = _mark_bitmap.size();
   146   do {
   147     HeapWord* addr = _mark_bitmap.bit_to_addr(beg_bit);
   148     if (_mark_bitmap.is_marked(beg_bit)) {
   149       oop obj = (oop)addr;
   150       assert(obj->is_gc_marked(), "obj header is not marked");
   151       end_bit = _mark_bitmap.find_obj_end(beg_bit, last_bit);
   152       const size_t size = _mark_bitmap.obj_size(beg_bit, end_bit);
   153       assert(size == (size_t)obj->size(), "end bit wrong?");
   154       beg_bit = _mark_bitmap.find_obj_beg(beg_bit + 1, last_bit);
   155       assert(beg_bit > end_bit, "bit set in middle of an obj");
   156     } else {
   157       if (addr >= boundaries[bidx] && addr < boundaries[bidx + 1]) {
   158         // a dead object in the current space.
   159         oop obj = (oop)addr;
   160         end_bit = _mark_bitmap.addr_to_bit(addr + obj->size());
   161         assert(!obj->is_gc_marked(), "obj marked in header, not in bitmap");
   162         tmp_bit = beg_bit + 1;
   163         beg_bit = _mark_bitmap.find_obj_beg(tmp_bit, end_bit);
   164         assert(beg_bit == end_bit, "beg bit set in unmarked obj");
   165         beg_bit = _mark_bitmap.find_obj_end(tmp_bit, end_bit);
   166         assert(beg_bit == end_bit, "end bit set in unmarked obj");
   167       } else if (addr < boundaries[bidx + 2]) {
   168         // addr is between top in the current space and bottom in the next.
   169         end_bit = beg_bit + pointer_delta(boundaries[bidx + 2], addr);
   170         tmp_bit = beg_bit;
   171         beg_bit = _mark_bitmap.find_obj_beg(tmp_bit, end_bit);
   172         assert(beg_bit == end_bit, "beg bit set above top");
   173         beg_bit = _mark_bitmap.find_obj_end(tmp_bit, end_bit);
   174         assert(beg_bit == end_bit, "end bit set above top");
   175         bidx += 2;
   176       } else if (bidx < bidx_max - 2) {
   177         bidx += 2; // ???
   178       } else {
   179         tmp_bit = beg_bit;
   180         beg_bit = _mark_bitmap.find_obj_beg(tmp_bit, last_bit);
   181         assert(beg_bit == last_bit, "beg bit set outside heap");
   182         beg_bit = _mark_bitmap.find_obj_end(tmp_bit, last_bit);
   183         assert(beg_bit == last_bit, "end bit set outside heap");
   184       }
   185     }
   186   } while (beg_bit < last_bit);
   187 }
   188 // XXX end - verification code; only works while we also mark in object headers
   190 #ifndef PRODUCT
   191 const char* PSParallelCompact::space_names[] = {
   192   "perm", "old ", "eden", "from", "to  "
   193 };
   195 void PSParallelCompact::print_chunk_ranges()
   196 {
   197   tty->print_cr("space  bottom     top        end        new_top");
   198   tty->print_cr("------ ---------- ---------- ---------- ----------");
   200   for (unsigned int id = 0; id < last_space_id; ++id) {
   201     const MutableSpace* space = _space_info[id].space();
   202     tty->print_cr("%u %s "
   203                   SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " "
   204                   SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ",
   205                   id, space_names[id],
   206                   summary_data().addr_to_chunk_idx(space->bottom()),
   207                   summary_data().addr_to_chunk_idx(space->top()),
   208                   summary_data().addr_to_chunk_idx(space->end()),
   209                   summary_data().addr_to_chunk_idx(_space_info[id].new_top()));
   210   }
   211 }
   213 void
   214 print_generic_summary_chunk(size_t i, const ParallelCompactData::ChunkData* c)
   215 {
   216 #define CHUNK_IDX_FORMAT        SIZE_FORMAT_W(7)
   217 #define CHUNK_DATA_FORMAT       SIZE_FORMAT_W(5)
   219   ParallelCompactData& sd = PSParallelCompact::summary_data();
   220   size_t dci = c->destination() ? sd.addr_to_chunk_idx(c->destination()) : 0;
   221   tty->print_cr(CHUNK_IDX_FORMAT " " PTR_FORMAT " "
   222                 CHUNK_IDX_FORMAT " " PTR_FORMAT " "
   223                 CHUNK_DATA_FORMAT " " CHUNK_DATA_FORMAT " "
   224                 CHUNK_DATA_FORMAT " " CHUNK_IDX_FORMAT " %d",
   225                 i, c->data_location(), dci, c->destination(),
   226                 c->partial_obj_size(), c->live_obj_size(),
   227                 c->data_size(), c->source_chunk(), c->destination_count());
   229 #undef  CHUNK_IDX_FORMAT
   230 #undef  CHUNK_DATA_FORMAT
   231 }
   233 void
   234 print_generic_summary_data(ParallelCompactData& summary_data,
   235                            HeapWord* const beg_addr,
   236                            HeapWord* const end_addr)
   237 {
   238   size_t total_words = 0;
   239   size_t i = summary_data.addr_to_chunk_idx(beg_addr);
   240   const size_t last = summary_data.addr_to_chunk_idx(end_addr);
   241   HeapWord* pdest = 0;
   243   while (i <= last) {
   244     ParallelCompactData::ChunkData* c = summary_data.chunk(i);
   245     if (c->data_size() != 0 || c->destination() != pdest) {
   246       print_generic_summary_chunk(i, c);
   247       total_words += c->data_size();
   248       pdest = c->destination();
   249     }
   250     ++i;
   251   }
   253   tty->print_cr("summary_data_bytes=" SIZE_FORMAT, total_words * HeapWordSize);
   254 }
   256 void
   257 print_generic_summary_data(ParallelCompactData& summary_data,
   258                            SpaceInfo* space_info)
   259 {
   260   for (unsigned int id = 0; id < PSParallelCompact::last_space_id; ++id) {
   261     const MutableSpace* space = space_info[id].space();
   262     print_generic_summary_data(summary_data, space->bottom(),
   263                                MAX2(space->top(), space_info[id].new_top()));
   264   }
   265 }
   267 void
   268 print_initial_summary_chunk(size_t i,
   269                             const ParallelCompactData::ChunkData* c,
   270                             bool newline = true)
   271 {
   272   tty->print(SIZE_FORMAT_W(5) " " PTR_FORMAT " "
   273              SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " "
   274              SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
   275              i, c->destination(),
   276              c->partial_obj_size(), c->live_obj_size(),
   277              c->data_size(), c->source_chunk(), c->destination_count());
   278   if (newline) tty->cr();
   279 }
   281 void
   282 print_initial_summary_data(ParallelCompactData& summary_data,
   283                            const MutableSpace* space) {
   284   if (space->top() == space->bottom()) {
   285     return;
   286   }
   288   const size_t chunk_size = ParallelCompactData::ChunkSize;
   289   HeapWord* const top_aligned_up = summary_data.chunk_align_up(space->top());
   290   const size_t end_chunk = summary_data.addr_to_chunk_idx(top_aligned_up);
   291   const ParallelCompactData::ChunkData* c = summary_data.chunk(end_chunk - 1);
   292   HeapWord* end_addr = c->destination() + c->data_size();
   293   const size_t live_in_space = pointer_delta(end_addr, space->bottom());
   295   // Print (and count) the full chunks at the beginning of the space.
   296   size_t full_chunk_count = 0;
   297   size_t i = summary_data.addr_to_chunk_idx(space->bottom());
   298   while (i < end_chunk && summary_data.chunk(i)->data_size() == chunk_size) {
   299     print_initial_summary_chunk(i, summary_data.chunk(i));
   300     ++full_chunk_count;
   301     ++i;
   302   }
   304   size_t live_to_right = live_in_space - full_chunk_count * chunk_size;
   306   double max_reclaimed_ratio = 0.0;
   307   size_t max_reclaimed_ratio_chunk = 0;
   308   size_t max_dead_to_right = 0;
   309   size_t max_live_to_right = 0;
   311   // Print the 'reclaimed ratio' for chunks while there is something live in the
   312   // chunk or to the right of it.  The remaining chunks are empty (and
   313   // uninteresting), and computing the ratio will result in division by 0.
   314   while (i < end_chunk && live_to_right > 0) {
   315     c = summary_data.chunk(i);
   316     HeapWord* const chunk_addr = summary_data.chunk_to_addr(i);
   317     const size_t used_to_right = pointer_delta(space->top(), chunk_addr);
   318     const size_t dead_to_right = used_to_right - live_to_right;
   319     const double reclaimed_ratio = double(dead_to_right) / live_to_right;
   321     if (reclaimed_ratio > max_reclaimed_ratio) {
   322             max_reclaimed_ratio = reclaimed_ratio;
   323             max_reclaimed_ratio_chunk = i;
   324             max_dead_to_right = dead_to_right;
   325             max_live_to_right = live_to_right;
   326     }
   328     print_initial_summary_chunk(i, c, false);
   329     tty->print_cr(" %12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10),
   330                   reclaimed_ratio, dead_to_right, live_to_right);
   332     live_to_right -= c->data_size();
   333     ++i;
   334   }
   336   // Any remaining chunks are empty.  Print one more if there is one.
   337   if (i < end_chunk) {
   338     print_initial_summary_chunk(i, summary_data.chunk(i));
   339   }
   341   tty->print_cr("max:  " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " "
   342                 "l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f",
   343                 max_reclaimed_ratio_chunk, max_dead_to_right,
   344                 max_live_to_right, max_reclaimed_ratio);
   345 }
   347 void
   348 print_initial_summary_data(ParallelCompactData& summary_data,
   349                            SpaceInfo* space_info) {
   350   unsigned int id = PSParallelCompact::perm_space_id;
   351   const MutableSpace* space;
   352   do {
   353     space = space_info[id].space();
   354     print_initial_summary_data(summary_data, space);
   355   } while (++id < PSParallelCompact::eden_space_id);
   357   do {
   358     space = space_info[id].space();
   359     print_generic_summary_data(summary_data, space->bottom(), space->top());
   360   } while (++id < PSParallelCompact::last_space_id);
   361 }
   362 #endif  // #ifndef PRODUCT
   364 #ifdef  ASSERT
   365 size_t add_obj_count;
   366 size_t add_obj_size;
   367 size_t mark_bitmap_count;
   368 size_t mark_bitmap_size;
   369 #endif  // #ifdef ASSERT
   371 ParallelCompactData::ParallelCompactData()
   372 {
   373   _region_start = 0;
   375   _chunk_vspace = 0;
   376   _chunk_data = 0;
   377   _chunk_count = 0;
   379   _block_vspace = 0;
   380   _block_data = 0;
   381   _block_count = 0;
   382 }
   384 bool ParallelCompactData::initialize(MemRegion covered_region)
   385 {
   386   _region_start = covered_region.start();
   387   const size_t region_size = covered_region.word_size();
   388   DEBUG_ONLY(_region_end = _region_start + region_size;)
   390   assert(chunk_align_down(_region_start) == _region_start,
   391          "region start not aligned");
   392   assert((region_size & ChunkSizeOffsetMask) == 0,
   393          "region size not a multiple of ChunkSize");
   395   bool result = initialize_chunk_data(region_size);
   397   // Initialize the block data if it will be used for updating pointers, or if
   398   // this is a debug build.
   399   if (!UseParallelOldGCChunkPointerCalc || trueInDebug) {
   400     result = result && initialize_block_data(region_size);
   401   }
   403   return result;
   404 }
   406 PSVirtualSpace*
   407 ParallelCompactData::create_vspace(size_t count, size_t element_size)
   408 {
   409   const size_t raw_bytes = count * element_size;
   410   const size_t page_sz = os::page_size_for_region(raw_bytes, raw_bytes, 10);
   411   const size_t granularity = os::vm_allocation_granularity();
   412   const size_t bytes = align_size_up(raw_bytes, MAX2(page_sz, granularity));
   414   const size_t rs_align = page_sz == (size_t) os::vm_page_size() ? 0 :
   415     MAX2(page_sz, granularity);
   416   ReservedSpace rs(bytes, rs_align, rs_align > 0);
   417   os::trace_page_sizes("par compact", raw_bytes, raw_bytes, page_sz, rs.base(),
   418                        rs.size());
   419   PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
   420   if (vspace != 0) {
   421     if (vspace->expand_by(bytes)) {
   422       return vspace;
   423     }
   424     delete vspace;
   425     // Release memory reserved in the space.
   426     rs.release();
   427   }
   429   return 0;
   430 }
   432 bool ParallelCompactData::initialize_chunk_data(size_t region_size)
   433 {
   434   const size_t count = (region_size + ChunkSizeOffsetMask) >> Log2ChunkSize;
   435   _chunk_vspace = create_vspace(count, sizeof(ChunkData));
   436   if (_chunk_vspace != 0) {
   437     _chunk_data = (ChunkData*)_chunk_vspace->reserved_low_addr();
   438     _chunk_count = count;
   439     return true;
   440   }
   441   return false;
   442 }
   444 bool ParallelCompactData::initialize_block_data(size_t region_size)
   445 {
   446   const size_t count = (region_size + BlockOffsetMask) >> Log2BlockSize;
   447   _block_vspace = create_vspace(count, sizeof(BlockData));
   448   if (_block_vspace != 0) {
   449     _block_data = (BlockData*)_block_vspace->reserved_low_addr();
   450     _block_count = count;
   451     return true;
   452   }
   453   return false;
   454 }
   456 void ParallelCompactData::clear()
   457 {
   458   if (_block_data) {
   459     memset(_block_data, 0, _block_vspace->committed_size());
   460   }
   461   memset(_chunk_data, 0, _chunk_vspace->committed_size());
   462 }
   464 void ParallelCompactData::clear_range(size_t beg_chunk, size_t end_chunk) {
   465   assert(beg_chunk <= _chunk_count, "beg_chunk out of range");
   466   assert(end_chunk <= _chunk_count, "end_chunk out of range");
   467   assert(ChunkSize % BlockSize == 0, "ChunkSize not a multiple of BlockSize");
   469   const size_t chunk_cnt = end_chunk - beg_chunk;
   471   if (_block_data) {
   472     const size_t blocks_per_chunk = ChunkSize / BlockSize;
   473     const size_t beg_block = beg_chunk * blocks_per_chunk;
   474     const size_t block_cnt = chunk_cnt * blocks_per_chunk;
   475     memset(_block_data + beg_block, 0, block_cnt * sizeof(BlockData));
   476   }
   477   memset(_chunk_data + beg_chunk, 0, chunk_cnt * sizeof(ChunkData));
   478 }
   480 HeapWord* ParallelCompactData::partial_obj_end(size_t chunk_idx) const
   481 {
   482   const ChunkData* cur_cp = chunk(chunk_idx);
   483   const ChunkData* const end_cp = chunk(chunk_count() - 1);
   485   HeapWord* result = chunk_to_addr(chunk_idx);
   486   if (cur_cp < end_cp) {
   487     do {
   488       result += cur_cp->partial_obj_size();
   489     } while (cur_cp->partial_obj_size() == ChunkSize && ++cur_cp < end_cp);
   490   }
   491   return result;
   492 }
   494 void ParallelCompactData::add_obj(HeapWord* addr, size_t len)
   495 {
   496   const size_t obj_ofs = pointer_delta(addr, _region_start);
   497   const size_t beg_chunk = obj_ofs >> Log2ChunkSize;
   498   const size_t end_chunk = (obj_ofs + len - 1) >> Log2ChunkSize;
   500   DEBUG_ONLY(Atomic::inc_ptr(&add_obj_count);)
   501   DEBUG_ONLY(Atomic::add_ptr(len, &add_obj_size);)
   503   if (beg_chunk == end_chunk) {
   504     // All in one chunk.
   505     _chunk_data[beg_chunk].add_live_obj(len);
   506     return;
   507   }
   509   // First chunk.
   510   const size_t beg_ofs = chunk_offset(addr);
   511   _chunk_data[beg_chunk].add_live_obj(ChunkSize - beg_ofs);
   513   klassOop klass = ((oop)addr)->klass();
   514   // Middle chunks--completely spanned by this object.
   515   for (size_t chunk = beg_chunk + 1; chunk < end_chunk; ++chunk) {
   516     _chunk_data[chunk].set_partial_obj_size(ChunkSize);
   517     _chunk_data[chunk].set_partial_obj_addr(addr);
   518   }
   520   // Last chunk.
   521   const size_t end_ofs = chunk_offset(addr + len - 1);
   522   _chunk_data[end_chunk].set_partial_obj_size(end_ofs + 1);
   523   _chunk_data[end_chunk].set_partial_obj_addr(addr);
   524 }
   526 void
   527 ParallelCompactData::summarize_dense_prefix(HeapWord* beg, HeapWord* end)
   528 {
   529   assert(chunk_offset(beg) == 0, "not ChunkSize aligned");
   530   assert(chunk_offset(end) == 0, "not ChunkSize aligned");
   532   size_t cur_chunk = addr_to_chunk_idx(beg);
   533   const size_t end_chunk = addr_to_chunk_idx(end);
   534   HeapWord* addr = beg;
   535   while (cur_chunk < end_chunk) {
   536     _chunk_data[cur_chunk].set_destination(addr);
   537     _chunk_data[cur_chunk].set_destination_count(0);
   538     _chunk_data[cur_chunk].set_source_chunk(cur_chunk);
   539     _chunk_data[cur_chunk].set_data_location(addr);
   541     // Update live_obj_size so the chunk appears completely full.
   542     size_t live_size = ChunkSize - _chunk_data[cur_chunk].partial_obj_size();
   543     _chunk_data[cur_chunk].set_live_obj_size(live_size);
   545     ++cur_chunk;
   546     addr += ChunkSize;
   547   }
   548 }
   550 bool ParallelCompactData::summarize(HeapWord* target_beg, HeapWord* target_end,
   551                                     HeapWord* source_beg, HeapWord* source_end,
   552                                     HeapWord** target_next,
   553                                     HeapWord** source_next) {
   554   // This is too strict.
   555   // assert(chunk_offset(source_beg) == 0, "not ChunkSize aligned");
   557   if (TraceParallelOldGCSummaryPhase) {
   558     tty->print_cr("tb=" PTR_FORMAT " te=" PTR_FORMAT " "
   559                   "sb=" PTR_FORMAT " se=" PTR_FORMAT " "
   560                   "tn=" PTR_FORMAT " sn=" PTR_FORMAT,
   561                   target_beg, target_end,
   562                   source_beg, source_end,
   563                   target_next != 0 ? *target_next : (HeapWord*) 0,
   564                   source_next != 0 ? *source_next : (HeapWord*) 0);
   565   }
   567   size_t cur_chunk = addr_to_chunk_idx(source_beg);
   568   const size_t end_chunk = addr_to_chunk_idx(chunk_align_up(source_end));
   570   HeapWord *dest_addr = target_beg;
   571   while (cur_chunk < end_chunk) {
   572     size_t words = _chunk_data[cur_chunk].data_size();
   574 #if     1
   575     assert(pointer_delta(target_end, dest_addr) >= words,
   576            "source region does not fit into target region");
   577 #else
   578     // XXX - need some work on the corner cases here.  If the chunk does not
   579     // fit, then must either make sure any partial_obj from the chunk fits, or
   580     // 'undo' the initial part of the partial_obj that is in the previous chunk.
   581     if (dest_addr + words >= target_end) {
   582       // Let the caller know where to continue.
   583       *target_next = dest_addr;
   584       *source_next = chunk_to_addr(cur_chunk);
   585       return false;
   586     }
   587 #endif  // #if 1
   589     _chunk_data[cur_chunk].set_destination(dest_addr);
   591     // Set the destination_count for cur_chunk, and if necessary, update
   592     // source_chunk for a destination chunk.  The source_chunk field is updated
   593     // if cur_chunk is the first (left-most) chunk to be copied to a destination
   594     // chunk.
   595     //
   596     // The destination_count calculation is a bit subtle.  A chunk that has data
   597     // that compacts into itself does not count itself as a destination.  This
   598     // maintains the invariant that a zero count means the chunk is available
   599     // and can be claimed and then filled.
   600     if (words > 0) {
   601       HeapWord* const last_addr = dest_addr + words - 1;
   602       const size_t dest_chunk_1 = addr_to_chunk_idx(dest_addr);
   603       const size_t dest_chunk_2 = addr_to_chunk_idx(last_addr);
   604 #if     0
   605       // Initially assume that the destination chunks will be the same and
   606       // adjust the value below if necessary.  Under this assumption, if
   607       // cur_chunk == dest_chunk_2, then cur_chunk will be compacted completely
   608       // into itself.
   609       uint destination_count = cur_chunk == dest_chunk_2 ? 0 : 1;
   610       if (dest_chunk_1 != dest_chunk_2) {
   611         // Destination chunks differ; adjust destination_count.
   612         destination_count += 1;
   613         // Data from cur_chunk will be copied to the start of dest_chunk_2.
   614         _chunk_data[dest_chunk_2].set_source_chunk(cur_chunk);
   615       } else if (chunk_offset(dest_addr) == 0) {
   616         // Data from cur_chunk will be copied to the start of the destination
   617         // chunk.
   618         _chunk_data[dest_chunk_1].set_source_chunk(cur_chunk);
   619       }
   620 #else
   621       // Initially assume that the destination chunks will be different and
   622       // adjust the value below if necessary.  Under this assumption, if
   623       // cur_chunk == dest_chunk2, then cur_chunk will be compacted partially
   624       // into dest_chunk_1 and partially into itself.
   625       uint destination_count = cur_chunk == dest_chunk_2 ? 1 : 2;
   626       if (dest_chunk_1 != dest_chunk_2) {
   627         // Data from cur_chunk will be copied to the start of dest_chunk_2.
   628         _chunk_data[dest_chunk_2].set_source_chunk(cur_chunk);
   629       } else {
   630         // Destination chunks are the same; adjust destination_count.
   631         destination_count -= 1;
   632         if (chunk_offset(dest_addr) == 0) {
   633           // Data from cur_chunk will be copied to the start of the destination
   634           // chunk.
   635           _chunk_data[dest_chunk_1].set_source_chunk(cur_chunk);
   636         }
   637       }
   638 #endif  // #if 0
   640       _chunk_data[cur_chunk].set_destination_count(destination_count);
   641       _chunk_data[cur_chunk].set_data_location(chunk_to_addr(cur_chunk));
   642       dest_addr += words;
   643     }
   645     ++cur_chunk;
   646   }
   648   *target_next = dest_addr;
   649   return true;
   650 }
   652 bool ParallelCompactData::partial_obj_ends_in_block(size_t block_index) {
   653   HeapWord* block_addr = block_to_addr(block_index);
   654   HeapWord* block_end_addr = block_addr + BlockSize;
   655   size_t chunk_index = addr_to_chunk_idx(block_addr);
   656   HeapWord* partial_obj_end_addr = partial_obj_end(chunk_index);
   658   // An object that ends at the end of the block, ends
   659   // in the block (the last word of the object is to
   660   // the left of the end).
   661   if ((block_addr < partial_obj_end_addr) &&
   662       (partial_obj_end_addr <= block_end_addr)) {
   663     return true;
   664   }
   666   return false;
   667 }
   669 HeapWord* ParallelCompactData::calc_new_pointer(HeapWord* addr) {
   670   HeapWord* result = NULL;
   671   if (UseParallelOldGCChunkPointerCalc) {
   672     result = chunk_calc_new_pointer(addr);
   673   } else {
   674     result = block_calc_new_pointer(addr);
   675   }
   676   return result;
   677 }
   679 // This method is overly complicated (expensive) to be called
   680 // for every reference.
   681 // Try to restructure this so that a NULL is returned if
   682 // the object is dead.  But don't wast the cycles to explicitly check
   683 // that it is dead since only live objects should be passed in.
   685 HeapWord* ParallelCompactData::chunk_calc_new_pointer(HeapWord* addr) {
   686   assert(addr != NULL, "Should detect NULL oop earlier");
   687   assert(PSParallelCompact::gc_heap()->is_in(addr), "addr not in heap");
   688 #ifdef ASSERT
   689   if (PSParallelCompact::mark_bitmap()->is_unmarked(addr)) {
   690     gclog_or_tty->print_cr("calc_new_pointer:: addr " PTR_FORMAT, addr);
   691   }
   692 #endif
   693   assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "obj not marked");
   695   // Chunk covering the object.
   696   size_t chunk_index = addr_to_chunk_idx(addr);
   697   const ChunkData* const chunk_ptr = chunk(chunk_index);
   698   HeapWord* const chunk_addr = chunk_align_down(addr);
   700   assert(addr < chunk_addr + ChunkSize, "Chunk does not cover object");
   701   assert(addr_to_chunk_ptr(chunk_addr) == chunk_ptr, "sanity check");
   703   HeapWord* result = chunk_ptr->destination();
   705   // If all the data in the chunk is live, then the new location of the object
   706   // can be calculated from the destination of the chunk plus the offset of the
   707   // object in the chunk.
   708   if (chunk_ptr->data_size() == ChunkSize) {
   709     result += pointer_delta(addr, chunk_addr);
   710     return result;
   711   }
   713   // The new location of the object is
   714   //    chunk destination +
   715   //    size of the partial object extending onto the chunk +
   716   //    sizes of the live objects in the Chunk that are to the left of addr
   717   const size_t partial_obj_size = chunk_ptr->partial_obj_size();
   718   HeapWord* const search_start = chunk_addr + partial_obj_size;
   720   const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();
   721   size_t live_to_left = bitmap->live_words_in_range(search_start, oop(addr));
   723   result += partial_obj_size + live_to_left;
   724   assert(result <= addr, "object cannot move to the right");
   725   return result;
   726 }
   728 HeapWord* ParallelCompactData::block_calc_new_pointer(HeapWord* addr) {
   729   assert(addr != NULL, "Should detect NULL oop earlier");
   730   assert(PSParallelCompact::gc_heap()->is_in(addr), "addr not in heap");
   731 #ifdef ASSERT
   732   if (PSParallelCompact::mark_bitmap()->is_unmarked(addr)) {
   733     gclog_or_tty->print_cr("calc_new_pointer:: addr " PTR_FORMAT, addr);
   734   }
   735 #endif
   736   assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "obj not marked");
   738   // Chunk covering the object.
   739   size_t chunk_index = addr_to_chunk_idx(addr);
   740   const ChunkData* const chunk_ptr = chunk(chunk_index);
   741   HeapWord* const chunk_addr = chunk_align_down(addr);
   743   assert(addr < chunk_addr + ChunkSize, "Chunk does not cover object");
   744   assert(addr_to_chunk_ptr(chunk_addr) == chunk_ptr, "sanity check");
   746   HeapWord* result = chunk_ptr->destination();
   748   // If all the data in the chunk is live, then the new location of the object
   749   // can be calculated from the destination of the chunk plus the offset of the
   750   // object in the chunk.
   751   if (chunk_ptr->data_size() == ChunkSize) {
   752     result += pointer_delta(addr, chunk_addr);
   753     return result;
   754   }
   756   // The new location of the object is
   757   //    chunk destination +
   758   //    block offset +
   759   //    sizes of the live objects in the Block that are to the left of addr
   760   const size_t block_offset = addr_to_block_ptr(addr)->offset();
   761   HeapWord* const search_start = chunk_addr + block_offset;
   763   const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();
   764   size_t live_to_left = bitmap->live_words_in_range(search_start, oop(addr));
   766   result += block_offset + live_to_left;
   767   assert(result <= addr, "object cannot move to the right");
   768   assert(result == chunk_calc_new_pointer(addr), "Should match");
   769   return result;
   770 }
   772 klassOop ParallelCompactData::calc_new_klass(klassOop old_klass) {
   773   klassOop updated_klass;
   774   if (PSParallelCompact::should_update_klass(old_klass)) {
   775     updated_klass = (klassOop) calc_new_pointer(old_klass);
   776   } else {
   777     updated_klass = old_klass;
   778   }
   780   return updated_klass;
   781 }
   783 #ifdef  ASSERT
   784 void ParallelCompactData::verify_clear(const PSVirtualSpace* vspace)
   785 {
   786   const size_t* const beg = (const size_t*)vspace->committed_low_addr();
   787   const size_t* const end = (const size_t*)vspace->committed_high_addr();
   788   for (const size_t* p = beg; p < end; ++p) {
   789     assert(*p == 0, "not zero");
   790   }
   791 }
   793 void ParallelCompactData::verify_clear()
   794 {
   795   verify_clear(_chunk_vspace);
   796   verify_clear(_block_vspace);
   797 }
   798 #endif  // #ifdef ASSERT
   800 #ifdef NOT_PRODUCT
   801 ParallelCompactData::ChunkData* debug_chunk(size_t chunk_index) {
   802   ParallelCompactData& sd = PSParallelCompact::summary_data();
   803   return sd.chunk(chunk_index);
   804 }
   805 #endif
   807 elapsedTimer        PSParallelCompact::_accumulated_time;
   808 unsigned int        PSParallelCompact::_total_invocations = 0;
   809 unsigned int        PSParallelCompact::_maximum_compaction_gc_num = 0;
   810 jlong               PSParallelCompact::_time_of_last_gc = 0;
   811 CollectorCounters*  PSParallelCompact::_counters = NULL;
   812 ParMarkBitMap       PSParallelCompact::_mark_bitmap;
   813 ParallelCompactData PSParallelCompact::_summary_data;
   815 PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
   817 void PSParallelCompact::IsAliveClosure::do_object(oop p)   { ShouldNotReachHere(); }
   818 bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
   820 void PSParallelCompact::KeepAliveClosure::do_oop(oop* p)       { PSParallelCompact::KeepAliveClosure::do_oop_work(p); }
   821 void PSParallelCompact::KeepAliveClosure::do_oop(narrowOop* p) { PSParallelCompact::KeepAliveClosure::do_oop_work(p); }
   823 PSParallelCompact::AdjustPointerClosure PSParallelCompact::_adjust_root_pointer_closure(true);
   824 PSParallelCompact::AdjustPointerClosure PSParallelCompact::_adjust_pointer_closure(false);
   826 void PSParallelCompact::AdjustPointerClosure::do_oop(oop* p)       { adjust_pointer(p, _is_root); }
   827 void PSParallelCompact::AdjustPointerClosure::do_oop(narrowOop* p) { adjust_pointer(p, _is_root); }
   829 void PSParallelCompact::FollowStackClosure::do_void() { follow_stack(_compaction_manager); }
   831 void PSParallelCompact::MarkAndPushClosure::do_oop(oop* p)       { mark_and_push(_compaction_manager, p); }
   832 void PSParallelCompact::MarkAndPushClosure::do_oop(narrowOop* p) { mark_and_push(_compaction_manager, p); }
   834 void PSParallelCompact::post_initialize() {
   835   ParallelScavengeHeap* heap = gc_heap();
   836   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
   838   MemRegion mr = heap->reserved_region();
   839   _ref_processor = ReferenceProcessor::create_ref_processor(
   840     mr,                         // span
   841     true,                       // atomic_discovery
   842     true,                       // mt_discovery
   843     &_is_alive_closure,
   844     ParallelGCThreads,
   845     ParallelRefProcEnabled);
   846   _counters = new CollectorCounters("PSParallelCompact", 1);
   848   // Initialize static fields in ParCompactionManager.
   849   ParCompactionManager::initialize(mark_bitmap());
   850 }
   852 bool PSParallelCompact::initialize() {
   853   ParallelScavengeHeap* heap = gc_heap();
   854   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
   855   MemRegion mr = heap->reserved_region();
   857   // Was the old gen get allocated successfully?
   858   if (!heap->old_gen()->is_allocated()) {
   859     return false;
   860   }
   862   initialize_space_info();
   863   initialize_dead_wood_limiter();
   865   if (!_mark_bitmap.initialize(mr)) {
   866     vm_shutdown_during_initialization("Unable to allocate bit map for "
   867       "parallel garbage collection for the requested heap size.");
   868     return false;
   869   }
   871   if (!_summary_data.initialize(mr)) {
   872     vm_shutdown_during_initialization("Unable to allocate tables for "
   873       "parallel garbage collection for the requested heap size.");
   874     return false;
   875   }
   877   return true;
   878 }
   880 void PSParallelCompact::initialize_space_info()
   881 {
   882   memset(&_space_info, 0, sizeof(_space_info));
   884   ParallelScavengeHeap* heap = gc_heap();
   885   PSYoungGen* young_gen = heap->young_gen();
   886   MutableSpace* perm_space = heap->perm_gen()->object_space();
   888   _space_info[perm_space_id].set_space(perm_space);
   889   _space_info[old_space_id].set_space(heap->old_gen()->object_space());
   890   _space_info[eden_space_id].set_space(young_gen->eden_space());
   891   _space_info[from_space_id].set_space(young_gen->from_space());
   892   _space_info[to_space_id].set_space(young_gen->to_space());
   894   _space_info[perm_space_id].set_start_array(heap->perm_gen()->start_array());
   895   _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
   897   _space_info[perm_space_id].set_min_dense_prefix(perm_space->top());
   898   if (TraceParallelOldGCDensePrefix) {
   899     tty->print_cr("perm min_dense_prefix=" PTR_FORMAT,
   900                   _space_info[perm_space_id].min_dense_prefix());
   901   }
   902 }
   904 void PSParallelCompact::initialize_dead_wood_limiter()
   905 {
   906   const size_t max = 100;
   907   _dwl_mean = double(MIN2(ParallelOldDeadWoodLimiterMean, max)) / 100.0;
   908   _dwl_std_dev = double(MIN2(ParallelOldDeadWoodLimiterStdDev, max)) / 100.0;
   909   _dwl_first_term = 1.0 / (sqrt(2.0 * M_PI) * _dwl_std_dev);
   910   DEBUG_ONLY(_dwl_initialized = true;)
   911   _dwl_adjustment = normal_distribution(1.0);
   912 }
   914 // Simple class for storing info about the heap at the start of GC, to be used
   915 // after GC for comparison/printing.
   916 class PreGCValues {
   917 public:
   918   PreGCValues() { }
   919   PreGCValues(ParallelScavengeHeap* heap) { fill(heap); }
   921   void fill(ParallelScavengeHeap* heap) {
   922     _heap_used      = heap->used();
   923     _young_gen_used = heap->young_gen()->used_in_bytes();
   924     _old_gen_used   = heap->old_gen()->used_in_bytes();
   925     _perm_gen_used  = heap->perm_gen()->used_in_bytes();
   926   };
   928   size_t heap_used() const      { return _heap_used; }
   929   size_t young_gen_used() const { return _young_gen_used; }
   930   size_t old_gen_used() const   { return _old_gen_used; }
   931   size_t perm_gen_used() const  { return _perm_gen_used; }
   933 private:
   934   size_t _heap_used;
   935   size_t _young_gen_used;
   936   size_t _old_gen_used;
   937   size_t _perm_gen_used;
   938 };
   940 void
   941 PSParallelCompact::clear_data_covering_space(SpaceId id)
   942 {
   943   // At this point, top is the value before GC, new_top() is the value that will
   944   // be set at the end of GC.  The marking bitmap is cleared to top; nothing
   945   // should be marked above top.  The summary data is cleared to the larger of
   946   // top & new_top.
   947   MutableSpace* const space = _space_info[id].space();
   948   HeapWord* const bot = space->bottom();
   949   HeapWord* const top = space->top();
   950   HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
   952   const idx_t beg_bit = _mark_bitmap.addr_to_bit(bot);
   953   const idx_t end_bit = BitMap::word_align_up(_mark_bitmap.addr_to_bit(top));
   954   _mark_bitmap.clear_range(beg_bit, end_bit);
   956   const size_t beg_chunk = _summary_data.addr_to_chunk_idx(bot);
   957   const size_t end_chunk =
   958     _summary_data.addr_to_chunk_idx(_summary_data.chunk_align_up(max_top));
   959   _summary_data.clear_range(beg_chunk, end_chunk);
   960 }
   962 void PSParallelCompact::pre_compact(PreGCValues* pre_gc_values)
   963 {
   964   // Update the from & to space pointers in space_info, since they are swapped
   965   // at each young gen gc.  Do the update unconditionally (even though a
   966   // promotion failure does not swap spaces) because an unknown number of minor
   967   // collections will have swapped the spaces an unknown number of times.
   968   TraceTime tm("pre compact", print_phases(), true, gclog_or_tty);
   969   ParallelScavengeHeap* heap = gc_heap();
   970   _space_info[from_space_id].set_space(heap->young_gen()->from_space());
   971   _space_info[to_space_id].set_space(heap->young_gen()->to_space());
   973   pre_gc_values->fill(heap);
   975   ParCompactionManager::reset();
   976   NOT_PRODUCT(_mark_bitmap.reset_counters());
   977   DEBUG_ONLY(add_obj_count = add_obj_size = 0;)
   978   DEBUG_ONLY(mark_bitmap_count = mark_bitmap_size = 0;)
   980   // Increment the invocation count
   981   heap->increment_total_collections(true);
   983   // We need to track unique mark sweep invocations as well.
   984   _total_invocations++;
   986   if (PrintHeapAtGC) {
   987     Universe::print_heap_before_gc();
   988   }
   990   // Fill in TLABs
   991   heap->accumulate_statistics_all_tlabs();
   992   heap->ensure_parsability(true);  // retire TLABs
   994   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
   995     HandleMark hm;  // Discard invalid handles created during verification
   996     gclog_or_tty->print(" VerifyBeforeGC:");
   997     Universe::verify(true);
   998   }
  1000   // Verify object start arrays
  1001   if (VerifyObjectStartArray &&
  1002       VerifyBeforeGC) {
  1003     heap->old_gen()->verify_object_start_array();
  1004     heap->perm_gen()->verify_object_start_array();
  1007   DEBUG_ONLY(mark_bitmap()->verify_clear();)
  1008   DEBUG_ONLY(summary_data().verify_clear();)
  1010   // Have worker threads release resources the next time they run a task.
  1011   gc_task_manager()->release_all_resources();
  1014 void PSParallelCompact::post_compact()
  1016   TraceTime tm("post compact", print_phases(), true, gclog_or_tty);
  1018   // Clear the marking bitmap and summary data and update top() in each space.
  1019   for (unsigned int id = perm_space_id; id < last_space_id; ++id) {
  1020     clear_data_covering_space(SpaceId(id));
  1021     _space_info[id].space()->set_top(_space_info[id].new_top());
  1024   MutableSpace* const eden_space = _space_info[eden_space_id].space();
  1025   MutableSpace* const from_space = _space_info[from_space_id].space();
  1026   MutableSpace* const to_space   = _space_info[to_space_id].space();
  1028   ParallelScavengeHeap* heap = gc_heap();
  1029   bool eden_empty = eden_space->is_empty();
  1030   if (!eden_empty) {
  1031     eden_empty = absorb_live_data_from_eden(heap->size_policy(),
  1032                                             heap->young_gen(), heap->old_gen());
  1035   // Update heap occupancy information which is used as input to the soft ref
  1036   // clearing policy at the next gc.
  1037   Universe::update_heap_info_at_gc();
  1039   bool young_gen_empty = eden_empty && from_space->is_empty() &&
  1040     to_space->is_empty();
  1042   BarrierSet* bs = heap->barrier_set();
  1043   if (bs->is_a(BarrierSet::ModRef)) {
  1044     ModRefBarrierSet* modBS = (ModRefBarrierSet*)bs;
  1045     MemRegion old_mr = heap->old_gen()->reserved();
  1046     MemRegion perm_mr = heap->perm_gen()->reserved();
  1047     assert(perm_mr.end() <= old_mr.start(), "Generations out of order");
  1049     if (young_gen_empty) {
  1050       modBS->clear(MemRegion(perm_mr.start(), old_mr.end()));
  1051     } else {
  1052       modBS->invalidate(MemRegion(perm_mr.start(), old_mr.end()));
  1056   Threads::gc_epilogue();
  1057   CodeCache::gc_epilogue();
  1059   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
  1061   ref_processor()->enqueue_discovered_references(NULL);
  1063   if (ZapUnusedHeapArea) {
  1064     heap->gen_mangle_unused_area();
  1067   // Update time of last GC
  1068   reset_millis_since_last_gc();
  1071 HeapWord*
  1072 PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id,
  1073                                                     bool maximum_compaction)
  1075   const size_t chunk_size = ParallelCompactData::ChunkSize;
  1076   const ParallelCompactData& sd = summary_data();
  1078   const MutableSpace* const space = _space_info[id].space();
  1079   HeapWord* const top_aligned_up = sd.chunk_align_up(space->top());
  1080   const ChunkData* const beg_cp = sd.addr_to_chunk_ptr(space->bottom());
  1081   const ChunkData* const end_cp = sd.addr_to_chunk_ptr(top_aligned_up);
  1083   // Skip full chunks at the beginning of the space--they are necessarily part
  1084   // of the dense prefix.
  1085   size_t full_count = 0;
  1086   const ChunkData* cp;
  1087   for (cp = beg_cp; cp < end_cp && cp->data_size() == chunk_size; ++cp) {
  1088     ++full_count;
  1091   assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");
  1092   const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;
  1093   const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval;
  1094   if (maximum_compaction || cp == end_cp || interval_ended) {
  1095     _maximum_compaction_gc_num = total_invocations();
  1096     return sd.chunk_to_addr(cp);
  1099   HeapWord* const new_top = _space_info[id].new_top();
  1100   const size_t space_live = pointer_delta(new_top, space->bottom());
  1101   const size_t space_used = space->used_in_words();
  1102   const size_t space_capacity = space->capacity_in_words();
  1104   const double cur_density = double(space_live) / space_capacity;
  1105   const double deadwood_density =
  1106     (1.0 - cur_density) * (1.0 - cur_density) * cur_density * cur_density;
  1107   const size_t deadwood_goal = size_t(space_capacity * deadwood_density);
  1109   if (TraceParallelOldGCDensePrefix) {
  1110     tty->print_cr("cur_dens=%5.3f dw_dens=%5.3f dw_goal=" SIZE_FORMAT,
  1111                   cur_density, deadwood_density, deadwood_goal);
  1112     tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "
  1113                   "space_cap=" SIZE_FORMAT,
  1114                   space_live, space_used,
  1115                   space_capacity);
  1118   // XXX - Use binary search?
  1119   HeapWord* dense_prefix = sd.chunk_to_addr(cp);
  1120   const ChunkData* full_cp = cp;
  1121   const ChunkData* const top_cp = sd.addr_to_chunk_ptr(space->top() - 1);
  1122   while (cp < end_cp) {
  1123     HeapWord* chunk_destination = cp->destination();
  1124     const size_t cur_deadwood = pointer_delta(dense_prefix, chunk_destination);
  1125     if (TraceParallelOldGCDensePrefix && Verbose) {
  1126       tty->print_cr("c#=" SIZE_FORMAT_W(4) " dst=" PTR_FORMAT " "
  1127                     "dp=" SIZE_FORMAT_W(8) " " "cdw=" SIZE_FORMAT_W(8),
  1128                     sd.chunk(cp), chunk_destination,
  1129                     dense_prefix, cur_deadwood);
  1132     if (cur_deadwood >= deadwood_goal) {
  1133       // Found the chunk that has the correct amount of deadwood to the left.
  1134       // This typically occurs after crossing a fairly sparse set of chunks, so
  1135       // iterate backwards over those sparse chunks, looking for the chunk that
  1136       // has the lowest density of live objects 'to the right.'
  1137       size_t space_to_left = sd.chunk(cp) * chunk_size;
  1138       size_t live_to_left = space_to_left - cur_deadwood;
  1139       size_t space_to_right = space_capacity - space_to_left;
  1140       size_t live_to_right = space_live - live_to_left;
  1141       double density_to_right = double(live_to_right) / space_to_right;
  1142       while (cp > full_cp) {
  1143         --cp;
  1144         const size_t prev_chunk_live_to_right = live_to_right - cp->data_size();
  1145         const size_t prev_chunk_space_to_right = space_to_right + chunk_size;
  1146         double prev_chunk_density_to_right =
  1147           double(prev_chunk_live_to_right) / prev_chunk_space_to_right;
  1148         if (density_to_right <= prev_chunk_density_to_right) {
  1149           return dense_prefix;
  1151         if (TraceParallelOldGCDensePrefix && Verbose) {
  1152           tty->print_cr("backing up from c=" SIZE_FORMAT_W(4) " d2r=%10.8f "
  1153                         "pc_d2r=%10.8f", sd.chunk(cp), density_to_right,
  1154                         prev_chunk_density_to_right);
  1156         dense_prefix -= chunk_size;
  1157         live_to_right = prev_chunk_live_to_right;
  1158         space_to_right = prev_chunk_space_to_right;
  1159         density_to_right = prev_chunk_density_to_right;
  1161       return dense_prefix;
  1164     dense_prefix += chunk_size;
  1165     ++cp;
  1168   return dense_prefix;
  1171 #ifndef PRODUCT
  1172 void PSParallelCompact::print_dense_prefix_stats(const char* const algorithm,
  1173                                                  const SpaceId id,
  1174                                                  const bool maximum_compaction,
  1175                                                  HeapWord* const addr)
  1177   const size_t chunk_idx = summary_data().addr_to_chunk_idx(addr);
  1178   ChunkData* const cp = summary_data().chunk(chunk_idx);
  1179   const MutableSpace* const space = _space_info[id].space();
  1180   HeapWord* const new_top = _space_info[id].new_top();
  1182   const size_t space_live = pointer_delta(new_top, space->bottom());
  1183   const size_t dead_to_left = pointer_delta(addr, cp->destination());
  1184   const size_t space_cap = space->capacity_in_words();
  1185   const double dead_to_left_pct = double(dead_to_left) / space_cap;
  1186   const size_t live_to_right = new_top - cp->destination();
  1187   const size_t dead_to_right = space->top() - addr - live_to_right;
  1189   tty->print_cr("%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W(5) " "
  1190                 "spl=" SIZE_FORMAT " "
  1191                 "d2l=" SIZE_FORMAT " d2l%%=%6.4f "
  1192                 "d2r=" SIZE_FORMAT " l2r=" SIZE_FORMAT
  1193                 " ratio=%10.8f",
  1194                 algorithm, addr, chunk_idx,
  1195                 space_live,
  1196                 dead_to_left, dead_to_left_pct,
  1197                 dead_to_right, live_to_right,
  1198                 double(dead_to_right) / live_to_right);
  1200 #endif  // #ifndef PRODUCT
  1202 // Return a fraction indicating how much of the generation can be treated as
  1203 // "dead wood" (i.e., not reclaimed).  The function uses a normal distribution
  1204 // based on the density of live objects in the generation to determine a limit,
  1205 // which is then adjusted so the return value is min_percent when the density is
  1206 // 1.
  1207 //
  1208 // The following table shows some return values for a different values of the
  1209 // standard deviation (ParallelOldDeadWoodLimiterStdDev); the mean is 0.5 and
  1210 // min_percent is 1.
  1211 //
  1212 //                          fraction allowed as dead wood
  1213 //         -----------------------------------------------------------------
  1214 // density std_dev=70 std_dev=75 std_dev=80 std_dev=85 std_dev=90 std_dev=95
  1215 // ------- ---------- ---------- ---------- ---------- ---------- ----------
  1216 // 0.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
  1217 // 0.05000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
  1218 // 0.10000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
  1219 // 0.15000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
  1220 // 0.20000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
  1221 // 0.25000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
  1222 // 0.30000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
  1223 // 0.35000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
  1224 // 0.40000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
  1225 // 0.45000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
  1226 // 0.50000 0.13832410 0.11599237 0.09847664 0.08456518 0.07338887 0.06431510
  1227 // 0.55000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
  1228 // 0.60000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
  1229 // 0.65000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
  1230 // 0.70000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
  1231 // 0.75000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
  1232 // 0.80000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
  1233 // 0.85000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
  1234 // 0.90000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
  1235 // 0.95000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
  1236 // 1.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
  1238 double PSParallelCompact::dead_wood_limiter(double density, size_t min_percent)
  1240   assert(_dwl_initialized, "uninitialized");
  1242   // The raw limit is the value of the normal distribution at x = density.
  1243   const double raw_limit = normal_distribution(density);
  1245   // Adjust the raw limit so it becomes the minimum when the density is 1.
  1246   //
  1247   // First subtract the adjustment value (which is simply the precomputed value
  1248   // normal_distribution(1.0)); this yields a value of 0 when the density is 1.
  1249   // Then add the minimum value, so the minimum is returned when the density is
  1250   // 1.  Finally, prevent negative values, which occur when the mean is not 0.5.
  1251   const double min = double(min_percent) / 100.0;
  1252   const double limit = raw_limit - _dwl_adjustment + min;
  1253   return MAX2(limit, 0.0);
  1256 ParallelCompactData::ChunkData*
  1257 PSParallelCompact::first_dead_space_chunk(const ChunkData* beg,
  1258                                           const ChunkData* end)
  1260   const size_t chunk_size = ParallelCompactData::ChunkSize;
  1261   ParallelCompactData& sd = summary_data();
  1262   size_t left = sd.chunk(beg);
  1263   size_t right = end > beg ? sd.chunk(end) - 1 : left;
  1265   // Binary search.
  1266   while (left < right) {
  1267     // Equivalent to (left + right) / 2, but does not overflow.
  1268     const size_t middle = left + (right - left) / 2;
  1269     ChunkData* const middle_ptr = sd.chunk(middle);
  1270     HeapWord* const dest = middle_ptr->destination();
  1271     HeapWord* const addr = sd.chunk_to_addr(middle);
  1272     assert(dest != NULL, "sanity");
  1273     assert(dest <= addr, "must move left");
  1275     if (middle > left && dest < addr) {
  1276       right = middle - 1;
  1277     } else if (middle < right && middle_ptr->data_size() == chunk_size) {
  1278       left = middle + 1;
  1279     } else {
  1280       return middle_ptr;
  1283   return sd.chunk(left);
  1286 ParallelCompactData::ChunkData*
  1287 PSParallelCompact::dead_wood_limit_chunk(const ChunkData* beg,
  1288                                          const ChunkData* end,
  1289                                          size_t dead_words)
  1291   ParallelCompactData& sd = summary_data();
  1292   size_t left = sd.chunk(beg);
  1293   size_t right = end > beg ? sd.chunk(end) - 1 : left;
  1295   // Binary search.
  1296   while (left < right) {
  1297     // Equivalent to (left + right) / 2, but does not overflow.
  1298     const size_t middle = left + (right - left) / 2;
  1299     ChunkData* const middle_ptr = sd.chunk(middle);
  1300     HeapWord* const dest = middle_ptr->destination();
  1301     HeapWord* const addr = sd.chunk_to_addr(middle);
  1302     assert(dest != NULL, "sanity");
  1303     assert(dest <= addr, "must move left");
  1305     const size_t dead_to_left = pointer_delta(addr, dest);
  1306     if (middle > left && dead_to_left > dead_words) {
  1307       right = middle - 1;
  1308     } else if (middle < right && dead_to_left < dead_words) {
  1309       left = middle + 1;
  1310     } else {
  1311       return middle_ptr;
  1314   return sd.chunk(left);
  1317 // The result is valid during the summary phase, after the initial summarization
  1318 // of each space into itself, and before final summarization.
  1319 inline double
  1320 PSParallelCompact::reclaimed_ratio(const ChunkData* const cp,
  1321                                    HeapWord* const bottom,
  1322                                    HeapWord* const top,
  1323                                    HeapWord* const new_top)
  1325   ParallelCompactData& sd = summary_data();
  1327   assert(cp != NULL, "sanity");
  1328   assert(bottom != NULL, "sanity");
  1329   assert(top != NULL, "sanity");
  1330   assert(new_top != NULL, "sanity");
  1331   assert(top >= new_top, "summary data problem?");
  1332   assert(new_top > bottom, "space is empty; should not be here");
  1333   assert(new_top >= cp->destination(), "sanity");
  1334   assert(top >= sd.chunk_to_addr(cp), "sanity");
  1336   HeapWord* const destination = cp->destination();
  1337   const size_t dense_prefix_live  = pointer_delta(destination, bottom);
  1338   const size_t compacted_region_live = pointer_delta(new_top, destination);
  1339   const size_t compacted_region_used = pointer_delta(top, sd.chunk_to_addr(cp));
  1340   const size_t reclaimable = compacted_region_used - compacted_region_live;
  1342   const double divisor = dense_prefix_live + 1.25 * compacted_region_live;
  1343   return double(reclaimable) / divisor;
  1346 // Return the address of the end of the dense prefix, a.k.a. the start of the
  1347 // compacted region.  The address is always on a chunk boundary.
  1348 //
  1349 // Completely full chunks at the left are skipped, since no compaction can occur
  1350 // in those chunks.  Then the maximum amount of dead wood to allow is computed,
  1351 // based on the density (amount live / capacity) of the generation; the chunk
  1352 // with approximately that amount of dead space to the left is identified as the
  1353 // limit chunk.  Chunks between the last completely full chunk and the limit
  1354 // chunk are scanned and the one that has the best (maximum) reclaimed_ratio()
  1355 // is selected.
  1356 HeapWord*
  1357 PSParallelCompact::compute_dense_prefix(const SpaceId id,
  1358                                         bool maximum_compaction)
  1360   const size_t chunk_size = ParallelCompactData::ChunkSize;
  1361   const ParallelCompactData& sd = summary_data();
  1363   const MutableSpace* const space = _space_info[id].space();
  1364   HeapWord* const top = space->top();
  1365   HeapWord* const top_aligned_up = sd.chunk_align_up(top);
  1366   HeapWord* const new_top = _space_info[id].new_top();
  1367   HeapWord* const new_top_aligned_up = sd.chunk_align_up(new_top);
  1368   HeapWord* const bottom = space->bottom();
  1369   const ChunkData* const beg_cp = sd.addr_to_chunk_ptr(bottom);
  1370   const ChunkData* const top_cp = sd.addr_to_chunk_ptr(top_aligned_up);
  1371   const ChunkData* const new_top_cp = sd.addr_to_chunk_ptr(new_top_aligned_up);
  1373   // Skip full chunks at the beginning of the space--they are necessarily part
  1374   // of the dense prefix.
  1375   const ChunkData* const full_cp = first_dead_space_chunk(beg_cp, new_top_cp);
  1376   assert(full_cp->destination() == sd.chunk_to_addr(full_cp) ||
  1377          space->is_empty(), "no dead space allowed to the left");
  1378   assert(full_cp->data_size() < chunk_size || full_cp == new_top_cp - 1,
  1379          "chunk must have dead space");
  1381   // The gc number is saved whenever a maximum compaction is done, and used to
  1382   // determine when the maximum compaction interval has expired.  This avoids
  1383   // successive max compactions for different reasons.
  1384   assert(total_invocations() >= _maximum_compaction_gc_num, "sanity");
  1385   const size_t gcs_since_max = total_invocations() - _maximum_compaction_gc_num;
  1386   const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval ||
  1387     total_invocations() == HeapFirstMaximumCompactionCount;
  1388   if (maximum_compaction || full_cp == top_cp || interval_ended) {
  1389     _maximum_compaction_gc_num = total_invocations();
  1390     return sd.chunk_to_addr(full_cp);
  1393   const size_t space_live = pointer_delta(new_top, bottom);
  1394   const size_t space_used = space->used_in_words();
  1395   const size_t space_capacity = space->capacity_in_words();
  1397   const double density = double(space_live) / double(space_capacity);
  1398   const size_t min_percent_free =
  1399           id == perm_space_id ? PermMarkSweepDeadRatio : MarkSweepDeadRatio;
  1400   const double limiter = dead_wood_limiter(density, min_percent_free);
  1401   const size_t dead_wood_max = space_used - space_live;
  1402   const size_t dead_wood_limit = MIN2(size_t(space_capacity * limiter),
  1403                                       dead_wood_max);
  1405   if (TraceParallelOldGCDensePrefix) {
  1406     tty->print_cr("space_live=" SIZE_FORMAT " " "space_used=" SIZE_FORMAT " "
  1407                   "space_cap=" SIZE_FORMAT,
  1408                   space_live, space_used,
  1409                   space_capacity);
  1410     tty->print_cr("dead_wood_limiter(%6.4f, %d)=%6.4f "
  1411                   "dead_wood_max=" SIZE_FORMAT " dead_wood_limit=" SIZE_FORMAT,
  1412                   density, min_percent_free, limiter,
  1413                   dead_wood_max, dead_wood_limit);
  1416   // Locate the chunk with the desired amount of dead space to the left.
  1417   const ChunkData* const limit_cp =
  1418     dead_wood_limit_chunk(full_cp, top_cp, dead_wood_limit);
  1420   // Scan from the first chunk with dead space to the limit chunk and find the
  1421   // one with the best (largest) reclaimed ratio.
  1422   double best_ratio = 0.0;
  1423   const ChunkData* best_cp = full_cp;
  1424   for (const ChunkData* cp = full_cp; cp < limit_cp; ++cp) {
  1425     double tmp_ratio = reclaimed_ratio(cp, bottom, top, new_top);
  1426     if (tmp_ratio > best_ratio) {
  1427       best_cp = cp;
  1428       best_ratio = tmp_ratio;
  1432 #if     0
  1433   // Something to consider:  if the chunk with the best ratio is 'close to' the
  1434   // first chunk w/free space, choose the first chunk with free space
  1435   // ("first-free").  The first-free chunk is usually near the start of the
  1436   // heap, which means we are copying most of the heap already, so copy a bit
  1437   // more to get complete compaction.
  1438   if (pointer_delta(best_cp, full_cp, sizeof(ChunkData)) < 4) {
  1439     _maximum_compaction_gc_num = total_invocations();
  1440     best_cp = full_cp;
  1442 #endif  // #if 0
  1444   return sd.chunk_to_addr(best_cp);
  1447 void PSParallelCompact::summarize_spaces_quick()
  1449   for (unsigned int i = 0; i < last_space_id; ++i) {
  1450     const MutableSpace* space = _space_info[i].space();
  1451     bool result = _summary_data.summarize(space->bottom(), space->end(),
  1452                                           space->bottom(), space->top(),
  1453                                           _space_info[i].new_top_addr());
  1454     assert(result, "should never fail");
  1455     _space_info[i].set_dense_prefix(space->bottom());
  1459 void PSParallelCompact::fill_dense_prefix_end(SpaceId id)
  1461   HeapWord* const dense_prefix_end = dense_prefix(id);
  1462   const ChunkData* chunk = _summary_data.addr_to_chunk_ptr(dense_prefix_end);
  1463   const idx_t dense_prefix_bit = _mark_bitmap.addr_to_bit(dense_prefix_end);
  1464   if (dead_space_crosses_boundary(chunk, dense_prefix_bit)) {
  1465     // Only enough dead space is filled so that any remaining dead space to the
  1466     // left is larger than the minimum filler object.  (The remainder is filled
  1467     // during the copy/update phase.)
  1468     //
  1469     // The size of the dead space to the right of the boundary is not a
  1470     // concern, since compaction will be able to use whatever space is
  1471     // available.
  1472     //
  1473     // Here '||' is the boundary, 'x' represents a don't care bit and a box
  1474     // surrounds the space to be filled with an object.
  1475     //
  1476     // In the 32-bit VM, each bit represents two 32-bit words:
  1477     //                              +---+
  1478     // a) beg_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
  1479     //    end_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
  1480     //                              +---+
  1481     //
  1482     // In the 64-bit VM, each bit represents one 64-bit word:
  1483     //                              +------------+
  1484     // b) beg_bits:  ...  x   x   x | 0   ||   0 | x  x  ...
  1485     //    end_bits:  ...  x   x   1 | 0   ||   0 | x  x  ...
  1486     //                              +------------+
  1487     //                          +-------+
  1488     // c) beg_bits:  ...  x   x | 0   0 | ||   0   x  x  ...
  1489     //    end_bits:  ...  x   1 | 0   0 | ||   0   x  x  ...
  1490     //                          +-------+
  1491     //                      +-----------+
  1492     // d) beg_bits:  ...  x | 0   0   0 | ||   0   x  x  ...
  1493     //    end_bits:  ...  1 | 0   0   0 | ||   0   x  x  ...
  1494     //                      +-----------+
  1495     //                          +-------+
  1496     // e) beg_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
  1497     //    end_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
  1498     //                          +-------+
  1500     // Initially assume case a, c or e will apply.
  1501     size_t obj_len = (size_t)oopDesc::header_size();
  1502     HeapWord* obj_beg = dense_prefix_end - obj_len;
  1504 #ifdef  _LP64
  1505     if (_mark_bitmap.is_obj_end(dense_prefix_bit - 2)) {
  1506       // Case b above.
  1507       obj_beg = dense_prefix_end - 1;
  1508     } else if (!_mark_bitmap.is_obj_end(dense_prefix_bit - 3) &&
  1509                _mark_bitmap.is_obj_end(dense_prefix_bit - 4)) {
  1510       // Case d above.
  1511       obj_beg = dense_prefix_end - 3;
  1512       obj_len = 3;
  1514 #endif  // #ifdef _LP64
  1516     MemRegion region(obj_beg, obj_len);
  1517     SharedHeap::fill_region_with_object(region);
  1518     _mark_bitmap.mark_obj(obj_beg, obj_len);
  1519     _summary_data.add_obj(obj_beg, obj_len);
  1520     assert(start_array(id) != NULL, "sanity");
  1521     start_array(id)->allocate_block(obj_beg);
  1525 void
  1526 PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction)
  1528   assert(id < last_space_id, "id out of range");
  1529   assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom(),
  1530          "should have been set in summarize_spaces_quick()");
  1532   const MutableSpace* space = _space_info[id].space();
  1533   if (_space_info[id].new_top() != space->bottom()) {
  1534     HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction);
  1535     _space_info[id].set_dense_prefix(dense_prefix_end);
  1537 #ifndef PRODUCT
  1538     if (TraceParallelOldGCDensePrefix) {
  1539       print_dense_prefix_stats("ratio", id, maximum_compaction,
  1540                                dense_prefix_end);
  1541       HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction);
  1542       print_dense_prefix_stats("density", id, maximum_compaction, addr);
  1544 #endif  // #ifndef PRODUCT
  1546     // If dead space crosses the dense prefix boundary, it is (at least
  1547     // partially) filled with a dummy object, marked live and added to the
  1548     // summary data.  This simplifies the copy/update phase and must be done
  1549     // before the final locations of objects are determined, to prevent leaving
  1550     // a fragment of dead space that is too small to fill with an object.
  1551     if (!maximum_compaction && dense_prefix_end != space->bottom()) {
  1552       fill_dense_prefix_end(id);
  1555     // Compute the destination of each Chunk, and thus each object.
  1556     _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end);
  1557     _summary_data.summarize(dense_prefix_end, space->end(),
  1558                             dense_prefix_end, space->top(),
  1559                             _space_info[id].new_top_addr());
  1562   if (TraceParallelOldGCSummaryPhase) {
  1563     const size_t chunk_size = ParallelCompactData::ChunkSize;
  1564     HeapWord* const dense_prefix_end = _space_info[id].dense_prefix();
  1565     const size_t dp_chunk = _summary_data.addr_to_chunk_idx(dense_prefix_end);
  1566     const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom());
  1567     HeapWord* const new_top = _space_info[id].new_top();
  1568     const HeapWord* nt_aligned_up = _summary_data.chunk_align_up(new_top);
  1569     const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end);
  1570     tty->print_cr("id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " "
  1571                   "dp_chunk=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " "
  1572                   "cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT,
  1573                   id, space->capacity_in_words(), dense_prefix_end,
  1574                   dp_chunk, dp_words / chunk_size,
  1575                   cr_words / chunk_size, new_top);
  1579 void PSParallelCompact::summary_phase(ParCompactionManager* cm,
  1580                                       bool maximum_compaction)
  1582   EventMark m("2 summarize");
  1583   TraceTime tm("summary phase", print_phases(), true, gclog_or_tty);
  1584   // trace("2");
  1586 #ifdef  ASSERT
  1587   if (VerifyParallelOldWithMarkSweep  &&
  1588       (PSParallelCompact::total_invocations() %
  1589          VerifyParallelOldWithMarkSweepInterval) == 0) {
  1590     verify_mark_bitmap(_mark_bitmap);
  1592   if (TraceParallelOldGCMarkingPhase) {
  1593     tty->print_cr("add_obj_count=" SIZE_FORMAT " "
  1594                   "add_obj_bytes=" SIZE_FORMAT,
  1595                   add_obj_count, add_obj_size * HeapWordSize);
  1596     tty->print_cr("mark_bitmap_count=" SIZE_FORMAT " "
  1597                   "mark_bitmap_bytes=" SIZE_FORMAT,
  1598                   mark_bitmap_count, mark_bitmap_size * HeapWordSize);
  1600 #endif  // #ifdef ASSERT
  1602   // Quick summarization of each space into itself, to see how much is live.
  1603   summarize_spaces_quick();
  1605   if (TraceParallelOldGCSummaryPhase) {
  1606     tty->print_cr("summary_phase:  after summarizing each space to self");
  1607     Universe::print();
  1608     NOT_PRODUCT(print_chunk_ranges());
  1609     if (Verbose) {
  1610       NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
  1614   // The amount of live data that will end up in old space (assuming it fits).
  1615   size_t old_space_total_live = 0;
  1616   unsigned int id;
  1617   for (id = old_space_id; id < last_space_id; ++id) {
  1618     old_space_total_live += pointer_delta(_space_info[id].new_top(),
  1619                                           _space_info[id].space()->bottom());
  1622   const MutableSpace* old_space = _space_info[old_space_id].space();
  1623   if (old_space_total_live > old_space->capacity_in_words()) {
  1624     // XXX - should also try to expand
  1625     maximum_compaction = true;
  1626   } else if (!UseParallelOldGCDensePrefix) {
  1627     maximum_compaction = true;
  1630   // Permanent and Old generations.
  1631   summarize_space(perm_space_id, maximum_compaction);
  1632   summarize_space(old_space_id, maximum_compaction);
  1634   // Summarize the remaining spaces (those in the young gen) into old space.  If
  1635   // the live data from a space doesn't fit, the existing summarization is left
  1636   // intact, so the data is compacted down within the space itself.
  1637   HeapWord** new_top_addr = _space_info[old_space_id].new_top_addr();
  1638   HeapWord* const target_space_end = old_space->end();
  1639   for (id = eden_space_id; id < last_space_id; ++id) {
  1640     const MutableSpace* space = _space_info[id].space();
  1641     const size_t live = pointer_delta(_space_info[id].new_top(),
  1642                                       space->bottom());
  1643     const size_t available = pointer_delta(target_space_end, *new_top_addr);
  1644     if (live > 0 && live <= available) {
  1645       // All the live data will fit.
  1646       if (TraceParallelOldGCSummaryPhase) {
  1647         tty->print_cr("summarizing %d into old_space @ " PTR_FORMAT,
  1648                       id, *new_top_addr);
  1650       _summary_data.summarize(*new_top_addr, target_space_end,
  1651                               space->bottom(), space->top(),
  1652                               new_top_addr);
  1654       // Clear the source_chunk field for each chunk in the space.
  1655       HeapWord* const new_top = _space_info[id].new_top();
  1656       HeapWord* const clear_end = _summary_data.chunk_align_up(new_top);
  1657       ChunkData* beg_chunk = _summary_data.addr_to_chunk_ptr(space->bottom());
  1658       ChunkData* end_chunk = _summary_data.addr_to_chunk_ptr(clear_end);
  1659       while (beg_chunk < end_chunk) {
  1660         beg_chunk->set_source_chunk(0);
  1661         ++beg_chunk;
  1664       // Reset the new_top value for the space.
  1665       _space_info[id].set_new_top(space->bottom());
  1669   // Fill in the block data after any changes to the chunks have
  1670   // been made.
  1671 #ifdef  ASSERT
  1672   summarize_blocks(cm, perm_space_id);
  1673   summarize_blocks(cm, old_space_id);
  1674 #else
  1675   if (!UseParallelOldGCChunkPointerCalc) {
  1676     summarize_blocks(cm, perm_space_id);
  1677     summarize_blocks(cm, old_space_id);
  1679 #endif
  1681   if (TraceParallelOldGCSummaryPhase) {
  1682     tty->print_cr("summary_phase:  after final summarization");
  1683     Universe::print();
  1684     NOT_PRODUCT(print_chunk_ranges());
  1685     if (Verbose) {
  1686       NOT_PRODUCT(print_generic_summary_data(_summary_data, _space_info));
  1691 // Fill in the BlockData.
  1692 // Iterate over the spaces and within each space iterate over
  1693 // the chunks and fill in the BlockData for each chunk.
  1695 void PSParallelCompact::summarize_blocks(ParCompactionManager* cm,
  1696                                          SpaceId first_compaction_space_id) {
  1697 #if     0
  1698   DEBUG_ONLY(ParallelCompactData::BlockData::set_cur_phase(1);)
  1699   for (SpaceId cur_space_id = first_compaction_space_id;
  1700        cur_space_id != last_space_id;
  1701        cur_space_id = next_compaction_space_id(cur_space_id)) {
  1702     // Iterate over the chunks in the space
  1703     size_t start_chunk_index =
  1704       _summary_data.addr_to_chunk_idx(space(cur_space_id)->bottom());
  1705     BitBlockUpdateClosure bbu(mark_bitmap(),
  1706                               cm,
  1707                               start_chunk_index);
  1708     // Iterate over blocks.
  1709     for (size_t chunk_index =  start_chunk_index;
  1710          chunk_index < _summary_data.chunk_count() &&
  1711          _summary_data.chunk_to_addr(chunk_index) < space(cur_space_id)->top();
  1712          chunk_index++) {
  1714       // Reset the closure for the new chunk.  Note that the closure
  1715       // maintains some data that does not get reset for each chunk
  1716       // so a new instance of the closure is no appropriate.
  1717       bbu.reset_chunk(chunk_index);
  1719       // Start the iteration with the first live object.  This
  1720       // may return the end of the chunk.  That is acceptable since
  1721       // it will properly limit the iterations.
  1722       ParMarkBitMap::idx_t left_offset = mark_bitmap()->addr_to_bit(
  1723         _summary_data.first_live_or_end_in_chunk(chunk_index));
  1725       // End the iteration at the end of the chunk.
  1726       HeapWord* chunk_addr = _summary_data.chunk_to_addr(chunk_index);
  1727       HeapWord* chunk_end = chunk_addr + ParallelCompactData::ChunkSize;
  1728       ParMarkBitMap::idx_t right_offset =
  1729         mark_bitmap()->addr_to_bit(chunk_end);
  1731       // Blocks that have not objects starting in them can be
  1732       // skipped because their data will never be used.
  1733       if (left_offset < right_offset) {
  1735         // Iterate through the objects in the chunk.
  1736         ParMarkBitMap::idx_t last_offset =
  1737           mark_bitmap()->pair_iterate(&bbu, left_offset, right_offset);
  1739         // If last_offset is less than right_offset, then the iterations
  1740         // terminated while it was looking for an end bit.  "last_offset"
  1741         // is then the offset for the last start bit.  In this situation
  1742         // the "offset" field for the next block to the right (_cur_block + 1)
  1743         // will not have been update although there may be live data
  1744         // to the left of the chunk.
  1746         size_t cur_block_plus_1 = bbu.cur_block() + 1;
  1747         HeapWord* cur_block_plus_1_addr =
  1748         _summary_data.block_to_addr(bbu.cur_block()) +
  1749         ParallelCompactData::BlockSize;
  1750         HeapWord* last_offset_addr = mark_bitmap()->bit_to_addr(last_offset);
  1751  #if 1  // This code works.  The else doesn't but should.  Why does it?
  1752         // The current block (cur_block()) has already been updated.
  1753         // The last block that may need to be updated is either the
  1754         // next block (current block + 1) or the block where the
  1755         // last object starts (which can be greater than the
  1756         // next block if there were no objects found in intervening
  1757         // blocks).
  1758         size_t last_block =
  1759           MAX2(bbu.cur_block() + 1,
  1760                _summary_data.addr_to_block_idx(last_offset_addr));
  1761  #else
  1762         // The current block has already been updated.  The only block
  1763         // that remains to be updated is the block where the last
  1764         // object in the chunk starts.
  1765         size_t last_block = _summary_data.addr_to_block_idx(last_offset_addr);
  1766  #endif
  1767         assert_bit_is_start(last_offset);
  1768         assert((last_block == _summary_data.block_count()) ||
  1769              (_summary_data.block(last_block)->raw_offset() == 0),
  1770           "Should not have been set");
  1771         // Is the last block still in the current chunk?  If still
  1772         // in this chunk, update the last block (the counting that
  1773         // included the current block is meant for the offset of the last
  1774         // block).  If not in this chunk, do nothing.  Should not
  1775         // update a block in the next chunk.
  1776         if (ParallelCompactData::chunk_contains_block(bbu.chunk_index(),
  1777                                                       last_block)) {
  1778           if (last_offset < right_offset) {
  1779             // The last object started in this chunk but ends beyond
  1780             // this chunk.  Update the block for this last object.
  1781             assert(mark_bitmap()->is_marked(last_offset), "Should be marked");
  1782             // No end bit was found.  The closure takes care of
  1783             // the cases where
  1784             //   an objects crosses over into the next block
  1785             //   an objects starts and ends in the next block
  1786             // It does not handle the case where an object is
  1787             // the first object in a later block and extends
  1788             // past the end of the chunk (i.e., the closure
  1789             // only handles complete objects that are in the range
  1790             // it is given).  That object is handed back here
  1791             // for any special consideration necessary.
  1792             //
  1793             // Is the first bit in the last block a start or end bit?
  1794             //
  1795             // If the partial object ends in the last block L,
  1796             // then the 1st bit in L may be an end bit.
  1797             //
  1798             // Else does the last object start in a block after the current
  1799             // block? A block AA will already have been updated if an
  1800             // object ends in the next block AA+1.  An object found to end in
  1801             // the AA+1 is the trigger that updates AA.  Objects are being
  1802             // counted in the current block for updaing a following
  1803             // block.  An object may start in later block
  1804             // block but may extend beyond the last block in the chunk.
  1805             // Updates are only done when the end of an object has been
  1806             // found. If the last object (covered by block L) starts
  1807             // beyond the current block, then no object ends in L (otherwise
  1808             // L would be the current block).  So the first bit in L is
  1809             // a start bit.
  1810             //
  1811             // Else the last objects start in the current block and ends
  1812             // beyond the chunk.  The current block has already been
  1813             // updated and there is no later block (with an object
  1814             // starting in it) that needs to be updated.
  1815             //
  1816             if (_summary_data.partial_obj_ends_in_block(last_block)) {
  1817               _summary_data.block(last_block)->set_end_bit_offset(
  1818                 bbu.live_data_left());
  1819             } else if (last_offset_addr >= cur_block_plus_1_addr) {
  1820               //   The start of the object is on a later block
  1821               // (to the right of the current block and there are no
  1822               // complete live objects to the left of this last object
  1823               // within the chunk.
  1824               //   The first bit in the block is for the start of the
  1825               // last object.
  1826               _summary_data.block(last_block)->set_start_bit_offset(
  1827                 bbu.live_data_left());
  1828             } else {
  1829               //   The start of the last object was found in
  1830               // the current chunk (which has already
  1831               // been updated).
  1832               assert(bbu.cur_block() ==
  1833                       _summary_data.addr_to_block_idx(last_offset_addr),
  1834                 "Should be a block already processed");
  1836 #ifdef ASSERT
  1837             // Is there enough block information to find this object?
  1838             // The destination of the chunk has not been set so the
  1839             // values returned by calc_new_pointer() and
  1840             // block_calc_new_pointer() will only be
  1841             // offsets.  But they should agree.
  1842             HeapWord* moved_obj_with_chunks =
  1843               _summary_data.chunk_calc_new_pointer(last_offset_addr);
  1844             HeapWord* moved_obj_with_blocks =
  1845               _summary_data.calc_new_pointer(last_offset_addr);
  1846             assert(moved_obj_with_chunks == moved_obj_with_blocks,
  1847               "Block calculation is wrong");
  1848 #endif
  1849           } else if (last_block < _summary_data.block_count()) {
  1850             // Iterations ended looking for a start bit (but
  1851             // did not run off the end of the block table).
  1852             _summary_data.block(last_block)->set_start_bit_offset(
  1853               bbu.live_data_left());
  1856 #ifdef ASSERT
  1857         // Is there enough block information to find this object?
  1858           HeapWord* left_offset_addr = mark_bitmap()->bit_to_addr(left_offset);
  1859         HeapWord* moved_obj_with_chunks =
  1860           _summary_data.calc_new_pointer(left_offset_addr);
  1861         HeapWord* moved_obj_with_blocks =
  1862           _summary_data.calc_new_pointer(left_offset_addr);
  1863           assert(moved_obj_with_chunks == moved_obj_with_blocks,
  1864           "Block calculation is wrong");
  1865 #endif
  1867         // Is there another block after the end of this chunk?
  1868 #ifdef ASSERT
  1869         if (last_block < _summary_data.block_count()) {
  1870         // No object may have been found in a block.  If that
  1871         // block is at the end of the chunk, the iteration will
  1872         // terminate without incrementing the current block so
  1873         // that the current block is not the last block in the
  1874         // chunk.  That situation precludes asserting that the
  1875         // current block is the last block in the chunk.  Assert
  1876         // the lesser condition that the current block does not
  1877         // exceed the chunk.
  1878           assert(_summary_data.block_to_addr(last_block) <=
  1879                (_summary_data.chunk_to_addr(chunk_index) +
  1880                  ParallelCompactData::ChunkSize),
  1881               "Chunk and block inconsistency");
  1882           assert(last_offset <= right_offset, "Iteration over ran end");
  1884 #endif
  1886 #ifdef ASSERT
  1887       if (PrintGCDetails && Verbose) {
  1888         if (_summary_data.chunk(chunk_index)->partial_obj_size() == 1) {
  1889           size_t first_block =
  1890             chunk_index / ParallelCompactData::BlocksPerChunk;
  1891           gclog_or_tty->print_cr("first_block " PTR_FORMAT
  1892             " _offset " PTR_FORMAT
  1893             "_first_is_start_bit %d",
  1894             first_block,
  1895             _summary_data.block(first_block)->raw_offset(),
  1896             _summary_data.block(first_block)->first_is_start_bit());
  1899 #endif
  1902   DEBUG_ONLY(ParallelCompactData::BlockData::set_cur_phase(16);)
  1903 #endif  // #if 0
  1906 // This method should contain all heap-specific policy for invoking a full
  1907 // collection.  invoke_no_policy() will only attempt to compact the heap; it
  1908 // will do nothing further.  If we need to bail out for policy reasons, scavenge
  1909 // before full gc, or any other specialized behavior, it needs to be added here.
  1910 //
  1911 // Note that this method should only be called from the vm_thread while at a
  1912 // safepoint.
  1913 void PSParallelCompact::invoke(bool maximum_heap_compaction) {
  1914   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
  1915   assert(Thread::current() == (Thread*)VMThread::vm_thread(),
  1916          "should be in vm thread");
  1917   ParallelScavengeHeap* heap = gc_heap();
  1918   GCCause::Cause gc_cause = heap->gc_cause();
  1919   assert(!heap->is_gc_active(), "not reentrant");
  1921   PSAdaptiveSizePolicy* policy = heap->size_policy();
  1923   // Before each allocation/collection attempt, find out from the
  1924   // policy object if GCs are, on the whole, taking too long. If so,
  1925   // bail out without attempting a collection.  The exceptions are
  1926   // for explicitly requested GC's.
  1927   if (!policy->gc_time_limit_exceeded() ||
  1928       GCCause::is_user_requested_gc(gc_cause) ||
  1929       GCCause::is_serviceability_requested_gc(gc_cause)) {
  1930     IsGCActiveMark mark;
  1932     if (ScavengeBeforeFullGC) {
  1933       PSScavenge::invoke_no_policy();
  1936     PSParallelCompact::invoke_no_policy(maximum_heap_compaction);
  1940 bool ParallelCompactData::chunk_contains(size_t chunk_index, HeapWord* addr) {
  1941   size_t addr_chunk_index = addr_to_chunk_idx(addr);
  1942   return chunk_index == addr_chunk_index;
  1945 bool ParallelCompactData::chunk_contains_block(size_t chunk_index,
  1946                                                size_t block_index) {
  1947   size_t first_block_in_chunk = chunk_index * BlocksPerChunk;
  1948   size_t last_block_in_chunk = (chunk_index + 1) * BlocksPerChunk - 1;
  1950   return (first_block_in_chunk <= block_index) &&
  1951          (block_index <= last_block_in_chunk);
  1954 // This method contains no policy. You should probably
  1955 // be calling invoke() instead.
  1956 void PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
  1957   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
  1958   assert(ref_processor() != NULL, "Sanity");
  1960   if (GC_locker::check_active_before_gc()) {
  1961     return;
  1964   TimeStamp marking_start;
  1965   TimeStamp compaction_start;
  1966   TimeStamp collection_exit;
  1968   ParallelScavengeHeap* heap = gc_heap();
  1969   GCCause::Cause gc_cause = heap->gc_cause();
  1970   PSYoungGen* young_gen = heap->young_gen();
  1971   PSOldGen* old_gen = heap->old_gen();
  1972   PSPermGen* perm_gen = heap->perm_gen();
  1973   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
  1975   if (ZapUnusedHeapArea) {
  1976     // Save information needed to minimize mangling
  1977     heap->record_gen_tops_before_GC();
  1980   _print_phases = PrintGCDetails && PrintParallelOldGCPhaseTimes;
  1982   // Make sure data structures are sane, make the heap parsable, and do other
  1983   // miscellaneous bookkeeping.
  1984   PreGCValues pre_gc_values;
  1985   pre_compact(&pre_gc_values);
  1987   // Get the compaction manager reserved for the VM thread.
  1988   ParCompactionManager* const vmthread_cm =
  1989     ParCompactionManager::manager_array(gc_task_manager()->workers());
  1991   // Place after pre_compact() where the number of invocations is incremented.
  1992   AdaptiveSizePolicyOutput(size_policy, heap->total_collections());
  1995     ResourceMark rm;
  1996     HandleMark hm;
  1998     const bool is_system_gc = gc_cause == GCCause::_java_lang_system_gc;
  2000     // This is useful for debugging but don't change the output the
  2001     // the customer sees.
  2002     const char* gc_cause_str = "Full GC";
  2003     if (is_system_gc && PrintGCDetails) {
  2004       gc_cause_str = "Full GC (System)";
  2006     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
  2007     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  2008     TraceTime t1(gc_cause_str, PrintGC, !PrintGCDetails, gclog_or_tty);
  2009     TraceCollectorStats tcs(counters());
  2010     TraceMemoryManagerStats tms(true /* Full GC */);
  2012     if (TraceGen1Time) accumulated_time()->start();
  2014     // Let the size policy know we're starting
  2015     size_policy->major_collection_begin();
  2017     // When collecting the permanent generation methodOops may be moving,
  2018     // so we either have to flush all bcp data or convert it into bci.
  2019     CodeCache::gc_prologue();
  2020     Threads::gc_prologue();
  2022     NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
  2023     COMPILER2_PRESENT(DerivedPointerTable::clear());
  2025     ref_processor()->enable_discovery();
  2027     bool marked_for_unloading = false;
  2029     marking_start.update();
  2030     marking_phase(vmthread_cm, maximum_heap_compaction);
  2032 #ifndef PRODUCT
  2033     if (TraceParallelOldGCMarkingPhase) {
  2034       gclog_or_tty->print_cr("marking_phase: cas_tries %d  cas_retries %d "
  2035         "cas_by_another %d",
  2036         mark_bitmap()->cas_tries(), mark_bitmap()->cas_retries(),
  2037         mark_bitmap()->cas_by_another());
  2039 #endif  // #ifndef PRODUCT
  2041 #ifdef ASSERT
  2042     if (VerifyParallelOldWithMarkSweep &&
  2043         (PSParallelCompact::total_invocations() %
  2044            VerifyParallelOldWithMarkSweepInterval) == 0) {
  2045       gclog_or_tty->print_cr("Verify marking with mark_sweep_phase1()");
  2046       if (PrintGCDetails && Verbose) {
  2047         gclog_or_tty->print_cr("mark_sweep_phase1:");
  2049       // Clear the discovered lists so that discovered objects
  2050       // don't look like they have been discovered twice.
  2051       ref_processor()->clear_discovered_references();
  2053       PSMarkSweep::allocate_stacks();
  2054       MemRegion mr = Universe::heap()->reserved_region();
  2055       PSMarkSweep::ref_processor()->enable_discovery();
  2056       PSMarkSweep::mark_sweep_phase1(maximum_heap_compaction);
  2058 #endif
  2060     bool max_on_system_gc = UseMaximumCompactionOnSystemGC && is_system_gc;
  2061     summary_phase(vmthread_cm, maximum_heap_compaction || max_on_system_gc);
  2063 #ifdef ASSERT
  2064     if (VerifyParallelOldWithMarkSweep &&
  2065         (PSParallelCompact::total_invocations() %
  2066            VerifyParallelOldWithMarkSweepInterval) == 0) {
  2067       if (PrintGCDetails && Verbose) {
  2068         gclog_or_tty->print_cr("mark_sweep_phase2:");
  2070       PSMarkSweep::mark_sweep_phase2();
  2072 #endif
  2074     COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity"));
  2075     COMPILER2_PRESENT(DerivedPointerTable::set_active(false));
  2077     // adjust_roots() updates Universe::_intArrayKlassObj which is
  2078     // needed by the compaction for filling holes in the dense prefix.
  2079     adjust_roots();
  2081 #ifdef ASSERT
  2082     if (VerifyParallelOldWithMarkSweep &&
  2083         (PSParallelCompact::total_invocations() %
  2084            VerifyParallelOldWithMarkSweepInterval) == 0) {
  2085       // Do a separate verify phase so that the verify
  2086       // code can use the the forwarding pointers to
  2087       // check the new pointer calculation.  The restore_marks()
  2088       // has to be done before the real compact.
  2089       vmthread_cm->set_action(ParCompactionManager::VerifyUpdate);
  2090       compact_perm(vmthread_cm);
  2091       compact_serial(vmthread_cm);
  2092       vmthread_cm->set_action(ParCompactionManager::ResetObjects);
  2093       compact_perm(vmthread_cm);
  2094       compact_serial(vmthread_cm);
  2095       vmthread_cm->set_action(ParCompactionManager::UpdateAndCopy);
  2097       // For debugging only
  2098       PSMarkSweep::restore_marks();
  2099       PSMarkSweep::deallocate_stacks();
  2101 #endif
  2103     compaction_start.update();
  2104     // Does the perm gen always have to be done serially because
  2105     // klasses are used in the update of an object?
  2106     compact_perm(vmthread_cm);
  2108     if (UseParallelOldGCCompacting) {
  2109       compact();
  2110     } else {
  2111       compact_serial(vmthread_cm);
  2114     // Reset the mark bitmap, summary data, and do other bookkeeping.  Must be
  2115     // done before resizing.
  2116     post_compact();
  2118     // Let the size policy know we're done
  2119     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
  2121     if (UseAdaptiveSizePolicy) {
  2122       if (PrintAdaptiveSizePolicy) {
  2123         gclog_or_tty->print("AdaptiveSizeStart: ");
  2124         gclog_or_tty->stamp();
  2125         gclog_or_tty->print_cr(" collection: %d ",
  2126                        heap->total_collections());
  2127         if (Verbose) {
  2128           gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d"
  2129             " perm_gen_capacity: %d ",
  2130             old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes(),
  2131             perm_gen->capacity_in_bytes());
  2135       // Don't check if the size_policy is ready here.  Let
  2136       // the size_policy check that internally.
  2137       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
  2138           ((gc_cause != GCCause::_java_lang_system_gc) ||
  2139             UseAdaptiveSizePolicyWithSystemGC)) {
  2140         // Calculate optimal free space amounts
  2141         assert(young_gen->max_size() >
  2142           young_gen->from_space()->capacity_in_bytes() +
  2143           young_gen->to_space()->capacity_in_bytes(),
  2144           "Sizes of space in young gen are out-of-bounds");
  2145         size_t max_eden_size = young_gen->max_size() -
  2146           young_gen->from_space()->capacity_in_bytes() -
  2147           young_gen->to_space()->capacity_in_bytes();
  2148         size_policy->compute_generation_free_space(
  2149                               young_gen->used_in_bytes(),
  2150                               young_gen->eden_space()->used_in_bytes(),
  2151                               old_gen->used_in_bytes(),
  2152                               perm_gen->used_in_bytes(),
  2153                               young_gen->eden_space()->capacity_in_bytes(),
  2154                               old_gen->max_gen_size(),
  2155                               max_eden_size,
  2156                               true /* full gc*/,
  2157                               gc_cause);
  2159         heap->resize_old_gen(
  2160           size_policy->calculated_old_free_size_in_bytes());
  2162         // Don't resize the young generation at an major collection.  A
  2163         // desired young generation size may have been calculated but
  2164         // resizing the young generation complicates the code because the
  2165         // resizing of the old generation may have moved the boundary
  2166         // between the young generation and the old generation.  Let the
  2167         // young generation resizing happen at the minor collections.
  2169       if (PrintAdaptiveSizePolicy) {
  2170         gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",
  2171                        heap->total_collections());
  2175     if (UsePerfData) {
  2176       PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();
  2177       counters->update_counters();
  2178       counters->update_old_capacity(old_gen->capacity_in_bytes());
  2179       counters->update_young_capacity(young_gen->capacity_in_bytes());
  2182     heap->resize_all_tlabs();
  2184     // We collected the perm gen, so we'll resize it here.
  2185     perm_gen->compute_new_size(pre_gc_values.perm_gen_used());
  2187     if (TraceGen1Time) accumulated_time()->stop();
  2189     if (PrintGC) {
  2190       if (PrintGCDetails) {
  2191         // No GC timestamp here.  This is after GC so it would be confusing.
  2192         young_gen->print_used_change(pre_gc_values.young_gen_used());
  2193         old_gen->print_used_change(pre_gc_values.old_gen_used());
  2194         heap->print_heap_change(pre_gc_values.heap_used());
  2195         // Print perm gen last (print_heap_change() excludes the perm gen).
  2196         perm_gen->print_used_change(pre_gc_values.perm_gen_used());
  2197       } else {
  2198         heap->print_heap_change(pre_gc_values.heap_used());
  2202     // Track memory usage and detect low memory
  2203     MemoryService::track_memory_usage();
  2204     heap->update_counters();
  2206     if (PrintGCDetails) {
  2207       if (size_policy->print_gc_time_limit_would_be_exceeded()) {
  2208         if (size_policy->gc_time_limit_exceeded()) {
  2209           gclog_or_tty->print_cr("      GC time is exceeding GCTimeLimit "
  2210             "of %d%%", GCTimeLimit);
  2211         } else {
  2212           gclog_or_tty->print_cr("      GC time would exceed GCTimeLimit "
  2213             "of %d%%", GCTimeLimit);
  2216       size_policy->set_print_gc_time_limit_would_be_exceeded(false);
  2220   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
  2221     HandleMark hm;  // Discard invalid handles created during verification
  2222     gclog_or_tty->print(" VerifyAfterGC:");
  2223     Universe::verify(false);
  2226   // Re-verify object start arrays
  2227   if (VerifyObjectStartArray &&
  2228       VerifyAfterGC) {
  2229     old_gen->verify_object_start_array();
  2230     perm_gen->verify_object_start_array();
  2233   if (ZapUnusedHeapArea) {
  2234     old_gen->object_space()->check_mangled_unused_area_complete();
  2235     perm_gen->object_space()->check_mangled_unused_area_complete();
  2238   NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
  2240   collection_exit.update();
  2242   if (PrintHeapAtGC) {
  2243     Universe::print_heap_after_gc();
  2245   if (PrintGCTaskTimeStamps) {
  2246     gclog_or_tty->print_cr("VM-Thread " INT64_FORMAT " " INT64_FORMAT " "
  2247                            INT64_FORMAT,
  2248                            marking_start.ticks(), compaction_start.ticks(),
  2249                            collection_exit.ticks());
  2250     gc_task_manager()->print_task_time_stamps();
  2254 bool PSParallelCompact::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,
  2255                                              PSYoungGen* young_gen,
  2256                                              PSOldGen* old_gen) {
  2257   MutableSpace* const eden_space = young_gen->eden_space();
  2258   assert(!eden_space->is_empty(), "eden must be non-empty");
  2259   assert(young_gen->virtual_space()->alignment() ==
  2260          old_gen->virtual_space()->alignment(), "alignments do not match");
  2262   if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary)) {
  2263     return false;
  2266   // Both generations must be completely committed.
  2267   if (young_gen->virtual_space()->uncommitted_size() != 0) {
  2268     return false;
  2270   if (old_gen->virtual_space()->uncommitted_size() != 0) {
  2271     return false;
  2274   // Figure out how much to take from eden.  Include the average amount promoted
  2275   // in the total; otherwise the next young gen GC will simply bail out to a
  2276   // full GC.
  2277   const size_t alignment = old_gen->virtual_space()->alignment();
  2278   const size_t eden_used = eden_space->used_in_bytes();
  2279   const size_t promoted = (size_t)size_policy->avg_promoted()->padded_average();
  2280   const size_t absorb_size = align_size_up(eden_used + promoted, alignment);
  2281   const size_t eden_capacity = eden_space->capacity_in_bytes();
  2283   if (absorb_size >= eden_capacity) {
  2284     return false; // Must leave some space in eden.
  2287   const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;
  2288   if (new_young_size < young_gen->min_gen_size()) {
  2289     return false; // Respect young gen minimum size.
  2292   if (TraceAdaptiveGCBoundary && Verbose) {
  2293     gclog_or_tty->print(" absorbing " SIZE_FORMAT "K:  "
  2294                         "eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "
  2295                         "from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "
  2296                         "young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",
  2297                         absorb_size / K,
  2298                         eden_capacity / K, (eden_capacity - absorb_size) / K,
  2299                         young_gen->from_space()->used_in_bytes() / K,
  2300                         young_gen->to_space()->used_in_bytes() / K,
  2301                         young_gen->capacity_in_bytes() / K, new_young_size / K);
  2304   // Fill the unused part of the old gen.
  2305   MutableSpace* const old_space = old_gen->object_space();
  2306   MemRegion old_gen_unused(old_space->top(), old_space->end());
  2307   if (!old_gen_unused.is_empty()) {
  2308     SharedHeap::fill_region_with_object(old_gen_unused);
  2311   // Take the live data from eden and set both top and end in the old gen to
  2312   // eden top.  (Need to set end because reset_after_change() mangles the region
  2313   // from end to virtual_space->high() in debug builds).
  2314   HeapWord* const new_top = eden_space->top();
  2315   old_gen->virtual_space()->expand_into(young_gen->virtual_space(),
  2316                                         absorb_size);
  2317   young_gen->reset_after_change();
  2318   old_space->set_top(new_top);
  2319   old_space->set_end(new_top);
  2320   old_gen->reset_after_change();
  2322   // Update the object start array for the filler object and the data from eden.
  2323   ObjectStartArray* const start_array = old_gen->start_array();
  2324   HeapWord* const start = old_gen_unused.start();
  2325   for (HeapWord* addr = start; addr < new_top; addr += oop(addr)->size()) {
  2326     start_array->allocate_block(addr);
  2329   // Could update the promoted average here, but it is not typically updated at
  2330   // full GCs and the value to use is unclear.  Something like
  2331   //
  2332   // cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.
  2334   size_policy->set_bytes_absorbed_from_eden(absorb_size);
  2335   return true;
  2338 GCTaskManager* const PSParallelCompact::gc_task_manager() {
  2339   assert(ParallelScavengeHeap::gc_task_manager() != NULL,
  2340     "shouldn't return NULL");
  2341   return ParallelScavengeHeap::gc_task_manager();
  2344 void PSParallelCompact::marking_phase(ParCompactionManager* cm,
  2345                                       bool maximum_heap_compaction) {
  2346   // Recursively traverse all live objects and mark them
  2347   EventMark m("1 mark object");
  2348   TraceTime tm("marking phase", print_phases(), true, gclog_or_tty);
  2350   ParallelScavengeHeap* heap = gc_heap();
  2351   uint parallel_gc_threads = heap->gc_task_manager()->workers();
  2352   TaskQueueSetSuper* qset = ParCompactionManager::chunk_array();
  2353   ParallelTaskTerminator terminator(parallel_gc_threads, qset);
  2355   PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
  2356   PSParallelCompact::FollowStackClosure follow_stack_closure(cm);
  2359     TraceTime tm_m("par mark", print_phases(), true, gclog_or_tty);
  2361     GCTaskQueue* q = GCTaskQueue::create();
  2363     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::universe));
  2364     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jni_handles));
  2365     // We scan the thread roots in parallel
  2366     Threads::create_thread_roots_marking_tasks(q);
  2367     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::object_synchronizer));
  2368     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::flat_profiler));
  2369     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::management));
  2370     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::system_dictionary));
  2371     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::jvmti));
  2372     q->enqueue(new MarkFromRootsTask(MarkFromRootsTask::vm_symbols));
  2374     if (parallel_gc_threads > 1) {
  2375       for (uint j = 0; j < parallel_gc_threads; j++) {
  2376         q->enqueue(new StealMarkingTask(&terminator));
  2380     WaitForBarrierGCTask* fin = WaitForBarrierGCTask::create();
  2381     q->enqueue(fin);
  2383     gc_task_manager()->add_list(q);
  2385     fin->wait_for();
  2387     // We have to release the barrier tasks!
  2388     WaitForBarrierGCTask::destroy(fin);
  2391   // Process reference objects found during marking
  2393     TraceTime tm_r("reference processing", print_phases(), true, gclog_or_tty);
  2394     ReferencePolicy *soft_ref_policy;
  2395     if (maximum_heap_compaction) {
  2396       soft_ref_policy = new AlwaysClearPolicy();
  2397     } else {
  2398 #ifdef COMPILER2
  2399       soft_ref_policy = new LRUMaxHeapPolicy();
  2400 #else
  2401       soft_ref_policy = new LRUCurrentHeapPolicy();
  2402 #endif // COMPILER2
  2404     assert(soft_ref_policy != NULL, "No soft reference policy");
  2405     if (ref_processor()->processing_is_mt()) {
  2406       RefProcTaskExecutor task_executor;
  2407       ref_processor()->process_discovered_references(
  2408         soft_ref_policy, is_alive_closure(), &mark_and_push_closure,
  2409         &follow_stack_closure, &task_executor);
  2410     } else {
  2411       ref_processor()->process_discovered_references(
  2412         soft_ref_policy, is_alive_closure(), &mark_and_push_closure,
  2413         &follow_stack_closure, NULL);
  2417   TraceTime tm_c("class unloading", print_phases(), true, gclog_or_tty);
  2418   // Follow system dictionary roots and unload classes.
  2419   bool purged_class = SystemDictionary::do_unloading(is_alive_closure());
  2421   // Follow code cache roots.
  2422   CodeCache::do_unloading(is_alive_closure(), &mark_and_push_closure,
  2423                           purged_class);
  2424   follow_stack(cm); // Flush marking stack.
  2426   // Update subklass/sibling/implementor links of live klasses
  2427   // revisit_klass_stack is used in follow_weak_klass_links().
  2428   follow_weak_klass_links(cm);
  2430   // Visit symbol and interned string tables and delete unmarked oops
  2431   SymbolTable::unlink(is_alive_closure());
  2432   StringTable::unlink(is_alive_closure());
  2434   assert(cm->marking_stack()->size() == 0, "stack should be empty by now");
  2435   assert(cm->overflow_stack()->is_empty(), "stack should be empty by now");
  2438 // This should be moved to the shared markSweep code!
  2439 class PSAlwaysTrueClosure: public BoolObjectClosure {
  2440 public:
  2441   void do_object(oop p) { ShouldNotReachHere(); }
  2442   bool do_object_b(oop p) { return true; }
  2443 };
  2444 static PSAlwaysTrueClosure always_true;
  2446 void PSParallelCompact::adjust_roots() {
  2447   // Adjust the pointers to reflect the new locations
  2448   EventMark m("3 adjust roots");
  2449   TraceTime tm("adjust roots", print_phases(), true, gclog_or_tty);
  2451   // General strong roots.
  2452   Universe::oops_do(adjust_root_pointer_closure());
  2453   ReferenceProcessor::oops_do(adjust_root_pointer_closure());
  2454   JNIHandles::oops_do(adjust_root_pointer_closure());   // Global (strong) JNI handles
  2455   Threads::oops_do(adjust_root_pointer_closure());
  2456   ObjectSynchronizer::oops_do(adjust_root_pointer_closure());
  2457   FlatProfiler::oops_do(adjust_root_pointer_closure());
  2458   Management::oops_do(adjust_root_pointer_closure());
  2459   JvmtiExport::oops_do(adjust_root_pointer_closure());
  2460   // SO_AllClasses
  2461   SystemDictionary::oops_do(adjust_root_pointer_closure());
  2462   vmSymbols::oops_do(adjust_root_pointer_closure());
  2464   // Now adjust pointers in remaining weak roots.  (All of which should
  2465   // have been cleared if they pointed to non-surviving objects.)
  2466   // Global (weak) JNI handles
  2467   JNIHandles::weak_oops_do(&always_true, adjust_root_pointer_closure());
  2469   CodeCache::oops_do(adjust_pointer_closure());
  2470   SymbolTable::oops_do(adjust_root_pointer_closure());
  2471   StringTable::oops_do(adjust_root_pointer_closure());
  2472   ref_processor()->weak_oops_do(adjust_root_pointer_closure());
  2473   // Roots were visited so references into the young gen in roots
  2474   // may have been scanned.  Process them also.
  2475   // Should the reference processor have a span that excludes
  2476   // young gen objects?
  2477   PSScavenge::reference_processor()->weak_oops_do(
  2478                                               adjust_root_pointer_closure());
  2481 void PSParallelCompact::compact_perm(ParCompactionManager* cm) {
  2482   EventMark m("4 compact perm");
  2483   TraceTime tm("compact perm gen", print_phases(), true, gclog_or_tty);
  2484   // trace("4");
  2486   gc_heap()->perm_gen()->start_array()->reset();
  2487   move_and_update(cm, perm_space_id);
  2490 void PSParallelCompact::enqueue_chunk_draining_tasks(GCTaskQueue* q,
  2491                                                      uint parallel_gc_threads) {
  2492   TraceTime tm("drain task setup", print_phases(), true, gclog_or_tty);
  2494   const unsigned int task_count = MAX2(parallel_gc_threads, 1U);
  2495   for (unsigned int j = 0; j < task_count; j++) {
  2496     q->enqueue(new DrainStacksCompactionTask());
  2499   // Find all chunks that are available (can be filled immediately) and
  2500   // distribute them to the thread stacks.  The iteration is done in reverse
  2501   // order (high to low) so the chunks will be removed in ascending order.
  2503   const ParallelCompactData& sd = PSParallelCompact::summary_data();
  2505   size_t fillable_chunks = 0;   // A count for diagnostic purposes.
  2506   unsigned int which = 0;       // The worker thread number.
  2508   for (unsigned int id = to_space_id; id > perm_space_id; --id) {
  2509     SpaceInfo* const space_info = _space_info + id;
  2510     MutableSpace* const space = space_info->space();
  2511     HeapWord* const new_top = space_info->new_top();
  2513     const size_t beg_chunk = sd.addr_to_chunk_idx(space_info->dense_prefix());
  2514     const size_t end_chunk = sd.addr_to_chunk_idx(sd.chunk_align_up(new_top));
  2515     assert(end_chunk > 0, "perm gen cannot be empty");
  2517     for (size_t cur = end_chunk - 1; cur >= beg_chunk; --cur) {
  2518       if (sd.chunk(cur)->claim_unsafe()) {
  2519         ParCompactionManager* cm = ParCompactionManager::manager_array(which);
  2520         cm->save_for_processing(cur);
  2522         if (TraceParallelOldGCCompactionPhase && Verbose) {
  2523           const size_t count_mod_8 = fillable_chunks & 7;
  2524           if (count_mod_8 == 0) gclog_or_tty->print("fillable: ");
  2525           gclog_or_tty->print(" " SIZE_FORMAT_W(7), cur);
  2526           if (count_mod_8 == 7) gclog_or_tty->cr();
  2529         NOT_PRODUCT(++fillable_chunks;)
  2531         // Assign chunks to threads in round-robin fashion.
  2532         if (++which == task_count) {
  2533           which = 0;
  2539   if (TraceParallelOldGCCompactionPhase) {
  2540     if (Verbose && (fillable_chunks & 7) != 0) gclog_or_tty->cr();
  2541     gclog_or_tty->print_cr("%u initially fillable chunks", fillable_chunks);
  2545 #define PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING 4
  2547 void PSParallelCompact::enqueue_dense_prefix_tasks(GCTaskQueue* q,
  2548                                                     uint parallel_gc_threads) {
  2549   TraceTime tm("dense prefix task setup", print_phases(), true, gclog_or_tty);
  2551   ParallelCompactData& sd = PSParallelCompact::summary_data();
  2553   // Iterate over all the spaces adding tasks for updating
  2554   // chunks in the dense prefix.  Assume that 1 gc thread
  2555   // will work on opening the gaps and the remaining gc threads
  2556   // will work on the dense prefix.
  2557   SpaceId space_id = old_space_id;
  2558   while (space_id != last_space_id) {
  2559     HeapWord* const dense_prefix_end = _space_info[space_id].dense_prefix();
  2560     const MutableSpace* const space = _space_info[space_id].space();
  2562     if (dense_prefix_end == space->bottom()) {
  2563       // There is no dense prefix for this space.
  2564       space_id = next_compaction_space_id(space_id);
  2565       continue;
  2568     // The dense prefix is before this chunk.
  2569     size_t chunk_index_end_dense_prefix =
  2570         sd.addr_to_chunk_idx(dense_prefix_end);
  2571     ChunkData* const dense_prefix_cp = sd.chunk(chunk_index_end_dense_prefix);
  2572     assert(dense_prefix_end == space->end() ||
  2573            dense_prefix_cp->available() ||
  2574            dense_prefix_cp->claimed(),
  2575            "The chunk after the dense prefix should always be ready to fill");
  2577     size_t chunk_index_start = sd.addr_to_chunk_idx(space->bottom());
  2579     // Is there dense prefix work?
  2580     size_t total_dense_prefix_chunks =
  2581       chunk_index_end_dense_prefix - chunk_index_start;
  2582     // How many chunks of the dense prefix should be given to
  2583     // each thread?
  2584     if (total_dense_prefix_chunks > 0) {
  2585       uint tasks_for_dense_prefix = 1;
  2586       if (UseParallelDensePrefixUpdate) {
  2587         if (total_dense_prefix_chunks <=
  2588             (parallel_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)) {
  2589           // Don't over partition.  This assumes that
  2590           // PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING is a small integer value
  2591           // so there are not many chunks to process.
  2592           tasks_for_dense_prefix = parallel_gc_threads;
  2593         } else {
  2594           // Over partition
  2595           tasks_for_dense_prefix = parallel_gc_threads *
  2596             PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING;
  2599       size_t chunks_per_thread = total_dense_prefix_chunks /
  2600         tasks_for_dense_prefix;
  2601       // Give each thread at least 1 chunk.
  2602       if (chunks_per_thread == 0) {
  2603         chunks_per_thread = 1;
  2606       for (uint k = 0; k < tasks_for_dense_prefix; k++) {
  2607         if (chunk_index_start >= chunk_index_end_dense_prefix) {
  2608           break;
  2610         // chunk_index_end is not processed
  2611         size_t chunk_index_end = MIN2(chunk_index_start + chunks_per_thread,
  2612                                       chunk_index_end_dense_prefix);
  2613         q->enqueue(new UpdateDensePrefixTask(
  2614                                  space_id,
  2615                                  chunk_index_start,
  2616                                  chunk_index_end));
  2617         chunk_index_start = chunk_index_end;
  2620     // This gets any part of the dense prefix that did not
  2621     // fit evenly.
  2622     if (chunk_index_start < chunk_index_end_dense_prefix) {
  2623       q->enqueue(new UpdateDensePrefixTask(
  2624                                  space_id,
  2625                                  chunk_index_start,
  2626                                  chunk_index_end_dense_prefix));
  2628     space_id = next_compaction_space_id(space_id);
  2629   }  // End tasks for dense prefix
  2632 void PSParallelCompact::enqueue_chunk_stealing_tasks(
  2633                                      GCTaskQueue* q,
  2634                                      ParallelTaskTerminator* terminator_ptr,
  2635                                      uint parallel_gc_threads) {
  2636   TraceTime tm("steal task setup", print_phases(), true, gclog_or_tty);
  2638   // Once a thread has drained it's stack, it should try to steal chunks from
  2639   // other threads.
  2640   if (parallel_gc_threads > 1) {
  2641     for (uint j = 0; j < parallel_gc_threads; j++) {
  2642       q->enqueue(new StealChunkCompactionTask(terminator_ptr));
  2647 void PSParallelCompact::compact() {
  2648   EventMark m("5 compact");
  2649   // trace("5");
  2650   TraceTime tm("compaction phase", print_phases(), true, gclog_or_tty);
  2652   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
  2653   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
  2654   PSOldGen* old_gen = heap->old_gen();
  2655   old_gen->start_array()->reset();
  2656   uint parallel_gc_threads = heap->gc_task_manager()->workers();
  2657   TaskQueueSetSuper* qset = ParCompactionManager::chunk_array();
  2658   ParallelTaskTerminator terminator(parallel_gc_threads, qset);
  2660   GCTaskQueue* q = GCTaskQueue::create();
  2661   enqueue_chunk_draining_tasks(q, parallel_gc_threads);
  2662   enqueue_dense_prefix_tasks(q, parallel_gc_threads);
  2663   enqueue_chunk_stealing_tasks(q, &terminator, parallel_gc_threads);
  2666     TraceTime tm_pc("par compact", print_phases(), true, gclog_or_tty);
  2668     WaitForBarrierGCTask* fin = WaitForBarrierGCTask::create();
  2669     q->enqueue(fin);
  2671     gc_task_manager()->add_list(q);
  2673     fin->wait_for();
  2675     // We have to release the barrier tasks!
  2676     WaitForBarrierGCTask::destroy(fin);
  2678 #ifdef  ASSERT
  2679     // Verify that all chunks have been processed before the deferred updates.
  2680     // Note that perm_space_id is skipped; this type of verification is not
  2681     // valid until the perm gen is compacted by chunks.
  2682     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
  2683       verify_complete(SpaceId(id));
  2685 #endif
  2689     // Update the deferred objects, if any.  Any compaction manager can be used.
  2690     TraceTime tm_du("deferred updates", print_phases(), true, gclog_or_tty);
  2691     ParCompactionManager* cm = ParCompactionManager::manager_array(0);
  2692     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
  2693       update_deferred_objects(cm, SpaceId(id));
  2698 #ifdef  ASSERT
  2699 void PSParallelCompact::verify_complete(SpaceId space_id) {
  2700   // All Chunks between space bottom() to new_top() should be marked as filled
  2701   // and all Chunks between new_top() and top() should be available (i.e.,
  2702   // should have been emptied).
  2703   ParallelCompactData& sd = summary_data();
  2704   SpaceInfo si = _space_info[space_id];
  2705   HeapWord* new_top_addr = sd.chunk_align_up(si.new_top());
  2706   HeapWord* old_top_addr = sd.chunk_align_up(si.space()->top());
  2707   const size_t beg_chunk = sd.addr_to_chunk_idx(si.space()->bottom());
  2708   const size_t new_top_chunk = sd.addr_to_chunk_idx(new_top_addr);
  2709   const size_t old_top_chunk = sd.addr_to_chunk_idx(old_top_addr);
  2711   bool issued_a_warning = false;
  2713   size_t cur_chunk;
  2714   for (cur_chunk = beg_chunk; cur_chunk < new_top_chunk; ++cur_chunk) {
  2715     const ChunkData* const c = sd.chunk(cur_chunk);
  2716     if (!c->completed()) {
  2717       warning("chunk " SIZE_FORMAT " not filled:  "
  2718               "destination_count=" SIZE_FORMAT,
  2719               cur_chunk, c->destination_count());
  2720       issued_a_warning = true;
  2724   for (cur_chunk = new_top_chunk; cur_chunk < old_top_chunk; ++cur_chunk) {
  2725     const ChunkData* const c = sd.chunk(cur_chunk);
  2726     if (!c->available()) {
  2727       warning("chunk " SIZE_FORMAT " not empty:   "
  2728               "destination_count=" SIZE_FORMAT,
  2729               cur_chunk, c->destination_count());
  2730       issued_a_warning = true;
  2734   if (issued_a_warning) {
  2735     print_chunk_ranges();
  2738 #endif  // #ifdef ASSERT
  2740 void PSParallelCompact::compact_serial(ParCompactionManager* cm) {
  2741   EventMark m("5 compact serial");
  2742   TraceTime tm("compact serial", print_phases(), true, gclog_or_tty);
  2744   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
  2745   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
  2747   PSYoungGen* young_gen = heap->young_gen();
  2748   PSOldGen* old_gen = heap->old_gen();
  2750   old_gen->start_array()->reset();
  2751   old_gen->move_and_update(cm);
  2752   young_gen->move_and_update(cm);
  2756 void PSParallelCompact::follow_stack(ParCompactionManager* cm) {
  2757   while(!cm->overflow_stack()->is_empty()) {
  2758     oop obj = cm->overflow_stack()->pop();
  2759     obj->follow_contents(cm);
  2762   oop obj;
  2763   // obj is a reference!!!
  2764   while (cm->marking_stack()->pop_local(obj)) {
  2765     // It would be nice to assert about the type of objects we might
  2766     // pop, but they can come from anywhere, unfortunately.
  2767     obj->follow_contents(cm);
  2771 void
  2772 PSParallelCompact::follow_weak_klass_links(ParCompactionManager* serial_cm) {
  2773   // All klasses on the revisit stack are marked at this point.
  2774   // Update and follow all subklass, sibling and implementor links.
  2775   for (uint i = 0; i < ParallelGCThreads+1; i++) {
  2776     ParCompactionManager* cm = ParCompactionManager::manager_array(i);
  2777     KeepAliveClosure keep_alive_closure(cm);
  2778     for (int i = 0; i < cm->revisit_klass_stack()->length(); i++) {
  2779       cm->revisit_klass_stack()->at(i)->follow_weak_klass_links(
  2780         is_alive_closure(),
  2781         &keep_alive_closure);
  2783     follow_stack(cm);
  2787 void
  2788 PSParallelCompact::revisit_weak_klass_link(ParCompactionManager* cm, Klass* k) {
  2789   cm->revisit_klass_stack()->push(k);
  2792 #ifdef VALIDATE_MARK_SWEEP
  2794 void PSParallelCompact::track_adjusted_pointer(void* p, bool isroot) {
  2795   if (!ValidateMarkSweep)
  2796     return;
  2798   if (!isroot) {
  2799     if (_pointer_tracking) {
  2800       guarantee(_adjusted_pointers->contains(p), "should have seen this pointer");
  2801       _adjusted_pointers->remove(p);
  2803   } else {
  2804     ptrdiff_t index = _root_refs_stack->find(p);
  2805     if (index != -1) {
  2806       int l = _root_refs_stack->length();
  2807       if (l > 0 && l - 1 != index) {
  2808         void* last = _root_refs_stack->pop();
  2809         assert(last != p, "should be different");
  2810         _root_refs_stack->at_put(index, last);
  2811       } else {
  2812         _root_refs_stack->remove(p);
  2819 void PSParallelCompact::check_adjust_pointer(void* p) {
  2820   _adjusted_pointers->push(p);
  2824 class AdjusterTracker: public OopClosure {
  2825  public:
  2826   AdjusterTracker() {};
  2827   void do_oop(oop* o)         { PSParallelCompact::check_adjust_pointer(o); }
  2828   void do_oop(narrowOop* o)   { PSParallelCompact::check_adjust_pointer(o); }
  2829 };
  2832 void PSParallelCompact::track_interior_pointers(oop obj) {
  2833   if (ValidateMarkSweep) {
  2834     _adjusted_pointers->clear();
  2835     _pointer_tracking = true;
  2837     AdjusterTracker checker;
  2838     obj->oop_iterate(&checker);
  2843 void PSParallelCompact::check_interior_pointers() {
  2844   if (ValidateMarkSweep) {
  2845     _pointer_tracking = false;
  2846     guarantee(_adjusted_pointers->length() == 0, "should have processed the same pointers");
  2851 void PSParallelCompact::reset_live_oop_tracking(bool at_perm) {
  2852   if (ValidateMarkSweep) {
  2853     guarantee((size_t)_live_oops->length() == _live_oops_index, "should be at end of live oops");
  2854     _live_oops_index = at_perm ? _live_oops_index_at_perm : 0;
  2859 void PSParallelCompact::register_live_oop(oop p, size_t size) {
  2860   if (ValidateMarkSweep) {
  2861     _live_oops->push(p);
  2862     _live_oops_size->push(size);
  2863     _live_oops_index++;
  2867 void PSParallelCompact::validate_live_oop(oop p, size_t size) {
  2868   if (ValidateMarkSweep) {
  2869     oop obj = _live_oops->at((int)_live_oops_index);
  2870     guarantee(obj == p, "should be the same object");
  2871     guarantee(_live_oops_size->at((int)_live_oops_index) == size, "should be the same size");
  2872     _live_oops_index++;
  2876 void PSParallelCompact::live_oop_moved_to(HeapWord* q, size_t size,
  2877                                   HeapWord* compaction_top) {
  2878   assert(oop(q)->forwardee() == NULL || oop(q)->forwardee() == oop(compaction_top),
  2879          "should be moved to forwarded location");
  2880   if (ValidateMarkSweep) {
  2881     PSParallelCompact::validate_live_oop(oop(q), size);
  2882     _live_oops_moved_to->push(oop(compaction_top));
  2884   if (RecordMarkSweepCompaction) {
  2885     _cur_gc_live_oops->push(q);
  2886     _cur_gc_live_oops_moved_to->push(compaction_top);
  2887     _cur_gc_live_oops_size->push(size);
  2892 void PSParallelCompact::compaction_complete() {
  2893   if (RecordMarkSweepCompaction) {
  2894     GrowableArray<HeapWord*>* _tmp_live_oops          = _cur_gc_live_oops;
  2895     GrowableArray<HeapWord*>* _tmp_live_oops_moved_to = _cur_gc_live_oops_moved_to;
  2896     GrowableArray<size_t>   * _tmp_live_oops_size     = _cur_gc_live_oops_size;
  2898     _cur_gc_live_oops           = _last_gc_live_oops;
  2899     _cur_gc_live_oops_moved_to  = _last_gc_live_oops_moved_to;
  2900     _cur_gc_live_oops_size      = _last_gc_live_oops_size;
  2901     _last_gc_live_oops          = _tmp_live_oops;
  2902     _last_gc_live_oops_moved_to = _tmp_live_oops_moved_to;
  2903     _last_gc_live_oops_size     = _tmp_live_oops_size;
  2908 void PSParallelCompact::print_new_location_of_heap_address(HeapWord* q) {
  2909   if (!RecordMarkSweepCompaction) {
  2910     tty->print_cr("Requires RecordMarkSweepCompaction to be enabled");
  2911     return;
  2914   if (_last_gc_live_oops == NULL) {
  2915     tty->print_cr("No compaction information gathered yet");
  2916     return;
  2919   for (int i = 0; i < _last_gc_live_oops->length(); i++) {
  2920     HeapWord* old_oop = _last_gc_live_oops->at(i);
  2921     size_t    sz      = _last_gc_live_oops_size->at(i);
  2922     if (old_oop <= q && q < (old_oop + sz)) {
  2923       HeapWord* new_oop = _last_gc_live_oops_moved_to->at(i);
  2924       size_t offset = (q - old_oop);
  2925       tty->print_cr("Address " PTR_FORMAT, q);
  2926       tty->print_cr(" Was in oop " PTR_FORMAT ", size %d, at offset %d", old_oop, sz, offset);
  2927       tty->print_cr(" Now in oop " PTR_FORMAT ", actual address " PTR_FORMAT, new_oop, new_oop + offset);
  2928       return;
  2932   tty->print_cr("Address " PTR_FORMAT " not found in live oop information from last GC", q);
  2934 #endif //VALIDATE_MARK_SWEEP
  2936 // Update interior oops in the ranges of chunks [beg_chunk, end_chunk).
  2937 void
  2938 PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,
  2939                                                        SpaceId space_id,
  2940                                                        size_t beg_chunk,
  2941                                                        size_t end_chunk) {
  2942   ParallelCompactData& sd = summary_data();
  2943   ParMarkBitMap* const mbm = mark_bitmap();
  2945   HeapWord* beg_addr = sd.chunk_to_addr(beg_chunk);
  2946   HeapWord* const end_addr = sd.chunk_to_addr(end_chunk);
  2947   assert(beg_chunk <= end_chunk, "bad chunk range");
  2948   assert(end_addr <= dense_prefix(space_id), "not in the dense prefix");
  2950 #ifdef  ASSERT
  2951   // Claim the chunks to avoid triggering an assert when they are marked as
  2952   // filled.
  2953   for (size_t claim_chunk = beg_chunk; claim_chunk < end_chunk; ++claim_chunk) {
  2954     assert(sd.chunk(claim_chunk)->claim_unsafe(), "claim() failed");
  2956 #endif  // #ifdef ASSERT
  2958   if (beg_addr != space(space_id)->bottom()) {
  2959     // Find the first live object or block of dead space that *starts* in this
  2960     // range of chunks.  If a partial object crosses onto the chunk, skip it; it
  2961     // will be marked for 'deferred update' when the object head is processed.
  2962     // If dead space crosses onto the chunk, it is also skipped; it will be
  2963     // filled when the prior chunk is processed.  If neither of those apply, the
  2964     // first word in the chunk is the start of a live object or dead space.
  2965     assert(beg_addr > space(space_id)->bottom(), "sanity");
  2966     const ChunkData* const cp = sd.chunk(beg_chunk);
  2967     if (cp->partial_obj_size() != 0) {
  2968       beg_addr = sd.partial_obj_end(beg_chunk);
  2969     } else if (dead_space_crosses_boundary(cp, mbm->addr_to_bit(beg_addr))) {
  2970       beg_addr = mbm->find_obj_beg(beg_addr, end_addr);
  2974   if (beg_addr < end_addr) {
  2975     // A live object or block of dead space starts in this range of Chunks.
  2976      HeapWord* const dense_prefix_end = dense_prefix(space_id);
  2978     // Create closures and iterate.
  2979     UpdateOnlyClosure update_closure(mbm, cm, space_id);
  2980     FillClosure fill_closure(cm, space_id);
  2981     ParMarkBitMap::IterationStatus status;
  2982     status = mbm->iterate(&update_closure, &fill_closure, beg_addr, end_addr,
  2983                           dense_prefix_end);
  2984     if (status == ParMarkBitMap::incomplete) {
  2985       update_closure.do_addr(update_closure.source());
  2989   // Mark the chunks as filled.
  2990   ChunkData* const beg_cp = sd.chunk(beg_chunk);
  2991   ChunkData* const end_cp = sd.chunk(end_chunk);
  2992   for (ChunkData* cp = beg_cp; cp < end_cp; ++cp) {
  2993     cp->set_completed();
  2997 // Return the SpaceId for the space containing addr.  If addr is not in the
  2998 // heap, last_space_id is returned.  In debug mode it expects the address to be
  2999 // in the heap and asserts such.
  3000 PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
  3001   assert(Universe::heap()->is_in_reserved(addr), "addr not in the heap");
  3003   for (unsigned int id = perm_space_id; id < last_space_id; ++id) {
  3004     if (_space_info[id].space()->contains(addr)) {
  3005       return SpaceId(id);
  3009   assert(false, "no space contains the addr");
  3010   return last_space_id;
  3013 void PSParallelCompact::update_deferred_objects(ParCompactionManager* cm,
  3014                                                 SpaceId id) {
  3015   assert(id < last_space_id, "bad space id");
  3017   ParallelCompactData& sd = summary_data();
  3018   const SpaceInfo* const space_info = _space_info + id;
  3019   ObjectStartArray* const start_array = space_info->start_array();
  3021   const MutableSpace* const space = space_info->space();
  3022   assert(space_info->dense_prefix() >= space->bottom(), "dense_prefix not set");
  3023   HeapWord* const beg_addr = space_info->dense_prefix();
  3024   HeapWord* const end_addr = sd.chunk_align_up(space_info->new_top());
  3026   const ChunkData* const beg_chunk = sd.addr_to_chunk_ptr(beg_addr);
  3027   const ChunkData* const end_chunk = sd.addr_to_chunk_ptr(end_addr);
  3028   const ChunkData* cur_chunk;
  3029   for (cur_chunk = beg_chunk; cur_chunk < end_chunk; ++cur_chunk) {
  3030     HeapWord* const addr = cur_chunk->deferred_obj_addr();
  3031     if (addr != NULL) {
  3032       if (start_array != NULL) {
  3033         start_array->allocate_block(addr);
  3035       oop(addr)->update_contents(cm);
  3036       assert(oop(addr)->is_oop_or_null(), "should be an oop now");
  3041 // Skip over count live words starting from beg, and return the address of the
  3042 // next live word.  Unless marked, the word corresponding to beg is assumed to
  3043 // be dead.  Callers must either ensure beg does not correspond to the middle of
  3044 // an object, or account for those live words in some other way.  Callers must
  3045 // also ensure that there are enough live words in the range [beg, end) to skip.
  3046 HeapWord*
  3047 PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
  3049   assert(count > 0, "sanity");
  3051   ParMarkBitMap* m = mark_bitmap();
  3052   idx_t bits_to_skip = m->words_to_bits(count);
  3053   idx_t cur_beg = m->addr_to_bit(beg);
  3054   const idx_t search_end = BitMap::word_align_up(m->addr_to_bit(end));
  3056   do {
  3057     cur_beg = m->find_obj_beg(cur_beg, search_end);
  3058     idx_t cur_end = m->find_obj_end(cur_beg, search_end);
  3059     const size_t obj_bits = cur_end - cur_beg + 1;
  3060     if (obj_bits > bits_to_skip) {
  3061       return m->bit_to_addr(cur_beg + bits_to_skip);
  3063     bits_to_skip -= obj_bits;
  3064     cur_beg = cur_end + 1;
  3065   } while (bits_to_skip > 0);
  3067   // Skipping the desired number of words landed just past the end of an object.
  3068   // Find the start of the next object.
  3069   cur_beg = m->find_obj_beg(cur_beg, search_end);
  3070   assert(cur_beg < m->addr_to_bit(end), "not enough live words to skip");
  3071   return m->bit_to_addr(cur_beg);
  3074 HeapWord*
  3075 PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
  3076                                  size_t src_chunk_idx)
  3078   ParMarkBitMap* const bitmap = mark_bitmap();
  3079   const ParallelCompactData& sd = summary_data();
  3080   const size_t ChunkSize = ParallelCompactData::ChunkSize;
  3082   assert(sd.is_chunk_aligned(dest_addr), "not aligned");
  3084   const ChunkData* const src_chunk_ptr = sd.chunk(src_chunk_idx);
  3085   const size_t partial_obj_size = src_chunk_ptr->partial_obj_size();
  3086   HeapWord* const src_chunk_destination = src_chunk_ptr->destination();
  3088   assert(dest_addr >= src_chunk_destination, "wrong src chunk");
  3089   assert(src_chunk_ptr->data_size() > 0, "src chunk cannot be empty");
  3091   HeapWord* const src_chunk_beg = sd.chunk_to_addr(src_chunk_idx);
  3092   HeapWord* const src_chunk_end = src_chunk_beg + ChunkSize;
  3094   HeapWord* addr = src_chunk_beg;
  3095   if (dest_addr == src_chunk_destination) {
  3096     // Return the first live word in the source chunk.
  3097     if (partial_obj_size == 0) {
  3098       addr = bitmap->find_obj_beg(addr, src_chunk_end);
  3099       assert(addr < src_chunk_end, "no objects start in src chunk");
  3101     return addr;
  3104   // Must skip some live data.
  3105   size_t words_to_skip = dest_addr - src_chunk_destination;
  3106   assert(src_chunk_ptr->data_size() > words_to_skip, "wrong src chunk");
  3108   if (partial_obj_size >= words_to_skip) {
  3109     // All the live words to skip are part of the partial object.
  3110     addr += words_to_skip;
  3111     if (partial_obj_size == words_to_skip) {
  3112       // Find the first live word past the partial object.
  3113       addr = bitmap->find_obj_beg(addr, src_chunk_end);
  3114       assert(addr < src_chunk_end, "wrong src chunk");
  3116     return addr;
  3119   // Skip over the partial object (if any).
  3120   if (partial_obj_size != 0) {
  3121     words_to_skip -= partial_obj_size;
  3122     addr += partial_obj_size;
  3125   // Skip over live words due to objects that start in the chunk.
  3126   addr = skip_live_words(addr, src_chunk_end, words_to_skip);
  3127   assert(addr < src_chunk_end, "wrong src chunk");
  3128   return addr;
  3131 void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
  3132                                                      size_t beg_chunk,
  3133                                                      HeapWord* end_addr)
  3135   ParallelCompactData& sd = summary_data();
  3136   ChunkData* const beg = sd.chunk(beg_chunk);
  3137   HeapWord* const end_addr_aligned_up = sd.chunk_align_up(end_addr);
  3138   ChunkData* const end = sd.addr_to_chunk_ptr(end_addr_aligned_up);
  3139   size_t cur_idx = beg_chunk;
  3140   for (ChunkData* cur = beg; cur < end; ++cur, ++cur_idx) {
  3141     assert(cur->data_size() > 0, "chunk must have live data");
  3142     cur->decrement_destination_count();
  3143     if (cur_idx <= cur->source_chunk() && cur->available() && cur->claim()) {
  3144       cm->save_for_processing(cur_idx);
  3149 size_t PSParallelCompact::next_src_chunk(MoveAndUpdateClosure& closure,
  3150                                          SpaceId& src_space_id,
  3151                                          HeapWord*& src_space_top,
  3152                                          HeapWord* end_addr)
  3154   typedef ParallelCompactData::ChunkData ChunkData;
  3156   ParallelCompactData& sd = PSParallelCompact::summary_data();
  3157   const size_t chunk_size = ParallelCompactData::ChunkSize;
  3159   size_t src_chunk_idx = 0;
  3161   // Skip empty chunks (if any) up to the top of the space.
  3162   HeapWord* const src_aligned_up = sd.chunk_align_up(end_addr);
  3163   ChunkData* src_chunk_ptr = sd.addr_to_chunk_ptr(src_aligned_up);
  3164   HeapWord* const top_aligned_up = sd.chunk_align_up(src_space_top);
  3165   const ChunkData* const top_chunk_ptr = sd.addr_to_chunk_ptr(top_aligned_up);
  3166   while (src_chunk_ptr < top_chunk_ptr && src_chunk_ptr->data_size() == 0) {
  3167     ++src_chunk_ptr;
  3170   if (src_chunk_ptr < top_chunk_ptr) {
  3171     // The next source chunk is in the current space.  Update src_chunk_idx and
  3172     // the source address to match src_chunk_ptr.
  3173     src_chunk_idx = sd.chunk(src_chunk_ptr);
  3174     HeapWord* const src_chunk_addr = sd.chunk_to_addr(src_chunk_idx);
  3175     if (src_chunk_addr > closure.source()) {
  3176       closure.set_source(src_chunk_addr);
  3178     return src_chunk_idx;
  3181   // Switch to a new source space and find the first non-empty chunk.
  3182   unsigned int space_id = src_space_id + 1;
  3183   assert(space_id < last_space_id, "not enough spaces");
  3185   HeapWord* const destination = closure.destination();
  3187   do {
  3188     MutableSpace* space = _space_info[space_id].space();
  3189     HeapWord* const bottom = space->bottom();
  3190     const ChunkData* const bottom_cp = sd.addr_to_chunk_ptr(bottom);
  3192     // Iterate over the spaces that do not compact into themselves.
  3193     if (bottom_cp->destination() != bottom) {
  3194       HeapWord* const top_aligned_up = sd.chunk_align_up(space->top());
  3195       const ChunkData* const top_cp = sd.addr_to_chunk_ptr(top_aligned_up);
  3197       for (const ChunkData* src_cp = bottom_cp; src_cp < top_cp; ++src_cp) {
  3198         if (src_cp->live_obj_size() > 0) {
  3199           // Found it.
  3200           assert(src_cp->destination() == destination,
  3201                  "first live obj in the space must match the destination");
  3202           assert(src_cp->partial_obj_size() == 0,
  3203                  "a space cannot begin with a partial obj");
  3205           src_space_id = SpaceId(space_id);
  3206           src_space_top = space->top();
  3207           const size_t src_chunk_idx = sd.chunk(src_cp);
  3208           closure.set_source(sd.chunk_to_addr(src_chunk_idx));
  3209           return src_chunk_idx;
  3210         } else {
  3211           assert(src_cp->data_size() == 0, "sanity");
  3215   } while (++space_id < last_space_id);
  3217   assert(false, "no source chunk was found");
  3218   return 0;
  3221 void PSParallelCompact::fill_chunk(ParCompactionManager* cm, size_t chunk_idx)
  3223   typedef ParMarkBitMap::IterationStatus IterationStatus;
  3224   const size_t ChunkSize = ParallelCompactData::ChunkSize;
  3225   ParMarkBitMap* const bitmap = mark_bitmap();
  3226   ParallelCompactData& sd = summary_data();
  3227   ChunkData* const chunk_ptr = sd.chunk(chunk_idx);
  3229   // Get the items needed to construct the closure.
  3230   HeapWord* dest_addr = sd.chunk_to_addr(chunk_idx);
  3231   SpaceId dest_space_id = space_id(dest_addr);
  3232   ObjectStartArray* start_array = _space_info[dest_space_id].start_array();
  3233   HeapWord* new_top = _space_info[dest_space_id].new_top();
  3234   assert(dest_addr < new_top, "sanity");
  3235   const size_t words = MIN2(pointer_delta(new_top, dest_addr), ChunkSize);
  3237   // Get the source chunk and related info.
  3238   size_t src_chunk_idx = chunk_ptr->source_chunk();
  3239   SpaceId src_space_id = space_id(sd.chunk_to_addr(src_chunk_idx));
  3240   HeapWord* src_space_top = _space_info[src_space_id].space()->top();
  3242   MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);
  3243   closure.set_source(first_src_addr(dest_addr, src_chunk_idx));
  3245   // Adjust src_chunk_idx to prepare for decrementing destination counts (the
  3246   // destination count is not decremented when a chunk is copied to itself).
  3247   if (src_chunk_idx == chunk_idx) {
  3248     src_chunk_idx += 1;
  3251   if (bitmap->is_unmarked(closure.source())) {
  3252     // The first source word is in the middle of an object; copy the remainder
  3253     // of the object or as much as will fit.  The fact that pointer updates were
  3254     // deferred will be noted when the object header is processed.
  3255     HeapWord* const old_src_addr = closure.source();
  3256     closure.copy_partial_obj();
  3257     if (closure.is_full()) {
  3258       decrement_destination_counts(cm, src_chunk_idx, closure.source());
  3259       chunk_ptr->set_deferred_obj_addr(NULL);
  3260       chunk_ptr->set_completed();
  3261       return;
  3264     HeapWord* const end_addr = sd.chunk_align_down(closure.source());
  3265     if (sd.chunk_align_down(old_src_addr) != end_addr) {
  3266       // The partial object was copied from more than one source chunk.
  3267       decrement_destination_counts(cm, src_chunk_idx, end_addr);
  3269       // Move to the next source chunk, possibly switching spaces as well.  All
  3270       // args except end_addr may be modified.
  3271       src_chunk_idx = next_src_chunk(closure, src_space_id, src_space_top,
  3272                                      end_addr);
  3276   do {
  3277     HeapWord* const cur_addr = closure.source();
  3278     HeapWord* const end_addr = MIN2(sd.chunk_align_up(cur_addr + 1),
  3279                                     src_space_top);
  3280     IterationStatus status = bitmap->iterate(&closure, cur_addr, end_addr);
  3282     if (status == ParMarkBitMap::incomplete) {
  3283       // The last obj that starts in the source chunk does not end in the chunk.
  3284       assert(closure.source() < end_addr, "sanity")
  3285       HeapWord* const obj_beg = closure.source();
  3286       HeapWord* const range_end = MIN2(obj_beg + closure.words_remaining(),
  3287                                        src_space_top);
  3288       HeapWord* const obj_end = bitmap->find_obj_end(obj_beg, range_end);
  3289       if (obj_end < range_end) {
  3290         // The end was found; the entire object will fit.
  3291         status = closure.do_addr(obj_beg, bitmap->obj_size(obj_beg, obj_end));
  3292         assert(status != ParMarkBitMap::would_overflow, "sanity");
  3293       } else {
  3294         // The end was not found; the object will not fit.
  3295         assert(range_end < src_space_top, "obj cannot cross space boundary");
  3296         status = ParMarkBitMap::would_overflow;
  3300     if (status == ParMarkBitMap::would_overflow) {
  3301       // The last object did not fit.  Note that interior oop updates were
  3302       // deferred, then copy enough of the object to fill the chunk.
  3303       chunk_ptr->set_deferred_obj_addr(closure.destination());
  3304       status = closure.copy_until_full(); // copies from closure.source()
  3306       decrement_destination_counts(cm, src_chunk_idx, closure.source());
  3307       chunk_ptr->set_completed();
  3308       return;
  3311     if (status == ParMarkBitMap::full) {
  3312       decrement_destination_counts(cm, src_chunk_idx, closure.source());
  3313       chunk_ptr->set_deferred_obj_addr(NULL);
  3314       chunk_ptr->set_completed();
  3315       return;
  3318     decrement_destination_counts(cm, src_chunk_idx, end_addr);
  3320     // Move to the next source chunk, possibly switching spaces as well.  All
  3321     // args except end_addr may be modified.
  3322     src_chunk_idx = next_src_chunk(closure, src_space_id, src_space_top,
  3323                                    end_addr);
  3324   } while (true);
  3327 void
  3328 PSParallelCompact::move_and_update(ParCompactionManager* cm, SpaceId space_id) {
  3329   const MutableSpace* sp = space(space_id);
  3330   if (sp->is_empty()) {
  3331     return;
  3334   ParallelCompactData& sd = PSParallelCompact::summary_data();
  3335   ParMarkBitMap* const bitmap = mark_bitmap();
  3336   HeapWord* const dp_addr = dense_prefix(space_id);
  3337   HeapWord* beg_addr = sp->bottom();
  3338   HeapWord* end_addr = sp->top();
  3340 #ifdef ASSERT
  3341   assert(beg_addr <= dp_addr && dp_addr <= end_addr, "bad dense prefix");
  3342   if (cm->should_verify_only()) {
  3343     VerifyUpdateClosure verify_update(cm, sp);
  3344     bitmap->iterate(&verify_update, beg_addr, end_addr);
  3345     return;
  3348   if (cm->should_reset_only()) {
  3349     ResetObjectsClosure reset_objects(cm);
  3350     bitmap->iterate(&reset_objects, beg_addr, end_addr);
  3351     return;
  3353 #endif
  3355   const size_t beg_chunk = sd.addr_to_chunk_idx(beg_addr);
  3356   const size_t dp_chunk = sd.addr_to_chunk_idx(dp_addr);
  3357   if (beg_chunk < dp_chunk) {
  3358     update_and_deadwood_in_dense_prefix(cm, space_id, beg_chunk, dp_chunk);
  3361   // The destination of the first live object that starts in the chunk is one
  3362   // past the end of the partial object entering the chunk (if any).
  3363   HeapWord* const dest_addr = sd.partial_obj_end(dp_chunk);
  3364   HeapWord* const new_top = _space_info[space_id].new_top();
  3365   assert(new_top >= dest_addr, "bad new_top value");
  3366   const size_t words = pointer_delta(new_top, dest_addr);
  3368   if (words > 0) {
  3369     ObjectStartArray* start_array = _space_info[space_id].start_array();
  3370     MoveAndUpdateClosure closure(bitmap, cm, start_array, dest_addr, words);
  3372     ParMarkBitMap::IterationStatus status;
  3373     status = bitmap->iterate(&closure, dest_addr, end_addr);
  3374     assert(status == ParMarkBitMap::full, "iteration not complete");
  3375     assert(bitmap->find_obj_beg(closure.source(), end_addr) == end_addr,
  3376            "live objects skipped because closure is full");
  3380 jlong PSParallelCompact::millis_since_last_gc() {
  3381   jlong ret_val = os::javaTimeMillis() - _time_of_last_gc;
  3382   // XXX See note in genCollectedHeap::millis_since_last_gc().
  3383   if (ret_val < 0) {
  3384     NOT_PRODUCT(warning("time warp: %d", ret_val);)
  3385     return 0;
  3387   return ret_val;
  3390 void PSParallelCompact::reset_millis_since_last_gc() {
  3391   _time_of_last_gc = os::javaTimeMillis();
  3394 ParMarkBitMap::IterationStatus MoveAndUpdateClosure::copy_until_full()
  3396   if (source() != destination()) {
  3397     assert(source() > destination(), "must copy to the left");
  3398     Copy::aligned_conjoint_words(source(), destination(), words_remaining());
  3400   update_state(words_remaining());
  3401   assert(is_full(), "sanity");
  3402   return ParMarkBitMap::full;
  3405 void MoveAndUpdateClosure::copy_partial_obj()
  3407   size_t words = words_remaining();
  3409   HeapWord* const range_end = MIN2(source() + words, bitmap()->region_end());
  3410   HeapWord* const end_addr = bitmap()->find_obj_end(source(), range_end);
  3411   if (end_addr < range_end) {
  3412     words = bitmap()->obj_size(source(), end_addr);
  3415   // This test is necessary; if omitted, the pointer updates to a partial object
  3416   // that crosses the dense prefix boundary could be overwritten.
  3417   if (source() != destination()) {
  3418     assert(source() > destination(), "must copy to the left");
  3419     Copy::aligned_conjoint_words(source(), destination(), words);
  3421   update_state(words);
  3424 ParMarkBitMapClosure::IterationStatus
  3425 MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
  3426   assert(destination() != NULL, "sanity");
  3427   assert(bitmap()->obj_size(addr) == words, "bad size");
  3429   _source = addr;
  3430   assert(PSParallelCompact::summary_data().calc_new_pointer(source()) ==
  3431          destination(), "wrong destination");
  3433   if (words > words_remaining()) {
  3434     return ParMarkBitMap::would_overflow;
  3437   // The start_array must be updated even if the object is not moving.
  3438   if (_start_array != NULL) {
  3439     _start_array->allocate_block(destination());
  3442   if (destination() != source()) {
  3443     assert(destination() < source(), "must copy to the left");
  3444     Copy::aligned_conjoint_words(source(), destination(), words);
  3447   oop moved_oop = (oop) destination();
  3448   moved_oop->update_contents(compaction_manager());
  3449   assert(moved_oop->is_oop_or_null(), "Object should be whole at this point");
  3451   update_state(words);
  3452   assert(destination() == (HeapWord*)moved_oop + moved_oop->size(), "sanity");
  3453   return is_full() ? ParMarkBitMap::full : ParMarkBitMap::incomplete;
  3456 UpdateOnlyClosure::UpdateOnlyClosure(ParMarkBitMap* mbm,
  3457                                      ParCompactionManager* cm,
  3458                                      PSParallelCompact::SpaceId space_id) :
  3459   ParMarkBitMapClosure(mbm, cm),
  3460   _space_id(space_id),
  3461   _start_array(PSParallelCompact::start_array(space_id))
  3465 // Updates the references in the object to their new values.
  3466 ParMarkBitMapClosure::IterationStatus
  3467 UpdateOnlyClosure::do_addr(HeapWord* addr, size_t words) {
  3468   do_addr(addr);
  3469   return ParMarkBitMap::incomplete;
  3472 BitBlockUpdateClosure::BitBlockUpdateClosure(ParMarkBitMap* mbm,
  3473                         ParCompactionManager* cm,
  3474                         size_t chunk_index) :
  3475                         ParMarkBitMapClosure(mbm, cm),
  3476                         _live_data_left(0),
  3477                         _cur_block(0) {
  3478   _chunk_start =
  3479     PSParallelCompact::summary_data().chunk_to_addr(chunk_index);
  3480   _chunk_end =
  3481     PSParallelCompact::summary_data().chunk_to_addr(chunk_index) +
  3482                  ParallelCompactData::ChunkSize;
  3483   _chunk_index = chunk_index;
  3484   _cur_block =
  3485     PSParallelCompact::summary_data().addr_to_block_idx(_chunk_start);
  3488 bool BitBlockUpdateClosure::chunk_contains_cur_block() {
  3489   return ParallelCompactData::chunk_contains_block(_chunk_index, _cur_block);
  3492 void BitBlockUpdateClosure::reset_chunk(size_t chunk_index) {
  3493   DEBUG_ONLY(ParallelCompactData::BlockData::set_cur_phase(7);)
  3494   ParallelCompactData& sd = PSParallelCompact::summary_data();
  3495   _chunk_index = chunk_index;
  3496   _live_data_left = 0;
  3497   _chunk_start = sd.chunk_to_addr(chunk_index);
  3498   _chunk_end = sd.chunk_to_addr(chunk_index) + ParallelCompactData::ChunkSize;
  3500   // The first block in this chunk
  3501   size_t first_block =  sd.addr_to_block_idx(_chunk_start);
  3502   size_t partial_live_size = sd.chunk(chunk_index)->partial_obj_size();
  3504   // Set the offset to 0. By definition it should have that value
  3505   // but it may have been written while processing an earlier chunk.
  3506   if (partial_live_size == 0) {
  3507     // No live object extends onto the chunk.  The first bit
  3508     // in the bit map for the first chunk must be a start bit.
  3509     // Although there may not be any marked bits, it is safe
  3510     // to set it as a start bit.
  3511     sd.block(first_block)->set_start_bit_offset(0);
  3512     sd.block(first_block)->set_first_is_start_bit(true);
  3513   } else if (sd.partial_obj_ends_in_block(first_block)) {
  3514     sd.block(first_block)->set_end_bit_offset(0);
  3515     sd.block(first_block)->set_first_is_start_bit(false);
  3516   } else {
  3517     // The partial object extends beyond the first block.
  3518     // There is no object starting in the first block
  3519     // so the offset and bit parity are not needed.
  3520     // Set the the bit parity to start bit so assertions
  3521     // work when not bit is found.
  3522     sd.block(first_block)->set_end_bit_offset(0);
  3523     sd.block(first_block)->set_first_is_start_bit(false);
  3525   _cur_block = first_block;
  3526 #ifdef ASSERT
  3527   if (sd.block(first_block)->first_is_start_bit()) {
  3528     assert(!sd.partial_obj_ends_in_block(first_block),
  3529       "Partial object cannot end in first block");
  3532   if (PrintGCDetails && Verbose) {
  3533     if (partial_live_size == 1) {
  3534     gclog_or_tty->print_cr("first_block " PTR_FORMAT
  3535       " _offset " PTR_FORMAT
  3536       " _first_is_start_bit %d",
  3537       first_block,
  3538       sd.block(first_block)->raw_offset(),
  3539       sd.block(first_block)->first_is_start_bit());
  3542 #endif
  3543   DEBUG_ONLY(ParallelCompactData::BlockData::set_cur_phase(17);)
  3546 // This method is called when a object has been found (both beginning
  3547 // and end of the object) in the range of iteration.  This method is
  3548 // calculating the words of live data to the left of a block.  That live
  3549 // data includes any object starting to the left of the block (i.e.,
  3550 // the live-data-to-the-left of block AAA will include the full size
  3551 // of any object entering AAA).
  3553 ParMarkBitMapClosure::IterationStatus
  3554 BitBlockUpdateClosure::do_addr(HeapWord* addr, size_t words) {
  3555   // add the size to the block data.
  3556   HeapWord* obj = addr;
  3557   ParallelCompactData& sd = PSParallelCompact::summary_data();
  3559   assert(bitmap()->obj_size(obj) == words, "bad size");
  3560   assert(_chunk_start <= obj, "object is not in chunk");
  3561   assert(obj + words <= _chunk_end, "object is not in chunk");
  3563   // Update the live data to the left
  3564   size_t prev_live_data_left = _live_data_left;
  3565   _live_data_left = _live_data_left + words;
  3567   // Is this object in the current block.
  3568   size_t block_of_obj = sd.addr_to_block_idx(obj);
  3569   size_t block_of_obj_last = sd.addr_to_block_idx(obj + words - 1);
  3570   HeapWord* block_of_obj_last_addr = sd.block_to_addr(block_of_obj_last);
  3571   if (_cur_block < block_of_obj) {
  3573     //
  3574     // No object crossed the block boundary and this object was found
  3575     // on the other side of the block boundary.  Update the offset for
  3576     // the new block with the data size that does not include this object.
  3577     //
  3578     // The first bit in block_of_obj is a start bit except in the
  3579     // case where the partial object for the chunk extends into
  3580     // this block.
  3581     if (sd.partial_obj_ends_in_block(block_of_obj)) {
  3582       sd.block(block_of_obj)->set_end_bit_offset(prev_live_data_left);
  3583     } else {
  3584       sd.block(block_of_obj)->set_start_bit_offset(prev_live_data_left);
  3587     // Does this object pass beyond the its block?
  3588     if (block_of_obj < block_of_obj_last) {
  3589       // Object crosses block boundary.  Two blocks need to be udpated:
  3590       //        the current block where the object started
  3591       //        the block where the object ends
  3592       //
  3593       // The offset for blocks with no objects starting in them
  3594       // (e.g., blocks between _cur_block and  block_of_obj_last)
  3595       // should not be needed.
  3596       // Note that block_of_obj_last may be in another chunk.  If so,
  3597       // it should be overwritten later.  This is a problem (writting
  3598       // into a block in a later chunk) for parallel execution.
  3599       assert(obj < block_of_obj_last_addr,
  3600         "Object should start in previous block");
  3602       // obj is crossing into block_of_obj_last so the first bit
  3603       // is and end bit.
  3604       sd.block(block_of_obj_last)->set_end_bit_offset(_live_data_left);
  3606       _cur_block = block_of_obj_last;
  3607     } else {
  3608       // _first_is_start_bit has already been set correctly
  3609       // in the if-then-else above so don't reset it here.
  3610       _cur_block = block_of_obj;
  3612   } else {
  3613     // The current block only changes if the object extends beyound
  3614     // the block it starts in.
  3615     //
  3616     // The object starts in the current block.
  3617     // Does this object pass beyond the end of it?
  3618     if (block_of_obj < block_of_obj_last) {
  3619       // Object crosses block boundary.
  3620       // See note above on possible blocks between block_of_obj and
  3621       // block_of_obj_last
  3622       assert(obj < block_of_obj_last_addr,
  3623         "Object should start in previous block");
  3625       sd.block(block_of_obj_last)->set_end_bit_offset(_live_data_left);
  3627       _cur_block = block_of_obj_last;
  3631   // Return incomplete if there are more blocks to be done.
  3632   if (chunk_contains_cur_block()) {
  3633     return ParMarkBitMap::incomplete;
  3635   return ParMarkBitMap::complete;
  3638 // Verify the new location using the forwarding pointer
  3639 // from MarkSweep::mark_sweep_phase2().  Set the mark_word
  3640 // to the initial value.
  3641 ParMarkBitMapClosure::IterationStatus
  3642 PSParallelCompact::VerifyUpdateClosure::do_addr(HeapWord* addr, size_t words) {
  3643   // The second arg (words) is not used.
  3644   oop obj = (oop) addr;
  3645   HeapWord* forwarding_ptr = (HeapWord*) obj->mark()->decode_pointer();
  3646   HeapWord* new_pointer = summary_data().calc_new_pointer(obj);
  3647   if (forwarding_ptr == NULL) {
  3648     // The object is dead or not moving.
  3649     assert(bitmap()->is_unmarked(obj) || (new_pointer == (HeapWord*) obj),
  3650            "Object liveness is wrong.");
  3651     return ParMarkBitMap::incomplete;
  3653   assert(UseParallelOldGCDensePrefix ||
  3654          (HeapMaximumCompactionInterval > 1) ||
  3655          (MarkSweepAlwaysCompactCount > 1) ||
  3656          (forwarding_ptr == new_pointer),
  3657     "Calculation of new location is incorrect");
  3658   return ParMarkBitMap::incomplete;
  3661 // Reset objects modified for debug checking.
  3662 ParMarkBitMapClosure::IterationStatus
  3663 PSParallelCompact::ResetObjectsClosure::do_addr(HeapWord* addr, size_t words) {
  3664   // The second arg (words) is not used.
  3665   oop obj = (oop) addr;
  3666   obj->init_mark();
  3667   return ParMarkBitMap::incomplete;
  3670 // Prepare for compaction.  This method is executed once
  3671 // (i.e., by a single thread) before compaction.
  3672 // Save the updated location of the intArrayKlassObj for
  3673 // filling holes in the dense prefix.
  3674 void PSParallelCompact::compact_prologue() {
  3675   _updated_int_array_klass_obj = (klassOop)
  3676     summary_data().calc_new_pointer(Universe::intArrayKlassObj());
  3679 // The initial implementation of this method created a field
  3680 // _next_compaction_space_id in SpaceInfo and initialized
  3681 // that field in SpaceInfo::initialize_space_info().  That
  3682 // required that _next_compaction_space_id be declared a
  3683 // SpaceId in SpaceInfo and that would have required that
  3684 // either SpaceId be declared in a separate class or that
  3685 // it be declared in SpaceInfo.  It didn't seem consistent
  3686 // to declare it in SpaceInfo (didn't really fit logically).
  3687 // Alternatively, defining a separate class to define SpaceId
  3688 // seem excessive.  This implementation is simple and localizes
  3689 // the knowledge.
  3691 PSParallelCompact::SpaceId
  3692 PSParallelCompact::next_compaction_space_id(SpaceId id) {
  3693   assert(id < last_space_id, "id out of range");
  3694   switch (id) {
  3695     case perm_space_id :
  3696       return last_space_id;
  3697     case old_space_id :
  3698       return eden_space_id;
  3699     case eden_space_id :
  3700       return from_space_id;
  3701     case from_space_id :
  3702       return to_space_id;
  3703     case to_space_id :
  3704       return last_space_id;
  3705     default:
  3706       assert(false, "Bad space id");
  3707       return last_space_id;
  3711 // Here temporarily for debugging
  3712 #ifdef ASSERT
  3713   size_t ParallelCompactData::block_idx(BlockData* block) {
  3714     size_t index = pointer_delta(block,
  3715       PSParallelCompact::summary_data()._block_data, sizeof(BlockData));
  3716     return index;
  3718 #endif

mercurial