1 /*
   2  * Copyright 2001-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  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_g1CollectedHeap.cpp.incl"
  27 
  28 // turn it on so that the contents of the young list (scan-only /
  29 // to-be-collected) are printed at "strategic" points before / during
  30 // / after the collection --- this is useful for debugging
  31 #define SCAN_ONLY_VERBOSE 0
  32 // CURRENT STATUS
  33 // This file is under construction.  Search for "FIXME".
  34 
  35 // INVARIANTS/NOTES
  36 //
  37 // All allocation activity covered by the G1CollectedHeap interface is
  38 //   serialized by acquiring the HeapLock.  This happens in
  39 //   mem_allocate_work, which all such allocation functions call.
  40 //   (Note that this does not apply to TLAB allocation, which is not part
  41 //   of this interface: it is done by clients of this interface.)
  42 
  43 // Local to this file.
  44 
  45 // Finds the first HeapRegion.
  46 // No longer used, but might be handy someday.
  47 
  48 class FindFirstRegionClosure: public HeapRegionClosure {
  49   HeapRegion* _a_region;
  50 public:
  51   FindFirstRegionClosure() : _a_region(NULL) {}
  52   bool doHeapRegion(HeapRegion* r) {
  53     _a_region = r;
  54     return true;
  55   }
  56   HeapRegion* result() { return _a_region; }
  57 };
  58 
  59 
  60 class RefineCardTableEntryClosure: public CardTableEntryClosure {
  61   SuspendibleThreadSet* _sts;
  62   G1RemSet* _g1rs;
  63   ConcurrentG1Refine* _cg1r;
  64   bool _concurrent;
  65 public:
  66   RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
  67                               G1RemSet* g1rs,
  68                               ConcurrentG1Refine* cg1r) :
  69     _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
  70   {}
  71   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
  72     _g1rs->concurrentRefineOneCard(card_ptr, worker_i);
  73     if (_concurrent && _sts->should_yield()) {
  74       // Caller will actually yield.
  75       return false;
  76     }
  77     // Otherwise, we finished successfully; return true.
  78     return true;
  79   }
  80   void set_concurrent(bool b) { _concurrent = b; }
  81 };
  82 
  83 
  84 class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
  85   int _calls;
  86   G1CollectedHeap* _g1h;
  87   CardTableModRefBS* _ctbs;
  88   int _histo[256];
  89 public:
  90   ClearLoggedCardTableEntryClosure() :
  91     _calls(0)
  92   {
  93     _g1h = G1CollectedHeap::heap();
  94     _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
  95     for (int i = 0; i < 256; i++) _histo[i] = 0;
  96   }
  97   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
  98     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
  99       _calls++;
 100       unsigned char* ujb = (unsigned char*)card_ptr;
 101       int ind = (int)(*ujb);
 102       _histo[ind]++;
 103       *card_ptr = -1;
 104     }
 105     return true;
 106   }
 107   int calls() { return _calls; }
 108   void print_histo() {
 109     gclog_or_tty->print_cr("Card table value histogram:");
 110     for (int i = 0; i < 256; i++) {
 111       if (_histo[i] != 0) {
 112         gclog_or_tty->print_cr("  %d: %d", i, _histo[i]);
 113       }
 114     }
 115   }
 116 };
 117 
 118 class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
 119   int _calls;
 120   G1CollectedHeap* _g1h;
 121   CardTableModRefBS* _ctbs;
 122 public:
 123   RedirtyLoggedCardTableEntryClosure() :
 124     _calls(0)
 125   {
 126     _g1h = G1CollectedHeap::heap();
 127     _ctbs = (CardTableModRefBS*)_g1h->barrier_set();
 128   }
 129   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
 130     if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
 131       _calls++;
 132       *card_ptr = 0;
 133     }
 134     return true;
 135   }
 136   int calls() { return _calls; }
 137 };
 138 
 139 class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
 140 public:
 141   bool do_card_ptr(jbyte* card_ptr, int worker_i) {
 142     *card_ptr = CardTableModRefBS::dirty_card_val();
 143     return true;
 144   }
 145 };
 146 
 147 YoungList::YoungList(G1CollectedHeap* g1h)
 148   : _g1h(g1h), _head(NULL),
 149     _scan_only_head(NULL), _scan_only_tail(NULL), _curr_scan_only(NULL),
 150     _length(0), _scan_only_length(0),
 151     _last_sampled_rs_lengths(0),
 152     _survivor_head(NULL), _survivor_tail(NULL), _survivor_length(0)
 153 {
 154   guarantee( check_list_empty(false), "just making sure..." );
 155 }
 156 
 157 void YoungList::push_region(HeapRegion *hr) {
 158   assert(!hr->is_young(), "should not already be young");
 159   assert(hr->get_next_young_region() == NULL, "cause it should!");
 160 
 161   hr->set_next_young_region(_head);
 162   _head = hr;
 163 
 164   hr->set_young();
 165   double yg_surv_rate = _g1h->g1_policy()->predict_yg_surv_rate((int)_length);
 166   ++_length;
 167 }
 168 
 169 void YoungList::add_survivor_region(HeapRegion* hr) {
 170   assert(hr->is_survivor(), "should be flagged as survivor region");
 171   assert(hr->get_next_young_region() == NULL, "cause it should!");
 172 
 173   hr->set_next_young_region(_survivor_head);
 174   if (_survivor_head == NULL) {
 175     _survivor_tail = hr;
 176   }
 177   _survivor_head = hr;
 178 
 179   ++_survivor_length;
 180 }
 181 
 182 HeapRegion* YoungList::pop_region() {
 183   while (_head != NULL) {
 184     assert( length() > 0, "list should not be empty" );
 185     HeapRegion* ret = _head;
 186     _head = ret->get_next_young_region();
 187     ret->set_next_young_region(NULL);
 188     --_length;
 189     assert(ret->is_young(), "region should be very young");
 190 
 191     // Replace 'Survivor' region type with 'Young'. So the region will
 192     // be treated as a young region and will not be 'confused' with
 193     // newly created survivor regions.
 194     if (ret->is_survivor()) {
 195       ret->set_young();
 196     }
 197 
 198     if (!ret->is_scan_only()) {
 199       return ret;
 200     }
 201 
 202     // scan-only, we'll add it to the scan-only list
 203     if (_scan_only_tail == NULL) {
 204       guarantee( _scan_only_head == NULL, "invariant" );
 205 
 206       _scan_only_head = ret;
 207       _curr_scan_only = ret;
 208     } else {
 209       guarantee( _scan_only_head != NULL, "invariant" );
 210       _scan_only_tail->set_next_young_region(ret);
 211     }
 212     guarantee( ret->get_next_young_region() == NULL, "invariant" );
 213     _scan_only_tail = ret;
 214 
 215     // no need to be tagged as scan-only any more
 216     ret->set_young();
 217 
 218     ++_scan_only_length;
 219   }
 220   assert( length() == 0, "list should be empty" );
 221   return NULL;
 222 }
 223 
 224 void YoungList::empty_list(HeapRegion* list) {
 225   while (list != NULL) {
 226     HeapRegion* next = list->get_next_young_region();
 227     list->set_next_young_region(NULL);
 228     list->uninstall_surv_rate_group();
 229     list->set_not_young();
 230     list = next;
 231   }
 232 }
 233 
 234 void YoungList::empty_list() {
 235   assert(check_list_well_formed(), "young list should be well formed");
 236 
 237   empty_list(_head);
 238   _head = NULL;
 239   _length = 0;
 240 
 241   empty_list(_scan_only_head);
 242   _scan_only_head = NULL;
 243   _scan_only_tail = NULL;
 244   _scan_only_length = 0;
 245   _curr_scan_only = NULL;
 246 
 247   empty_list(_survivor_head);
 248   _survivor_head = NULL;
 249   _survivor_tail = NULL;
 250   _survivor_length = 0;
 251 
 252   _last_sampled_rs_lengths = 0;
 253 
 254   assert(check_list_empty(false), "just making sure...");
 255 }
 256 
 257 bool YoungList::check_list_well_formed() {
 258   bool ret = true;
 259 
 260   size_t length = 0;
 261   HeapRegion* curr = _head;
 262   HeapRegion* last = NULL;
 263   while (curr != NULL) {
 264     if (!curr->is_young() || curr->is_scan_only()) {
 265       gclog_or_tty->print_cr("### YOUNG REGION "PTR_FORMAT"-"PTR_FORMAT" "
 266                              "incorrectly tagged (%d, %d)",
 267                              curr->bottom(), curr->end(),
 268                              curr->is_young(), curr->is_scan_only());
 269       ret = false;
 270     }
 271     ++length;
 272     last = curr;
 273     curr = curr->get_next_young_region();
 274   }
 275   ret = ret && (length == _length);
 276 
 277   if (!ret) {
 278     gclog_or_tty->print_cr("### YOUNG LIST seems not well formed!");
 279     gclog_or_tty->print_cr("###   list has %d entries, _length is %d",
 280                            length, _length);
 281   }
 282 
 283   bool scan_only_ret = true;
 284   length = 0;
 285   curr = _scan_only_head;
 286   last = NULL;
 287   while (curr != NULL) {
 288     if (!curr->is_young() || curr->is_scan_only()) {
 289       gclog_or_tty->print_cr("### SCAN-ONLY REGION "PTR_FORMAT"-"PTR_FORMAT" "
 290                              "incorrectly tagged (%d, %d)",
 291                              curr->bottom(), curr->end(),
 292                              curr->is_young(), curr->is_scan_only());
 293       scan_only_ret = false;
 294     }
 295     ++length;
 296     last = curr;
 297     curr = curr->get_next_young_region();
 298   }
 299   scan_only_ret = scan_only_ret && (length == _scan_only_length);
 300 
 301   if ( (last != _scan_only_tail) ||
 302        (_scan_only_head == NULL && _scan_only_tail != NULL) ||
 303        (_scan_only_head != NULL && _scan_only_tail == NULL) ) {
 304      gclog_or_tty->print_cr("## _scan_only_tail is set incorrectly");
 305      scan_only_ret = false;
 306   }
 307 
 308   if (_curr_scan_only != NULL && _curr_scan_only != _scan_only_head) {
 309     gclog_or_tty->print_cr("### _curr_scan_only is set incorrectly");
 310     scan_only_ret = false;
 311    }
 312 
 313   if (!scan_only_ret) {
 314     gclog_or_tty->print_cr("### SCAN-ONLY LIST seems not well formed!");
 315     gclog_or_tty->print_cr("###   list has %d entries, _scan_only_length is %d",
 316                   length, _scan_only_length);
 317   }
 318 
 319   return ret && scan_only_ret;
 320 }
 321 
 322 bool YoungList::check_list_empty(bool ignore_scan_only_list,
 323                                  bool check_sample) {
 324   bool ret = true;
 325 
 326   if (_length != 0) {
 327     gclog_or_tty->print_cr("### YOUNG LIST should have 0 length, not %d",
 328                   _length);
 329     ret = false;
 330   }
 331   if (check_sample && _last_sampled_rs_lengths != 0) {
 332     gclog_or_tty->print_cr("### YOUNG LIST has non-zero last sampled RS lengths");
 333     ret = false;
 334   }
 335   if (_head != NULL) {
 336     gclog_or_tty->print_cr("### YOUNG LIST does not have a NULL head");
 337     ret = false;
 338   }
 339   if (!ret) {
 340     gclog_or_tty->print_cr("### YOUNG LIST does not seem empty");
 341   }
 342 
 343   if (ignore_scan_only_list)
 344     return ret;
 345 
 346   bool scan_only_ret = true;
 347   if (_scan_only_length != 0) {
 348     gclog_or_tty->print_cr("### SCAN-ONLY LIST should have 0 length, not %d",
 349                   _scan_only_length);
 350     scan_only_ret = false;
 351   }
 352   if (_scan_only_head != NULL) {
 353     gclog_or_tty->print_cr("### SCAN-ONLY LIST does not have a NULL head");
 354      scan_only_ret = false;
 355   }
 356   if (_scan_only_tail != NULL) {
 357     gclog_or_tty->print_cr("### SCAN-ONLY LIST does not have a NULL tail");
 358     scan_only_ret = false;
 359   }
 360   if (!scan_only_ret) {
 361     gclog_or_tty->print_cr("### SCAN-ONLY LIST does not seem empty");
 362   }
 363 
 364   return ret && scan_only_ret;
 365 }
 366 
 367 void
 368 YoungList::rs_length_sampling_init() {
 369   _sampled_rs_lengths = 0;
 370   _curr               = _head;
 371 }
 372 
 373 bool
 374 YoungList::rs_length_sampling_more() {
 375   return _curr != NULL;
 376 }
 377 
 378 void
 379 YoungList::rs_length_sampling_next() {
 380   assert( _curr != NULL, "invariant" );
 381   _sampled_rs_lengths += _curr->rem_set()->occupied();
 382   _curr = _curr->get_next_young_region();
 383   if (_curr == NULL) {
 384     _last_sampled_rs_lengths = _sampled_rs_lengths;
 385     // gclog_or_tty->print_cr("last sampled RS lengths = %d", _last_sampled_rs_lengths);
 386   }
 387 }
 388 
 389 void
 390 YoungList::reset_auxilary_lists() {
 391   // We could have just "moved" the scan-only list to the young list.
 392   // However, the scan-only list is ordered according to the region
 393   // age in descending order, so, by moving one entry at a time, we
 394   // ensure that it is recreated in ascending order.
 395 
 396   guarantee( is_empty(), "young list should be empty" );
 397   assert(check_list_well_formed(), "young list should be well formed");
 398 
 399   // Add survivor regions to SurvRateGroup.
 400   _g1h->g1_policy()->note_start_adding_survivor_regions();
 401   _g1h->g1_policy()->finished_recalculating_age_indexes(true /* is_survivors */);
 402   for (HeapRegion* curr = _survivor_head;
 403        curr != NULL;
 404        curr = curr->get_next_young_region()) {
 405     _g1h->g1_policy()->set_region_survivors(curr);
 406   }
 407   _g1h->g1_policy()->note_stop_adding_survivor_regions();
 408 
 409   if (_survivor_head != NULL) {
 410     _head           = _survivor_head;
 411     _length         = _survivor_length + _scan_only_length;
 412     _survivor_tail->set_next_young_region(_scan_only_head);
 413   } else {
 414     _head           = _scan_only_head;
 415     _length         = _scan_only_length;
 416   }
 417 
 418   for (HeapRegion* curr = _scan_only_head;
 419        curr != NULL;
 420        curr = curr->get_next_young_region()) {
 421     curr->recalculate_age_in_surv_rate_group();
 422   }
 423   _scan_only_head   = NULL;
 424   _scan_only_tail   = NULL;
 425   _scan_only_length = 0;
 426   _curr_scan_only   = NULL;
 427 
 428   _survivor_head    = NULL;
 429   _survivor_tail   = NULL;
 430   _survivor_length  = 0;
 431   _g1h->g1_policy()->finished_recalculating_age_indexes(false /* is_survivors */);
 432 
 433   assert(check_list_well_formed(), "young list should be well formed");
 434 }
 435 
 436 void YoungList::print() {
 437   HeapRegion* lists[] = {_head,   _scan_only_head, _survivor_head};
 438   const char* names[] = {"YOUNG", "SCAN-ONLY",     "SURVIVOR"};
 439 
 440   for (unsigned int list = 0; list < ARRAY_SIZE(lists); ++list) {
 441     gclog_or_tty->print_cr("%s LIST CONTENTS", names[list]);
 442     HeapRegion *curr = lists[list];
 443     if (curr == NULL)
 444       gclog_or_tty->print_cr("  empty");
 445     while (curr != NULL) {
 446       gclog_or_tty->print_cr("  [%08x-%08x], t: %08x, P: %08x, N: %08x, C: %08x, "
 447                              "age: %4d, y: %d, s-o: %d, surv: %d",
 448                              curr->bottom(), curr->end(),
 449                              curr->top(),
 450                              curr->prev_top_at_mark_start(),
 451                              curr->next_top_at_mark_start(),
 452                              curr->top_at_conc_mark_count(),
 453                              curr->age_in_surv_rate_group_cond(),
 454                              curr->is_young(),
 455                              curr->is_scan_only(),
 456                              curr->is_survivor());
 457       curr = curr->get_next_young_region();
 458     }
 459   }
 460 
 461   gclog_or_tty->print_cr("");
 462 }
 463 
 464 void G1CollectedHeap::stop_conc_gc_threads() {
 465   _cg1r->cg1rThread()->stop();
 466   _czft->stop();
 467   _cmThread->stop();
 468 }
 469 
 470 
 471 void G1CollectedHeap::check_ct_logs_at_safepoint() {
 472   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
 473   CardTableModRefBS* ct_bs = (CardTableModRefBS*)barrier_set();
 474 
 475   // Count the dirty cards at the start.
 476   CountNonCleanMemRegionClosure count1(this);
 477   ct_bs->mod_card_iterate(&count1);
 478   int orig_count = count1.n();
 479 
 480   // First clear the logged cards.
 481   ClearLoggedCardTableEntryClosure clear;
 482   dcqs.set_closure(&clear);
 483   dcqs.apply_closure_to_all_completed_buffers();
 484   dcqs.iterate_closure_all_threads(false);
 485   clear.print_histo();
 486 
 487   // Now ensure that there's no dirty cards.
 488   CountNonCleanMemRegionClosure count2(this);
 489   ct_bs->mod_card_iterate(&count2);
 490   if (count2.n() != 0) {
 491     gclog_or_tty->print_cr("Card table has %d entries; %d originally",
 492                            count2.n(), orig_count);
 493   }
 494   guarantee(count2.n() == 0, "Card table should be clean.");
 495 
 496   RedirtyLoggedCardTableEntryClosure redirty;
 497   JavaThread::dirty_card_queue_set().set_closure(&redirty);
 498   dcqs.apply_closure_to_all_completed_buffers();
 499   dcqs.iterate_closure_all_threads(false);
 500   gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
 501                          clear.calls(), orig_count);
 502   guarantee(redirty.calls() == clear.calls(),
 503             "Or else mechanism is broken.");
 504 
 505   CountNonCleanMemRegionClosure count3(this);
 506   ct_bs->mod_card_iterate(&count3);
 507   if (count3.n() != orig_count) {
 508     gclog_or_tty->print_cr("Should have restored them all: orig = %d, final = %d.",
 509                            orig_count, count3.n());
 510     guarantee(count3.n() >= orig_count, "Should have restored them all.");
 511   }
 512 
 513   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
 514 }
 515 
 516 // Private class members.
 517 
 518 G1CollectedHeap* G1CollectedHeap::_g1h;
 519 
 520 // Private methods.
 521 
 522 // Finds a HeapRegion that can be used to allocate a given size of block.
 523 
 524 
 525 HeapRegion* G1CollectedHeap::newAllocRegion_work(size_t word_size,
 526                                                  bool do_expand,
 527                                                  bool zero_filled) {
 528   ConcurrentZFThread::note_region_alloc();
 529   HeapRegion* res = alloc_free_region_from_lists(zero_filled);
 530   if (res == NULL && do_expand) {
 531     expand(word_size * HeapWordSize);
 532     res = alloc_free_region_from_lists(zero_filled);
 533     assert(res == NULL ||
 534            (!res->isHumongous() &&
 535             (!zero_filled ||
 536              res->zero_fill_state() == HeapRegion::Allocated)),
 537            "Alloc Regions must be zero filled (and non-H)");
 538   }
 539   if (res != NULL && res->is_empty()) _free_regions--;
 540   assert(res == NULL ||
 541          (!res->isHumongous() &&
 542           (!zero_filled ||
 543            res->zero_fill_state() == HeapRegion::Allocated)),
 544          "Non-young alloc Regions must be zero filled (and non-H)");
 545 
 546   if (G1TraceRegions) {
 547     if (res != NULL) {
 548       gclog_or_tty->print_cr("new alloc region %d:["PTR_FORMAT", "PTR_FORMAT"], "
 549                              "top "PTR_FORMAT,
 550                              res->hrs_index(), res->bottom(), res->end(), res->top());
 551     }
 552   }
 553 
 554   return res;
 555 }
 556 
 557 HeapRegion* G1CollectedHeap::newAllocRegionWithExpansion(int purpose,
 558                                                          size_t word_size,
 559                                                          bool zero_filled) {
 560   HeapRegion* alloc_region = NULL;
 561   if (_gc_alloc_region_counts[purpose] < g1_policy()->max_regions(purpose)) {
 562     alloc_region = newAllocRegion_work(word_size, true, zero_filled);
 563     if (purpose == GCAllocForSurvived && alloc_region != NULL) {
 564       alloc_region->set_survivor();
 565     }
 566     ++_gc_alloc_region_counts[purpose];
 567   } else {
 568     g1_policy()->note_alloc_region_limit_reached(purpose);
 569   }
 570   return alloc_region;
 571 }
 572 
 573 // If could fit into free regions w/o expansion, try.
 574 // Otherwise, if can expand, do so.
 575 // Otherwise, if using ex regions might help, try with ex given back.
 576 HeapWord* G1CollectedHeap::humongousObjAllocate(size_t word_size) {
 577   assert(regions_accounted_for(), "Region leakage!");
 578 
 579   // We can't allocate H regions while cleanupComplete is running, since
 580   // some of the regions we find to be empty might not yet be added to the
 581   // unclean list.  (If we're already at a safepoint, this call is
 582   // unnecessary, not to mention wrong.)
 583   if (!SafepointSynchronize::is_at_safepoint())
 584     wait_for_cleanup_complete();
 585 
 586   size_t num_regions =
 587     round_to(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
 588 
 589   // Special case if < one region???
 590 
 591   // Remember the ft size.
 592   size_t x_size = expansion_regions();
 593 
 594   HeapWord* res = NULL;
 595   bool eliminated_allocated_from_lists = false;
 596 
 597   // Can the allocation potentially fit in the free regions?
 598   if (free_regions() >= num_regions) {
 599     res = _hrs->obj_allocate(word_size);
 600   }
 601   if (res == NULL) {
 602     // Try expansion.
 603     size_t fs = _hrs->free_suffix();
 604     if (fs + x_size >= num_regions) {
 605       expand((num_regions - fs) * HeapRegion::GrainBytes);
 606       res = _hrs->obj_allocate(word_size);
 607       assert(res != NULL, "This should have worked.");
 608     } else {
 609       // Expansion won't help.  Are there enough free regions if we get rid
 610       // of reservations?
 611       size_t avail = free_regions();
 612       if (avail >= num_regions) {
 613         res = _hrs->obj_allocate(word_size);
 614         if (res != NULL) {
 615           remove_allocated_regions_from_lists();
 616           eliminated_allocated_from_lists = true;
 617         }
 618       }
 619     }
 620   }
 621   if (res != NULL) {
 622     // Increment by the number of regions allocated.
 623     // FIXME: Assumes regions all of size GrainBytes.
 624 #ifndef PRODUCT
 625     mr_bs()->verify_clean_region(MemRegion(res, res + num_regions *
 626                                            HeapRegion::GrainWords));
 627 #endif
 628     if (!eliminated_allocated_from_lists)
 629       remove_allocated_regions_from_lists();
 630     _summary_bytes_used += word_size * HeapWordSize;
 631     _free_regions -= num_regions;
 632     _num_humongous_regions += (int) num_regions;
 633   }
 634   assert(regions_accounted_for(), "Region Leakage");
 635   return res;
 636 }
 637 
 638 HeapWord*
 639 G1CollectedHeap::attempt_allocation_slow(size_t word_size,
 640                                          bool permit_collection_pause) {
 641   HeapWord* res = NULL;
 642   HeapRegion* allocated_young_region = NULL;
 643 
 644   assert( SafepointSynchronize::is_at_safepoint() ||
 645           Heap_lock->owned_by_self(), "pre condition of the call" );
 646 
 647   if (isHumongous(word_size)) {
 648     // Allocation of a humongous object can, in a sense, complete a
 649     // partial region, if the previous alloc was also humongous, and
 650     // caused the test below to succeed.
 651     if (permit_collection_pause)
 652       do_collection_pause_if_appropriate(word_size);
 653     res = humongousObjAllocate(word_size);
 654     assert(_cur_alloc_region == NULL
 655            || !_cur_alloc_region->isHumongous(),
 656            "Prevent a regression of this bug.");
 657 
 658   } else {
 659     // We may have concurrent cleanup working at the time. Wait for it
 660     // to complete. In the future we would probably want to make the
 661     // concurrent cleanup truly concurrent by decoupling it from the
 662     // allocation.
 663     if (!SafepointSynchronize::is_at_safepoint())
 664       wait_for_cleanup_complete();
 665     // If we do a collection pause, this will be reset to a non-NULL
 666     // value.  If we don't, nulling here ensures that we allocate a new
 667     // region below.
 668     if (_cur_alloc_region != NULL) {
 669       // We're finished with the _cur_alloc_region.
 670       _summary_bytes_used += _cur_alloc_region->used();
 671       _cur_alloc_region = NULL;
 672     }
 673     assert(_cur_alloc_region == NULL, "Invariant.");
 674     // Completion of a heap region is perhaps a good point at which to do
 675     // a collection pause.
 676     if (permit_collection_pause)
 677       do_collection_pause_if_appropriate(word_size);
 678     // Make sure we have an allocation region available.
 679     if (_cur_alloc_region == NULL) {
 680       if (!SafepointSynchronize::is_at_safepoint())
 681         wait_for_cleanup_complete();
 682       bool next_is_young = should_set_young_locked();
 683       // If the next region is not young, make sure it's zero-filled.
 684       _cur_alloc_region = newAllocRegion(word_size, !next_is_young);
 685       if (_cur_alloc_region != NULL) {
 686         _summary_bytes_used -= _cur_alloc_region->used();
 687         if (next_is_young) {
 688           set_region_short_lived_locked(_cur_alloc_region);
 689           allocated_young_region = _cur_alloc_region;
 690         }
 691       }
 692     }
 693     assert(_cur_alloc_region == NULL || !_cur_alloc_region->isHumongous(),
 694            "Prevent a regression of this bug.");
 695 
 696     // Now retry the allocation.
 697     if (_cur_alloc_region != NULL) {
 698       res = _cur_alloc_region->allocate(word_size);
 699     }
 700   }
 701 
 702   // NOTE: fails frequently in PRT
 703   assert(regions_accounted_for(), "Region leakage!");
 704 
 705   if (res != NULL) {
 706     if (!SafepointSynchronize::is_at_safepoint()) {
 707       assert( permit_collection_pause, "invariant" );
 708       assert( Heap_lock->owned_by_self(), "invariant" );
 709       Heap_lock->unlock();
 710     }
 711 
 712     if (allocated_young_region != NULL) {
 713       HeapRegion* hr = allocated_young_region;
 714       HeapWord* bottom = hr->bottom();
 715       HeapWord* end = hr->end();
 716       MemRegion mr(bottom, end);
 717       ((CardTableModRefBS*)_g1h->barrier_set())->dirty(mr);
 718     }
 719   }
 720 
 721   assert( SafepointSynchronize::is_at_safepoint() ||
 722           (res == NULL && Heap_lock->owned_by_self()) ||
 723           (res != NULL && !Heap_lock->owned_by_self()),
 724           "post condition of the call" );
 725 
 726   return res;
 727 }
 728 
 729 HeapWord*
 730 G1CollectedHeap::mem_allocate(size_t word_size,
 731                               bool   is_noref,
 732                               bool   is_tlab,
 733                               bool* gc_overhead_limit_was_exceeded) {
 734   debug_only(check_for_valid_allocation_state());
 735   assert(no_gc_in_progress(), "Allocation during gc not allowed");
 736   HeapWord* result = NULL;
 737 
 738   // Loop until the allocation is satisified,
 739   // or unsatisfied after GC.
 740   for (int try_count = 1; /* return or throw */; try_count += 1) {
 741     int gc_count_before;
 742     {
 743       Heap_lock->lock();
 744       result = attempt_allocation(word_size);
 745       if (result != NULL) {
 746         // attempt_allocation should have unlocked the heap lock
 747         assert(is_in(result), "result not in heap");
 748         return result;
 749       }
 750       // Read the gc count while the heap lock is held.
 751       gc_count_before = SharedHeap::heap()->total_collections();
 752       Heap_lock->unlock();
 753     }
 754 
 755     // Create the garbage collection operation...
 756     VM_G1CollectForAllocation op(word_size,
 757                                  gc_count_before);
 758 
 759     // ...and get the VM thread to execute it.
 760     VMThread::execute(&op);
 761     if (op.prologue_succeeded()) {
 762       result = op.result();
 763       assert(result == NULL || is_in(result), "result not in heap");
 764       return result;
 765     }
 766 
 767     // Give a warning if we seem to be looping forever.
 768     if ((QueuedAllocationWarningCount > 0) &&
 769         (try_count % QueuedAllocationWarningCount == 0)) {
 770       warning("G1CollectedHeap::mem_allocate_work retries %d times",
 771               try_count);
 772     }
 773   }
 774 }
 775 
 776 void G1CollectedHeap::abandon_cur_alloc_region() {
 777   if (_cur_alloc_region != NULL) {
 778     // We're finished with the _cur_alloc_region.
 779     if (_cur_alloc_region->is_empty()) {
 780       _free_regions++;
 781       free_region(_cur_alloc_region);
 782     } else {
 783       _summary_bytes_used += _cur_alloc_region->used();
 784     }
 785     _cur_alloc_region = NULL;
 786   }
 787 }
 788 
 789 class PostMCRemSetClearClosure: public HeapRegionClosure {
 790   ModRefBarrierSet* _mr_bs;
 791 public:
 792   PostMCRemSetClearClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
 793   bool doHeapRegion(HeapRegion* r) {
 794     r->reset_gc_time_stamp();
 795     if (r->continuesHumongous())
 796       return false;
 797     HeapRegionRemSet* hrrs = r->rem_set();
 798     if (hrrs != NULL) hrrs->clear();
 799     // You might think here that we could clear just the cards
 800     // corresponding to the used region.  But no: if we leave a dirty card
 801     // in a region we might allocate into, then it would prevent that card
 802     // from being enqueued, and cause it to be missed.
 803     // Re: the performance cost: we shouldn't be doing full GC anyway!
 804     _mr_bs->clear(MemRegion(r->bottom(), r->end()));
 805     return false;
 806   }
 807 };
 808 
 809 
 810 class PostMCRemSetInvalidateClosure: public HeapRegionClosure {
 811   ModRefBarrierSet* _mr_bs;
 812 public:
 813   PostMCRemSetInvalidateClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {}
 814   bool doHeapRegion(HeapRegion* r) {
 815     if (r->continuesHumongous()) return false;
 816     if (r->used_region().word_size() != 0) {
 817       _mr_bs->invalidate(r->used_region(), true /*whole heap*/);
 818     }
 819     return false;
 820   }
 821 };
 822 
 823 class RebuildRSOutOfRegionClosure: public HeapRegionClosure {
 824   G1CollectedHeap*   _g1h;
 825   UpdateRSOopClosure _cl;
 826   int                _worker_i;
 827 public:
 828   RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) :
 829     _cl(g1->g1_rem_set()->as_HRInto_G1RemSet(), worker_i),
 830     _worker_i(worker_i),
 831     _g1h(g1)
 832   { }
 833   bool doHeapRegion(HeapRegion* r) {
 834     if (!r->continuesHumongous()) {
 835       _cl.set_from(r);
 836       r->oop_iterate(&_cl);
 837     }
 838     return false;
 839   }
 840 };
 841 
 842 class ParRebuildRSTask: public AbstractGangTask {
 843   G1CollectedHeap* _g1;
 844 public:
 845   ParRebuildRSTask(G1CollectedHeap* g1)
 846     : AbstractGangTask("ParRebuildRSTask"),
 847       _g1(g1)
 848   { }
 849 
 850   void work(int i) {
 851     RebuildRSOutOfRegionClosure rebuild_rs(_g1, i);
 852     _g1->heap_region_par_iterate_chunked(&rebuild_rs, i,
 853                                          HeapRegion::RebuildRSClaimValue);
 854   }
 855 };
 856 
 857 void G1CollectedHeap::do_collection(bool full, bool clear_all_soft_refs,
 858                                     size_t word_size) {
 859   ResourceMark rm;
 860 
 861   if (full && DisableExplicitGC) {
 862     gclog_or_tty->print("\n\n\nDisabling Explicit GC\n\n\n");
 863     return;
 864   }
 865 
 866   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 867   assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
 868 
 869   if (GC_locker::is_active()) {
 870     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
 871   }
 872 
 873   {
 874     IsGCActiveMark x;
 875 
 876     // Timing
 877     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
 878     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
 879     TraceTime t(full ? "Full GC (System.gc())" : "Full GC", PrintGC, true, gclog_or_tty);
 880 
 881     double start = os::elapsedTime();
 882     GCOverheadReporter::recordSTWStart(start);
 883     g1_policy()->record_full_collection_start();
 884 
 885     gc_prologue(true);
 886     increment_total_collections();
 887 
 888     size_t g1h_prev_used = used();
 889     assert(used() == recalculate_used(), "Should be equal");
 890 
 891     if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
 892       HandleMark hm;  // Discard invalid handles created during verification
 893       prepare_for_verify();
 894       gclog_or_tty->print(" VerifyBeforeGC:");
 895       Universe::verify(true);
 896     }
 897     assert(regions_accounted_for(), "Region leakage!");
 898 
 899     COMPILER2_PRESENT(DerivedPointerTable::clear());
 900 
 901     // We want to discover references, but not process them yet.
 902     // This mode is disabled in
 903     // instanceRefKlass::process_discovered_references if the
 904     // generation does some collection work, or
 905     // instanceRefKlass::enqueue_discovered_references if the
 906     // generation returns without doing any work.
 907     ref_processor()->disable_discovery();
 908     ref_processor()->abandon_partial_discovery();
 909     ref_processor()->verify_no_references_recorded();
 910 
 911     // Abandon current iterations of concurrent marking and concurrent
 912     // refinement, if any are in progress.
 913     concurrent_mark()->abort();
 914 
 915     // Make sure we'll choose a new allocation region afterwards.
 916     abandon_cur_alloc_region();
 917     assert(_cur_alloc_region == NULL, "Invariant.");
 918     g1_rem_set()->as_HRInto_G1RemSet()->cleanupHRRS();
 919     tear_down_region_lists();
 920     set_used_regions_to_need_zero_fill();
 921     if (g1_policy()->in_young_gc_mode()) {
 922       empty_young_list();
 923       g1_policy()->set_full_young_gcs(true);
 924     }
 925 
 926     // Temporarily make reference _discovery_ single threaded (non-MT).
 927     ReferenceProcessorMTMutator rp_disc_ser(ref_processor(), false);
 928 
 929     // Temporarily make refs discovery atomic
 930     ReferenceProcessorAtomicMutator rp_disc_atomic(ref_processor(), true);
 931 
 932     // Temporarily clear _is_alive_non_header
 933     ReferenceProcessorIsAliveMutator rp_is_alive_null(ref_processor(), NULL);
 934 
 935     ref_processor()->enable_discovery();
 936     ref_processor()->setup_policy(clear_all_soft_refs);
 937 
 938     // Do collection work
 939     {
 940       HandleMark hm;  // Discard invalid handles created during gc
 941       G1MarkSweep::invoke_at_safepoint(ref_processor(), clear_all_soft_refs);
 942     }
 943     // Because freeing humongous regions may have added some unclean
 944     // regions, it is necessary to tear down again before rebuilding.
 945     tear_down_region_lists();
 946     rebuild_region_lists();
 947 
 948     _summary_bytes_used = recalculate_used();
 949 
 950     ref_processor()->enqueue_discovered_references();
 951 
 952     COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 953 
 954     if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
 955       HandleMark hm;  // Discard invalid handles created during verification
 956       gclog_or_tty->print(" VerifyAfterGC:");
 957       Universe::verify(false);
 958     }
 959     NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 960 
 961     reset_gc_time_stamp();
 962     // Since everything potentially moved, we will clear all remembered
 963     // sets, and clear all cards.  Later we will rebuild remebered
 964     // sets. We will also reset the GC time stamps of the regions.
 965     PostMCRemSetClearClosure rs_clear(mr_bs());
 966     heap_region_iterate(&rs_clear);
 967 
 968     // Resize the heap if necessary.
 969     resize_if_necessary_after_full_collection(full ? 0 : word_size);
 970 
 971     if (_cg1r->use_cache()) {
 972       _cg1r->clear_and_record_card_counts();
 973       _cg1r->clear_hot_cache();
 974     }
 975 
 976     // Rebuild remembered sets of all regions.
 977     if (ParallelGCThreads > 0) {
 978       ParRebuildRSTask rebuild_rs_task(this);
 979       assert(check_heap_region_claim_values(
 980              HeapRegion::InitialClaimValue), "sanity check");
 981       set_par_threads(workers()->total_workers());
 982       workers()->run_task(&rebuild_rs_task);
 983       set_par_threads(0);
 984       assert(check_heap_region_claim_values(
 985              HeapRegion::RebuildRSClaimValue), "sanity check");
 986       reset_heap_region_claim_values();
 987     } else {
 988       RebuildRSOutOfRegionClosure rebuild_rs(this);
 989       heap_region_iterate(&rebuild_rs);
 990     }
 991 
 992     if (PrintGC) {
 993       print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity());
 994     }
 995 
 996     if (true) { // FIXME
 997       // Ask the permanent generation to adjust size for full collections
 998       perm()->compute_new_size();
 999     }
1000 
1001     double end = os::elapsedTime();
1002     GCOverheadReporter::recordSTWEnd(end);
1003     g1_policy()->record_full_collection_end();
1004 
1005 #ifdef TRACESPINNING
1006     ParallelTaskTerminator::print_termination_counts();
1007 #endif
1008 
1009     gc_epilogue(true);
1010 
1011     // Abandon concurrent refinement.  This must happen last: in the
1012     // dirty-card logging system, some cards may be dirty by weak-ref
1013     // processing, and may be enqueued.  But the whole card table is
1014     // dirtied, so this should abandon those logs, and set "do_traversal"
1015     // to true.
1016     concurrent_g1_refine()->set_pya_restart();
1017     assert(!G1DeferredRSUpdate
1018            || (G1DeferredRSUpdate && (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
1019     assert(regions_accounted_for(), "Region leakage!");
1020   }
1021 
1022   if (g1_policy()->in_young_gc_mode()) {
1023     _young_list->reset_sampled_info();
1024     assert( check_young_list_empty(false, false),
1025             "young list should be empty at this point");
1026   }
1027 }
1028 
1029 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1030   do_collection(true, clear_all_soft_refs, 0);
1031 }
1032 
1033 // This code is mostly copied from TenuredGeneration.
1034 void
1035 G1CollectedHeap::
1036 resize_if_necessary_after_full_collection(size_t word_size) {
1037   assert(MinHeapFreeRatio <= MaxHeapFreeRatio, "sanity check");
1038 
1039   // Include the current allocation, if any, and bytes that will be
1040   // pre-allocated to support collections, as "used".
1041   const size_t used_after_gc = used();
1042   const size_t capacity_after_gc = capacity();
1043   const size_t free_after_gc = capacity_after_gc - used_after_gc;
1044 
1045   // We don't have floating point command-line arguments
1046   const double minimum_free_percentage = (double) MinHeapFreeRatio / 100;
1047   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1048   const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100;
1049   const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1050 
1051   size_t minimum_desired_capacity = (size_t) (used_after_gc / maximum_used_percentage);
1052   size_t maximum_desired_capacity = (size_t) (used_after_gc / minimum_used_percentage);
1053 
1054   // Don't shrink less than the initial size.
1055   minimum_desired_capacity =
1056     MAX2(minimum_desired_capacity,
1057          collector_policy()->initial_heap_byte_size());
1058   maximum_desired_capacity =
1059     MAX2(maximum_desired_capacity,
1060          collector_policy()->initial_heap_byte_size());
1061 
1062   // We are failing here because minimum_desired_capacity is
1063   assert(used_after_gc <= minimum_desired_capacity, "sanity check");
1064   assert(minimum_desired_capacity <= maximum_desired_capacity, "sanity check");
1065 
1066   if (PrintGC && Verbose) {
1067     const double free_percentage = ((double)free_after_gc) / capacity();
1068     gclog_or_tty->print_cr("Computing new size after full GC ");
1069     gclog_or_tty->print_cr("  "
1070                            "  minimum_free_percentage: %6.2f",
1071                            minimum_free_percentage);
1072     gclog_or_tty->print_cr("  "
1073                            "  maximum_free_percentage: %6.2f",
1074                            maximum_free_percentage);
1075     gclog_or_tty->print_cr("  "
1076                            "  capacity: %6.1fK"
1077                            "  minimum_desired_capacity: %6.1fK"
1078                            "  maximum_desired_capacity: %6.1fK",
1079                            capacity() / (double) K,
1080                            minimum_desired_capacity / (double) K,
1081                            maximum_desired_capacity / (double) K);
1082     gclog_or_tty->print_cr("  "
1083                            "   free_after_gc   : %6.1fK"
1084                            "   used_after_gc   : %6.1fK",
1085                            free_after_gc / (double) K,
1086                            used_after_gc / (double) K);
1087     gclog_or_tty->print_cr("  "
1088                            "   free_percentage: %6.2f",
1089                            free_percentage);
1090   }
1091   if (capacity() < minimum_desired_capacity) {
1092     // Don't expand unless it's significant
1093     size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
1094     expand(expand_bytes);
1095     if (PrintGC && Verbose) {
1096       gclog_or_tty->print_cr("    expanding:"
1097                              "  minimum_desired_capacity: %6.1fK"
1098                              "  expand_bytes: %6.1fK",
1099                              minimum_desired_capacity / (double) K,
1100                              expand_bytes / (double) K);
1101     }
1102 
1103     // No expansion, now see if we want to shrink
1104   } else if (capacity() > maximum_desired_capacity) {
1105     // Capacity too large, compute shrinking size
1106     size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity;
1107     shrink(shrink_bytes);
1108     if (PrintGC && Verbose) {
1109       gclog_or_tty->print_cr("  "
1110                              "  shrinking:"
1111                              "  initSize: %.1fK"
1112                              "  maximum_desired_capacity: %.1fK",
1113                              collector_policy()->initial_heap_byte_size() / (double) K,
1114                              maximum_desired_capacity / (double) K);
1115       gclog_or_tty->print_cr("  "
1116                              "  shrink_bytes: %.1fK",
1117                              shrink_bytes / (double) K);
1118     }
1119   }
1120 }
1121 
1122 
1123 HeapWord*
1124 G1CollectedHeap::satisfy_failed_allocation(size_t word_size) {
1125   HeapWord* result = NULL;
1126 
1127   // In a G1 heap, we're supposed to keep allocation from failing by
1128   // incremental pauses.  Therefore, at least for now, we'll favor
1129   // expansion over collection.  (This might change in the future if we can
1130   // do something smarter than full collection to satisfy a failed alloc.)
1131 
1132   result = expand_and_allocate(word_size);
1133   if (result != NULL) {
1134     assert(is_in(result), "result not in heap");
1135     return result;
1136   }
1137 
1138   // OK, I guess we have to try collection.
1139 
1140   do_collection(false, false, word_size);
1141 
1142   result = attempt_allocation(word_size, /*permit_collection_pause*/false);
1143 
1144   if (result != NULL) {
1145     assert(is_in(result), "result not in heap");
1146     return result;
1147   }
1148 
1149   // Try collecting soft references.
1150   do_collection(false, true, word_size);
1151   result = attempt_allocation(word_size, /*permit_collection_pause*/false);
1152   if (result != NULL) {
1153     assert(is_in(result), "result not in heap");
1154     return result;
1155   }
1156 
1157   // What else?  We might try synchronous finalization later.  If the total
1158   // space available is large enough for the allocation, then a more
1159   // complete compaction phase than we've tried so far might be
1160   // appropriate.
1161   return NULL;
1162 }
1163 
1164 // Attempting to expand the heap sufficiently
1165 // to support an allocation of the given "word_size".  If
1166 // successful, perform the allocation and return the address of the
1167 // allocated block, or else "NULL".
1168 
1169 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1170   size_t expand_bytes = word_size * HeapWordSize;
1171   if (expand_bytes < MinHeapDeltaBytes) {
1172     expand_bytes = MinHeapDeltaBytes;
1173   }
1174   expand(expand_bytes);
1175   assert(regions_accounted_for(), "Region leakage!");
1176   HeapWord* result = attempt_allocation(word_size, false /* permit_collection_pause */);
1177   return result;
1178 }
1179 
1180 size_t G1CollectedHeap::free_region_if_totally_empty(HeapRegion* hr) {
1181   size_t pre_used = 0;
1182   size_t cleared_h_regions = 0;
1183   size_t freed_regions = 0;
1184   UncleanRegionList local_list;
1185   free_region_if_totally_empty_work(hr, pre_used, cleared_h_regions,
1186                                     freed_regions, &local_list);
1187 
1188   finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
1189                           &local_list);
1190   return pre_used;
1191 }
1192 
1193 void
1194 G1CollectedHeap::free_region_if_totally_empty_work(HeapRegion* hr,
1195                                                    size_t& pre_used,
1196                                                    size_t& cleared_h,
1197                                                    size_t& freed_regions,
1198                                                    UncleanRegionList* list,
1199                                                    bool par) {
1200   assert(!hr->continuesHumongous(), "should have filtered these out");
1201   size_t res = 0;
1202   if (!hr->popular() && hr->used() > 0 && hr->garbage_bytes() == hr->used()) {
1203     if (!hr->is_young()) {
1204       if (G1PolicyVerbose > 0)
1205         gclog_or_tty->print_cr("Freeing empty region "PTR_FORMAT "(" SIZE_FORMAT " bytes)"
1206                                " during cleanup", hr, hr->used());
1207       free_region_work(hr, pre_used, cleared_h, freed_regions, list, par);
1208     }
1209   }
1210 }
1211 
1212 // FIXME: both this and shrink could probably be more efficient by
1213 // doing one "VirtualSpace::expand_by" call rather than several.
1214 void G1CollectedHeap::expand(size_t expand_bytes) {
1215   size_t old_mem_size = _g1_storage.committed_size();
1216   // We expand by a minimum of 1K.
1217   expand_bytes = MAX2(expand_bytes, (size_t)K);
1218   size_t aligned_expand_bytes =
1219     ReservedSpace::page_align_size_up(expand_bytes);
1220   aligned_expand_bytes = align_size_up(aligned_expand_bytes,
1221                                        HeapRegion::GrainBytes);
1222   expand_bytes = aligned_expand_bytes;
1223   while (expand_bytes > 0) {
1224     HeapWord* base = (HeapWord*)_g1_storage.high();
1225     // Commit more storage.
1226     bool successful = _g1_storage.expand_by(HeapRegion::GrainBytes);
1227     if (!successful) {
1228         expand_bytes = 0;
1229     } else {
1230       expand_bytes -= HeapRegion::GrainBytes;
1231       // Expand the committed region.
1232       HeapWord* high = (HeapWord*) _g1_storage.high();
1233       _g1_committed.set_end(high);
1234       // Create a new HeapRegion.
1235       MemRegion mr(base, high);
1236       bool is_zeroed = !_g1_max_committed.contains(base);
1237       HeapRegion* hr = new HeapRegion(_bot_shared, mr, is_zeroed);
1238 
1239       // Now update max_committed if necessary.
1240       _g1_max_committed.set_end(MAX2(_g1_max_committed.end(), high));
1241 
1242       // Add it to the HeapRegionSeq.
1243       _hrs->insert(hr);
1244       // Set the zero-fill state, according to whether it's already
1245       // zeroed.
1246       {
1247         MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
1248         if (is_zeroed) {
1249           hr->set_zero_fill_complete();
1250           put_free_region_on_list_locked(hr);
1251         } else {
1252           hr->set_zero_fill_needed();
1253           put_region_on_unclean_list_locked(hr);
1254         }
1255       }
1256       _free_regions++;
1257       // And we used up an expansion region to create it.
1258       _expansion_regions--;
1259       // Tell the cardtable about it.
1260       Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1261       // And the offset table as well.
1262       _bot_shared->resize(_g1_committed.word_size());
1263     }
1264   }
1265   if (Verbose && PrintGC) {
1266     size_t new_mem_size = _g1_storage.committed_size();
1267     gclog_or_tty->print_cr("Expanding garbage-first heap from %ldK by %ldK to %ldK",
1268                            old_mem_size/K, aligned_expand_bytes/K,
1269                            new_mem_size/K);
1270   }
1271 }
1272 
1273 void G1CollectedHeap::shrink_helper(size_t shrink_bytes)
1274 {
1275   size_t old_mem_size = _g1_storage.committed_size();
1276   size_t aligned_shrink_bytes =
1277     ReservedSpace::page_align_size_down(shrink_bytes);
1278   aligned_shrink_bytes = align_size_down(aligned_shrink_bytes,
1279                                          HeapRegion::GrainBytes);
1280   size_t num_regions_deleted = 0;
1281   MemRegion mr = _hrs->shrink_by(aligned_shrink_bytes, num_regions_deleted);
1282 
1283   assert(mr.end() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
1284   if (mr.byte_size() > 0)
1285     _g1_storage.shrink_by(mr.byte_size());
1286   assert(mr.start() == (HeapWord*)_g1_storage.high(), "Bad shrink!");
1287 
1288   _g1_committed.set_end(mr.start());
1289   _free_regions -= num_regions_deleted;
1290   _expansion_regions += num_regions_deleted;
1291 
1292   // Tell the cardtable about it.
1293   Universe::heap()->barrier_set()->resize_covered_region(_g1_committed);
1294 
1295   // And the offset table as well.
1296   _bot_shared->resize(_g1_committed.word_size());
1297 
1298   HeapRegionRemSet::shrink_heap(n_regions());
1299 
1300   if (Verbose && PrintGC) {
1301     size_t new_mem_size = _g1_storage.committed_size();
1302     gclog_or_tty->print_cr("Shrinking garbage-first heap from %ldK by %ldK to %ldK",
1303                            old_mem_size/K, aligned_shrink_bytes/K,
1304                            new_mem_size/K);
1305   }
1306 }
1307 
1308 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1309   release_gc_alloc_regions();
1310   tear_down_region_lists();  // We will rebuild them in a moment.
1311   shrink_helper(shrink_bytes);
1312   rebuild_region_lists();
1313 }
1314 
1315 // Public methods.
1316 
1317 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
1318 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
1319 #endif // _MSC_VER
1320 
1321 
1322 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
1323   SharedHeap(policy_),
1324   _g1_policy(policy_),
1325   _ref_processor(NULL),
1326   _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
1327   _bot_shared(NULL),
1328   _par_alloc_during_gc_lock(Mutex::leaf, "par alloc during GC lock"),
1329   _objs_with_preserved_marks(NULL), _preserved_marks_of_objs(NULL),
1330   _evac_failure_scan_stack(NULL) ,
1331   _mark_in_progress(false),
1332   _cg1r(NULL), _czft(NULL), _summary_bytes_used(0),
1333   _cur_alloc_region(NULL),
1334   _refine_cte_cl(NULL),
1335   _free_region_list(NULL), _free_region_list_size(0),
1336   _free_regions(0),
1337   _popular_object_boundary(NULL),
1338   _cur_pop_hr_index(0),
1339   _popular_regions_to_be_evacuated(NULL),
1340   _pop_obj_rc_at_copy(),
1341   _full_collection(false),
1342   _unclean_region_list(),
1343   _unclean_regions_coming(false),
1344   _young_list(new YoungList(this)),
1345   _gc_time_stamp(0),
1346   _surviving_young_words(NULL),
1347   _in_cset_fast_test(NULL),
1348   _in_cset_fast_test_base(NULL)
1349 {
1350   _g1h = this; // To catch bugs.
1351   if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) {
1352     vm_exit_during_initialization("Failed necessary allocation.");
1353   }
1354   int n_queues = MAX2((int)ParallelGCThreads, 1);
1355   _task_queues = new RefToScanQueueSet(n_queues);
1356 
1357   int n_rem_sets = HeapRegionRemSet::num_par_rem_sets();
1358   assert(n_rem_sets > 0, "Invariant.");
1359 
1360   HeapRegionRemSetIterator** iter_arr =
1361     NEW_C_HEAP_ARRAY(HeapRegionRemSetIterator*, n_queues);
1362   for (int i = 0; i < n_queues; i++) {
1363     iter_arr[i] = new HeapRegionRemSetIterator();
1364   }
1365   _rem_set_iterator = iter_arr;
1366 
1367   for (int i = 0; i < n_queues; i++) {
1368     RefToScanQueue* q = new RefToScanQueue();
1369     q->initialize();
1370     _task_queues->register_queue(i, q);
1371   }
1372 
1373   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
1374     _gc_alloc_regions[ap]       = NULL;
1375     _gc_alloc_region_counts[ap] = 0;
1376   }
1377   guarantee(_task_queues != NULL, "task_queues allocation failure.");
1378 }
1379 
1380 jint G1CollectedHeap::initialize() {
1381   os::enable_vtime();
1382 
1383   // Necessary to satisfy locking discipline assertions.
1384 
1385   MutexLocker x(Heap_lock);
1386 
1387   // While there are no constraints in the GC code that HeapWordSize
1388   // be any particular value, there are multiple other areas in the
1389   // system which believe this to be true (e.g. oop->object_size in some
1390   // cases incorrectly returns the size in wordSize units rather than
1391   // HeapWordSize).
1392   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1393 
1394   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
1395   size_t max_byte_size = collector_policy()->max_heap_byte_size();
1396 
1397   // Ensure that the sizes are properly aligned.
1398   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1399   Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
1400 
1401   // We allocate this in any case, but only do no work if the command line
1402   // param is off.
1403   _cg1r = new ConcurrentG1Refine();
1404 
1405   // Reserve the maximum.
1406   PermanentGenerationSpec* pgs = collector_policy()->permanent_generation();
1407   // Includes the perm-gen.
1408   ReservedSpace heap_rs(max_byte_size + pgs->max_size(),
1409                         HeapRegion::GrainBytes,
1410                         false /*ism*/);
1411 
1412   if (!heap_rs.is_reserved()) {
1413     vm_exit_during_initialization("Could not reserve enough space for object heap");
1414     return JNI_ENOMEM;
1415   }
1416 
1417   // It is important to do this in a way such that concurrent readers can't
1418   // temporarily think somethings in the heap.  (I've actually seen this
1419   // happen in asserts: DLD.)
1420   _reserved.set_word_size(0);
1421   _reserved.set_start((HeapWord*)heap_rs.base());
1422   _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
1423 
1424   _expansion_regions = max_byte_size/HeapRegion::GrainBytes;
1425 
1426   _num_humongous_regions = 0;
1427 
1428   // Create the gen rem set (and barrier set) for the entire reserved region.
1429   _rem_set = collector_policy()->create_rem_set(_reserved, 2);
1430   set_barrier_set(rem_set()->bs());
1431   if (barrier_set()->is_a(BarrierSet::ModRef)) {
1432     _mr_bs = (ModRefBarrierSet*)_barrier_set;
1433   } else {
1434     vm_exit_during_initialization("G1 requires a mod ref bs.");
1435     return JNI_ENOMEM;
1436   }
1437 
1438   // Also create a G1 rem set.
1439   if (G1UseHRIntoRS) {
1440     if (mr_bs()->is_a(BarrierSet::CardTableModRef)) {
1441       _g1_rem_set = new HRInto_G1RemSet(this, (CardTableModRefBS*)mr_bs());
1442     } else {
1443       vm_exit_during_initialization("G1 requires a cardtable mod ref bs.");
1444       return JNI_ENOMEM;
1445     }
1446   } else {
1447     _g1_rem_set = new StupidG1RemSet(this);
1448   }
1449 
1450   // Carve out the G1 part of the heap.
1451 
1452   ReservedSpace g1_rs   = heap_rs.first_part(max_byte_size);
1453   _g1_reserved = MemRegion((HeapWord*)g1_rs.base(),
1454                            g1_rs.size()/HeapWordSize);
1455   ReservedSpace perm_gen_rs = heap_rs.last_part(max_byte_size);
1456 
1457   _perm_gen = pgs->init(perm_gen_rs, pgs->init_size(), rem_set());
1458 
1459   _g1_storage.initialize(g1_rs, 0);
1460   _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0);
1461   _g1_max_committed = _g1_committed;
1462   _hrs = new HeapRegionSeq(_expansion_regions);
1463   guarantee(_hrs != NULL, "Couldn't allocate HeapRegionSeq");
1464   guarantee(_cur_alloc_region == NULL, "from constructor");
1465 
1466   _bot_shared = new G1BlockOffsetSharedArray(_reserved,
1467                                              heap_word_size(init_byte_size));
1468 
1469   _g1h = this;
1470 
1471   // Create the ConcurrentMark data structure and thread.
1472   // (Must do this late, so that "max_regions" is defined.)
1473   _cm       = new ConcurrentMark(heap_rs, (int) max_regions());
1474   _cmThread = _cm->cmThread();
1475 
1476   // ...and the concurrent zero-fill thread, if necessary.
1477   if (G1ConcZeroFill) {
1478     _czft = new ConcurrentZFThread();
1479   }
1480 
1481 
1482 
1483   // Allocate the popular regions; take them off free lists.
1484   size_t pop_byte_size = G1NumPopularRegions * HeapRegion::GrainBytes;
1485   expand(pop_byte_size);
1486   _popular_object_boundary =
1487     _g1_reserved.start() + (G1NumPopularRegions * HeapRegion::GrainWords);
1488   for (int i = 0; i < G1NumPopularRegions; i++) {
1489     HeapRegion* hr = newAllocRegion(HeapRegion::GrainWords);
1490     //    assert(hr != NULL && hr->bottom() < _popular_object_boundary,
1491     //     "Should be enough, and all should be below boundary.");
1492     hr->set_popular(true);
1493   }
1494   assert(_cur_pop_hr_index == 0, "Start allocating at the first region.");
1495 
1496   // Initialize the from_card cache structure of HeapRegionRemSet.
1497   HeapRegionRemSet::init_heap(max_regions());
1498 
1499   // Now expand into the rest of the initial heap size.
1500   expand(init_byte_size - pop_byte_size);
1501 
1502   // Perform any initialization actions delegated to the policy.
1503   g1_policy()->init();
1504 
1505   g1_policy()->note_start_of_mark_thread();
1506 
1507   _refine_cte_cl =
1508     new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
1509                                     g1_rem_set(),
1510                                     concurrent_g1_refine());
1511   JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
1512 
1513   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
1514                                                SATB_Q_FL_lock,
1515                                                0,
1516                                                Shared_SATB_Q_lock);
1517   if (G1RSBarrierUseQueue) {
1518     JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
1519                                                   DirtyCardQ_FL_lock,
1520                                                   G1DirtyCardQueueMax,
1521                                                   Shared_DirtyCardQ_lock);
1522   }
1523   if (G1DeferredRSUpdate) {
1524     dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
1525                                       DirtyCardQ_FL_lock,
1526                                       0,
1527                                       Shared_DirtyCardQ_lock,
1528                                       &JavaThread::dirty_card_queue_set());
1529   }
1530   // In case we're keeping closure specialization stats, initialize those
1531   // counts and that mechanism.
1532   SpecializationStats::clear();
1533 
1534   _gc_alloc_region_list = NULL;
1535 
1536   // Do later initialization work for concurrent refinement.
1537   _cg1r->init();
1538 
1539   const char* group_names[] = { "CR", "ZF", "CM", "CL" };
1540   GCOverheadReporter::initGCOverheadReporter(4, group_names);
1541 
1542   return JNI_OK;
1543 }
1544 
1545 void G1CollectedHeap::ref_processing_init() {
1546   SharedHeap::ref_processing_init();
1547   MemRegion mr = reserved_region();
1548   _ref_processor = ReferenceProcessor::create_ref_processor(
1549                                          mr,    // span
1550                                          false, // Reference discovery is not atomic
1551                                                 // (though it shouldn't matter here.)
1552                                          true,  // mt_discovery
1553                                          NULL,  // is alive closure: need to fill this in for efficiency
1554                                          ParallelGCThreads,
1555                                          ParallelRefProcEnabled,
1556                                          true); // Setting next fields of discovered
1557                                                 // lists requires a barrier.
1558 }
1559 
1560 size_t G1CollectedHeap::capacity() const {
1561   return _g1_committed.byte_size();
1562 }
1563 
1564 void G1CollectedHeap::iterate_dirty_card_closure(bool concurrent,
1565                                                  int worker_i) {
1566   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
1567   int n_completed_buffers = 0;
1568   while (dcqs.apply_closure_to_completed_buffer(worker_i, 0, true)) {
1569     n_completed_buffers++;
1570   }
1571   g1_policy()->record_update_rs_processed_buffers(worker_i,
1572                                                   (double) n_completed_buffers);
1573   dcqs.clear_n_completed_buffers();
1574   // Finish up the queue...
1575   if (worker_i == 0) concurrent_g1_refine()->clean_up_cache(worker_i,
1576                                                             g1_rem_set());
1577   assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!");
1578 }
1579 
1580 
1581 // Computes the sum of the storage used by the various regions.
1582 
1583 size_t G1CollectedHeap::used() const {
1584   assert(Heap_lock->owner() != NULL,
1585          "Should be owned on this thread's behalf.");
1586   size_t result = _summary_bytes_used;
1587   if (_cur_alloc_region != NULL)
1588     result += _cur_alloc_region->used();
1589   return result;
1590 }
1591 
1592 class SumUsedClosure: public HeapRegionClosure {
1593   size_t _used;
1594 public:
1595   SumUsedClosure() : _used(0) {}
1596   bool doHeapRegion(HeapRegion* r) {
1597     if (!r->continuesHumongous()) {
1598       _used += r->used();
1599     }
1600     return false;
1601   }
1602   size_t result() { return _used; }
1603 };
1604 
1605 size_t G1CollectedHeap::recalculate_used() const {
1606   SumUsedClosure blk;
1607   _hrs->iterate(&blk);
1608   return blk.result();
1609 }
1610 
1611 #ifndef PRODUCT
1612 class SumUsedRegionsClosure: public HeapRegionClosure {
1613   size_t _num;
1614 public:
1615   // _num is set to 1 to account for the popular region
1616   SumUsedRegionsClosure() : _num(G1NumPopularRegions) {}
1617   bool doHeapRegion(HeapRegion* r) {
1618     if (r->continuesHumongous() || r->used() > 0 || r->is_gc_alloc_region()) {
1619       _num += 1;
1620     }
1621     return false;
1622   }
1623   size_t result() { return _num; }
1624 };
1625 
1626 size_t G1CollectedHeap::recalculate_used_regions() const {
1627   SumUsedRegionsClosure blk;
1628   _hrs->iterate(&blk);
1629   return blk.result();
1630 }
1631 #endif // PRODUCT
1632 
1633 size_t G1CollectedHeap::unsafe_max_alloc() {
1634   if (_free_regions > 0) return HeapRegion::GrainBytes;
1635   // otherwise, is there space in the current allocation region?
1636 
1637   // We need to store the current allocation region in a local variable
1638   // here. The problem is that this method doesn't take any locks and
1639   // there may be other threads which overwrite the current allocation
1640   // region field. attempt_allocation(), for example, sets it to NULL
1641   // and this can happen *after* the NULL check here but before the call
1642   // to free(), resulting in a SIGSEGV. Note that this doesn't appear
1643   // to be a problem in the optimized build, since the two loads of the
1644   // current allocation region field are optimized away.
1645   HeapRegion* car = _cur_alloc_region;
1646 
1647   // FIXME: should iterate over all regions?
1648   if (car == NULL) {
1649     return 0;
1650   }
1651   return car->free();
1652 }
1653 
1654 void G1CollectedHeap::collect(GCCause::Cause cause) {
1655   // The caller doesn't have the Heap_lock
1656   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
1657   MutexLocker ml(Heap_lock);
1658   collect_locked(cause);
1659 }
1660 
1661 void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) {
1662   assert(Thread::current()->is_VM_thread(), "Precondition#1");
1663   assert(Heap_lock->is_locked(), "Precondition#2");
1664   GCCauseSetter gcs(this, cause);
1665   switch (cause) {
1666     case GCCause::_heap_inspection:
1667     case GCCause::_heap_dump: {
1668       HandleMark hm;
1669       do_full_collection(false);         // don't clear all soft refs
1670       break;
1671     }
1672     default: // XXX FIX ME
1673       ShouldNotReachHere(); // Unexpected use of this function
1674   }
1675 }
1676 
1677 
1678 void G1CollectedHeap::collect_locked(GCCause::Cause cause) {
1679   // Don't want to do a GC until cleanup is completed.
1680   wait_for_cleanup_complete();
1681 
1682   // Read the GC count while holding the Heap_lock
1683   int gc_count_before = SharedHeap::heap()->total_collections();
1684   {
1685     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
1686     VM_G1CollectFull op(gc_count_before, cause);
1687     VMThread::execute(&op);
1688   }
1689 }
1690 
1691 bool G1CollectedHeap::is_in(const void* p) const {
1692   if (_g1_committed.contains(p)) {
1693     HeapRegion* hr = _hrs->addr_to_region(p);
1694     return hr->is_in(p);
1695   } else {
1696     return _perm_gen->as_gen()->is_in(p);
1697   }
1698 }
1699 
1700 // Iteration functions.
1701 
1702 // Iterates an OopClosure over all ref-containing fields of objects
1703 // within a HeapRegion.
1704 
1705 class IterateOopClosureRegionClosure: public HeapRegionClosure {
1706   MemRegion _mr;
1707   OopClosure* _cl;
1708 public:
1709   IterateOopClosureRegionClosure(MemRegion mr, OopClosure* cl)
1710     : _mr(mr), _cl(cl) {}
1711   bool doHeapRegion(HeapRegion* r) {
1712     if (! r->continuesHumongous()) {
1713       r->oop_iterate(_cl);
1714     }
1715     return false;
1716   }
1717 };
1718 
1719 void G1CollectedHeap::oop_iterate(OopClosure* cl) {
1720   IterateOopClosureRegionClosure blk(_g1_committed, cl);
1721   _hrs->iterate(&blk);
1722 }
1723 
1724 void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl) {
1725   IterateOopClosureRegionClosure blk(mr, cl);
1726   _hrs->iterate(&blk);
1727 }
1728 
1729 // Iterates an ObjectClosure over all objects within a HeapRegion.
1730 
1731 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
1732   ObjectClosure* _cl;
1733 public:
1734   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
1735   bool doHeapRegion(HeapRegion* r) {
1736     if (! r->continuesHumongous()) {
1737       r->object_iterate(_cl);
1738     }
1739     return false;
1740   }
1741 };
1742 
1743 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
1744   IterateObjectClosureRegionClosure blk(cl);
1745   _hrs->iterate(&blk);
1746 }
1747 
1748 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) {
1749   // FIXME: is this right?
1750   guarantee(false, "object_iterate_since_last_GC not supported by G1 heap");
1751 }
1752 
1753 // Calls a SpaceClosure on a HeapRegion.
1754 
1755 class SpaceClosureRegionClosure: public HeapRegionClosure {
1756   SpaceClosure* _cl;
1757 public:
1758   SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
1759   bool doHeapRegion(HeapRegion* r) {
1760     _cl->do_space(r);
1761     return false;
1762   }
1763 };
1764 
1765 void G1CollectedHeap::space_iterate(SpaceClosure* cl) {
1766   SpaceClosureRegionClosure blk(cl);
1767   _hrs->iterate(&blk);
1768 }
1769 
1770 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) {
1771   _hrs->iterate(cl);
1772 }
1773 
1774 void G1CollectedHeap::heap_region_iterate_from(HeapRegion* r,
1775                                                HeapRegionClosure* cl) {
1776   _hrs->iterate_from(r, cl);
1777 }
1778 
1779 void
1780 G1CollectedHeap::heap_region_iterate_from(int idx, HeapRegionClosure* cl) {
1781   _hrs->iterate_from(idx, cl);
1782 }
1783 
1784 HeapRegion* G1CollectedHeap::region_at(size_t idx) { return _hrs->at(idx); }
1785 
1786 void
1787 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl,
1788                                                  int worker,
1789                                                  jint claim_value) {
1790   const size_t regions = n_regions();
1791   const size_t worker_num = (ParallelGCThreads > 0 ? ParallelGCThreads : 1);
1792   // try to spread out the starting points of the workers
1793   const size_t start_index = regions / worker_num * (size_t) worker;
1794 
1795   // each worker will actually look at all regions
1796   for (size_t count = 0; count < regions; ++count) {
1797     const size_t index = (start_index + count) % regions;
1798     assert(0 <= index && index < regions, "sanity");
1799     HeapRegion* r = region_at(index);
1800     // we'll ignore "continues humongous" regions (we'll process them
1801     // when we come across their corresponding "start humongous"
1802     // region) and regions already claimed
1803     if (r->claim_value() == claim_value || r->continuesHumongous()) {
1804       continue;
1805     }
1806     // OK, try to claim it
1807     if (r->claimHeapRegion(claim_value)) {
1808       // success!
1809       assert(!r->continuesHumongous(), "sanity");
1810       if (r->startsHumongous()) {
1811         // If the region is "starts humongous" we'll iterate over its
1812         // "continues humongous" first; in fact we'll do them
1813         // first. The order is important. In on case, calling the
1814         // closure on the "starts humongous" region might de-allocate
1815         // and clear all its "continues humongous" regions and, as a
1816         // result, we might end up processing them twice. So, we'll do
1817         // them first (notice: most closures will ignore them anyway) and
1818         // then we'll do the "starts humongous" region.
1819         for (size_t ch_index = index + 1; ch_index < regions; ++ch_index) {
1820           HeapRegion* chr = region_at(ch_index);
1821 
1822           // if the region has already been claimed or it's not
1823           // "continues humongous" we're done
1824           if (chr->claim_value() == claim_value ||
1825               !chr->continuesHumongous()) {
1826             break;
1827           }
1828 
1829           // Noone should have claimed it directly. We can given
1830           // that we claimed its "starts humongous" region.
1831           assert(chr->claim_value() != claim_value, "sanity");
1832           assert(chr->humongous_start_region() == r, "sanity");
1833 
1834           if (chr->claimHeapRegion(claim_value)) {
1835             // we should always be able to claim it; noone else should
1836             // be trying to claim this region
1837 
1838             bool res2 = cl->doHeapRegion(chr);
1839             assert(!res2, "Should not abort");
1840 
1841             // Right now, this holds (i.e., no closure that actually
1842             // does something with "continues humongous" regions
1843             // clears them). We might have to weaken it in the future,
1844             // but let's leave these two asserts here for extra safety.
1845             assert(chr->continuesHumongous(), "should still be the case");
1846             assert(chr->humongous_start_region() == r, "sanity");
1847           } else {
1848             guarantee(false, "we should not reach here");
1849           }
1850         }
1851       }
1852 
1853       assert(!r->continuesHumongous(), "sanity");
1854       bool res = cl->doHeapRegion(r);
1855       assert(!res, "Should not abort");
1856     }
1857   }
1858 }
1859 
1860 class ResetClaimValuesClosure: public HeapRegionClosure {
1861 public:
1862   bool doHeapRegion(HeapRegion* r) {
1863     r->set_claim_value(HeapRegion::InitialClaimValue);
1864     return false;
1865   }
1866 };
1867 
1868 void
1869 G1CollectedHeap::reset_heap_region_claim_values() {
1870   ResetClaimValuesClosure blk;
1871   heap_region_iterate(&blk);
1872 }
1873 
1874 #ifdef ASSERT
1875 // This checks whether all regions in the heap have the correct claim
1876 // value. I also piggy-backed on this a check to ensure that the
1877 // humongous_start_region() information on "continues humongous"
1878 // regions is correct.
1879 
1880 class CheckClaimValuesClosure : public HeapRegionClosure {
1881 private:
1882   jint _claim_value;
1883   size_t _failures;
1884   HeapRegion* _sh_region;
1885 public:
1886   CheckClaimValuesClosure(jint claim_value) :
1887     _claim_value(claim_value), _failures(0), _sh_region(NULL) { }
1888   bool doHeapRegion(HeapRegion* r) {
1889     if (r->claim_value() != _claim_value) {
1890       gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
1891                              "claim value = %d, should be %d",
1892                              r->bottom(), r->end(), r->claim_value(),
1893                              _claim_value);
1894       ++_failures;
1895     }
1896     if (!r->isHumongous()) {
1897       _sh_region = NULL;
1898     } else if (r->startsHumongous()) {
1899       _sh_region = r;
1900     } else if (r->continuesHumongous()) {
1901       if (r->humongous_start_region() != _sh_region) {
1902         gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), "
1903                                "HS = "PTR_FORMAT", should be "PTR_FORMAT,
1904                                r->bottom(), r->end(),
1905                                r->humongous_start_region(),
1906                                _sh_region);
1907         ++_failures;
1908       }
1909     }
1910     return false;
1911   }
1912   size_t failures() {
1913     return _failures;
1914   }
1915 };
1916 
1917 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) {
1918   CheckClaimValuesClosure cl(claim_value);
1919   heap_region_iterate(&cl);
1920   return cl.failures() == 0;
1921 }
1922 #endif // ASSERT
1923 
1924 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) {
1925   HeapRegion* r = g1_policy()->collection_set();
1926   while (r != NULL) {
1927     HeapRegion* next = r->next_in_collection_set();
1928     if (cl->doHeapRegion(r)) {
1929       cl->incomplete();
1930       return;
1931     }
1932     r = next;
1933   }
1934 }
1935 
1936 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r,
1937                                                   HeapRegionClosure *cl) {
1938   assert(r->in_collection_set(),
1939          "Start region must be a member of the collection set.");
1940   HeapRegion* cur = r;
1941   while (cur != NULL) {
1942     HeapRegion* next = cur->next_in_collection_set();
1943     if (cl->doHeapRegion(cur) && false) {
1944       cl->incomplete();
1945       return;
1946     }
1947     cur = next;
1948   }
1949   cur = g1_policy()->collection_set();
1950   while (cur != r) {
1951     HeapRegion* next = cur->next_in_collection_set();
1952     if (cl->doHeapRegion(cur) && false) {
1953       cl->incomplete();
1954       return;
1955     }
1956     cur = next;
1957   }
1958 }
1959 
1960 CompactibleSpace* G1CollectedHeap::first_compactible_space() {
1961   return _hrs->length() > 0 ? _hrs->at(0) : NULL;
1962 }
1963 
1964 
1965 Space* G1CollectedHeap::space_containing(const void* addr) const {
1966   Space* res = heap_region_containing(addr);
1967   if (res == NULL)
1968     res = perm_gen()->space_containing(addr);
1969   return res;
1970 }
1971 
1972 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
1973   Space* sp = space_containing(addr);
1974   if (sp != NULL) {
1975     return sp->block_start(addr);
1976   }
1977   return NULL;
1978 }
1979 
1980 size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
1981   Space* sp = space_containing(addr);
1982   assert(sp != NULL, "block_size of address outside of heap");
1983   return sp->block_size(addr);
1984 }
1985 
1986 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
1987   Space* sp = space_containing(addr);
1988   return sp->block_is_obj(addr);
1989 }
1990 
1991 bool G1CollectedHeap::supports_tlab_allocation() const {
1992   return true;
1993 }
1994 
1995 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
1996   return HeapRegion::GrainBytes;
1997 }
1998 
1999 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2000   // Return the remaining space in the cur alloc region, but not less than
2001   // the min TLAB size.
2002   // Also, no more than half the region size, since we can't allow tlabs to
2003   // grow big enough to accomodate humongous objects.
2004 
2005   // We need to story it locally, since it might change between when we
2006   // test for NULL and when we use it later.
2007   ContiguousSpace* cur_alloc_space = _cur_alloc_region;
2008   if (cur_alloc_space == NULL) {
2009     return HeapRegion::GrainBytes/2;
2010   } else {
2011     return MAX2(MIN2(cur_alloc_space->free(),
2012                      (size_t)(HeapRegion::GrainBytes/2)),
2013                 (size_t)MinTLABSize);
2014   }
2015 }
2016 
2017 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t size) {
2018   bool dummy;
2019   return G1CollectedHeap::mem_allocate(size, false, true, &dummy);
2020 }
2021 
2022 bool G1CollectedHeap::allocs_are_zero_filled() {
2023   return false;
2024 }
2025 
2026 size_t G1CollectedHeap::large_typearray_limit() {
2027   // FIXME
2028   return HeapRegion::GrainBytes/HeapWordSize;
2029 }
2030 
2031 size_t G1CollectedHeap::max_capacity() const {
2032   return _g1_committed.byte_size();
2033 }
2034 
2035 jlong G1CollectedHeap::millis_since_last_gc() {
2036   // assert(false, "NYI");
2037   return 0;
2038 }
2039 
2040 
2041 void G1CollectedHeap::prepare_for_verify() {
2042   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2043     ensure_parsability(false);
2044   }
2045   g1_rem_set()->prepare_for_verify();
2046 }
2047 
2048 class VerifyLivenessOopClosure: public OopClosure {
2049   G1CollectedHeap* g1h;
2050 public:
2051   VerifyLivenessOopClosure(G1CollectedHeap* _g1h) {
2052     g1h = _g1h;
2053   }
2054   void do_oop(narrowOop *p) {
2055     guarantee(false, "NYI");
2056   }
2057   void do_oop(oop *p) {
2058     oop obj = *p;
2059     assert(obj == NULL || !g1h->is_obj_dead(obj),
2060            "Dead object referenced by a not dead object");
2061   }
2062 };
2063 
2064 class VerifyObjsInRegionClosure: public ObjectClosure {
2065   G1CollectedHeap* _g1h;
2066   size_t _live_bytes;
2067   HeapRegion *_hr;
2068 public:
2069   VerifyObjsInRegionClosure(HeapRegion *hr) : _live_bytes(0), _hr(hr) {
2070     _g1h = G1CollectedHeap::heap();
2071   }
2072   void do_object(oop o) {
2073     VerifyLivenessOopClosure isLive(_g1h);
2074     assert(o != NULL, "Huh?");
2075     if (!_g1h->is_obj_dead(o)) {
2076       o->oop_iterate(&isLive);
2077       if (!_hr->obj_allocated_since_prev_marking(o))
2078         _live_bytes += (o->size() * HeapWordSize);
2079     }
2080   }
2081   size_t live_bytes() { return _live_bytes; }
2082 };
2083 
2084 class PrintObjsInRegionClosure : public ObjectClosure {
2085   HeapRegion *_hr;
2086   G1CollectedHeap *_g1;
2087 public:
2088   PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) {
2089     _g1 = G1CollectedHeap::heap();
2090   };
2091 
2092   void do_object(oop o) {
2093     if (o != NULL) {
2094       HeapWord *start = (HeapWord *) o;
2095       size_t word_sz = o->size();
2096       gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT
2097                           " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n",
2098                           (void*) o, word_sz,
2099                           _g1->isMarkedPrev(o),
2100                           _g1->isMarkedNext(o),
2101                           _hr->obj_allocated_since_prev_marking(o));
2102       HeapWord *end = start + word_sz;
2103       HeapWord *cur;
2104       int *val;
2105       for (cur = start; cur < end; cur++) {
2106         val = (int *) cur;
2107         gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
2108       }
2109     }
2110   }
2111 };
2112 
2113 class VerifyRegionClosure: public HeapRegionClosure {
2114 public:
2115   bool _allow_dirty;
2116   bool _par;
2117   VerifyRegionClosure(bool allow_dirty, bool par = false)
2118     : _allow_dirty(allow_dirty), _par(par) {}
2119   bool doHeapRegion(HeapRegion* r) {
2120     guarantee(_par || r->claim_value() == HeapRegion::InitialClaimValue,
2121               "Should be unclaimed at verify points.");
2122     if (r->isHumongous()) {
2123       if (r->startsHumongous()) {
2124         // Verify the single H object.
2125         oop(r->bottom())->verify();
2126         size_t word_sz = oop(r->bottom())->size();
2127         guarantee(r->top() == r->bottom() + word_sz,
2128                   "Only one object in a humongous region");
2129       }
2130     } else {
2131       VerifyObjsInRegionClosure not_dead_yet_cl(r);
2132       r->verify(_allow_dirty);
2133       r->object_iterate(&not_dead_yet_cl);
2134       guarantee(r->max_live_bytes() >= not_dead_yet_cl.live_bytes(),
2135                 "More live objects than counted in last complete marking.");
2136     }
2137     return false;
2138   }
2139 };
2140 
2141 class VerifyRootsClosure: public OopsInGenClosure {
2142 private:
2143   G1CollectedHeap* _g1h;
2144   bool             _failures;
2145 
2146 public:
2147   VerifyRootsClosure() :
2148     _g1h(G1CollectedHeap::heap()), _failures(false) { }
2149 
2150   bool failures() { return _failures; }
2151 
2152   void do_oop(narrowOop* p) {
2153     guarantee(false, "NYI");
2154   }
2155 
2156   void do_oop(oop* p) {
2157     oop obj = *p;
2158     if (obj != NULL) {
2159       if (_g1h->is_obj_dead(obj)) {
2160         gclog_or_tty->print_cr("Root location "PTR_FORMAT" "
2161                                "points to dead obj "PTR_FORMAT, p, (void*) obj);
2162         obj->print_on(gclog_or_tty);
2163         _failures = true;
2164       }
2165     }
2166   }
2167 };
2168 
2169 // This is the task used for parallel heap verification.
2170 
2171 class G1ParVerifyTask: public AbstractGangTask {
2172 private:
2173   G1CollectedHeap* _g1h;
2174   bool _allow_dirty;
2175 
2176 public:
2177   G1ParVerifyTask(G1CollectedHeap* g1h, bool allow_dirty) :
2178     AbstractGangTask("Parallel verify task"),
2179     _g1h(g1h), _allow_dirty(allow_dirty) { }
2180 
2181   void work(int worker_i) {
2182     VerifyRegionClosure blk(_allow_dirty, true);
2183     _g1h->heap_region_par_iterate_chunked(&blk, worker_i,
2184                                           HeapRegion::ParVerifyClaimValue);
2185   }
2186 };
2187 
2188 void G1CollectedHeap::verify(bool allow_dirty, bool silent) {
2189   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
2190     if (!silent) { gclog_or_tty->print("roots "); }
2191     VerifyRootsClosure rootsCl;
2192     process_strong_roots(false,
2193                          SharedHeap::SO_AllClasses,
2194                          &rootsCl,
2195                          &rootsCl);
2196     rem_set()->invalidate(perm_gen()->used_region(), false);
2197     if (!silent) { gclog_or_tty->print("heapRegions "); }
2198     if (GCParallelVerificationEnabled && ParallelGCThreads > 1) {
2199       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2200              "sanity check");
2201 
2202       G1ParVerifyTask task(this, allow_dirty);
2203       int n_workers = workers()->total_workers();
2204       set_par_threads(n_workers);
2205       workers()->run_task(&task);
2206       set_par_threads(0);
2207 
2208       assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue),
2209              "sanity check");
2210 
2211       reset_heap_region_claim_values();
2212 
2213       assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2214              "sanity check");
2215     } else {
2216       VerifyRegionClosure blk(allow_dirty);
2217       _hrs->iterate(&blk);
2218     }
2219     if (!silent) gclog_or_tty->print("remset ");
2220     rem_set()->verify();
2221     guarantee(!rootsCl.failures(), "should not have had failures");
2222   } else {
2223     if (!silent) gclog_or_tty->print("(SKIPPING roots, heapRegions, remset) ");
2224   }
2225 }
2226 
2227 class PrintRegionClosure: public HeapRegionClosure {
2228   outputStream* _st;
2229 public:
2230   PrintRegionClosure(outputStream* st) : _st(st) {}
2231   bool doHeapRegion(HeapRegion* r) {
2232     r->print_on(_st);
2233     return false;
2234   }
2235 };
2236 
2237 void G1CollectedHeap::print() const { print_on(gclog_or_tty); }
2238 
2239 void G1CollectedHeap::print_on(outputStream* st) const {
2240   PrintRegionClosure blk(st);
2241   _hrs->iterate(&blk);
2242 }
2243 
2244 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
2245   if (ParallelGCThreads > 0) {
2246     workers()->print_worker_threads();
2247   }
2248   st->print("\"G1 concurrent mark GC Thread\" ");
2249   _cmThread->print();
2250   st->cr();
2251   st->print("\"G1 concurrent refinement GC Thread\" ");
2252   _cg1r->cg1rThread()->print_on(st);
2253   st->cr();
2254   st->print("\"G1 zero-fill GC Thread\" ");
2255   _czft->print_on(st);
2256   st->cr();
2257 }
2258 
2259 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2260   if (ParallelGCThreads > 0) {
2261     workers()->threads_do(tc);
2262   }
2263   tc->do_thread(_cmThread);
2264   tc->do_thread(_cg1r->cg1rThread());
2265   tc->do_thread(_czft);
2266 }
2267 
2268 void G1CollectedHeap::print_tracing_info() const {
2269   concurrent_g1_refine()->print_final_card_counts();
2270 
2271   // We'll overload this to mean "trace GC pause statistics."
2272   if (TraceGen0Time || TraceGen1Time) {
2273     // The "G1CollectorPolicy" is keeping track of these stats, so delegate
2274     // to that.
2275     g1_policy()->print_tracing_info();
2276   }
2277   if (SummarizeG1RSStats) {
2278     g1_rem_set()->print_summary_info();
2279   }
2280   if (SummarizeG1ConcMark) {
2281     concurrent_mark()->print_summary_info();
2282   }
2283   if (SummarizeG1ZFStats) {
2284     ConcurrentZFThread::print_summary_info();
2285   }
2286   if (G1SummarizePopularity) {
2287     print_popularity_summary_info();
2288   }
2289   g1_policy()->print_yg_surv_rate_info();
2290 
2291   GCOverheadReporter::printGCOverhead();
2292 
2293   SpecializationStats::print();
2294 }
2295 
2296 
2297 int G1CollectedHeap::addr_to_arena_id(void* addr) const {
2298   HeapRegion* hr = heap_region_containing(addr);
2299   if (hr == NULL) {
2300     return 0;
2301   } else {
2302     return 1;
2303   }
2304 }
2305 
2306 G1CollectedHeap* G1CollectedHeap::heap() {
2307   assert(_sh->kind() == CollectedHeap::G1CollectedHeap,
2308          "not a garbage-first heap");
2309   return _g1h;
2310 }
2311 
2312 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) {
2313   if (PrintHeapAtGC){
2314     gclog_or_tty->print_cr(" {Heap before GC collections=%d:", total_collections());
2315     Universe::print();
2316   }
2317   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2318   // Call allocation profiler
2319   AllocationProfiler::iterate_since_last_gc();
2320   // Fill TLAB's and such
2321   ensure_parsability(true);
2322 }
2323 
2324 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) {
2325   // FIXME: what is this about?
2326   // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled"
2327   // is set.
2328   COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(),
2329                         "derived pointer present"));
2330 
2331   if (PrintHeapAtGC){
2332     gclog_or_tty->print_cr(" Heap after GC collections=%d:", total_collections());
2333     Universe::print();
2334     gclog_or_tty->print("} ");
2335   }
2336 }
2337 
2338 void G1CollectedHeap::do_collection_pause() {
2339   // Read the GC count while holding the Heap_lock
2340   // we need to do this _before_ wait_for_cleanup_complete(), to
2341   // ensure that we do not give up the heap lock and potentially
2342   // pick up the wrong count
2343   int gc_count_before = SharedHeap::heap()->total_collections();
2344 
2345   // Don't want to do a GC pause while cleanup is being completed!
2346   wait_for_cleanup_complete();
2347 
2348   g1_policy()->record_stop_world_start();
2349   {
2350     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
2351     VM_G1IncCollectionPause op(gc_count_before);
2352     VMThread::execute(&op);
2353   }
2354 }
2355 
2356 void
2357 G1CollectedHeap::doConcurrentMark() {
2358   if (G1ConcMark) {
2359     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2360     if (!_cmThread->in_progress()) {
2361       _cmThread->set_started();
2362       CGC_lock->notify();
2363     }
2364   }
2365 }
2366 
2367 class VerifyMarkedObjsClosure: public ObjectClosure {
2368     G1CollectedHeap* _g1h;
2369     public:
2370     VerifyMarkedObjsClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
2371     void do_object(oop obj) {
2372       assert(obj->mark()->is_marked() ? !_g1h->is_obj_dead(obj) : true,
2373              "markandsweep mark should agree with concurrent deadness");
2374     }
2375 };
2376 
2377 void
2378 G1CollectedHeap::checkConcurrentMark() {
2379     VerifyMarkedObjsClosure verifycl(this);
2380     //    MutexLockerEx x(getMarkBitMapLock(),
2381     //              Mutex::_no_safepoint_check_flag);
2382     object_iterate(&verifycl);
2383 }
2384 
2385 void G1CollectedHeap::do_sync_mark() {
2386   _cm->checkpointRootsInitial();
2387   _cm->markFromRoots();
2388   _cm->checkpointRootsFinal(false);
2389 }
2390 
2391 // <NEW PREDICTION>
2392 
2393 double G1CollectedHeap::predict_region_elapsed_time_ms(HeapRegion *hr,
2394                                                        bool young) {
2395   return _g1_policy->predict_region_elapsed_time_ms(hr, young);
2396 }
2397 
2398 void G1CollectedHeap::check_if_region_is_too_expensive(double
2399                                                            predicted_time_ms) {
2400   _g1_policy->check_if_region_is_too_expensive(predicted_time_ms);
2401 }
2402 
2403 size_t G1CollectedHeap::pending_card_num() {
2404   size_t extra_cards = 0;
2405   JavaThread *curr = Threads::first();
2406   while (curr != NULL) {
2407     DirtyCardQueue& dcq = curr->dirty_card_queue();
2408     extra_cards += dcq.size();
2409     curr = curr->next();
2410   }
2411   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2412   size_t buffer_size = dcqs.buffer_size();
2413   size_t buffer_num = dcqs.completed_buffers_num();
2414   return buffer_size * buffer_num + extra_cards;
2415 }
2416 
2417 size_t G1CollectedHeap::max_pending_card_num() {
2418   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
2419   size_t buffer_size = dcqs.buffer_size();
2420   size_t buffer_num  = dcqs.completed_buffers_num();
2421   int thread_num  = Threads::number_of_threads();
2422   return (buffer_num + thread_num) * buffer_size;
2423 }
2424 
2425 size_t G1CollectedHeap::cards_scanned() {
2426   HRInto_G1RemSet* g1_rset = (HRInto_G1RemSet*) g1_rem_set();
2427   return g1_rset->cardsScanned();
2428 }
2429 
2430 void
2431 G1CollectedHeap::setup_surviving_young_words() {
2432   guarantee( _surviving_young_words == NULL, "pre-condition" );
2433   size_t array_length = g1_policy()->young_cset_length();
2434   _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, array_length);
2435   if (_surviving_young_words == NULL) {
2436     vm_exit_out_of_memory(sizeof(size_t) * array_length,
2437                           "Not enough space for young surv words summary.");
2438   }
2439   memset(_surviving_young_words, 0, array_length * sizeof(size_t));
2440   for (size_t i = 0;  i < array_length; ++i) {
2441     guarantee( _surviving_young_words[i] == 0, "invariant" );
2442   }
2443 }
2444 
2445 void
2446 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) {
2447   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
2448   size_t array_length = g1_policy()->young_cset_length();
2449   for (size_t i = 0; i < array_length; ++i)
2450     _surviving_young_words[i] += surv_young_words[i];
2451 }
2452 
2453 void
2454 G1CollectedHeap::cleanup_surviving_young_words() {
2455   guarantee( _surviving_young_words != NULL, "pre-condition" );
2456   FREE_C_HEAP_ARRAY(size_t, _surviving_young_words);
2457   _surviving_young_words = NULL;
2458 }
2459 
2460 // </NEW PREDICTION>
2461 
2462 void
2463 G1CollectedHeap::do_collection_pause_at_safepoint(HeapRegion* popular_region) {
2464   char verbose_str[128];
2465   sprintf(verbose_str, "GC pause ");
2466   if (popular_region != NULL)
2467     strcat(verbose_str, "(popular)");
2468   else if (g1_policy()->in_young_gc_mode()) {
2469     if (g1_policy()->full_young_gcs())
2470       strcat(verbose_str, "(young)");
2471     else
2472       strcat(verbose_str, "(partial)");
2473   }
2474   bool reset_should_initiate_conc_mark = false;
2475   if (popular_region != NULL && g1_policy()->should_initiate_conc_mark()) {
2476     // we currently do not allow an initial mark phase to be piggy-backed
2477     // on a popular pause
2478     reset_should_initiate_conc_mark = true;
2479     g1_policy()->unset_should_initiate_conc_mark();
2480   }
2481   if (g1_policy()->should_initiate_conc_mark())
2482     strcat(verbose_str, " (initial-mark)");
2483 
2484   GCCauseSetter x(this, (popular_region == NULL ?
2485                          GCCause::_g1_inc_collection_pause :
2486                          GCCause::_g1_pop_region_collection_pause));
2487 
2488   // if PrintGCDetails is on, we'll print long statistics information
2489   // in the collector policy code, so let's not print this as the output
2490   // is messy if we do.
2491   gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
2492   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
2493   TraceTime t(verbose_str, PrintGC && !PrintGCDetails, true, gclog_or_tty);
2494 
2495   ResourceMark rm;
2496   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
2497   assert(Thread::current() == VMThread::vm_thread(), "should be in vm thread");
2498   guarantee(!is_gc_active(), "collection is not reentrant");
2499   assert(regions_accounted_for(), "Region leakage!");
2500 
2501   increment_gc_time_stamp();
2502 
2503   if (g1_policy()->in_young_gc_mode()) {
2504     assert(check_young_list_well_formed(),
2505                 "young list should be well formed");
2506   }
2507 
2508   if (GC_locker::is_active()) {
2509     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
2510   }
2511 
2512   bool abandoned = false;
2513   { // Call to jvmpi::post_class_unload_events must occur outside of active GC
2514     IsGCActiveMark x;
2515 
2516     gc_prologue(false);
2517     increment_total_collections();
2518 
2519 #if G1_REM_SET_LOGGING
2520     gclog_or_tty->print_cr("\nJust chose CS, heap:");
2521     print();
2522 #endif
2523 
2524     if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) {
2525       HandleMark hm;  // Discard invalid handles created during verification
2526       prepare_for_verify();
2527       gclog_or_tty->print(" VerifyBeforeGC:");
2528       Universe::verify(false);
2529     }
2530 
2531     COMPILER2_PRESENT(DerivedPointerTable::clear());
2532 
2533     // We want to turn off ref discovery, if necessary, and turn it back on
2534     // on again later if we do.
2535     bool was_enabled = ref_processor()->discovery_enabled();
2536     if (was_enabled) ref_processor()->disable_discovery();
2537 
2538     // Forget the current alloc region (we might even choose it to be part
2539     // of the collection set!).
2540     abandon_cur_alloc_region();
2541 
2542     // The elapsed time induced by the start time below deliberately elides
2543     // the possible verification above.
2544     double start_time_sec = os::elapsedTime();
2545     GCOverheadReporter::recordSTWStart(start_time_sec);
2546     size_t start_used_bytes = used();
2547     if (!G1ConcMark) {
2548       do_sync_mark();
2549     }
2550 
2551     g1_policy()->record_collection_pause_start(start_time_sec,
2552                                                start_used_bytes);
2553 
2554     guarantee(_in_cset_fast_test == NULL, "invariant");
2555     guarantee(_in_cset_fast_test_base == NULL, "invariant");
2556     _in_cset_fast_test_length = max_regions();
2557     _in_cset_fast_test_base =
2558                              NEW_C_HEAP_ARRAY(bool, _in_cset_fast_test_length);
2559     memset(_in_cset_fast_test_base, false,
2560                                      _in_cset_fast_test_length * sizeof(bool));
2561     // We're biasing _in_cset_fast_test to avoid subtracting the
2562     // beginning of the heap every time we want to index; basically
2563     // it's the same with what we do with the card table.
2564     _in_cset_fast_test = _in_cset_fast_test_base -
2565               ((size_t) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
2566 
2567 #if SCAN_ONLY_VERBOSE
2568     _young_list->print();
2569 #endif // SCAN_ONLY_VERBOSE
2570 
2571     if (g1_policy()->should_initiate_conc_mark()) {
2572       concurrent_mark()->checkpointRootsInitialPre();
2573     }
2574     save_marks();
2575 
2576     // We must do this before any possible evacuation that should propagate
2577     // marks, including evacuation of popular objects in a popular pause.
2578     if (mark_in_progress()) {
2579       double start_time_sec = os::elapsedTime();
2580 
2581       _cm->drainAllSATBBuffers();
2582       double finish_mark_ms = (os::elapsedTime() - start_time_sec) * 1000.0;
2583       g1_policy()->record_satb_drain_time(finish_mark_ms);
2584 
2585     }
2586     // Record the number of elements currently on the mark stack, so we
2587     // only iterate over these.  (Since evacuation may add to the mark
2588     // stack, doing more exposes race conditions.)  If no mark is in
2589     // progress, this will be zero.
2590     _cm->set_oops_do_bound();
2591 
2592     assert(regions_accounted_for(), "Region leakage.");
2593 
2594     bool abandoned = false;
2595 
2596     if (mark_in_progress())
2597       concurrent_mark()->newCSet();
2598 
2599     // Now choose the CS.
2600     if (popular_region == NULL) {
2601       g1_policy()->choose_collection_set();
2602     } else {
2603       // We may be evacuating a single region (for popularity).
2604       g1_policy()->record_popular_pause_preamble_start();
2605       popularity_pause_preamble(popular_region);
2606       g1_policy()->record_popular_pause_preamble_end();
2607       abandoned = (g1_policy()->collection_set() == NULL);
2608       // Now we allow more regions to be added (we have to collect
2609       // all popular regions).
2610       if (!abandoned) {
2611         g1_policy()->choose_collection_set(popular_region);
2612       }
2613     }
2614     // We may abandon a pause if we find no region that will fit in the MMU
2615     // pause.
2616     abandoned = (g1_policy()->collection_set() == NULL);
2617 
2618     // Nothing to do if we were unable to choose a collection set.
2619     if (!abandoned) {
2620 #if G1_REM_SET_LOGGING
2621       gclog_or_tty->print_cr("\nAfter pause, heap:");
2622       print();
2623 #endif
2624 
2625       setup_surviving_young_words();
2626 
2627       // Set up the gc allocation regions.
2628       get_gc_alloc_regions();
2629 
2630       // Actually do the work...
2631       evacuate_collection_set();
2632       free_collection_set(g1_policy()->collection_set());
2633       g1_policy()->clear_collection_set();
2634 
2635       FREE_C_HEAP_ARRAY(bool, _in_cset_fast_test_base);
2636       // this is more for peace of mind; we're nulling them here and
2637       // we're expecting them to be null at the beginning of the next GC
2638       _in_cset_fast_test = NULL;
2639       _in_cset_fast_test_base = NULL;
2640 
2641       if (popular_region != NULL) {
2642         // We have to wait until now, because we don't want the region to
2643         // be rescheduled for pop-evac during RS update.
2644         popular_region->set_popular_pending(false);
2645       }
2646 
2647       release_gc_alloc_regions();
2648 
2649       cleanup_surviving_young_words();
2650 
2651       if (g1_policy()->in_young_gc_mode()) {
2652         _young_list->reset_sampled_info();
2653         assert(check_young_list_empty(true),
2654                "young list should be empty");
2655 
2656 #if SCAN_ONLY_VERBOSE
2657         _young_list->print();
2658 #endif // SCAN_ONLY_VERBOSE
2659 
2660         g1_policy()->record_survivor_regions(_young_list->survivor_length(),
2661                                              _young_list->first_survivor_region(),
2662                                              _young_list->last_survivor_region());
2663         _young_list->reset_auxilary_lists();
2664       }
2665     } else {
2666       COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
2667     }
2668 
2669     if (evacuation_failed()) {
2670       _summary_bytes_used = recalculate_used();
2671     } else {
2672       // The "used" of the the collection set have already been subtracted
2673       // when they were freed.  Add in the bytes evacuated.
2674       _summary_bytes_used += g1_policy()->bytes_in_to_space();
2675     }
2676 
2677     if (g1_policy()->in_young_gc_mode() &&
2678         g1_policy()->should_initiate_conc_mark()) {
2679       concurrent_mark()->checkpointRootsInitialPost();
2680       set_marking_started();
2681       doConcurrentMark();
2682     }
2683 
2684 #if SCAN_ONLY_VERBOSE
2685     _young_list->print();
2686 #endif // SCAN_ONLY_VERBOSE
2687 
2688     double end_time_sec = os::elapsedTime();
2689     double pause_time_ms = (end_time_sec - start_time_sec) * MILLIUNITS;
2690     g1_policy()->record_pause_time_ms(pause_time_ms);
2691     GCOverheadReporter::recordSTWEnd(end_time_sec);
2692     g1_policy()->record_collection_pause_end(popular_region != NULL,
2693                                              abandoned);
2694 
2695     assert(regions_accounted_for(), "Region leakage.");
2696 
2697     if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) {
2698       HandleMark hm;  // Discard invalid handles created during verification
2699       gclog_or_tty->print(" VerifyAfterGC:");
2700       Universe::verify(false);
2701     }
2702 
2703     if (was_enabled) ref_processor()->enable_discovery();
2704 
2705     {
2706       size_t expand_bytes = g1_policy()->expansion_amount();
2707       if (expand_bytes > 0) {
2708         size_t bytes_before = capacity();
2709         expand(expand_bytes);
2710       }
2711     }
2712 
2713     if (mark_in_progress()) {
2714       concurrent_mark()->update_g1_committed();
2715     }
2716 
2717 #ifdef TRACESPINNING
2718     ParallelTaskTerminator::print_termination_counts();
2719 #endif
2720 
2721     gc_epilogue(false);
2722   }
2723 
2724   assert(verify_region_lists(), "Bad region lists.");
2725 
2726   if (reset_should_initiate_conc_mark)
2727     g1_policy()->set_should_initiate_conc_mark();
2728 
2729   if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) {
2730     gclog_or_tty->print_cr("Stopping after GC #%d", ExitAfterGCNum);
2731     print_tracing_info();
2732     vm_exit(-1);
2733   }
2734 }
2735 
2736 void G1CollectedHeap::set_gc_alloc_region(int purpose, HeapRegion* r) {
2737   assert(purpose >= 0 && purpose < GCAllocPurposeCount, "invalid purpose");
2738   HeapWord* original_top = NULL;
2739   if (r != NULL)
2740     original_top = r->top();
2741 
2742   // We will want to record the used space in r as being there before gc.
2743   // One we install it as a GC alloc region it's eligible for allocation.
2744   // So record it now and use it later.
2745   size_t r_used = 0;
2746   if (r != NULL) {
2747     r_used = r->used();
2748 
2749     if (ParallelGCThreads > 0) {
2750       // need to take the lock to guard against two threads calling
2751       // get_gc_alloc_region concurrently (very unlikely but...)
2752       MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
2753       r->save_marks();
2754     }
2755   }
2756   HeapRegion* old_alloc_region = _gc_alloc_regions[purpose];
2757   _gc_alloc_regions[purpose] = r;
2758   if (old_alloc_region != NULL) {
2759     // Replace aliases too.
2760     for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2761       if (_gc_alloc_regions[ap] == old_alloc_region) {
2762         _gc_alloc_regions[ap] = r;
2763       }
2764     }
2765   }
2766   if (r != NULL) {
2767     push_gc_alloc_region(r);
2768     if (mark_in_progress() && original_top != r->next_top_at_mark_start()) {
2769       // We are using a region as a GC alloc region after it has been used
2770       // as a mutator allocation region during the current marking cycle.
2771       // The mutator-allocated objects are currently implicitly marked, but
2772       // when we move hr->next_top_at_mark_start() forward at the the end
2773       // of the GC pause, they won't be.  We therefore mark all objects in
2774       // the "gap".  We do this object-by-object, since marking densely
2775       // does not currently work right with marking bitmap iteration.  This
2776       // means we rely on TLAB filling at the start of pauses, and no
2777       // "resuscitation" of filled TLAB's.  If we want to do this, we need
2778       // to fix the marking bitmap iteration.
2779       HeapWord* curhw = r->next_top_at_mark_start();
2780       HeapWord* t = original_top;
2781 
2782       while (curhw < t) {
2783         oop cur = (oop)curhw;
2784         // We'll assume parallel for generality.  This is rare code.
2785         concurrent_mark()->markAndGrayObjectIfNecessary(cur); // can't we just mark them?
2786         curhw = curhw + cur->size();
2787       }
2788       assert(curhw == t, "Should have parsed correctly.");
2789     }
2790     if (G1PolicyVerbose > 1) {
2791       gclog_or_tty->print("New alloc region ["PTR_FORMAT", "PTR_FORMAT", " PTR_FORMAT") "
2792                           "for survivors:", r->bottom(), original_top, r->end());
2793       r->print();
2794     }
2795     g1_policy()->record_before_bytes(r_used);
2796   }
2797 }
2798 
2799 void G1CollectedHeap::push_gc_alloc_region(HeapRegion* hr) {
2800   assert(Thread::current()->is_VM_thread() ||
2801          par_alloc_during_gc_lock()->owned_by_self(), "Precondition");
2802   assert(!hr->is_gc_alloc_region() && !hr->in_collection_set(),
2803          "Precondition.");
2804   hr->set_is_gc_alloc_region(true);
2805   hr->set_next_gc_alloc_region(_gc_alloc_region_list);
2806   _gc_alloc_region_list = hr;
2807 }
2808 
2809 #ifdef G1_DEBUG
2810 class FindGCAllocRegion: public HeapRegionClosure {
2811 public:
2812   bool doHeapRegion(HeapRegion* r) {
2813     if (r->is_gc_alloc_region()) {
2814       gclog_or_tty->print_cr("Region %d ["PTR_FORMAT"...] is still a gc_alloc_region.",
2815                              r->hrs_index(), r->bottom());
2816     }
2817     return false;
2818   }
2819 };
2820 #endif // G1_DEBUG
2821 
2822 void G1CollectedHeap::forget_alloc_region_list() {
2823   assert(Thread::current()->is_VM_thread(), "Precondition");
2824   while (_gc_alloc_region_list != NULL) {
2825     HeapRegion* r = _gc_alloc_region_list;
2826     assert(r->is_gc_alloc_region(), "Invariant.");
2827     _gc_alloc_region_list = r->next_gc_alloc_region();
2828     r->set_next_gc_alloc_region(NULL);
2829     r->set_is_gc_alloc_region(false);
2830     if (r->is_survivor()) {
2831       if (r->is_empty()) {
2832         r->set_not_young();
2833       } else {
2834         _young_list->add_survivor_region(r);
2835       }
2836     }
2837     if (r->is_empty()) {
2838       ++_free_regions;
2839     }
2840   }
2841 #ifdef G1_DEBUG
2842   FindGCAllocRegion fa;
2843   heap_region_iterate(&fa);
2844 #endif // G1_DEBUG
2845 }
2846 
2847 
2848 bool G1CollectedHeap::check_gc_alloc_regions() {
2849   // TODO: allocation regions check
2850   return true;
2851 }
2852 
2853 void G1CollectedHeap::get_gc_alloc_regions() {
2854   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2855     // Create new GC alloc regions.
2856     HeapRegion* alloc_region = _gc_alloc_regions[ap];
2857     // Clear this alloc region, so that in case it turns out to be
2858     // unacceptable, we end up with no allocation region, rather than a bad
2859     // one.
2860     _gc_alloc_regions[ap] = NULL;
2861     if (alloc_region == NULL || alloc_region->in_collection_set()) {
2862       // Can't re-use old one.  Allocate a new one.
2863       alloc_region = newAllocRegionWithExpansion(ap, 0);
2864     }
2865     if (alloc_region != NULL) {
2866       set_gc_alloc_region(ap, alloc_region);
2867     }
2868   }
2869   // Set alternative regions for allocation purposes that have reached
2870   // thier limit.
2871   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2872     GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(ap);
2873     if (_gc_alloc_regions[ap] == NULL && alt_purpose != ap) {
2874       _gc_alloc_regions[ap] = _gc_alloc_regions[alt_purpose];
2875     }
2876   }
2877   assert(check_gc_alloc_regions(), "alloc regions messed up");
2878 }
2879 
2880 void G1CollectedHeap::release_gc_alloc_regions() {
2881   // We keep a separate list of all regions that have been alloc regions in
2882   // the current collection pause.  Forget that now.
2883   forget_alloc_region_list();
2884 
2885   // The current alloc regions contain objs that have survived
2886   // collection. Make them no longer GC alloc regions.
2887   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2888     HeapRegion* r = _gc_alloc_regions[ap];
2889     if (r != NULL && r->is_empty()) {
2890       {
2891         MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
2892         r->set_zero_fill_complete();
2893         put_free_region_on_list_locked(r);
2894       }
2895     }
2896     // set_gc_alloc_region will also NULLify all aliases to the region
2897     set_gc_alloc_region(ap, NULL);
2898     _gc_alloc_region_counts[ap] = 0;
2899   }
2900 }
2901 
2902 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) {
2903   _drain_in_progress = false;
2904   set_evac_failure_closure(cl);
2905   _evac_failure_scan_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
2906 }
2907 
2908 void G1CollectedHeap::finalize_for_evac_failure() {
2909   assert(_evac_failure_scan_stack != NULL &&
2910          _evac_failure_scan_stack->length() == 0,
2911          "Postcondition");
2912   assert(!_drain_in_progress, "Postcondition");
2913   // Don't have to delete, since the scan stack is a resource object.
2914   _evac_failure_scan_stack = NULL;
2915 }
2916 
2917 
2918 
2919 // *** Sequential G1 Evacuation
2920 
2921 HeapWord* G1CollectedHeap::allocate_during_gc(GCAllocPurpose purpose, size_t word_size) {
2922   HeapRegion* alloc_region = _gc_alloc_regions[purpose];
2923   // let the caller handle alloc failure
2924   if (alloc_region == NULL) return NULL;
2925   assert(isHumongous(word_size) || !alloc_region->isHumongous(),
2926          "Either the object is humongous or the region isn't");
2927   HeapWord* block = alloc_region->allocate(word_size);
2928   if (block == NULL) {
2929     block = allocate_during_gc_slow(purpose, alloc_region, false, word_size);
2930   }
2931   return block;
2932 }
2933 
2934 class G1IsAliveClosure: public BoolObjectClosure {
2935   G1CollectedHeap* _g1;
2936 public:
2937   G1IsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
2938   void do_object(oop p) { assert(false, "Do not call."); }
2939   bool do_object_b(oop p) {
2940     // It is reachable if it is outside the collection set, or is inside
2941     // and forwarded.
2942 
2943 #ifdef G1_DEBUG
2944     gclog_or_tty->print_cr("is alive "PTR_FORMAT" in CS %d forwarded %d overall %d",
2945                            (void*) p, _g1->obj_in_cs(p), p->is_forwarded(),
2946                            !_g1->obj_in_cs(p) || p->is_forwarded());
2947 #endif // G1_DEBUG
2948 
2949     return !_g1->obj_in_cs(p) || p->is_forwarded();
2950   }
2951 };
2952 
2953 class G1KeepAliveClosure: public OopClosure {
2954   G1CollectedHeap* _g1;
2955 public:
2956   G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
2957   void do_oop(narrowOop* p) {
2958     guarantee(false, "NYI");
2959   }
2960   void do_oop(oop* p) {
2961     oop obj = *p;
2962 #ifdef G1_DEBUG
2963     if (PrintGC && Verbose) {
2964       gclog_or_tty->print_cr("keep alive *"PTR_FORMAT" = "PTR_FORMAT" "PTR_FORMAT,
2965                              p, (void*) obj, (void*) *p);
2966     }
2967 #endif // G1_DEBUG
2968 
2969     if (_g1->obj_in_cs(obj)) {
2970       assert( obj->is_forwarded(), "invariant" );
2971       *p = obj->forwardee();
2972 
2973 #ifdef G1_DEBUG
2974       gclog_or_tty->print_cr("     in CSet: moved "PTR_FORMAT" -> "PTR_FORMAT,
2975                              (void*) obj, (void*) *p);
2976 #endif // G1_DEBUG
2977     }
2978   }
2979 };
2980 
2981 class UpdateRSetImmediate : public OopsInHeapRegionClosure {
2982 private:
2983   G1CollectedHeap* _g1;
2984   G1RemSet* _g1_rem_set;
2985 public:
2986   UpdateRSetImmediate(G1CollectedHeap* g1) :
2987     _g1(g1), _g1_rem_set(g1->g1_rem_set()) {}
2988 
2989   void do_oop(narrowOop* p) {
2990     guarantee(false, "NYI");
2991   }
2992   void do_oop(oop* p) {
2993     assert(_from->is_in_reserved(p), "paranoia");
2994     if (*p != NULL && !_from->is_survivor()) {
2995       _g1_rem_set->par_write_ref(_from, p, 0);
2996     }
2997   }
2998 };
2999 
3000 class UpdateRSetDeferred : public OopsInHeapRegionClosure {
3001 private:
3002   G1CollectedHeap* _g1;
3003   DirtyCardQueue *_dcq;
3004   CardTableModRefBS* _ct_bs;
3005 
3006 public:
3007   UpdateRSetDeferred(G1CollectedHeap* g1, DirtyCardQueue* dcq) :
3008     _g1(g1), _ct_bs((CardTableModRefBS*)_g1->barrier_set()), _dcq(dcq) {}
3009 
3010   void do_oop(narrowOop* p) {
3011     guarantee(false, "NYI");
3012   }
3013   void do_oop(oop* p) {
3014     assert(_from->is_in_reserved(p), "paranoia");
3015     if (!_from->is_in_reserved(*p) && !_from->is_survivor()) {
3016       size_t card_index = _ct_bs->index_for(p);
3017       if (_ct_bs->mark_card_deferred(card_index)) {
3018         _dcq->enqueue((jbyte*)_ct_bs->byte_for_index(card_index));
3019       }
3020     }
3021   }
3022 };
3023 
3024 
3025 
3026 class RemoveSelfPointerClosure: public ObjectClosure {
3027 private:
3028   G1CollectedHeap* _g1;
3029   ConcurrentMark* _cm;
3030   HeapRegion* _hr;
3031   size_t _prev_marked_bytes;
3032   size_t _next_marked_bytes;
3033   OopsInHeapRegionClosure *_cl;
3034 public:
3035   RemoveSelfPointerClosure(G1CollectedHeap* g1, OopsInHeapRegionClosure* cl) :
3036     _g1(g1), _cm(_g1->concurrent_mark()),  _prev_marked_bytes(0),
3037     _next_marked_bytes(0), _cl(cl) {}
3038 
3039   size_t prev_marked_bytes() { return _prev_marked_bytes; }
3040   size_t next_marked_bytes() { return _next_marked_bytes; }
3041 
3042   // The original idea here was to coalesce evacuated and dead objects.
3043   // However that caused complications with the block offset table (BOT).
3044   // In particular if there were two TLABs, one of them partially refined.
3045   // |----- TLAB_1--------|----TLAB_2-~~~(partially refined part)~~~|
3046   // The BOT entries of the unrefined part of TLAB_2 point to the start
3047   // of TLAB_2. If the last object of the TLAB_1 and the first object
3048   // of TLAB_2 are coalesced, then the cards of the unrefined part
3049   // would point into middle of the filler object.
3050   //
3051   // The current approach is to not coalesce and leave the BOT contents intact.
3052   void do_object(oop obj) {
3053     if (obj->is_forwarded() && obj->forwardee() == obj) {
3054       // The object failed to move.
3055       assert(!_g1->is_obj_dead(obj), "We should not be preserving dead objs.");
3056       _cm->markPrev(obj);
3057       assert(_cm->isPrevMarked(obj), "Should be marked!");
3058       _prev_marked_bytes += (obj->size() * HeapWordSize);
3059       if (_g1->mark_in_progress() && !_g1->is_obj_ill(obj)) {
3060         _cm->markAndGrayObjectIfNecessary(obj);
3061       }
3062       obj->set_mark(markOopDesc::prototype());
3063       // While we were processing RSet buffers during the
3064       // collection, we actually didn't scan any cards on the
3065       // collection set, since we didn't want to update remebered
3066       // sets with entries that point into the collection set, given
3067       // that live objects fromthe collection set are about to move
3068       // and such entries will be stale very soon. This change also
3069       // dealt with a reliability issue which involved scanning a
3070       // card in the collection set and coming across an array that
3071       // was being chunked and looking malformed. The problem is
3072       // that, if evacuation fails, we might have remembered set
3073       // entries missing given that we skipped cards on the
3074       // collection set. So, we'll recreate such entries now.
3075       obj->oop_iterate(_cl);
3076       assert(_cm->isPrevMarked(obj), "Should be marked!");
3077     } else {
3078       // The object has been either evacuated or is dead. Fill it with a
3079       // dummy object.
3080       MemRegion mr((HeapWord*)obj, obj->size());
3081       CollectedHeap::fill_with_object(mr);
3082       _cm->clearRangeBothMaps(mr);
3083     }
3084   }
3085 };
3086 
3087 void G1CollectedHeap::remove_self_forwarding_pointers() {
3088   UpdateRSetImmediate immediate_update(_g1h);
3089   DirtyCardQueue dcq(&_g1h->dirty_card_queue_set());
3090   UpdateRSetDeferred deferred_update(_g1h, &dcq);
3091   OopsInHeapRegionClosure *cl;
3092   if (G1DeferredRSUpdate) {
3093     cl = &deferred_update;
3094   } else {
3095     cl = &immediate_update;
3096   }
3097   HeapRegion* cur = g1_policy()->collection_set();
3098   while (cur != NULL) {
3099     assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
3100 
3101     RemoveSelfPointerClosure rspc(_g1h, cl);
3102     if (cur->evacuation_failed()) {
3103       assert(cur->in_collection_set(), "bad CS");
3104       cl->set_region(cur);
3105       cur->object_iterate(&rspc);
3106 
3107       // A number of manipulations to make the TAMS be the current top,
3108       // and the marked bytes be the ones observed in the iteration.
3109       if (_g1h->concurrent_mark()->at_least_one_mark_complete()) {
3110         // The comments below are the postconditions achieved by the
3111         // calls.  Note especially the last such condition, which says that
3112         // the count of marked bytes has been properly restored.
3113         cur->note_start_of_marking(false);
3114         // _next_top_at_mark_start == top, _next_marked_bytes == 0
3115         cur->add_to_marked_bytes(rspc.prev_marked_bytes());
3116         // _next_marked_bytes == prev_marked_bytes.
3117         cur->note_end_of_marking();
3118         // _prev_top_at_mark_start == top(),
3119         // _prev_marked_bytes == prev_marked_bytes
3120       }
3121       // If there is no mark in progress, we modified the _next variables
3122       // above needlessly, but harmlessly.
3123       if (_g1h->mark_in_progress()) {
3124         cur->note_start_of_marking(false);
3125         // _next_top_at_mark_start == top, _next_marked_bytes == 0
3126         // _next_marked_bytes == next_marked_bytes.
3127       }
3128 
3129       // Now make sure the region has the right index in the sorted array.
3130       g1_policy()->note_change_in_marked_bytes(cur);
3131     }
3132     cur = cur->next_in_collection_set();
3133   }
3134   assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!");
3135 
3136   // Now restore saved marks, if any.
3137   if (_objs_with_preserved_marks != NULL) {
3138     assert(_preserved_marks_of_objs != NULL, "Both or none.");
3139     assert(_objs_with_preserved_marks->length() ==
3140            _preserved_marks_of_objs->length(), "Both or none.");
3141     guarantee(_objs_with_preserved_marks->length() ==
3142               _preserved_marks_of_objs->length(), "Both or none.");
3143     for (int i = 0; i < _objs_with_preserved_marks->length(); i++) {
3144       oop obj   = _objs_with_preserved_marks->at(i);
3145       markOop m = _preserved_marks_of_objs->at(i);
3146       obj->set_mark(m);
3147     }
3148     // Delete the preserved marks growable arrays (allocated on the C heap).
3149     delete _objs_with_preserved_marks;
3150     delete _preserved_marks_of_objs;
3151     _objs_with_preserved_marks = NULL;
3152     _preserved_marks_of_objs = NULL;
3153   }
3154 }
3155 
3156 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
3157   _evac_failure_scan_stack->push(obj);
3158 }
3159 
3160 void G1CollectedHeap::drain_evac_failure_scan_stack() {
3161   assert(_evac_failure_scan_stack != NULL, "precondition");
3162 
3163   while (_evac_failure_scan_stack->length() > 0) {
3164      oop obj = _evac_failure_scan_stack->pop();
3165      _evac_failure_closure->set_region(heap_region_containing(obj));
3166      obj->oop_iterate_backwards(_evac_failure_closure);
3167   }
3168 }
3169 
3170 void G1CollectedHeap::handle_evacuation_failure(oop old) {
3171   markOop m = old->mark();
3172   // forward to self
3173   assert(!old->is_forwarded(), "precondition");
3174 
3175   old->forward_to(old);
3176   handle_evacuation_failure_common(old, m);
3177 }
3178 
3179 oop
3180 G1CollectedHeap::handle_evacuation_failure_par(OopsInHeapRegionClosure* cl,
3181                                                oop old) {
3182   markOop m = old->mark();
3183   oop forward_ptr = old->forward_to_atomic(old);
3184   if (forward_ptr == NULL) {
3185     // Forward-to-self succeeded.
3186     if (_evac_failure_closure != cl) {
3187       MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag);
3188       assert(!_drain_in_progress,
3189              "Should only be true while someone holds the lock.");
3190       // Set the global evac-failure closure to the current thread's.
3191       assert(_evac_failure_closure == NULL, "Or locking has failed.");
3192       set_evac_failure_closure(cl);
3193       // Now do the common part.
3194       handle_evacuation_failure_common(old, m);
3195       // Reset to NULL.
3196       set_evac_failure_closure(NULL);
3197     } else {
3198       // The lock is already held, and this is recursive.
3199       assert(_drain_in_progress, "This should only be the recursive case.");
3200       handle_evacuation_failure_common(old, m);
3201     }
3202     return old;
3203   } else {
3204     // Someone else had a place to copy it.
3205     return forward_ptr;
3206   }
3207 }
3208 
3209 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) {
3210   set_evacuation_failed(true);
3211 
3212   preserve_mark_if_necessary(old, m);
3213 
3214   HeapRegion* r = heap_region_containing(old);
3215   if (!r->evacuation_failed()) {
3216     r->set_evacuation_failed(true);
3217     if (G1TraceRegions) {
3218       gclog_or_tty->print("evacuation failed in heap region "PTR_FORMAT" "
3219                           "["PTR_FORMAT","PTR_FORMAT")\n",
3220                           r, r->bottom(), r->end());
3221     }
3222   }
3223 
3224   push_on_evac_failure_scan_stack(old);
3225 
3226   if (!_drain_in_progress) {
3227     // prevent recursion in copy_to_survivor_space()
3228     _drain_in_progress = true;
3229     drain_evac_failure_scan_stack();
3230     _drain_in_progress = false;
3231   }
3232 }
3233 
3234 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) {
3235   if (m != markOopDesc::prototype()) {
3236     if (_objs_with_preserved_marks == NULL) {
3237       assert(_preserved_marks_of_objs == NULL, "Both or none.");
3238       _objs_with_preserved_marks =
3239         new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true);
3240       _preserved_marks_of_objs =
3241         new (ResourceObj::C_HEAP) GrowableArray<markOop>(40, true);
3242     }
3243     _objs_with_preserved_marks->push(obj);
3244     _preserved_marks_of_objs->push(m);
3245   }
3246 }
3247 
3248 // *** Parallel G1 Evacuation
3249 
3250 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
3251                                                   size_t word_size) {
3252   HeapRegion* alloc_region = _gc_alloc_regions[purpose];
3253   // let the caller handle alloc failure
3254   if (alloc_region == NULL) return NULL;
3255 
3256   HeapWord* block = alloc_region->par_allocate(word_size);
3257   if (block == NULL) {
3258     MutexLockerEx x(par_alloc_during_gc_lock(),
3259                     Mutex::_no_safepoint_check_flag);
3260     block = allocate_during_gc_slow(purpose, alloc_region, true, word_size);
3261   }
3262   return block;
3263 }
3264 
3265 void G1CollectedHeap::retire_alloc_region(HeapRegion* alloc_region,
3266                                             bool par) {
3267   // Another thread might have obtained alloc_region for the given
3268   // purpose, and might be attempting to allocate in it, and might
3269   // succeed.  Therefore, we can't do the "finalization" stuff on the
3270   // region below until we're sure the last allocation has happened.
3271   // We ensure this by allocating the remaining space with a garbage
3272   // object.
3273   if (par) par_allocate_remaining_space(alloc_region);
3274   // Now we can do the post-GC stuff on the region.
3275   alloc_region->note_end_of_copying();
3276   g1_policy()->record_after_bytes(alloc_region->used());
3277 }
3278 
3279 HeapWord*
3280 G1CollectedHeap::allocate_during_gc_slow(GCAllocPurpose purpose,
3281                                          HeapRegion*    alloc_region,
3282                                          bool           par,
3283                                          size_t         word_size) {
3284   HeapWord* block = NULL;
3285   // In the parallel case, a previous thread to obtain the lock may have
3286   // already assigned a new gc_alloc_region.
3287   if (alloc_region != _gc_alloc_regions[purpose]) {
3288     assert(par, "But should only happen in parallel case.");
3289     alloc_region = _gc_alloc_regions[purpose];
3290     if (alloc_region == NULL) return NULL;
3291     block = alloc_region->par_allocate(word_size);
3292     if (block != NULL) return block;
3293     // Otherwise, continue; this new region is empty, too.
3294   }
3295   assert(alloc_region != NULL, "We better have an allocation region");
3296   retire_alloc_region(alloc_region, par);
3297 
3298   if (_gc_alloc_region_counts[purpose] >= g1_policy()->max_regions(purpose)) {
3299     // Cannot allocate more regions for the given purpose.
3300     GCAllocPurpose alt_purpose = g1_policy()->alternative_purpose(purpose);
3301     // Is there an alternative?
3302     if (purpose != alt_purpose) {
3303       HeapRegion* alt_region = _gc_alloc_regions[alt_purpose];
3304       // Has not the alternative region been aliased?
3305       if (alloc_region != alt_region && alt_region != NULL) {
3306         // Try to allocate in the alternative region.
3307         if (par) {
3308           block = alt_region->par_allocate(word_size);
3309         } else {
3310           block = alt_region->allocate(word_size);
3311         }
3312         // Make an alias.
3313         _gc_alloc_regions[purpose] = _gc_alloc_regions[alt_purpose];
3314         if (block != NULL) {
3315           return block;
3316         }
3317         retire_alloc_region(alt_region, par);
3318       }
3319       // Both the allocation region and the alternative one are full
3320       // and aliased, replace them with a new allocation region.
3321       purpose = alt_purpose;
3322     } else {
3323       set_gc_alloc_region(purpose, NULL);
3324       return NULL;
3325     }
3326   }
3327 
3328   // Now allocate a new region for allocation.
3329   alloc_region = newAllocRegionWithExpansion(purpose, word_size, false /*zero_filled*/);
3330 
3331   // let the caller handle alloc failure
3332   if (alloc_region != NULL) {
3333 
3334     assert(check_gc_alloc_regions(), "alloc regions messed up");
3335     assert(alloc_region->saved_mark_at_top(),
3336            "Mark should have been saved already.");
3337     // We used to assert that the region was zero-filled here, but no
3338     // longer.
3339 
3340     // This must be done last: once it's installed, other regions may
3341     // allocate in it (without holding the lock.)
3342     set_gc_alloc_region(purpose, alloc_region);
3343 
3344     if (par) {
3345       block = alloc_region->par_allocate(word_size);
3346     } else {
3347       block = alloc_region->allocate(word_size);
3348     }
3349     // Caller handles alloc failure.
3350   } else {
3351     // This sets other apis using the same old alloc region to NULL, also.
3352     set_gc_alloc_region(purpose, NULL);
3353   }
3354   return block;  // May be NULL.
3355 }
3356 
3357 void G1CollectedHeap::par_allocate_remaining_space(HeapRegion* r) {
3358   HeapWord* block = NULL;
3359   size_t free_words;
3360   do {
3361     free_words = r->free()/HeapWordSize;
3362     // If there's too little space, no one can allocate, so we're done.
3363     if (free_words < (size_t)oopDesc::header_size()) return;
3364     // Otherwise, try to claim it.
3365     block = r->par_allocate(free_words);
3366   } while (block == NULL);
3367   fill_with_object(block, free_words);
3368 }
3369 
3370 #define use_local_bitmaps         1
3371 #define verify_local_bitmaps      0
3372 
3373 #ifndef PRODUCT
3374 
3375 class GCLabBitMap;
3376 class GCLabBitMapClosure: public BitMapClosure {
3377 private:
3378   ConcurrentMark* _cm;
3379   GCLabBitMap*    _bitmap;
3380 
3381 public:
3382   GCLabBitMapClosure(ConcurrentMark* cm,
3383                      GCLabBitMap* bitmap) {
3384     _cm     = cm;
3385     _bitmap = bitmap;
3386   }
3387 
3388   virtual bool do_bit(size_t offset);
3389 };
3390 
3391 #endif // PRODUCT
3392 
3393 #define oop_buffer_length 256
3394 
3395 class GCLabBitMap: public BitMap {
3396 private:
3397   ConcurrentMark* _cm;
3398 
3399   int       _shifter;
3400   size_t    _bitmap_word_covers_words;
3401 
3402   // beginning of the heap
3403   HeapWord* _heap_start;
3404 
3405   // this is the actual start of the GCLab
3406   HeapWord* _real_start_word;
3407 
3408   // this is the actual end of the GCLab
3409   HeapWord* _real_end_word;
3410 
3411   // this is the first word, possibly located before the actual start
3412   // of the GCLab, that corresponds to the first bit of the bitmap
3413   HeapWord* _start_word;
3414 
3415   // size of a GCLab in words
3416   size_t _gclab_word_size;
3417 
3418   static int shifter() {
3419     return MinObjAlignment - 1;
3420   }
3421 
3422   // how many heap words does a single bitmap word corresponds to?
3423   static size_t bitmap_word_covers_words() {
3424     return BitsPerWord << shifter();
3425   }
3426 
3427   static size_t gclab_word_size() {
3428     return ParallelGCG1AllocBufferSize / HeapWordSize;
3429   }
3430 
3431   static size_t bitmap_size_in_bits() {
3432     size_t bits_in_bitmap = gclab_word_size() >> shifter();
3433     // We are going to ensure that the beginning of a word in this
3434     // bitmap also corresponds to the beginning of a word in the
3435     // global marking bitmap. To handle the case where a GCLab
3436     // starts from the middle of the bitmap, we need to add enough
3437     // space (i.e. up to a bitmap word) to ensure that we have
3438     // enough bits in the bitmap.
3439     return bits_in_bitmap + BitsPerWord - 1;
3440   }
3441 public:
3442   GCLabBitMap(HeapWord* heap_start)
3443     : BitMap(bitmap_size_in_bits()),
3444       _cm(G1CollectedHeap::heap()->concurrent_mark()),
3445       _shifter(shifter()),
3446       _bitmap_word_covers_words(bitmap_word_covers_words()),
3447       _heap_start(heap_start),
3448       _gclab_word_size(gclab_word_size()),
3449       _real_start_word(NULL),
3450       _real_end_word(NULL),
3451       _start_word(NULL)
3452   {
3453     guarantee( size_in_words() >= bitmap_size_in_words(),
3454                "just making sure");
3455   }
3456 
3457   inline unsigned heapWordToOffset(HeapWord* addr) {
3458     unsigned offset = (unsigned) pointer_delta(addr, _start_word) >> _shifter;
3459     assert(offset < size(), "offset should be within bounds");
3460     return offset;
3461   }
3462 
3463   inline HeapWord* offsetToHeapWord(size_t offset) {
3464     HeapWord* addr =  _start_word + (offset << _shifter);
3465     assert(_real_start_word <= addr && addr < _real_end_word, "invariant");
3466     return addr;
3467   }
3468 
3469   bool fields_well_formed() {
3470     bool ret1 = (_real_start_word == NULL) &&
3471                 (_real_end_word == NULL) &&
3472                 (_start_word == NULL);
3473     if (ret1)
3474       return true;
3475 
3476     bool ret2 = _real_start_word >= _start_word &&
3477       _start_word < _real_end_word &&
3478       (_real_start_word + _gclab_word_size) == _real_end_word &&
3479       (_start_word + _gclab_word_size + _bitmap_word_covers_words)
3480                                                               > _real_end_word;
3481     return ret2;
3482   }
3483 
3484   inline bool mark(HeapWord* addr) {
3485     guarantee(use_local_bitmaps, "invariant");
3486     assert(fields_well_formed(), "invariant");
3487 
3488     if (addr >= _real_start_word && addr < _real_end_word) {
3489       assert(!isMarked(addr), "should not have already been marked");
3490 
3491       // first mark it on the bitmap
3492       at_put(heapWordToOffset(addr), true);
3493 
3494       return true;
3495     } else {
3496       return false;
3497     }
3498   }
3499 
3500   inline bool isMarked(HeapWord* addr) {
3501     guarantee(use_local_bitmaps, "invariant");
3502     assert(fields_well_formed(), "invariant");
3503 
3504     return at(heapWordToOffset(addr));
3505   }
3506 
3507   void set_buffer(HeapWord* start) {
3508     guarantee(use_local_bitmaps, "invariant");
3509     clear();
3510 
3511     assert(start != NULL, "invariant");
3512     _real_start_word = start;
3513     _real_end_word   = start + _gclab_word_size;
3514 
3515     size_t diff =
3516       pointer_delta(start, _heap_start) % _bitmap_word_covers_words;
3517     _start_word = start - diff;
3518 
3519     assert(fields_well_formed(), "invariant");
3520   }
3521 
3522 #ifndef PRODUCT
3523   void verify() {
3524     // verify that the marks have been propagated
3525     GCLabBitMapClosure cl(_cm, this);
3526     iterate(&cl);
3527   }
3528 #endif // PRODUCT
3529 
3530   void retire() {
3531     guarantee(use_local_bitmaps, "invariant");
3532     assert(fields_well_formed(), "invariant");
3533 
3534     if (_start_word != NULL) {
3535       CMBitMap*       mark_bitmap = _cm->nextMarkBitMap();
3536 
3537       // this means that the bitmap was set up for the GCLab
3538       assert(_real_start_word != NULL && _real_end_word != NULL, "invariant");
3539 
3540       mark_bitmap->mostly_disjoint_range_union(this,
3541                                 0, // always start from the start of the bitmap
3542                                 _start_word,
3543                                 size_in_words());
3544       _cm->grayRegionIfNecessary(MemRegion(_real_start_word, _real_end_word));
3545 
3546 #ifndef PRODUCT
3547       if (use_local_bitmaps && verify_local_bitmaps)
3548         verify();
3549 #endif // PRODUCT
3550     } else {
3551       assert(_real_start_word == NULL && _real_end_word == NULL, "invariant");
3552     }
3553   }
3554 
3555   static size_t bitmap_size_in_words() {
3556     return (bitmap_size_in_bits() + BitsPerWord - 1) / BitsPerWord;
3557   }
3558 };
3559 
3560 #ifndef PRODUCT
3561 
3562 bool GCLabBitMapClosure::do_bit(size_t offset) {
3563   HeapWord* addr = _bitmap->offsetToHeapWord(offset);
3564   guarantee(_cm->isMarked(oop(addr)), "it should be!");
3565   return true;
3566 }
3567 
3568 #endif // PRODUCT
3569 
3570 class G1ParGCAllocBuffer: public ParGCAllocBuffer {
3571 private:
3572   bool        _retired;
3573   bool        _during_marking;
3574   GCLabBitMap _bitmap;
3575 
3576 public:
3577   G1ParGCAllocBuffer() :
3578     ParGCAllocBuffer(ParallelGCG1AllocBufferSize / HeapWordSize),
3579     _during_marking(G1CollectedHeap::heap()->mark_in_progress()),
3580     _bitmap(G1CollectedHeap::heap()->reserved_region().start()),
3581     _retired(false)
3582   { }
3583 
3584   inline bool mark(HeapWord* addr) {
3585     guarantee(use_local_bitmaps, "invariant");
3586     assert(_during_marking, "invariant");
3587     return _bitmap.mark(addr);
3588   }
3589 
3590   inline void set_buf(HeapWord* buf) {
3591     if (use_local_bitmaps && _during_marking)
3592       _bitmap.set_buffer(buf);
3593     ParGCAllocBuffer::set_buf(buf);
3594     _retired = false;
3595   }
3596 
3597   inline void retire(bool end_of_gc, bool retain) {
3598     if (_retired)
3599       return;
3600     if (use_local_bitmaps && _during_marking) {
3601       _bitmap.retire();
3602     }
3603     ParGCAllocBuffer::retire(end_of_gc, retain);
3604     _retired = true;
3605   }
3606 };
3607 
3608 
3609 class G1ParScanThreadState : public StackObj {
3610 protected:
3611   G1CollectedHeap* _g1h;
3612   RefToScanQueue*  _refs;
3613   DirtyCardQueue   _dcq;
3614   CardTableModRefBS* _ct_bs;
3615   G1RemSet* _g1_rem;
3616 
3617   typedef GrowableArray<oop*> OverflowQueue;
3618   OverflowQueue* _overflowed_refs;
3619 
3620   G1ParGCAllocBuffer _alloc_buffers[GCAllocPurposeCount];
3621   ageTable           _age_table;
3622 
3623   size_t           _alloc_buffer_waste;
3624   size_t           _undo_waste;
3625 
3626   OopsInHeapRegionClosure*      _evac_failure_cl;
3627   G1ParScanHeapEvacClosure*     _evac_cl;
3628   G1ParScanPartialArrayClosure* _partial_scan_cl;
3629 
3630   int _hash_seed;
3631   int _queue_num;
3632 
3633   int _term_attempts;
3634 #if G1_DETAILED_STATS
3635   int _pushes, _pops, _steals, _steal_attempts;
3636   int _overflow_pushes;
3637 #endif
3638 
3639   double _start;
3640   double _start_strong_roots;
3641   double _strong_roots_time;
3642   double _start_term;
3643   double _term_time;
3644 
3645   // Map from young-age-index (0 == not young, 1 is youngest) to
3646   // surviving words. base is what we get back from the malloc call
3647   size_t* _surviving_young_words_base;
3648   // this points into the array, as we use the first few entries for padding
3649   size_t* _surviving_young_words;
3650 
3651 #define PADDING_ELEM_NUM (64 / sizeof(size_t))
3652 
3653   void   add_to_alloc_buffer_waste(size_t waste) { _alloc_buffer_waste += waste; }
3654 
3655   void   add_to_undo_waste(size_t waste)         { _undo_waste += waste; }
3656 
3657   DirtyCardQueue& dirty_card_queue()             { return _dcq;  }
3658   CardTableModRefBS* ctbs()                      { return _ct_bs; }
3659 
3660   void immediate_rs_update(HeapRegion* from, oop* p, int tid) {
3661     _g1_rem->par_write_ref(from, p, tid);
3662   }
3663 
3664   void deferred_rs_update(HeapRegion* from, oop* p, int tid) {
3665     // If the new value of the field points to the same region or
3666     // is the to-space, we don't need to include it in the Rset updates.
3667     if (!from->is_in_reserved(*p) && !from->is_survivor()) {
3668       size_t card_index = ctbs()->index_for(p);
3669       // If the card hasn't been added to the buffer, do it.
3670       if (ctbs()->mark_card_deferred(card_index)) {
3671         dirty_card_queue().enqueue((jbyte*)ctbs()->byte_for_index(card_index));
3672       }
3673     }
3674   }
3675 
3676 public:
3677   G1ParScanThreadState(G1CollectedHeap* g1h, int queue_num)
3678     : _g1h(g1h),
3679       _refs(g1h->task_queue(queue_num)),
3680       _dcq(&g1h->dirty_card_queue_set()),
3681       _ct_bs((CardTableModRefBS*)_g1h->barrier_set()),
3682       _g1_rem(g1h->g1_rem_set()),
3683       _hash_seed(17), _queue_num(queue_num),
3684       _term_attempts(0),
3685       _age_table(false),
3686 #if G1_DETAILED_STATS
3687       _pushes(0), _pops(0), _steals(0),
3688       _steal_attempts(0),  _overflow_pushes(0),
3689 #endif
3690       _strong_roots_time(0), _term_time(0),
3691       _alloc_buffer_waste(0), _undo_waste(0)
3692   {
3693     // we allocate G1YoungSurvRateNumRegions plus one entries, since
3694     // we "sacrifice" entry 0 to keep track of surviving bytes for
3695     // non-young regions (where the age is -1)
3696     // We also add a few elements at the beginning and at the end in
3697     // an attempt to eliminate cache contention
3698     size_t real_length = 1 + _g1h->g1_policy()->young_cset_length();
3699     size_t array_length = PADDING_ELEM_NUM +
3700                           real_length +
3701                           PADDING_ELEM_NUM;
3702     _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length);
3703     if (_surviving_young_words_base == NULL)
3704       vm_exit_out_of_memory(array_length * sizeof(size_t),
3705                             "Not enough space for young surv histo.");
3706     _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM;
3707     memset(_surviving_young_words, 0, real_length * sizeof(size_t));
3708 
3709     _overflowed_refs = new OverflowQueue(10);
3710 
3711     _start = os::elapsedTime();
3712   }
3713 
3714   ~G1ParScanThreadState() {
3715     FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base);
3716   }
3717 
3718   RefToScanQueue*   refs()            { return _refs;             }
3719   OverflowQueue*    overflowed_refs() { return _overflowed_refs;  }
3720   ageTable*         age_table()       { return &_age_table;       }
3721 
3722   G1ParGCAllocBuffer* alloc_buffer(GCAllocPurpose purpose) {
3723     return &_alloc_buffers[purpose];
3724   }
3725 
3726   size_t alloc_buffer_waste()                    { return _alloc_buffer_waste; }
3727   size_t undo_waste()                            { return _undo_waste; }
3728 
3729   void push_on_queue(oop* ref) {
3730     assert(ref != NULL, "invariant");
3731     assert(has_partial_array_mask(ref) || _g1h->obj_in_cs(*ref), "invariant");
3732 
3733     if (!refs()->push(ref)) {
3734       overflowed_refs()->push(ref);
3735       IF_G1_DETAILED_STATS(note_overflow_push());
3736     } else {
3737       IF_G1_DETAILED_STATS(note_push());
3738     }
3739   }
3740 
3741   void pop_from_queue(oop*& ref) {
3742     if (!refs()->pop_local(ref)) {
3743       ref = NULL;
3744     } else {
3745       assert(ref != NULL, "invariant");
3746       assert(has_partial_array_mask(ref) || _g1h->obj_in_cs(*ref),
3747              "invariant");
3748 
3749       IF_G1_DETAILED_STATS(note_pop());
3750     }
3751   }
3752 
3753   void pop_from_overflow_queue(oop*& ref) {
3754     ref = overflowed_refs()->pop();
3755   }
3756 
3757   int refs_to_scan()                             { return refs()->size();                 }
3758   int overflowed_refs_to_scan()                  { return overflowed_refs()->length();    }
3759 
3760   void update_rs(HeapRegion* from, oop* p, int tid) {
3761     if (G1DeferredRSUpdate) {
3762       deferred_rs_update(from, p, tid);
3763     } else {
3764       immediate_rs_update(from, p, tid);
3765     }
3766   }
3767 
3768   HeapWord* allocate_slow(GCAllocPurpose purpose, size_t word_sz) {
3769 
3770     HeapWord* obj = NULL;
3771     if (word_sz * 100 <
3772         (size_t)(ParallelGCG1AllocBufferSize / HeapWordSize) *
3773                                                   ParallelGCBufferWastePct) {
3774       G1ParGCAllocBuffer* alloc_buf = alloc_buffer(purpose);
3775       add_to_alloc_buffer_waste(alloc_buf->words_remaining());
3776       alloc_buf->retire(false, false);
3777 
3778       HeapWord* buf =
3779         _g1h->par_allocate_during_gc(purpose, ParallelGCG1AllocBufferSize / HeapWordSize);
3780       if (buf == NULL) return NULL; // Let caller handle allocation failure.
3781       // Otherwise.
3782       alloc_buf->set_buf(buf);
3783 
3784       obj = alloc_buf->allocate(word_sz);
3785       assert(obj != NULL, "buffer was definitely big enough...");
3786     } else {
3787       obj = _g1h->par_allocate_during_gc(purpose, word_sz);
3788     }
3789     return obj;
3790   }
3791 
3792   HeapWord* allocate(GCAllocPurpose purpose, size_t word_sz) {
3793     HeapWord* obj = alloc_buffer(purpose)->allocate(word_sz);
3794     if (obj != NULL) return obj;
3795     return allocate_slow(purpose, word_sz);
3796   }
3797 
3798   void undo_allocation(GCAllocPurpose purpose, HeapWord* obj, size_t word_sz) {
3799     if (alloc_buffer(purpose)->contains(obj)) {
3800       guarantee(alloc_buffer(purpose)->contains(obj + word_sz - 1),
3801                 "should contain whole object");
3802       alloc_buffer(purpose)->undo_allocation(obj, word_sz);
3803     } else {
3804       CollectedHeap::fill_with_object(obj, word_sz);
3805       add_to_undo_waste(word_sz);
3806     }
3807   }
3808 
3809   void set_evac_failure_closure(OopsInHeapRegionClosure* evac_failure_cl) {
3810     _evac_failure_cl = evac_failure_cl;
3811   }
3812   OopsInHeapRegionClosure* evac_failure_closure() {
3813     return _evac_failure_cl;
3814   }
3815 
3816   void set_evac_closure(G1ParScanHeapEvacClosure* evac_cl) {
3817     _evac_cl = evac_cl;
3818   }
3819 
3820   void set_partial_scan_closure(G1ParScanPartialArrayClosure* partial_scan_cl) {
3821     _partial_scan_cl = partial_scan_cl;
3822   }
3823 
3824   int* hash_seed() { return &_hash_seed; }
3825   int  queue_num() { return _queue_num; }
3826 
3827   int term_attempts()   { return _term_attempts; }
3828   void note_term_attempt()  { _term_attempts++; }
3829 
3830 #if G1_DETAILED_STATS
3831   int pushes()          { return _pushes; }
3832   int pops()            { return _pops; }
3833   int steals()          { return _steals; }
3834   int steal_attempts()  { return _steal_attempts; }
3835   int overflow_pushes() { return _overflow_pushes; }
3836 
3837   void note_push()          { _pushes++; }
3838   void note_pop()           { _pops++; }
3839   void note_steal()         { _steals++; }
3840   void note_steal_attempt() { _steal_attempts++; }
3841   void note_overflow_push() { _overflow_pushes++; }
3842 #endif
3843 
3844   void start_strong_roots() {
3845     _start_strong_roots = os::elapsedTime();
3846   }
3847   void end_strong_roots() {
3848     _strong_roots_time += (os::elapsedTime() - _start_strong_roots);
3849   }
3850   double strong_roots_time() { return _strong_roots_time; }
3851 
3852   void start_term_time() {
3853     note_term_attempt();
3854     _start_term = os::elapsedTime();
3855   }
3856   void end_term_time() {
3857     _term_time += (os::elapsedTime() - _start_term);
3858   }
3859   double term_time() { return _term_time; }
3860 
3861   double elapsed() {
3862     return os::elapsedTime() - _start;
3863   }
3864 
3865   size_t* surviving_young_words() {
3866     // We add on to hide entry 0 which accumulates surviving words for
3867     // age -1 regions (i.e. non-young ones)
3868     return _surviving_young_words;
3869   }
3870 
3871   void retire_alloc_buffers() {
3872     for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
3873       size_t waste = _alloc_buffers[ap].words_remaining();
3874       add_to_alloc_buffer_waste(waste);
3875       _alloc_buffers[ap].retire(true, false);
3876     }
3877   }
3878 
3879 private:
3880   void deal_with_reference(oop* ref_to_scan) {
3881     if (has_partial_array_mask(ref_to_scan)) {
3882       _partial_scan_cl->do_oop_nv(ref_to_scan);
3883     } else {
3884       // Note: we can use "raw" versions of "region_containing" because
3885       // "obj_to_scan" is definitely in the heap, and is not in a
3886       // humongous region.
3887       HeapRegion* r = _g1h->heap_region_containing_raw(ref_to_scan);
3888       _evac_cl->set_region(r);
3889       _evac_cl->do_oop_nv(ref_to_scan);
3890     }
3891   }
3892 
3893 public:
3894   void trim_queue() {
3895     // I've replicated the loop twice, first to drain the overflow
3896     // queue, second to drain the task queue. This is better than
3897     // having a single loop, which checks both conditions and, inside
3898     // it, either pops the overflow queue or the task queue, as each
3899     // loop is tighter. Also, the decision to drain the overflow queue
3900     // first is not arbitrary, as the overflow queue is not visible
3901     // to the other workers, whereas the task queue is. So, we want to
3902     // drain the "invisible" entries first, while allowing the other
3903     // workers to potentially steal the "visible" entries.
3904 
3905     while (refs_to_scan() > 0 || overflowed_refs_to_scan() > 0) {
3906       while (overflowed_refs_to_scan() > 0) {
3907         oop *ref_to_scan = NULL;
3908         pop_from_overflow_queue(ref_to_scan);
3909         assert(ref_to_scan != NULL, "invariant");
3910         // We shouldn't have pushed it on the queue if it was not
3911         // pointing into the CSet.
3912         assert(ref_to_scan != NULL, "sanity");
3913         assert(has_partial_array_mask(ref_to_scan) ||
3914                                       _g1h->obj_in_cs(*ref_to_scan), "sanity");
3915 
3916         deal_with_reference(ref_to_scan);
3917       }
3918 
3919       while (refs_to_scan() > 0) {
3920         oop *ref_to_scan = NULL;
3921         pop_from_queue(ref_to_scan);
3922 
3923         if (ref_to_scan != NULL) {
3924           // We shouldn't have pushed it on the queue if it was not
3925           // pointing into the CSet.
3926           assert(has_partial_array_mask(ref_to_scan) ||
3927                                       _g1h->obj_in_cs(*ref_to_scan), "sanity");
3928 
3929           deal_with_reference(ref_to_scan);
3930         }
3931       }
3932     }
3933   }
3934 };
3935 
3936 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) :
3937   _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()),
3938   _par_scan_state(par_scan_state) { }
3939 
3940 // This closure is applied to the fields of the objects that have just been copied.
3941 // Should probably be made inline and moved in g1OopClosures.inline.hpp.
3942 void G1ParScanClosure::do_oop_nv(oop* p) {
3943   oop obj = *p;
3944 
3945   if (obj != NULL) {
3946     if (_g1->in_cset_fast_test(obj)) {
3947       // We're not going to even bother checking whether the object is
3948       // already forwarded or not, as this usually causes an immediate
3949       // stall. We'll try to prefetch the object (for write, given that
3950       // we might need to install the forwarding reference) and we'll
3951       // get back to it when pop it from the queue
3952       Prefetch::write(obj->mark_addr(), 0);
3953       Prefetch::read(obj->mark_addr(), (HeapWordSize*2));
3954 
3955       // slightly paranoid test; I'm trying to catch potential
3956       // problems before we go into push_on_queue to know where the
3957       // problem is coming from
3958       assert(obj == *p, "the value of *p should not have changed");
3959       _par_scan_state->push_on_queue(p);
3960     } else {
3961       _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
3962     }
3963   }
3964 }
3965 
3966 void G1ParCopyHelper::mark_forwardee(oop* p) {
3967   // This is called _after_ do_oop_work has been called, hence after
3968   // the object has been relocated to its new location and *p points
3969   // to its new location.
3970 
3971   oop thisOop = *p;
3972   if (thisOop != NULL) {
3973     assert((_g1->evacuation_failed()) || (!_g1->obj_in_cs(thisOop)),
3974            "shouldn't still be in the CSet if evacuation didn't fail.");
3975     HeapWord* addr = (HeapWord*)thisOop;
3976     if (_g1->is_in_g1_reserved(addr))
3977       _cm->grayRoot(oop(addr));
3978   }
3979 }
3980 
3981 oop G1ParCopyHelper::copy_to_survivor_space(oop old) {
3982   size_t    word_sz = old->size();
3983   HeapRegion* from_region = _g1->heap_region_containing_raw(old);
3984   // +1 to make the -1 indexes valid...
3985   int       young_index = from_region->young_index_in_cset()+1;
3986   assert( (from_region->is_young() && young_index > 0) ||
3987           (!from_region->is_young() && young_index == 0), "invariant" );
3988   G1CollectorPolicy* g1p = _g1->g1_policy();
3989   markOop m = old->mark();
3990   int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age()
3991                                            : m->age();
3992   GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age,
3993                                                              word_sz);
3994   HeapWord* obj_ptr = _par_scan_state->allocate(alloc_purpose, word_sz);
3995   oop       obj     = oop(obj_ptr);
3996 
3997   if (obj_ptr == NULL) {
3998     // This will either forward-to-self, or detect that someone else has
3999     // installed a forwarding pointer.
4000     OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure();
4001     return _g1->handle_evacuation_failure_par(cl, old);
4002   }
4003 
4004   // We're going to allocate linearly, so might as well prefetch ahead.
4005   Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes);
4006 
4007   oop forward_ptr = old->forward_to_atomic(obj);
4008   if (forward_ptr == NULL) {
4009     Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz);
4010     if (g1p->track_object_age(alloc_purpose)) {
4011       // We could simply do obj->incr_age(). However, this causes a
4012       // performance issue. obj->incr_age() will first check whether
4013       // the object has a displaced mark by checking its mark word;
4014       // getting the mark word from the new location of the object
4015       // stalls. So, given that we already have the mark word and we
4016       // are about to install it anyway, it's better to increase the
4017       // age on the mark word, when the object does not have a
4018       // displaced mark word. We're not expecting many objects to have
4019       // a displaced marked word, so that case is not optimized
4020       // further (it could be...) and we simply call obj->incr_age().
4021 
4022       if (m->has_displaced_mark_helper()) {
4023         // in this case, we have to install the mark word first,
4024         // otherwise obj looks to be forwarded (the old mark word,
4025         // which contains the forward pointer, was copied)
4026         obj->set_mark(m);
4027         obj->incr_age();
4028       } else {
4029         m = m->incr_age();
4030         obj->set_mark(m);
4031       }
4032       _par_scan_state->age_table()->add(obj, word_sz);
4033     } else {
4034       obj->set_mark(m);
4035     }
4036 
4037     // preserve "next" mark bit
4038     if (_g1->mark_in_progress() && !_g1->is_obj_ill(old)) {
4039       if (!use_local_bitmaps ||
4040           !_par_scan_state->alloc_buffer(alloc_purpose)->mark(obj_ptr)) {
4041         // if we couldn't mark it on the local bitmap (this happens when
4042         // the object was not allocated in the GCLab), we have to bite
4043         // the bullet and do the standard parallel mark
4044         _cm->markAndGrayObjectIfNecessary(obj);
4045       }
4046 #if 1
4047       if (_g1->isMarkedNext(old)) {
4048         _cm->nextMarkBitMap()->parClear((HeapWord*)old);
4049       }
4050 #endif
4051     }
4052 
4053     size_t* surv_young_words = _par_scan_state->surviving_young_words();
4054     surv_young_words[young_index] += word_sz;
4055 
4056     if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) {
4057       arrayOop(old)->set_length(0);
4058       _par_scan_state->push_on_queue(set_partial_array_mask(old));
4059     } else {
4060       // No point in using the slower heap_region_containing() method,
4061       // given that we know obj is in the heap.
4062       _scanner->set_region(_g1->heap_region_containing_raw(obj));
4063       obj->oop_iterate_backwards(_scanner);
4064     }
4065   } else {
4066     _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz);
4067     obj = forward_ptr;
4068   }
4069   return obj;
4070 }
4071 
4072 template<bool do_gen_barrier, G1Barrier barrier,
4073          bool do_mark_forwardee, bool skip_cset_test>
4074 void G1ParCopyClosure<do_gen_barrier, barrier,
4075                       do_mark_forwardee, skip_cset_test>::do_oop_work(oop* p) {
4076   oop obj = *p;
4077   assert(barrier != G1BarrierRS || obj != NULL,
4078          "Precondition: G1BarrierRS implies obj is nonNull");
4079 
4080   // The only time we skip the cset test is when we're scanning
4081   // references popped from the queue. And we only push on the queue
4082   // references that we know point into the cset, so no point in
4083   // checking again. But we'll leave an assert here for peace of mind.
4084   assert(!skip_cset_test || _g1->obj_in_cs(obj), "invariant");
4085 
4086   // here the null check is implicit in the cset_fast_test() test
4087   if (skip_cset_test || _g1->in_cset_fast_test(obj)) {
4088 #if G1_REM_SET_LOGGING
4089     gclog_or_tty->print_cr("Loc "PTR_FORMAT" contains pointer "PTR_FORMAT" "
4090                            "into CS.", p, (void*) obj);
4091 #endif
4092     if (obj->is_forwarded()) {
4093       *p = obj->forwardee();
4094     } else {
4095       *p = copy_to_survivor_space(obj);
4096     }
4097     // When scanning the RS, we only care about objs in CS.
4098     if (barrier == G1BarrierRS) {
4099       _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
4100     }
4101   }
4102 
4103   // When scanning moved objs, must look at all oops.
4104   if (barrier == G1BarrierEvac && obj != NULL) {
4105     _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num());
4106   }
4107 
4108   if (do_gen_barrier && obj != NULL) {
4109     par_do_barrier(p);
4110   }
4111 }
4112 
4113 template void G1ParCopyClosure<false, G1BarrierEvac, false, true>::do_oop_work(oop* p);
4114 
4115 template<class T> void G1ParScanPartialArrayClosure::process_array_chunk(
4116   oop obj, int start, int end) {
4117   // process our set of indices (include header in first chunk)
4118   assert(start < end, "invariant");
4119   T* const base      = (T*)objArrayOop(obj)->base();
4120   T* const start_addr = (start == 0) ? (T*) obj : base + start;
4121   T* const end_addr   = base + end;
4122   MemRegion mr((HeapWord*)start_addr, (HeapWord*)end_addr);
4123   _scanner.set_region(_g1->heap_region_containing(obj));
4124   obj->oop_iterate(&_scanner, mr);
4125 }
4126 
4127 void G1ParScanPartialArrayClosure::do_oop_nv(oop* p) {
4128   assert(!UseCompressedOops, "Needs to be fixed to work with compressed oops");
4129   assert(has_partial_array_mask(p), "invariant");
4130   oop old = clear_partial_array_mask(p);
4131   assert(old->is_objArray(), "must be obj array");
4132   assert(old->is_forwarded(), "must be forwarded");
4133   assert(Universe::heap()->is_in_reserved(old), "must be in heap.");
4134 
4135   objArrayOop obj = objArrayOop(old->forwardee());
4136   assert((void*)old != (void*)old->forwardee(), "self forwarding here?");
4137   // Process ParGCArrayScanChunk elements now
4138   // and push the remainder back onto queue
4139   int start     = arrayOop(old)->length();
4140   int end       = obj->length();
4141   int remainder = end - start;
4142   assert(start <= end, "just checking");
4143   if (remainder > 2 * ParGCArrayScanChunk) {
4144     // Test above combines last partial chunk with a full chunk
4145     end = start + ParGCArrayScanChunk;
4146     arrayOop(old)->set_length(end);
4147     // Push remainder.
4148     _par_scan_state->push_on_queue(set_partial_array_mask(old));
4149   } else {
4150     // Restore length so that the heap remains parsable in
4151     // case of evacuation failure.
4152     arrayOop(old)->set_length(end);
4153   }
4154 
4155   // process our set of indices (include header in first chunk)
4156   process_array_chunk<oop>(obj, start, end);
4157 }
4158 
4159 int G1ScanAndBalanceClosure::_nq = 0;
4160 
4161 class G1ParEvacuateFollowersClosure : public VoidClosure {
4162 protected:
4163   G1CollectedHeap*              _g1h;
4164   G1ParScanThreadState*         _par_scan_state;
4165   RefToScanQueueSet*            _queues;
4166   ParallelTaskTerminator*       _terminator;
4167 
4168   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
4169   RefToScanQueueSet*      queues()         { return _queues; }
4170   ParallelTaskTerminator* terminator()     { return _terminator; }
4171 
4172 public:
4173   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
4174                                 G1ParScanThreadState* par_scan_state,
4175                                 RefToScanQueueSet* queues,
4176                                 ParallelTaskTerminator* terminator)
4177     : _g1h(g1h), _par_scan_state(par_scan_state),
4178       _queues(queues), _terminator(terminator) {}
4179 
4180   void do_void() {
4181     G1ParScanThreadState* pss = par_scan_state();
4182     while (true) {
4183       oop* ref_to_scan;
4184       pss->trim_queue();
4185       IF_G1_DETAILED_STATS(pss->note_steal_attempt());
4186       if (queues()->steal(pss->queue_num(),
4187                           pss->hash_seed(),
4188                           ref_to_scan)) {
4189         IF_G1_DETAILED_STATS(pss->note_steal());
4190 
4191         // slightly paranoid tests; I'm trying to catch potential
4192         // problems before we go into push_on_queue to know where the
4193         // problem is coming from
4194         assert(ref_to_scan != NULL, "invariant");
4195         assert(has_partial_array_mask(ref_to_scan) ||
4196                                    _g1h->obj_in_cs(*ref_to_scan), "invariant");
4197         pss->push_on_queue(ref_to_scan);
4198         continue;
4199       }
4200       pss->start_term_time();
4201       if (terminator()->offer_termination()) break;
4202       pss->end_term_time();
4203     }
4204     pss->end_term_time();
4205     pss->retire_alloc_buffers();
4206   }
4207 };
4208 
4209 class G1ParTask : public AbstractGangTask {
4210 protected:
4211   G1CollectedHeap*       _g1h;
4212   RefToScanQueueSet      *_queues;
4213   ParallelTaskTerminator _terminator;
4214 
4215   Mutex _stats_lock;
4216   Mutex* stats_lock() { return &_stats_lock; }
4217 
4218   size_t getNCards() {
4219     return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
4220       / G1BlockOffsetSharedArray::N_bytes;
4221   }
4222 
4223 public:
4224   G1ParTask(G1CollectedHeap* g1h, int workers, RefToScanQueueSet *task_queues)
4225     : AbstractGangTask("G1 collection"),
4226       _g1h(g1h),
4227       _queues(task_queues),
4228       _terminator(workers, _queues),
4229       _stats_lock(Mutex::leaf, "parallel G1 stats lock", true)
4230   {}
4231 
4232   RefToScanQueueSet* queues() { return _queues; }
4233 
4234   RefToScanQueue *work_queue(int i) {
4235     return queues()->queue(i);
4236   }
4237 
4238   void work(int i) {
4239     ResourceMark rm;
4240     HandleMark   hm;
4241 
4242     G1ParScanThreadState            pss(_g1h, i);
4243     G1ParScanHeapEvacClosure        scan_evac_cl(_g1h, &pss);
4244     G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss);
4245     G1ParScanPartialArrayClosure    partial_scan_cl(_g1h, &pss);
4246 
4247     pss.set_evac_closure(&scan_evac_cl);
4248     pss.set_evac_failure_closure(&evac_failure_cl);
4249     pss.set_partial_scan_closure(&partial_scan_cl);
4250 
4251     G1ParScanExtRootClosure         only_scan_root_cl(_g1h, &pss);
4252     G1ParScanPermClosure            only_scan_perm_cl(_g1h, &pss);
4253     G1ParScanHeapRSClosure          only_scan_heap_rs_cl(_g1h, &pss);
4254 
4255     G1ParScanAndMarkExtRootClosure  scan_mark_root_cl(_g1h, &pss);
4256     G1ParScanAndMarkPermClosure     scan_mark_perm_cl(_g1h, &pss);
4257     G1ParScanAndMarkHeapRSClosure   scan_mark_heap_rs_cl(_g1h, &pss);
4258 
4259     OopsInHeapRegionClosure        *scan_root_cl;
4260     OopsInHeapRegionClosure        *scan_perm_cl;
4261     OopsInHeapRegionClosure        *scan_so_cl;
4262 
4263     if (_g1h->g1_policy()->should_initiate_conc_mark()) {
4264       scan_root_cl = &scan_mark_root_cl;
4265       scan_perm_cl = &scan_mark_perm_cl;
4266       scan_so_cl   = &scan_mark_heap_rs_cl;
4267     } else {
4268       scan_root_cl = &only_scan_root_cl;
4269       scan_perm_cl = &only_scan_perm_cl;
4270       scan_so_cl   = &only_scan_heap_rs_cl;
4271     }
4272 
4273     pss.start_strong_roots();
4274     _g1h->g1_process_strong_roots(/* not collecting perm */ false,
4275                                   SharedHeap::SO_AllClasses,
4276                                   scan_root_cl,
4277                                   &only_scan_heap_rs_cl,
4278                                   scan_so_cl,
4279                                   scan_perm_cl,
4280                                   i);
4281     pss.end_strong_roots();
4282     {
4283       double start = os::elapsedTime();
4284       G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator);
4285       evac.do_void();
4286       double elapsed_ms = (os::elapsedTime()-start)*1000.0;
4287       double term_ms = pss.term_time()*1000.0;
4288       _g1h->g1_policy()->record_obj_copy_time(i, elapsed_ms-term_ms);
4289       _g1h->g1_policy()->record_termination_time(i, term_ms);
4290     }
4291     if (G1UseSurvivorSpace) {
4292       _g1h->g1_policy()->record_thread_age_table(pss.age_table());
4293     }
4294     _g1h->update_surviving_young_words(pss.surviving_young_words()+1);
4295 
4296     // Clean up any par-expanded rem sets.
4297     HeapRegionRemSet::par_cleanup();
4298 
4299     MutexLocker x(stats_lock());
4300     if (ParallelGCVerbose) {
4301       gclog_or_tty->print("Thread %d complete:\n", i);
4302 #if G1_DETAILED_STATS
4303       gclog_or_tty->print("  Pushes: %7d    Pops: %7d   Overflows: %7d   Steals %7d (in %d attempts)\n",
4304                           pss.pushes(),
4305                           pss.pops(),
4306                           pss.overflow_pushes(),
4307                           pss.steals(),
4308                           pss.steal_attempts());
4309 #endif
4310       double elapsed      = pss.elapsed();
4311       double strong_roots = pss.strong_roots_time();
4312       double term         = pss.term_time();
4313       gclog_or_tty->print("  Elapsed: %7.2f ms.\n"
4314                           "    Strong roots: %7.2f ms (%6.2f%%)\n"
4315                           "    Termination:  %7.2f ms (%6.2f%%) (in %d entries)\n",
4316                           elapsed * 1000.0,
4317                           strong_roots * 1000.0, (strong_roots*100.0/elapsed),
4318                           term * 1000.0, (term*100.0/elapsed),
4319                           pss.term_attempts());
4320       size_t total_waste = pss.alloc_buffer_waste() + pss.undo_waste();
4321       gclog_or_tty->print("  Waste: %8dK\n"
4322                  "    Alloc Buffer: %8dK\n"
4323                  "    Undo: %8dK\n",
4324                  (total_waste * HeapWordSize) / K,
4325                  (pss.alloc_buffer_waste() * HeapWordSize) / K,
4326                  (pss.undo_waste() * HeapWordSize) / K);
4327     }
4328 
4329     assert(pss.refs_to_scan() == 0, "Task queue should be empty");
4330     assert(pss.overflowed_refs_to_scan() == 0, "Overflow queue should be empty");
4331   }
4332 };
4333 
4334 // *** Common G1 Evacuation Stuff
4335 
4336 class G1CountClosure: public OopsInHeapRegionClosure {
4337 public:
4338   int n;
4339   G1CountClosure() : n(0) {}
4340   void do_oop(narrowOop* p) {
4341     guarantee(false, "NYI");
4342   }
4343   void do_oop(oop* p) {
4344     oop obj = *p;
4345     assert(obj != NULL && G1CollectedHeap::heap()->obj_in_cs(obj),
4346            "Rem set closure called on non-rem-set pointer.");
4347     n++;
4348   }
4349 };
4350 
4351 static G1CountClosure count_closure;
4352 
4353 void
4354 G1CollectedHeap::
4355 g1_process_strong_roots(bool collecting_perm_gen,
4356                         SharedHeap::ScanningOption so,
4357                         OopClosure* scan_non_heap_roots,
4358                         OopsInHeapRegionClosure* scan_rs,
4359                         OopsInHeapRegionClosure* scan_so,
4360                         OopsInGenClosure* scan_perm,
4361                         int worker_i) {
4362   // First scan the strong roots, including the perm gen.
4363   double ext_roots_start = os::elapsedTime();
4364   double closure_app_time_sec = 0.0;
4365 
4366   BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots);
4367   BufferingOopsInGenClosure buf_scan_perm(scan_perm);
4368   buf_scan_perm.set_generation(perm_gen());
4369 
4370   process_strong_roots(collecting_perm_gen, so,
4371                        &buf_scan_non_heap_roots,
4372                        &buf_scan_perm);
4373   // Finish up any enqueued closure apps.
4374   buf_scan_non_heap_roots.done();
4375   buf_scan_perm.done();
4376   double ext_roots_end = os::elapsedTime();
4377   g1_policy()->reset_obj_copy_time(worker_i);
4378   double obj_copy_time_sec =
4379     buf_scan_non_heap_roots.closure_app_seconds() +
4380     buf_scan_perm.closure_app_seconds();
4381   g1_policy()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0);
4382   double ext_root_time_ms =
4383     ((ext_roots_end - ext_roots_start) - obj_copy_time_sec) * 1000.0;
4384   g1_policy()->record_ext_root_scan_time(worker_i, ext_root_time_ms);
4385 
4386   // Scan strong roots in mark stack.
4387   if (!_process_strong_tasks->is_task_claimed(G1H_PS_mark_stack_oops_do)) {
4388     concurrent_mark()->oops_do(scan_non_heap_roots);
4389   }
4390   double mark_stack_scan_ms = (os::elapsedTime() - ext_roots_end) * 1000.0;
4391   g1_policy()->record_mark_stack_scan_time(worker_i, mark_stack_scan_ms);
4392 
4393   // XXX What should this be doing in the parallel case?
4394   g1_policy()->record_collection_pause_end_CH_strong_roots();
4395   if (G1VerifyRemSet) {
4396     // :::: FIXME ::::
4397     // The stupid remembered set doesn't know how to filter out dead
4398     // objects, which the smart one does, and so when it is created
4399     // and then compared the number of entries in each differs and
4400     // the verification code fails.
4401     guarantee(false, "verification code is broken, see note");
4402 
4403     // Let's make sure that the current rem set agrees with the stupidest
4404     // one possible!
4405     bool refs_enabled = ref_processor()->discovery_enabled();
4406     if (refs_enabled) ref_processor()->disable_discovery();
4407     StupidG1RemSet stupid(this);
4408     count_closure.n = 0;
4409     stupid.oops_into_collection_set_do(&count_closure, worker_i);
4410     int stupid_n = count_closure.n;
4411     count_closure.n = 0;
4412     g1_rem_set()->oops_into_collection_set_do(&count_closure, worker_i);
4413     guarantee(count_closure.n == stupid_n, "Old and new rem sets differ.");
4414     gclog_or_tty->print_cr("\nFound %d pointers in heap RS.", count_closure.n);
4415     if (refs_enabled) ref_processor()->enable_discovery();
4416   }
4417   if (scan_so != NULL) {
4418     scan_scan_only_set(scan_so, worker_i);
4419   }
4420   // Now scan the complement of the collection set.
4421   if (scan_rs != NULL) {
4422     g1_rem_set()->oops_into_collection_set_do(scan_rs, worker_i);
4423   }
4424   // Finish with the ref_processor roots.
4425   if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) {
4426     ref_processor()->oops_do(scan_non_heap_roots);
4427   }
4428   g1_policy()->record_collection_pause_end_G1_strong_roots();
4429   _process_strong_tasks->all_tasks_completed();
4430 }
4431 
4432 void
4433 G1CollectedHeap::scan_scan_only_region(HeapRegion* r,
4434                                        OopsInHeapRegionClosure* oc,
4435                                        int worker_i) {
4436   HeapWord* startAddr = r->bottom();
4437   HeapWord* endAddr = r->used_region().end();
4438 
4439   oc->set_region(r);
4440 
4441   HeapWord* p = r->bottom();
4442   HeapWord* t = r->top();
4443   guarantee( p == r->next_top_at_mark_start(), "invariant" );
4444   while (p < t) {
4445     oop obj = oop(p);
4446     p += obj->oop_iterate(oc);
4447   }
4448 }
4449 
4450 void
4451 G1CollectedHeap::scan_scan_only_set(OopsInHeapRegionClosure* oc,
4452                                     int worker_i) {
4453   double start = os::elapsedTime();
4454 
4455   BufferingOopsInHeapRegionClosure boc(oc);
4456 
4457   FilterInHeapRegionAndIntoCSClosure scan_only(this, &boc);
4458   FilterAndMarkInHeapRegionAndIntoCSClosure scan_and_mark(this, &boc, concurrent_mark());
4459 
4460   OopsInHeapRegionClosure *foc;
4461   if (g1_policy()->should_initiate_conc_mark())
4462     foc = &scan_and_mark;
4463   else
4464     foc = &scan_only;
4465 
4466   HeapRegion* hr;
4467   int n = 0;
4468   while ((hr = _young_list->par_get_next_scan_only_region()) != NULL) {
4469     scan_scan_only_region(hr, foc, worker_i);
4470     ++n;
4471   }
4472   boc.done();
4473 
4474   double closure_app_s = boc.closure_app_seconds();
4475   g1_policy()->record_obj_copy_time(worker_i, closure_app_s * 1000.0);
4476   double ms = (os::elapsedTime() - start - closure_app_s)*1000.0;
4477   g1_policy()->record_scan_only_time(worker_i, ms, n);
4478 }
4479 
4480 void
4481 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure,
4482                                        OopClosure* non_root_closure) {
4483   SharedHeap::process_weak_roots(root_closure, non_root_closure);
4484 }
4485 
4486 
4487 class SaveMarksClosure: public HeapRegionClosure {
4488 public:
4489   bool doHeapRegion(HeapRegion* r) {
4490     r->save_marks();
4491     return false;
4492   }
4493 };
4494 
4495 void G1CollectedHeap::save_marks() {
4496   if (ParallelGCThreads == 0) {
4497     SaveMarksClosure sm;
4498     heap_region_iterate(&sm);
4499   }
4500   // We do this even in the parallel case
4501   perm_gen()->save_marks();
4502 }
4503 
4504 void G1CollectedHeap::evacuate_collection_set() {
4505   set_evacuation_failed(false);
4506 
4507   g1_rem_set()->prepare_for_oops_into_collection_set_do();
4508   concurrent_g1_refine()->set_use_cache(false);
4509   int n_workers = (ParallelGCThreads > 0 ? workers()->total_workers() : 1);
4510   set_par_threads(n_workers);
4511   G1ParTask g1_par_task(this, n_workers, _task_queues);
4512 
4513   init_for_evac_failure(NULL);
4514 
4515   change_strong_roots_parity();  // In preparation for parallel strong roots.
4516   rem_set()->prepare_for_younger_refs_iterate(true);
4517 
4518   assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty");
4519   double start_par = os::elapsedTime();
4520   if (ParallelGCThreads > 0) {
4521     // The individual threads will set their evac-failure closures.
4522     workers()->run_task(&g1_par_task);
4523   } else {
4524     g1_par_task.work(0);
4525   }
4526 
4527   double par_time = (os::elapsedTime() - start_par) * 1000.0;
4528   g1_policy()->record_par_time(par_time);
4529   set_par_threads(0);
4530   // Is this the right thing to do here?  We don't save marks
4531   // on individual heap regions when we allocate from
4532   // them in parallel, so this seems like the correct place for this.
4533   retire_all_alloc_regions();
4534   {
4535     G1IsAliveClosure is_alive(this);
4536     G1KeepAliveClosure keep_alive(this);
4537     JNIHandles::weak_oops_do(&is_alive, &keep_alive);
4538   }
4539   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
4540 
4541   concurrent_g1_refine()->set_use_cache(true);
4542 
4543   finalize_for_evac_failure();
4544 
4545   // Must do this before removing self-forwarding pointers, which clears
4546   // the per-region evac-failure flags.
4547   concurrent_mark()->complete_marking_in_collection_set();
4548 
4549   if (evacuation_failed()) {
4550     remove_self_forwarding_pointers();
4551     if (PrintGCDetails) {
4552       gclog_or_tty->print(" (evacuation failed)");
4553     } else if (PrintGC) {
4554       gclog_or_tty->print("--");
4555     }
4556   }
4557 
4558   if (G1DeferredRSUpdate) {
4559     RedirtyLoggedCardTableEntryFastClosure redirty;
4560     dirty_card_queue_set().set_closure(&redirty);
4561     dirty_card_queue_set().apply_closure_to_all_completed_buffers();
4562     JavaThread::dirty_card_queue_set().merge_bufferlists(&dirty_card_queue_set());
4563     assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
4564   }
4565 
4566   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
4567 }
4568 
4569 void G1CollectedHeap::free_region(HeapRegion* hr) {
4570   size_t pre_used = 0;
4571   size_t cleared_h_regions = 0;
4572   size_t freed_regions = 0;
4573   UncleanRegionList local_list;
4574 
4575   HeapWord* start = hr->bottom();
4576   HeapWord* end   = hr->prev_top_at_mark_start();
4577   size_t used_bytes = hr->used();
4578   size_t live_bytes = hr->max_live_bytes();
4579   if (used_bytes > 0) {
4580     guarantee( live_bytes <= used_bytes, "invariant" );
4581   } else {
4582     guarantee( live_bytes == 0, "invariant" );
4583   }
4584 
4585   size_t garbage_bytes = used_bytes - live_bytes;
4586   if (garbage_bytes > 0)
4587     g1_policy()->decrease_known_garbage_bytes(garbage_bytes);
4588 
4589   free_region_work(hr, pre_used, cleared_h_regions, freed_regions,
4590                    &local_list);
4591   finish_free_region_work(pre_used, cleared_h_regions, freed_regions,
4592                           &local_list);
4593 }
4594 
4595 void
4596 G1CollectedHeap::free_region_work(HeapRegion* hr,
4597                                   size_t& pre_used,
4598                                   size_t& cleared_h_regions,
4599                                   size_t& freed_regions,
4600                                   UncleanRegionList* list,
4601                                   bool par) {
4602   assert(!hr->popular(), "should not free popular regions");
4603   pre_used += hr->used();
4604   if (hr->isHumongous()) {
4605     assert(hr->startsHumongous(),
4606            "Only the start of a humongous region should be freed.");
4607     int ind = _hrs->find(hr);
4608     assert(ind != -1, "Should have an index.");
4609     // Clear the start region.
4610     hr->hr_clear(par, true /*clear_space*/);
4611     list->insert_before_head(hr);
4612     cleared_h_regions++;
4613     freed_regions++;
4614     // Clear any continued regions.
4615     ind++;
4616     while ((size_t)ind < n_regions()) {
4617       HeapRegion* hrc = _hrs->at(ind);
4618       if (!hrc->continuesHumongous()) break;
4619       // Otherwise, does continue the H region.
4620       assert(hrc->humongous_start_region() == hr, "Huh?");
4621       hrc->hr_clear(par, true /*clear_space*/);
4622       cleared_h_regions++;
4623       freed_regions++;
4624       list->insert_before_head(hrc);
4625       ind++;
4626     }
4627   } else {
4628     hr->hr_clear(par, true /*clear_space*/);
4629     list->insert_before_head(hr);
4630     freed_regions++;
4631     // If we're using clear2, this should not be enabled.
4632     // assert(!hr->in_cohort(), "Can't be both free and in a cohort.");
4633   }
4634 }
4635 
4636 void G1CollectedHeap::finish_free_region_work(size_t pre_used,
4637                                               size_t cleared_h_regions,
4638                                               size_t freed_regions,
4639                                               UncleanRegionList* list) {
4640   if (list != NULL && list->sz() > 0) {
4641     prepend_region_list_on_unclean_list(list);
4642   }
4643   // Acquire a lock, if we're parallel, to update possibly-shared
4644   // variables.
4645   Mutex* lock = (n_par_threads() > 0) ? ParGCRareEvent_lock : NULL;
4646   {
4647     MutexLockerEx x(lock, Mutex::_no_safepoint_check_flag);
4648     _summary_bytes_used -= pre_used;
4649     _num_humongous_regions -= (int) cleared_h_regions;
4650     _free_regions += freed_regions;
4651   }
4652 }
4653 
4654 
4655 void G1CollectedHeap::dirtyCardsForYoungRegions(CardTableModRefBS* ct_bs, HeapRegion* list) {
4656   while (list != NULL) {
4657     guarantee( list->is_young(), "invariant" );
4658 
4659     HeapWord* bottom = list->bottom();
4660     HeapWord* end = list->end();
4661     MemRegion mr(bottom, end);
4662     ct_bs->dirty(mr);
4663 
4664     list = list->get_next_young_region();
4665   }
4666 }
4667 
4668 void G1CollectedHeap::cleanUpCardTable() {
4669   CardTableModRefBS* ct_bs = (CardTableModRefBS*) (barrier_set());
4670   double start = os::elapsedTime();
4671 
4672   ct_bs->clear(_g1_committed);
4673 
4674   // now, redirty the cards of the scan-only and survivor regions
4675   // (it seemed faster to do it this way, instead of iterating over
4676   // all regions and then clearing / dirtying as approprite)
4677   dirtyCardsForYoungRegions(ct_bs, _young_list->first_scan_only_region());
4678   dirtyCardsForYoungRegions(ct_bs, _young_list->first_survivor_region());
4679 
4680   double elapsed = os::elapsedTime() - start;
4681   g1_policy()->record_clear_ct_time( elapsed * 1000.0);
4682 }
4683 
4684 
4685 void G1CollectedHeap::do_collection_pause_if_appropriate(size_t word_size) {
4686   // First do any popular regions.
4687   HeapRegion* hr;
4688   while ((hr = popular_region_to_evac()) != NULL) {
4689     evac_popular_region(hr);
4690   }
4691   // Now do heuristic pauses.
4692   if (g1_policy()->should_do_collection_pause(word_size)) {
4693     do_collection_pause();
4694   }
4695 }
4696 
4697 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head) {
4698   double young_time_ms     = 0.0;
4699   double non_young_time_ms = 0.0;
4700 
4701   G1CollectorPolicy* policy = g1_policy();
4702 
4703   double start_sec = os::elapsedTime();
4704   bool non_young = true;
4705 
4706   HeapRegion* cur = cs_head;
4707   int age_bound = -1;
4708   size_t rs_lengths = 0;
4709 
4710   while (cur != NULL) {
4711     if (non_young) {
4712       if (cur->is_young()) {
4713         double end_sec = os::elapsedTime();
4714         double elapsed_ms = (end_sec - start_sec) * 1000.0;
4715         non_young_time_ms += elapsed_ms;
4716 
4717         start_sec = os::elapsedTime();
4718         non_young = false;
4719       }
4720     } else {
4721       if (!cur->is_on_free_list()) {
4722         double end_sec = os::elapsedTime();
4723         double elapsed_ms = (end_sec - start_sec) * 1000.0;
4724         young_time_ms += elapsed_ms;
4725 
4726         start_sec = os::elapsedTime();
4727         non_young = true;
4728       }
4729     }
4730 
4731     rs_lengths += cur->rem_set()->occupied();
4732 
4733     HeapRegion* next = cur->next_in_collection_set();
4734     assert(cur->in_collection_set(), "bad CS");
4735     cur->set_next_in_collection_set(NULL);
4736     cur->set_in_collection_set(false);
4737 
4738     if (cur->is_young()) {
4739       int index = cur->young_index_in_cset();
4740       guarantee( index != -1, "invariant" );
4741       guarantee( (size_t)index < policy->young_cset_length(), "invariant" );
4742       size_t words_survived = _surviving_young_words[index];
4743       cur->record_surv_words_in_group(words_survived);
4744     } else {
4745       int index = cur->young_index_in_cset();
4746       guarantee( index == -1, "invariant" );
4747     }
4748 
4749     assert( (cur->is_young() && cur->young_index_in_cset() > -1) ||
4750             (!cur->is_young() && cur->young_index_in_cset() == -1),
4751             "invariant" );
4752 
4753     if (!cur->evacuation_failed()) {
4754       // And the region is empty.
4755       assert(!cur->is_empty(),
4756              "Should not have empty regions in a CS.");
4757       free_region(cur);
4758     } else {
4759       guarantee( !cur->is_scan_only(), "should not be scan only" );
4760       cur->uninstall_surv_rate_group();
4761       if (cur->is_young())
4762         cur->set_young_index_in_cset(-1);
4763       cur->set_not_young();
4764       cur->set_evacuation_failed(false);
4765     }
4766     cur = next;
4767   }
4768 
4769   policy->record_max_rs_lengths(rs_lengths);
4770   policy->cset_regions_freed();
4771 
4772   double end_sec = os::elapsedTime();
4773   double elapsed_ms = (end_sec - start_sec) * 1000.0;
4774   if (non_young)
4775     non_young_time_ms += elapsed_ms;
4776   else
4777     young_time_ms += elapsed_ms;
4778 
4779   policy->record_young_free_cset_time_ms(young_time_ms);
4780   policy->record_non_young_free_cset_time_ms(non_young_time_ms);
4781 }
4782 
4783 HeapRegion*
4784 G1CollectedHeap::alloc_region_from_unclean_list_locked(bool zero_filled) {
4785   assert(ZF_mon->owned_by_self(), "Precondition");
4786   HeapRegion* res = pop_unclean_region_list_locked();
4787   if (res != NULL) {
4788     assert(!res->continuesHumongous() &&
4789            res->zero_fill_state() != HeapRegion::Allocated,
4790            "Only free regions on unclean list.");
4791     if (zero_filled) {
4792       res->ensure_zero_filled_locked();
4793       res->set_zero_fill_allocated();
4794     }
4795   }
4796   return res;
4797 }
4798 
4799 HeapRegion* G1CollectedHeap::alloc_region_from_unclean_list(bool zero_filled) {
4800   MutexLockerEx zx(ZF_mon, Mutex::_no_safepoint_check_flag);
4801   return alloc_region_from_unclean_list_locked(zero_filled);
4802 }
4803 
4804 void G1CollectedHeap::put_region_on_unclean_list(HeapRegion* r) {
4805   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4806   put_region_on_unclean_list_locked(r);
4807   if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
4808 }
4809 
4810 void G1CollectedHeap::set_unclean_regions_coming(bool b) {
4811   MutexLockerEx x(Cleanup_mon);
4812   set_unclean_regions_coming_locked(b);
4813 }
4814 
4815 void G1CollectedHeap::set_unclean_regions_coming_locked(bool b) {
4816   assert(Cleanup_mon->owned_by_self(), "Precondition");
4817   _unclean_regions_coming = b;
4818   // Wake up mutator threads that might be waiting for completeCleanup to
4819   // finish.
4820   if (!b) Cleanup_mon->notify_all();
4821 }
4822 
4823 void G1CollectedHeap::wait_for_cleanup_complete() {
4824   MutexLockerEx x(Cleanup_mon);
4825   wait_for_cleanup_complete_locked();
4826 }
4827 
4828 void G1CollectedHeap::wait_for_cleanup_complete_locked() {
4829   assert(Cleanup_mon->owned_by_self(), "precondition");
4830   while (_unclean_regions_coming) {
4831     Cleanup_mon->wait();
4832   }
4833 }
4834 
4835 void
4836 G1CollectedHeap::put_region_on_unclean_list_locked(HeapRegion* r) {
4837   assert(ZF_mon->owned_by_self(), "precondition.");
4838   _unclean_region_list.insert_before_head(r);
4839 }
4840 
4841 void
4842 G1CollectedHeap::prepend_region_list_on_unclean_list(UncleanRegionList* list) {
4843   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4844   prepend_region_list_on_unclean_list_locked(list);
4845   if (should_zf()) ZF_mon->notify_all(); // Wake up ZF thread.
4846 }
4847 
4848 void
4849 G1CollectedHeap::
4850 prepend_region_list_on_unclean_list_locked(UncleanRegionList* list) {
4851   assert(ZF_mon->owned_by_self(), "precondition.");
4852   _unclean_region_list.prepend_list(list);
4853 }
4854 
4855 HeapRegion* G1CollectedHeap::pop_unclean_region_list_locked() {
4856   assert(ZF_mon->owned_by_self(), "precondition.");
4857   HeapRegion* res = _unclean_region_list.pop();
4858   if (res != NULL) {
4859     // Inform ZF thread that there's a new unclean head.
4860     if (_unclean_region_list.hd() != NULL && should_zf())
4861       ZF_mon->notify_all();
4862   }
4863   return res;
4864 }
4865 
4866 HeapRegion* G1CollectedHeap::peek_unclean_region_list_locked() {
4867   assert(ZF_mon->owned_by_self(), "precondition.");
4868   return _unclean_region_list.hd();
4869 }
4870 
4871 
4872 bool G1CollectedHeap::move_cleaned_region_to_free_list_locked() {
4873   assert(ZF_mon->owned_by_self(), "Precondition");
4874   HeapRegion* r = peek_unclean_region_list_locked();
4875   if (r != NULL && r->zero_fill_state() == HeapRegion::ZeroFilled) {
4876     // Result of below must be equal to "r", since we hold the lock.
4877     (void)pop_unclean_region_list_locked();
4878     put_free_region_on_list_locked(r);
4879     return true;
4880   } else {
4881     return false;
4882   }
4883 }
4884 
4885 bool G1CollectedHeap::move_cleaned_region_to_free_list() {
4886   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4887   return move_cleaned_region_to_free_list_locked();
4888 }
4889 
4890 
4891 void G1CollectedHeap::put_free_region_on_list_locked(HeapRegion* r) {
4892   assert(ZF_mon->owned_by_self(), "precondition.");
4893   assert(_free_region_list_size == free_region_list_length(), "Inv");
4894   assert(r->zero_fill_state() == HeapRegion::ZeroFilled,
4895         "Regions on free list must be zero filled");
4896   assert(!r->isHumongous(), "Must not be humongous.");
4897   assert(r->is_empty(), "Better be empty");
4898   assert(!r->is_on_free_list(),
4899          "Better not already be on free list");
4900   assert(!r->is_on_unclean_list(),
4901          "Better not already be on unclean list");
4902   r->set_on_free_list(true);
4903   r->set_next_on_free_list(_free_region_list);
4904   _free_region_list = r;
4905   _free_region_list_size++;
4906   assert(_free_region_list_size == free_region_list_length(), "Inv");
4907 }
4908 
4909 void G1CollectedHeap::put_free_region_on_list(HeapRegion* r) {
4910   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4911   put_free_region_on_list_locked(r);
4912 }
4913 
4914 HeapRegion* G1CollectedHeap::pop_free_region_list_locked() {
4915   assert(ZF_mon->owned_by_self(), "precondition.");
4916   assert(_free_region_list_size == free_region_list_length(), "Inv");
4917   HeapRegion* res = _free_region_list;
4918   if (res != NULL) {
4919     _free_region_list = res->next_from_free_list();
4920     _free_region_list_size--;
4921     res->set_on_free_list(false);
4922     res->set_next_on_free_list(NULL);
4923     assert(_free_region_list_size == free_region_list_length(), "Inv");
4924   }
4925   return res;
4926 }
4927 
4928 
4929 HeapRegion* G1CollectedHeap::alloc_free_region_from_lists(bool zero_filled) {
4930   // By self, or on behalf of self.
4931   assert(Heap_lock->is_locked(), "Precondition");
4932   HeapRegion* res = NULL;
4933   bool first = true;
4934   while (res == NULL) {
4935     if (zero_filled || !first) {
4936       MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4937       res = pop_free_region_list_locked();
4938       if (res != NULL) {
4939         assert(!res->zero_fill_is_allocated(),
4940                "No allocated regions on free list.");
4941         res->set_zero_fill_allocated();
4942       } else if (!first) {
4943         break;  // We tried both, time to return NULL.
4944       }
4945     }
4946 
4947     if (res == NULL) {
4948       res = alloc_region_from_unclean_list(zero_filled);
4949     }
4950     assert(res == NULL ||
4951            !zero_filled ||
4952            res->zero_fill_is_allocated(),
4953            "We must have allocated the region we're returning");
4954     first = false;
4955   }
4956   return res;
4957 }
4958 
4959 void G1CollectedHeap::remove_allocated_regions_from_lists() {
4960   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
4961   {
4962     HeapRegion* prev = NULL;
4963     HeapRegion* cur = _unclean_region_list.hd();
4964     while (cur != NULL) {
4965       HeapRegion* next = cur->next_from_unclean_list();
4966       if (cur->zero_fill_is_allocated()) {
4967         // Remove from the list.
4968         if (prev == NULL) {
4969           (void)_unclean_region_list.pop();
4970         } else {
4971           _unclean_region_list.delete_after(prev);
4972         }
4973         cur->set_on_unclean_list(false);
4974         cur->set_next_on_unclean_list(NULL);
4975       } else {
4976         prev = cur;
4977       }
4978       cur = next;
4979     }
4980     assert(_unclean_region_list.sz() == unclean_region_list_length(),
4981            "Inv");
4982   }
4983 
4984   {
4985     HeapRegion* prev = NULL;
4986     HeapRegion* cur = _free_region_list;
4987     while (cur != NULL) {
4988       HeapRegion* next = cur->next_from_free_list();
4989       if (cur->zero_fill_is_allocated()) {
4990         // Remove from the list.
4991         if (prev == NULL) {
4992           _free_region_list = cur->next_from_free_list();
4993         } else {
4994           prev->set_next_on_free_list(cur->next_from_free_list());
4995         }
4996         cur->set_on_free_list(false);
4997         cur->set_next_on_free_list(NULL);
4998         _free_region_list_size--;
4999       } else {
5000         prev = cur;
5001       }
5002       cur = next;
5003     }
5004     assert(_free_region_list_size == free_region_list_length(), "Inv");
5005   }
5006 }
5007 
5008 bool G1CollectedHeap::verify_region_lists() {
5009   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
5010   return verify_region_lists_locked();
5011 }
5012 
5013 bool G1CollectedHeap::verify_region_lists_locked() {
5014   HeapRegion* unclean = _unclean_region_list.hd();
5015   while (unclean != NULL) {
5016     guarantee(unclean->is_on_unclean_list(), "Well, it is!");
5017     guarantee(!unclean->is_on_free_list(), "Well, it shouldn't be!");
5018     guarantee(unclean->zero_fill_state() != HeapRegion::Allocated,
5019               "Everything else is possible.");
5020     unclean = unclean->next_from_unclean_list();
5021   }
5022   guarantee(_unclean_region_list.sz() == unclean_region_list_length(), "Inv");
5023 
5024   HeapRegion* free_r = _free_region_list;
5025   while (free_r != NULL) {
5026     assert(free_r->is_on_free_list(), "Well, it is!");
5027     assert(!free_r->is_on_unclean_list(), "Well, it shouldn't be!");
5028     switch (free_r->zero_fill_state()) {
5029     case HeapRegion::NotZeroFilled:
5030     case HeapRegion::ZeroFilling:
5031       guarantee(false, "Should not be on free list.");
5032       break;
5033     default:
5034       // Everything else is possible.
5035       break;
5036     }
5037     free_r = free_r->next_from_free_list();
5038   }
5039   guarantee(_free_region_list_size == free_region_list_length(), "Inv");
5040   // If we didn't do an assertion...
5041   return true;
5042 }
5043 
5044 size_t G1CollectedHeap::free_region_list_length() {
5045   assert(ZF_mon->owned_by_self(), "precondition.");
5046   size_t len = 0;
5047   HeapRegion* cur = _free_region_list;
5048   while (cur != NULL) {
5049     len++;
5050     cur = cur->next_from_free_list();
5051   }
5052   return len;
5053 }
5054 
5055 size_t G1CollectedHeap::unclean_region_list_length() {
5056   assert(ZF_mon->owned_by_self(), "precondition.");
5057   return _unclean_region_list.length();
5058 }
5059 
5060 size_t G1CollectedHeap::n_regions() {
5061   return _hrs->length();
5062 }
5063 
5064 size_t G1CollectedHeap::max_regions() {
5065   return
5066     (size_t)align_size_up(g1_reserved_obj_bytes(), HeapRegion::GrainBytes) /
5067     HeapRegion::GrainBytes;
5068 }
5069 
5070 size_t G1CollectedHeap::free_regions() {
5071   /* Possibly-expensive assert.
5072   assert(_free_regions == count_free_regions(),
5073          "_free_regions is off.");
5074   */
5075   return _free_regions;
5076 }
5077 
5078 bool G1CollectedHeap::should_zf() {
5079   return _free_region_list_size < (size_t) G1ConcZFMaxRegions;
5080 }
5081 
5082 class RegionCounter: public HeapRegionClosure {
5083   size_t _n;
5084 public:
5085   RegionCounter() : _n(0) {}
5086   bool doHeapRegion(HeapRegion* r) {
5087     if (r->is_empty() && !r->popular()) {
5088       assert(!r->isHumongous(), "H regions should not be empty.");
5089       _n++;
5090     }
5091     return false;
5092   }
5093   int res() { return (int) _n; }
5094 };
5095 
5096 size_t G1CollectedHeap::count_free_regions() {
5097   RegionCounter rc;
5098   heap_region_iterate(&rc);
5099   size_t n = rc.res();
5100   if (_cur_alloc_region != NULL && _cur_alloc_region->is_empty())
5101     n--;
5102   return n;
5103 }
5104 
5105 size_t G1CollectedHeap::count_free_regions_list() {
5106   size_t n = 0;
5107   size_t o = 0;
5108   ZF_mon->lock_without_safepoint_check();
5109   HeapRegion* cur = _free_region_list;
5110   while (cur != NULL) {
5111     cur = cur->next_from_free_list();
5112     n++;
5113   }
5114   size_t m = unclean_region_list_length();
5115   ZF_mon->unlock();
5116   return n + m;
5117 }
5118 
5119 bool G1CollectedHeap::should_set_young_locked() {
5120   assert(heap_lock_held_for_gc(),
5121               "the heap lock should already be held by or for this thread");
5122   return  (g1_policy()->in_young_gc_mode() &&
5123            g1_policy()->should_add_next_region_to_young_list());
5124 }
5125 
5126 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
5127   assert(heap_lock_held_for_gc(),
5128               "the heap lock should already be held by or for this thread");
5129   _young_list->push_region(hr);
5130   g1_policy()->set_region_short_lived(hr);
5131 }
5132 
5133 class NoYoungRegionsClosure: public HeapRegionClosure {
5134 private:
5135   bool _success;
5136 public:
5137   NoYoungRegionsClosure() : _success(true) { }
5138   bool doHeapRegion(HeapRegion* r) {
5139     if (r->is_young()) {
5140       gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young",
5141                              r->bottom(), r->end());
5142       _success = false;
5143     }
5144     return false;
5145   }
5146   bool success() { return _success; }
5147 };
5148 
5149 bool G1CollectedHeap::check_young_list_empty(bool ignore_scan_only_list,
5150                                              bool check_sample) {
5151   bool ret = true;
5152 
5153   ret = _young_list->check_list_empty(ignore_scan_only_list, check_sample);
5154   if (!ignore_scan_only_list) {
5155     NoYoungRegionsClosure closure;
5156     heap_region_iterate(&closure);
5157     ret = ret && closure.success();
5158   }
5159 
5160   return ret;
5161 }
5162 
5163 void G1CollectedHeap::empty_young_list() {
5164   assert(heap_lock_held_for_gc(),
5165               "the heap lock should already be held by or for this thread");
5166   assert(g1_policy()->in_young_gc_mode(), "should be in young GC mode");
5167 
5168   _young_list->empty_list();
5169 }
5170 
5171 bool G1CollectedHeap::all_alloc_regions_no_allocs_since_save_marks() {
5172   bool no_allocs = true;
5173   for (int ap = 0; ap < GCAllocPurposeCount && no_allocs; ++ap) {
5174     HeapRegion* r = _gc_alloc_regions[ap];
5175     no_allocs = r == NULL || r->saved_mark_at_top();
5176   }
5177   return no_allocs;
5178 }
5179 
5180 void G1CollectedHeap::retire_all_alloc_regions() {
5181   for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
5182     HeapRegion* r = _gc_alloc_regions[ap];
5183     if (r != NULL) {
5184       // Check for aliases.
5185       bool has_processed_alias = false;
5186       for (int i = 0; i < ap; ++i) {
5187         if (_gc_alloc_regions[i] == r) {
5188           has_processed_alias = true;
5189           break;
5190         }
5191       }
5192       if (!has_processed_alias) {
5193         retire_alloc_region(r, false /* par */);
5194       }
5195     }
5196   }
5197 }
5198 
5199 
5200 // Done at the start of full GC.
5201 void G1CollectedHeap::tear_down_region_lists() {
5202   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
5203   while (pop_unclean_region_list_locked() != NULL) ;
5204   assert(_unclean_region_list.hd() == NULL && _unclean_region_list.sz() == 0,
5205          "Postconditions of loop.")
5206   while (pop_free_region_list_locked() != NULL) ;
5207   assert(_free_region_list == NULL, "Postcondition of loop.");
5208   if (_free_region_list_size != 0) {
5209     gclog_or_tty->print_cr("Size is %d.", _free_region_list_size);
5210     print();
5211   }
5212   assert(_free_region_list_size == 0, "Postconditions of loop.");
5213 }
5214 
5215 
5216 class RegionResetter: public HeapRegionClosure {
5217   G1CollectedHeap* _g1;
5218   int _n;
5219 public:
5220   RegionResetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
5221   bool doHeapRegion(HeapRegion* r) {
5222     if (r->continuesHumongous()) return false;
5223     if (r->top() > r->bottom()) {
5224       if (r->top() < r->end()) {
5225         Copy::fill_to_words(r->top(),
5226                           pointer_delta(r->end(), r->top()));
5227       }
5228       r->set_zero_fill_allocated();
5229     } else {
5230       assert(r->is_empty(), "tautology");
5231       if (r->popular()) {
5232         if (r->zero_fill_state() != HeapRegion::Allocated) {
5233           r->ensure_zero_filled_locked();
5234           r->set_zero_fill_allocated();
5235         }
5236       } else {
5237         _n++;
5238         switch (r->zero_fill_state()) {
5239         case HeapRegion::NotZeroFilled:
5240         case HeapRegion::ZeroFilling:
5241           _g1->put_region_on_unclean_list_locked(r);
5242           break;
5243         case HeapRegion::Allocated:
5244           r->set_zero_fill_complete();
5245           // no break; go on to put on free list.
5246         case HeapRegion::ZeroFilled:
5247           _g1->put_free_region_on_list_locked(r);
5248           break;
5249         }
5250       }
5251     }
5252     return false;
5253   }
5254 
5255   int getFreeRegionCount() {return _n;}
5256 };
5257 
5258 // Done at the end of full GC.
5259 void G1CollectedHeap::rebuild_region_lists() {
5260   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
5261   // This needs to go at the end of the full GC.
5262   RegionResetter rs;
5263   heap_region_iterate(&rs);
5264   _free_regions = rs.getFreeRegionCount();
5265   // Tell the ZF thread it may have work to do.
5266   if (should_zf()) ZF_mon->notify_all();
5267 }
5268 
5269 class UsedRegionsNeedZeroFillSetter: public HeapRegionClosure {
5270   G1CollectedHeap* _g1;
5271   int _n;
5272 public:
5273   UsedRegionsNeedZeroFillSetter() : _g1(G1CollectedHeap::heap()), _n(0) {}
5274   bool doHeapRegion(HeapRegion* r) {
5275     if (r->continuesHumongous()) return false;
5276     if (r->top() > r->bottom()) {
5277       // There are assertions in "set_zero_fill_needed()" below that
5278       // require top() == bottom(), so this is technically illegal.
5279       // We'll skirt the law here, by making that true temporarily.
5280       DEBUG_ONLY(HeapWord* save_top = r->top();
5281                  r->set_top(r->bottom()));
5282       r->set_zero_fill_needed();
5283       DEBUG_ONLY(r->set_top(save_top));
5284     }
5285     return false;
5286   }
5287 };
5288 
5289 // Done at the start of full GC.
5290 void G1CollectedHeap::set_used_regions_to_need_zero_fill() {
5291   MutexLockerEx x(ZF_mon, Mutex::_no_safepoint_check_flag);
5292   // This needs to go at the end of the full GC.
5293   UsedRegionsNeedZeroFillSetter rs;
5294   heap_region_iterate(&rs);
5295 }
5296 
5297 class CountObjClosure: public ObjectClosure {
5298   size_t _n;
5299 public:
5300   CountObjClosure() : _n(0) {}
5301   void do_object(oop obj) { _n++; }
5302   size_t n() { return _n; }
5303 };
5304 
5305 size_t G1CollectedHeap::pop_object_used_objs() {
5306   size_t sum_objs = 0;
5307   for (int i = 0; i < G1NumPopularRegions; i++) {
5308     CountObjClosure cl;
5309     _hrs->at(i)->object_iterate(&cl);
5310     sum_objs += cl.n();
5311   }
5312   return sum_objs;
5313 }
5314 
5315 size_t G1CollectedHeap::pop_object_used_bytes() {
5316   size_t sum_bytes = 0;
5317   for (int i = 0; i < G1NumPopularRegions; i++) {
5318     sum_bytes += _hrs->at(i)->used();
5319   }
5320   return sum_bytes;
5321 }
5322 
5323 
5324 static int nq = 0;
5325 
5326 HeapWord* G1CollectedHeap::allocate_popular_object(size_t word_size) {
5327   while (_cur_pop_hr_index < G1NumPopularRegions) {
5328     HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
5329     HeapWord* res = cur_pop_region->allocate(word_size);
5330     if (res != NULL) {
5331       // We account for popular objs directly in the used summary:
5332       _summary_bytes_used += (word_size * HeapWordSize);
5333       return res;
5334     }
5335     // Otherwise, try the next region (first making sure that we remember
5336     // the last "top" value as the "next_top_at_mark_start", so that
5337     // objects made popular during markings aren't automatically considered
5338     // live).
5339     cur_pop_region->note_end_of_copying();
5340     // Otherwise, try the next region.
5341     _cur_pop_hr_index++;
5342   }
5343   // XXX: For now !!!
5344   vm_exit_out_of_memory(word_size,
5345                         "Not enough pop obj space (To Be Fixed)");
5346   return NULL;
5347 }
5348 
5349 class HeapRegionList: public CHeapObj {
5350   public:
5351   HeapRegion* hr;
5352   HeapRegionList* next;
5353 };
5354 
5355 void G1CollectedHeap::schedule_popular_region_evac(HeapRegion* r) {
5356   // This might happen during parallel GC, so protect by this lock.
5357   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
5358   // We don't schedule regions whose evacuations are already pending, or
5359   // are already being evacuated.
5360   if (!r->popular_pending() && !r->in_collection_set()) {
5361     r->set_popular_pending(true);
5362     if (G1TracePopularity) {
5363       gclog_or_tty->print_cr("Scheduling region "PTR_FORMAT" "
5364                              "["PTR_FORMAT", "PTR_FORMAT") for pop-object evacuation.",
5365                              r, r->bottom(), r->end());
5366     }
5367     HeapRegionList* hrl = new HeapRegionList;
5368     hrl->hr = r;
5369     hrl->next = _popular_regions_to_be_evacuated;
5370     _popular_regions_to_be_evacuated = hrl;
5371   }
5372 }
5373 
5374 HeapRegion* G1CollectedHeap::popular_region_to_evac() {
5375   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
5376   HeapRegion* res = NULL;
5377   while (_popular_regions_to_be_evacuated != NULL && res == NULL) {
5378     HeapRegionList* hrl = _popular_regions_to_be_evacuated;
5379     _popular_regions_to_be_evacuated = hrl->next;
5380     res = hrl->hr;
5381     // The G1RSPopLimit may have increased, so recheck here...
5382     if (res->rem_set()->occupied() < (size_t) G1RSPopLimit) {
5383       // Hah: don't need to schedule.
5384       if (G1TracePopularity) {
5385         gclog_or_tty->print_cr("Unscheduling region "PTR_FORMAT" "
5386                                "["PTR_FORMAT", "PTR_FORMAT") "
5387                                "for pop-object evacuation (size %d < limit %d)",
5388                                res, res->bottom(), res->end(),
5389                                res->rem_set()->occupied(), G1RSPopLimit);
5390       }
5391       res->set_popular_pending(false);
5392       res = NULL;
5393     }
5394     // We do not reset res->popular() here; if we did so, it would allow
5395     // the region to be "rescheduled" for popularity evacuation.  Instead,
5396     // this is done in the collection pause, with the world stopped.
5397     // So the invariant is that the regions in the list have the popularity
5398     // boolean set, but having the boolean set does not imply membership
5399     // on the list (though there can at most one such pop-pending region
5400     // not on the list at any time).
5401     delete hrl;
5402   }
5403   return res;
5404 }
5405 
5406 void G1CollectedHeap::evac_popular_region(HeapRegion* hr) {
5407   while (true) {
5408     // Don't want to do a GC pause while cleanup is being completed!
5409     wait_for_cleanup_complete();
5410 
5411     // Read the GC count while holding the Heap_lock
5412     int gc_count_before = SharedHeap::heap()->total_collections();
5413     g1_policy()->record_stop_world_start();
5414 
5415     {
5416       MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
5417       VM_G1PopRegionCollectionPause op(gc_count_before, hr);
5418       VMThread::execute(&op);
5419 
5420       // If the prolog succeeded, we didn't do a GC for this.
5421       if (op.prologue_succeeded()) break;
5422     }
5423     // Otherwise we didn't.  We should recheck the size, though, since
5424     // the limit may have increased...
5425     if (hr->rem_set()->occupied() < (size_t) G1RSPopLimit) {
5426       hr->set_popular_pending(false);
5427       break;
5428     }
5429   }
5430 }
5431 
5432 void G1CollectedHeap::atomic_inc_obj_rc(oop obj) {
5433   Atomic::inc(obj_rc_addr(obj));
5434 }
5435 
5436 class CountRCClosure: public OopsInHeapRegionClosure {
5437   G1CollectedHeap* _g1h;
5438   bool _parallel;
5439 public:
5440   CountRCClosure(G1CollectedHeap* g1h) :
5441     _g1h(g1h), _parallel(ParallelGCThreads > 0)
5442   {}
5443   void do_oop(narrowOop* p) {
5444     guarantee(false, "NYI");
5445   }
5446   void do_oop(oop* p) {
5447     oop obj = *p;
5448     assert(obj != NULL, "Precondition.");
5449     if (_parallel) {
5450       // We go sticky at the limit to avoid excess contention.
5451       // If we want to track the actual RC's further, we'll need to keep a
5452       // per-thread hash table or something for the popular objects.
5453       if (_g1h->obj_rc(obj) < G1ObjPopLimit) {
5454         _g1h->atomic_inc_obj_rc(obj);
5455       }
5456     } else {
5457       _g1h->inc_obj_rc(obj);
5458     }
5459   }
5460 };
5461 
5462 class EvacPopObjClosure: public ObjectClosure {
5463   G1CollectedHeap* _g1h;
5464   size_t _pop_objs;
5465   size_t _max_rc;
5466 public:
5467   EvacPopObjClosure(G1CollectedHeap* g1h) :
5468     _g1h(g1h), _pop_objs(0), _max_rc(0) {}
5469 
5470   void do_object(oop obj) {
5471     size_t rc = _g1h->obj_rc(obj);
5472     _max_rc = MAX2(rc, _max_rc);
5473     if (rc >= (size_t) G1ObjPopLimit) {
5474       _g1h->_pop_obj_rc_at_copy.add((double)rc);
5475       size_t word_sz = obj->size();
5476       HeapWord* new_pop_loc = _g1h->allocate_popular_object(word_sz);
5477       oop new_pop_obj = (oop)new_pop_loc;
5478       Copy::aligned_disjoint_words((HeapWord*)obj, new_pop_loc, word_sz);
5479       obj->forward_to(new_pop_obj);
5480       G1ScanAndBalanceClosure scan_and_balance(_g1h);
5481       new_pop_obj->oop_iterate_backwards(&scan_and_balance);
5482       // preserve "next" mark bit if marking is in progress.
5483       if (_g1h->mark_in_progress() && !_g1h->is_obj_ill(obj)) {
5484         _g1h->concurrent_mark()->markAndGrayObjectIfNecessary(new_pop_obj);
5485       }
5486 
5487       if (G1TracePopularity) {
5488         gclog_or_tty->print_cr("Found obj " PTR_FORMAT " of word size " SIZE_FORMAT
5489                                " pop (%d), move to " PTR_FORMAT,
5490                                (void*) obj, word_sz,
5491                                _g1h->obj_rc(obj), (void*) new_pop_obj);
5492       }
5493       _pop_objs++;
5494     }
5495   }
5496   size_t pop_objs() { return _pop_objs; }
5497   size_t max_rc() { return _max_rc; }
5498 };
5499 
5500 class G1ParCountRCTask : public AbstractGangTask {
5501   G1CollectedHeap* _g1h;
5502   BitMap _bm;
5503 
5504   size_t getNCards() {
5505     return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1)
5506       / G1BlockOffsetSharedArray::N_bytes;
5507   }
5508   CountRCClosure _count_rc_closure;
5509 public:
5510   G1ParCountRCTask(G1CollectedHeap* g1h) :
5511     AbstractGangTask("G1 Par RC Count task"),
5512     _g1h(g1h), _bm(getNCards()), _count_rc_closure(g1h)
5513   {}
5514 
5515   void work(int i) {
5516     ResourceMark rm;
5517     HandleMark   hm;
5518     _g1h->g1_rem_set()->oops_into_collection_set_do(&_count_rc_closure, i);
5519   }
5520 };
5521 
5522 void G1CollectedHeap::popularity_pause_preamble(HeapRegion* popular_region) {
5523   // We're evacuating a single region (for popularity).
5524   if (G1TracePopularity) {
5525     gclog_or_tty->print_cr("Doing pop region pause for ["PTR_FORMAT", "PTR_FORMAT")",
5526                            popular_region->bottom(), popular_region->end());
5527   }
5528   g1_policy()->set_single_region_collection_set(popular_region);
5529   size_t max_rc;
5530   if (!compute_reference_counts_and_evac_popular(popular_region,
5531                                                  &max_rc)) {
5532     // We didn't evacuate any popular objects.
5533     // We increase the RS popularity limit, to prevent this from
5534     // happening in the future.
5535     if (G1RSPopLimit < (1 << 30)) {
5536       G1RSPopLimit *= 2;
5537     }
5538     // For now, interesting enough for a message:
5539 #if 1
5540     gclog_or_tty->print_cr("In pop region pause for ["PTR_FORMAT", "PTR_FORMAT"), "
5541                            "failed to find a pop object (max = %d).",
5542                            popular_region->bottom(), popular_region->end(),
5543                            max_rc);
5544     gclog_or_tty->print_cr("Increased G1RSPopLimit to %d.", G1RSPopLimit);
5545 #endif // 0
5546     // Also, we reset the collection set to NULL, to make the rest of
5547     // the collection do nothing.
5548     assert(popular_region->next_in_collection_set() == NULL,
5549            "should be single-region.");
5550     popular_region->set_in_collection_set(false);
5551     popular_region->set_popular_pending(false);
5552     g1_policy()->clear_collection_set();
5553   }
5554 }
5555 
5556 bool G1CollectedHeap::
5557 compute_reference_counts_and_evac_popular(HeapRegion* popular_region,
5558                                           size_t* max_rc) {
5559   HeapWord* rc_region_bot;
5560   HeapWord* rc_region_end;
5561 
5562   // Set up the reference count region.
5563   HeapRegion* rc_region = newAllocRegion(HeapRegion::GrainWords);
5564   if (rc_region != NULL) {
5565     rc_region_bot = rc_region->bottom();
5566     rc_region_end = rc_region->end();
5567   } else {
5568     rc_region_bot = NEW_C_HEAP_ARRAY(HeapWord, HeapRegion::GrainWords);
5569     if (rc_region_bot == NULL) {
5570       vm_exit_out_of_memory(HeapRegion::GrainWords,
5571                             "No space for RC region.");
5572     }
5573     rc_region_end = rc_region_bot + HeapRegion::GrainWords;
5574   }
5575 
5576   if (G1TracePopularity)
5577     gclog_or_tty->print_cr("RC region is ["PTR_FORMAT", "PTR_FORMAT")",
5578                            rc_region_bot, rc_region_end);
5579   if (rc_region_bot > popular_region->bottom()) {
5580     _rc_region_above = true;
5581     _rc_region_diff =
5582       pointer_delta(rc_region_bot, popular_region->bottom(), 1);
5583   } else {
5584     assert(rc_region_bot < popular_region->bottom(), "Can't be equal.");
5585     _rc_region_above = false;
5586     _rc_region_diff =
5587       pointer_delta(popular_region->bottom(), rc_region_bot, 1);
5588   }
5589   g1_policy()->record_pop_compute_rc_start();
5590   // Count external references.
5591   g1_rem_set()->prepare_for_oops_into_collection_set_do();
5592   if (ParallelGCThreads > 0) {
5593 
5594     set_par_threads(workers()->total_workers());
5595     G1ParCountRCTask par_count_rc_task(this);
5596     workers()->run_task(&par_count_rc_task);
5597     set_par_threads(0);
5598 
5599   } else {
5600     CountRCClosure count_rc_closure(this);
5601     g1_rem_set()->oops_into_collection_set_do(&count_rc_closure, 0);
5602   }
5603   g1_rem_set()->cleanup_after_oops_into_collection_set_do();
5604   g1_policy()->record_pop_compute_rc_end();
5605 
5606   // Now evacuate popular objects.
5607   g1_policy()->record_pop_evac_start();
5608   EvacPopObjClosure evac_pop_obj_cl(this);
5609   popular_region->object_iterate(&evac_pop_obj_cl);
5610   *max_rc = evac_pop_obj_cl.max_rc();
5611 
5612   // Make sure the last "top" value of the current popular region is copied
5613   // as the "next_top_at_mark_start", so that objects made popular during
5614   // markings aren't automatically considered live.
5615   HeapRegion* cur_pop_region = _hrs->at(_cur_pop_hr_index);
5616   cur_pop_region->note_end_of_copying();
5617 
5618   if (rc_region != NULL) {
5619     free_region(rc_region);
5620   } else {
5621     FREE_C_HEAP_ARRAY(HeapWord, rc_region_bot);
5622   }
5623   g1_policy()->record_pop_evac_end();
5624 
5625   return evac_pop_obj_cl.pop_objs() > 0;
5626 }
5627 
5628 class CountPopObjInfoClosure: public HeapRegionClosure {
5629   size_t _objs;
5630   size_t _bytes;
5631 
5632   class CountObjClosure: public ObjectClosure {
5633     int _n;
5634   public:
5635     CountObjClosure() : _n(0) {}
5636     void do_object(oop obj) { _n++; }
5637     size_t n() { return _n; }
5638   };
5639 
5640 public:
5641   CountPopObjInfoClosure() : _objs(0), _bytes(0) {}
5642   bool doHeapRegion(HeapRegion* r) {
5643     _bytes += r->used();
5644     CountObjClosure blk;
5645     r->object_iterate(&blk);
5646     _objs += blk.n();
5647     return false;
5648   }
5649   size_t objs() { return _objs; }
5650   size_t bytes() { return _bytes; }
5651 };
5652 
5653 
5654 void G1CollectedHeap::print_popularity_summary_info() const {
5655   CountPopObjInfoClosure blk;
5656   for (int i = 0; i <= _cur_pop_hr_index; i++) {
5657     blk.doHeapRegion(_hrs->at(i));
5658   }
5659   gclog_or_tty->print_cr("\nPopular objects: %d objs, %d bytes.",
5660                          blk.objs(), blk.bytes());
5661   gclog_or_tty->print_cr("   RC at copy = [avg = %5.2f, max = %5.2f, sd = %5.2f].",
5662                 _pop_obj_rc_at_copy.avg(),
5663                 _pop_obj_rc_at_copy.maximum(),
5664                 _pop_obj_rc_at_copy.sd());
5665 }
5666 
5667 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
5668   _refine_cte_cl->set_concurrent(concurrent);
5669 }
5670 
5671 #ifndef PRODUCT
5672 
5673 class PrintHeapRegionClosure: public HeapRegionClosure {
5674 public:
5675   bool doHeapRegion(HeapRegion *r) {
5676     gclog_or_tty->print("Region: "PTR_FORMAT":", r);
5677     if (r != NULL) {
5678       if (r->is_on_free_list())
5679         gclog_or_tty->print("Free ");
5680       if (r->is_young())
5681         gclog_or_tty->print("Young ");
5682       if (r->isHumongous())
5683         gclog_or_tty->print("Is Humongous ");
5684       r->print();
5685     }
5686     return false;
5687   }
5688 };
5689 
5690 class SortHeapRegionClosure : public HeapRegionClosure {
5691   size_t young_regions,free_regions, unclean_regions;
5692   size_t hum_regions, count;
5693   size_t unaccounted, cur_unclean, cur_alloc;
5694   size_t total_free;
5695   HeapRegion* cur;
5696 public:
5697   SortHeapRegionClosure(HeapRegion *_cur) : cur(_cur), young_regions(0),
5698     free_regions(0), unclean_regions(0),
5699     hum_regions(0),
5700     count(0), unaccounted(0),
5701     cur_alloc(0), total_free(0)
5702   {}
5703   bool doHeapRegion(HeapRegion *r) {
5704     count++;
5705     if (r->is_on_free_list()) free_regions++;
5706     else if (r->is_on_unclean_list()) unclean_regions++;
5707     else if (r->isHumongous())  hum_regions++;
5708     else if (r->is_young()) young_regions++;
5709     else if (r == cur) cur_alloc++;
5710     else unaccounted++;
5711     return false;
5712   }
5713   void print() {
5714     total_free = free_regions + unclean_regions;
5715     gclog_or_tty->print("%d regions\n", count);
5716     gclog_or_tty->print("%d free: free_list = %d unclean = %d\n",
5717                         total_free, free_regions, unclean_regions);
5718     gclog_or_tty->print("%d humongous %d young\n",
5719                         hum_regions, young_regions);
5720     gclog_or_tty->print("%d cur_alloc\n", cur_alloc);
5721     gclog_or_tty->print("UHOH unaccounted = %d\n", unaccounted);
5722   }
5723 };
5724 
5725 void G1CollectedHeap::print_region_counts() {
5726   SortHeapRegionClosure sc(_cur_alloc_region);
5727   PrintHeapRegionClosure cl;
5728   heap_region_iterate(&cl);
5729   heap_region_iterate(&sc);
5730   sc.print();
5731   print_region_accounting_info();
5732 };
5733 
5734 bool G1CollectedHeap::regions_accounted_for() {
5735   // TODO: regions accounting for young/survivor/tenured
5736   return true;
5737 }
5738 
5739 bool G1CollectedHeap::print_region_accounting_info() {
5740   gclog_or_tty->print_cr("P regions: %d.", G1NumPopularRegions);
5741   gclog_or_tty->print_cr("Free regions: %d (count: %d count list %d) (clean: %d unclean: %d).",
5742                          free_regions(),
5743                          count_free_regions(), count_free_regions_list(),
5744                          _free_region_list_size, _unclean_region_list.sz());
5745   gclog_or_tty->print_cr("cur_alloc: %d.",
5746                          (_cur_alloc_region == NULL ? 0 : 1));
5747   gclog_or_tty->print_cr("H regions: %d.", _num_humongous_regions);
5748 
5749   // TODO: check regions accounting for young/survivor/tenured
5750   return true;
5751 }
5752 
5753 bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
5754   HeapRegion* hr = heap_region_containing(p);
5755   if (hr == NULL) {
5756     return is_in_permanent(p);
5757   } else {
5758     return hr->is_in(p);
5759   }
5760 }
5761 #endif // PRODUCT
5762 
5763 void G1CollectedHeap::g1_unimplemented() {
5764   // Unimplemented();
5765 }
5766 
5767 
5768 // Local Variables: ***
5769 // c-indentation-style: gnu ***
5770 // End: ***