1 /*
   2  * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "gc/g1/concurrentG1Refine.hpp"
  27 #include "gc/g1/g1BlockOffsetTable.inline.hpp"
  28 #include "gc/g1/g1CollectedHeap.inline.hpp"
  29 #include "gc/g1/heapRegionManager.inline.hpp"
  30 #include "gc/g1/heapRegionRemSet.hpp"
  31 #include "gc/shared/space.inline.hpp"
  32 #include "memory/allocation.hpp"
  33 #include "memory/padded.inline.hpp"
  34 #include "oops/oop.inline.hpp"
  35 #include "runtime/atomic.inline.hpp"
  36 #include "utilities/bitMap.inline.hpp"
  37 #include "utilities/globalDefinitions.hpp"
  38 #include "utilities/growableArray.hpp"
  39 
  40 class PerRegionTable: public CHeapObj<mtGC> {
  41   friend class OtherRegionsTable;
  42   friend class HeapRegionRemSetIterator;
  43 
  44   HeapRegion*     _hr;
  45   BitMap          _bm;
  46   jint            _occupied;
  47 
  48   // next pointer for free/allocated 'all' list
  49   PerRegionTable* _next;
  50 
  51   // prev pointer for the allocated 'all' list
  52   PerRegionTable* _prev;
  53 
  54   // next pointer in collision list
  55   PerRegionTable * _collision_list_next;
  56 
  57   // Global free list of PRTs
  58   static PerRegionTable* _free_list;
  59 
  60 protected:
  61   // We need access in order to union things into the base table.
  62   BitMap* bm() { return &_bm; }
  63 
  64   void recount_occupied() {
  65     _occupied = (jint) bm()->count_one_bits();
  66   }
  67 
  68   PerRegionTable(HeapRegion* hr) :
  69     _hr(hr),
  70     _occupied(0),
  71     _bm(HeapRegion::CardsPerRegion, false /* in-resource-area */),
  72     _collision_list_next(NULL), _next(NULL), _prev(NULL)
  73   {}
  74 
  75   void add_card_work(CardIdx_t from_card, bool par) {
  76     if (!_bm.at(from_card)) {
  77       if (par) {
  78         if (_bm.par_at_put(from_card, 1)) {
  79           Atomic::inc(&_occupied);
  80         }
  81       } else {
  82         _bm.at_put(from_card, 1);
  83         _occupied++;
  84       }
  85     }
  86   }
  87 
  88   void add_reference_work(OopOrNarrowOopStar from, bool par) {
  89     // Must make this robust in case "from" is not in "_hr", because of
  90     // concurrency.
  91 
  92     HeapRegion* loc_hr = hr();
  93     // If the test below fails, then this table was reused concurrently
  94     // with this operation.  This is OK, since the old table was coarsened,
  95     // and adding a bit to the new table is never incorrect.
  96     // If the table used to belong to a continues humongous region and is
  97     // now reused for the corresponding start humongous region, we need to
  98     // make sure that we detect this. Thus, we call is_in_reserved_raw()
  99     // instead of just is_in_reserved() here.
 100     if (loc_hr->is_in_reserved(from)) {
 101       size_t hw_offset = pointer_delta((HeapWord*)from, loc_hr->bottom());
 102       CardIdx_t from_card = (CardIdx_t)
 103           hw_offset >> (CardTableModRefBS::card_shift - LogHeapWordSize);
 104 
 105       assert(0 <= from_card && (size_t)from_card < HeapRegion::CardsPerRegion,
 106              "Must be in range.");
 107       add_card_work(from_card, par);
 108     }
 109   }
 110 
 111 public:
 112 
 113   HeapRegion* hr() const { return _hr; }
 114 
 115   jint occupied() const {
 116     // Overkill, but if we ever need it...
 117     // guarantee(_occupied == _bm.count_one_bits(), "Check");
 118     return _occupied;
 119   }
 120 
 121   void init(HeapRegion* hr, bool clear_links_to_all_list) {
 122     if (clear_links_to_all_list) {
 123       set_next(NULL);
 124       set_prev(NULL);
 125     }
 126     _hr = hr;
 127     _collision_list_next = NULL;
 128     _occupied = 0;
 129     _bm.clear();
 130   }
 131 
 132   void add_reference(OopOrNarrowOopStar from) {
 133     add_reference_work(from, /*parallel*/ true);
 134   }
 135 
 136   void seq_add_reference(OopOrNarrowOopStar from) {
 137     add_reference_work(from, /*parallel*/ false);
 138   }
 139 
 140   void scrub(CardTableModRefBS* ctbs, BitMap* card_bm) {
 141     HeapWord* hr_bot = hr()->bottom();
 142     size_t hr_first_card_index = ctbs->index_for(hr_bot);
 143     bm()->set_intersection_at_offset(*card_bm, hr_first_card_index);
 144     recount_occupied();
 145   }
 146 
 147   void add_card(CardIdx_t from_card_index) {
 148     add_card_work(from_card_index, /*parallel*/ true);
 149   }
 150 
 151   void seq_add_card(CardIdx_t from_card_index) {
 152     add_card_work(from_card_index, /*parallel*/ false);
 153   }
 154 
 155   // (Destructively) union the bitmap of the current table into the given
 156   // bitmap (which is assumed to be of the same size.)
 157   void union_bitmap_into(BitMap* bm) {
 158     bm->set_union(_bm);
 159   }
 160 
 161   // Mem size in bytes.
 162   size_t mem_size() const {
 163     return sizeof(PerRegionTable) + _bm.size_in_words() * HeapWordSize;
 164   }
 165 
 166   // Requires "from" to be in "hr()".
 167   bool contains_reference(OopOrNarrowOopStar from) const {
 168     assert(hr()->is_in_reserved(from), "Precondition.");
 169     size_t card_ind = pointer_delta(from, hr()->bottom(),
 170                                     CardTableModRefBS::card_size);
 171     return _bm.at(card_ind);
 172   }
 173 
 174   // Bulk-free the PRTs from prt to last, assumes that they are
 175   // linked together using their _next field.
 176   static void bulk_free(PerRegionTable* prt, PerRegionTable* last) {
 177     while (true) {
 178       PerRegionTable* fl = _free_list;
 179       last->set_next(fl);
 180       PerRegionTable* res = (PerRegionTable*) Atomic::cmpxchg_ptr(prt, &_free_list, fl);
 181       if (res == fl) {
 182         return;
 183       }
 184     }
 185     ShouldNotReachHere();
 186   }
 187 
 188   static void free(PerRegionTable* prt) {
 189     bulk_free(prt, prt);
 190   }
 191 
 192   // Returns an initialized PerRegionTable instance.
 193   static PerRegionTable* alloc(HeapRegion* hr) {
 194     PerRegionTable* fl = _free_list;
 195     while (fl != NULL) {
 196       PerRegionTable* nxt = fl->next();
 197       PerRegionTable* res =
 198         (PerRegionTable*)
 199         Atomic::cmpxchg_ptr(nxt, &_free_list, fl);
 200       if (res == fl) {
 201         fl->init(hr, true);
 202         return fl;
 203       } else {
 204         fl = _free_list;
 205       }
 206     }
 207     assert(fl == NULL, "Loop condition.");
 208     return new PerRegionTable(hr);
 209   }
 210 
 211   PerRegionTable* next() const { return _next; }
 212   void set_next(PerRegionTable* next) { _next = next; }
 213   PerRegionTable* prev() const { return _prev; }
 214   void set_prev(PerRegionTable* prev) { _prev = prev; }
 215 
 216   // Accessor and Modification routines for the pointer for the
 217   // singly linked collision list that links the PRTs within the
 218   // OtherRegionsTable::_fine_grain_regions hash table.
 219   //
 220   // It might be useful to also make the collision list doubly linked
 221   // to avoid iteration over the collisions list during scrubbing/deletion.
 222   // OTOH there might not be many collisions.
 223 
 224   PerRegionTable* collision_list_next() const {
 225     return _collision_list_next;
 226   }
 227 
 228   void set_collision_list_next(PerRegionTable* next) {
 229     _collision_list_next = next;
 230   }
 231 
 232   PerRegionTable** collision_list_next_addr() {
 233     return &_collision_list_next;
 234   }
 235 
 236   static size_t fl_mem_size() {
 237     PerRegionTable* cur = _free_list;
 238     size_t res = 0;
 239     while (cur != NULL) {
 240       res += cur->mem_size();
 241       cur = cur->next();
 242     }
 243     return res;
 244   }
 245 
 246   static void test_fl_mem_size();
 247 };
 248 
 249 PerRegionTable* PerRegionTable::_free_list = NULL;
 250 
 251 size_t OtherRegionsTable::_max_fine_entries = 0;
 252 size_t OtherRegionsTable::_mod_max_fine_entries_mask = 0;
 253 size_t OtherRegionsTable::_fine_eviction_stride = 0;
 254 size_t OtherRegionsTable::_fine_eviction_sample_size = 0;
 255 
 256 OtherRegionsTable::OtherRegionsTable(HeapRegion* hr, Mutex* m) :
 257   _g1h(G1CollectedHeap::heap()),
 258   _hr(hr), _m(m),
 259   _coarse_map(G1CollectedHeap::heap()->max_regions(),
 260               false /* in-resource-area */),
 261   _fine_grain_regions(NULL),
 262   _first_all_fine_prts(NULL), _last_all_fine_prts(NULL),
 263   _n_fine_entries(0), _n_coarse_entries(0),
 264   _fine_eviction_start(0),
 265   _sparse_table(hr)
 266 {
 267   typedef PerRegionTable* PerRegionTablePtr;
 268 
 269   if (_max_fine_entries == 0) {
 270     assert(_mod_max_fine_entries_mask == 0, "Both or none.");
 271     size_t max_entries_log = (size_t)log2_long((jlong)G1RSetRegionEntries);
 272     _max_fine_entries = (size_t)1 << max_entries_log;
 273     _mod_max_fine_entries_mask = _max_fine_entries - 1;
 274 
 275     assert(_fine_eviction_sample_size == 0
 276            && _fine_eviction_stride == 0, "All init at same time.");
 277     _fine_eviction_sample_size = MAX2((size_t)4, max_entries_log);
 278     _fine_eviction_stride = _max_fine_entries / _fine_eviction_sample_size;
 279   }
 280 
 281   _fine_grain_regions = NEW_C_HEAP_ARRAY3(PerRegionTablePtr, _max_fine_entries,
 282                         mtGC, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 283 
 284   if (_fine_grain_regions == NULL) {
 285     vm_exit_out_of_memory(sizeof(void*)*_max_fine_entries, OOM_MALLOC_ERROR,
 286                           "Failed to allocate _fine_grain_entries.");
 287   }
 288 
 289   for (size_t i = 0; i < _max_fine_entries; i++) {
 290     _fine_grain_regions[i] = NULL;
 291   }
 292 }
 293 
 294 void OtherRegionsTable::link_to_all(PerRegionTable* prt) {
 295   // We always append to the beginning of the list for convenience;
 296   // the order of entries in this list does not matter.
 297   if (_first_all_fine_prts != NULL) {
 298     assert(_first_all_fine_prts->prev() == NULL, "invariant");
 299     _first_all_fine_prts->set_prev(prt);
 300     prt->set_next(_first_all_fine_prts);
 301   } else {
 302     // this is the first element we insert. Adjust the "last" pointer
 303     _last_all_fine_prts = prt;
 304     assert(prt->next() == NULL, "just checking");
 305   }
 306   // the new element is always the first element without a predecessor
 307   prt->set_prev(NULL);
 308   _first_all_fine_prts = prt;
 309 
 310   assert(prt->prev() == NULL, "just checking");
 311   assert(_first_all_fine_prts == prt, "just checking");
 312   assert((_first_all_fine_prts == NULL && _last_all_fine_prts == NULL) ||
 313          (_first_all_fine_prts != NULL && _last_all_fine_prts != NULL),
 314          "just checking");
 315   assert(_last_all_fine_prts == NULL || _last_all_fine_prts->next() == NULL,
 316          "just checking");
 317   assert(_first_all_fine_prts == NULL || _first_all_fine_prts->prev() == NULL,
 318          "just checking");
 319 }
 320 
 321 void OtherRegionsTable::unlink_from_all(PerRegionTable* prt) {
 322   if (prt->prev() != NULL) {
 323     assert(_first_all_fine_prts != prt, "just checking");
 324     prt->prev()->set_next(prt->next());
 325     // removing the last element in the list?
 326     if (_last_all_fine_prts == prt) {
 327       _last_all_fine_prts = prt->prev();
 328     }
 329   } else {
 330     assert(_first_all_fine_prts == prt, "just checking");
 331     _first_all_fine_prts = prt->next();
 332     // list is empty now?
 333     if (_first_all_fine_prts == NULL) {
 334       _last_all_fine_prts = NULL;
 335     }
 336   }
 337 
 338   if (prt->next() != NULL) {
 339     prt->next()->set_prev(prt->prev());
 340   }
 341 
 342   prt->set_next(NULL);
 343   prt->set_prev(NULL);
 344 
 345   assert((_first_all_fine_prts == NULL && _last_all_fine_prts == NULL) ||
 346          (_first_all_fine_prts != NULL && _last_all_fine_prts != NULL),
 347          "just checking");
 348   assert(_last_all_fine_prts == NULL || _last_all_fine_prts->next() == NULL,
 349          "just checking");
 350   assert(_first_all_fine_prts == NULL || _first_all_fine_prts->prev() == NULL,
 351          "just checking");
 352 }
 353 
 354 int**  FromCardCache::_cache = NULL;
 355 uint   FromCardCache::_max_regions = 0;
 356 size_t FromCardCache::_static_mem_size = 0;
 357 
 358 void FromCardCache::initialize(uint n_par_rs, uint max_num_regions) {
 359   guarantee(_cache == NULL, "Should not call this multiple times");
 360 
 361   _max_regions = max_num_regions;
 362   _cache = Padded2DArray<int, mtGC>::create_unfreeable(n_par_rs,
 363                                                        _max_regions,
 364                                                        &_static_mem_size);
 365 
 366   invalidate(0, _max_regions);
 367 }
 368 
 369 void FromCardCache::invalidate(uint start_idx, size_t new_num_regions) {
 370   guarantee((size_t)start_idx + new_num_regions <= max_uintx,
 371             "Trying to invalidate beyond maximum region, from %u size " SIZE_FORMAT,
 372             start_idx, new_num_regions);
 373   for (uint i = 0; i < HeapRegionRemSet::num_par_rem_sets(); i++) {
 374     uint end_idx = (start_idx + (uint)new_num_regions);
 375     assert(end_idx <= _max_regions, "Must be within max.");
 376     for (uint j = start_idx; j < end_idx; j++) {
 377       set(i, j, InvalidCard);
 378     }
 379   }
 380 }
 381 
 382 #ifndef PRODUCT
 383 void FromCardCache::print(outputStream* out) {
 384   for (uint i = 0; i < HeapRegionRemSet::num_par_rem_sets(); i++) {
 385     for (uint j = 0; j < _max_regions; j++) {
 386       out->print_cr("_from_card_cache[%u][%u] = %d.",
 387                     i, j, at(i, j));
 388     }
 389   }
 390 }
 391 #endif
 392 
 393 void FromCardCache::clear(uint region_idx) {
 394   uint num_par_remsets = HeapRegionRemSet::num_par_rem_sets();
 395   for (uint i = 0; i < num_par_remsets; i++) {
 396     set(i, region_idx, InvalidCard);
 397   }
 398 }
 399 
 400 void OtherRegionsTable::add_reference(OopOrNarrowOopStar from, uint tid) {
 401   uint cur_hrm_ind = _hr->hrm_index();
 402 
 403   int from_card = (int)(uintptr_t(from) >> CardTableModRefBS::card_shift);
 404 
 405   if (FromCardCache::contains_or_replace(tid, cur_hrm_ind, from_card)) {
 406     assert(contains_reference(from), "We just added it!");
 407     return;
 408   }
 409 
 410   // Note that this may be a continued H region.
 411   HeapRegion* from_hr = _g1h->heap_region_containing(from);
 412   RegionIdx_t from_hrm_ind = (RegionIdx_t) from_hr->hrm_index();
 413 
 414   // If the region is already coarsened, return.
 415   if (_coarse_map.at(from_hrm_ind)) {
 416     assert(contains_reference(from), "We just added it!");
 417     return;
 418   }
 419 
 420   // Otherwise find a per-region table to add it to.
 421   size_t ind = from_hrm_ind & _mod_max_fine_entries_mask;
 422   PerRegionTable* prt = find_region_table(ind, from_hr);
 423   if (prt == NULL) {
 424     MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
 425     // Confirm that it's really not there...
 426     prt = find_region_table(ind, from_hr);
 427     if (prt == NULL) {
 428 
 429       uintptr_t from_hr_bot_card_index =
 430         uintptr_t(from_hr->bottom())
 431           >> CardTableModRefBS::card_shift;
 432       CardIdx_t card_index = from_card - from_hr_bot_card_index;
 433       assert(0 <= card_index && (size_t)card_index < HeapRegion::CardsPerRegion,
 434              "Must be in range.");
 435       if (G1HRRSUseSparseTable &&
 436           _sparse_table.add_card(from_hrm_ind, card_index)) {
 437         assert(contains_reference_locked(from), "We just added it!");
 438         return;
 439       }
 440 
 441       if (_n_fine_entries == _max_fine_entries) {
 442         prt = delete_region_table();
 443         // There is no need to clear the links to the 'all' list here:
 444         // prt will be reused immediately, i.e. remain in the 'all' list.
 445         prt->init(from_hr, false /* clear_links_to_all_list */);
 446       } else {
 447         prt = PerRegionTable::alloc(from_hr);
 448         link_to_all(prt);
 449       }
 450 
 451       PerRegionTable* first_prt = _fine_grain_regions[ind];
 452       prt->set_collision_list_next(first_prt);
 453       // The assignment into _fine_grain_regions allows the prt to
 454       // start being used concurrently. In addition to
 455       // collision_list_next which must be visible (else concurrent
 456       // parsing of the list, if any, may fail to see other entries),
 457       // the content of the prt must be visible (else for instance
 458       // some mark bits may not yet seem cleared or a 'later' update
 459       // performed by a concurrent thread could be undone when the
 460       // zeroing becomes visible). This requires store ordering.
 461       OrderAccess::release_store_ptr((volatile PerRegionTable*)&_fine_grain_regions[ind], prt);
 462       _n_fine_entries++;
 463 
 464       if (G1HRRSUseSparseTable) {
 465         // Transfer from sparse to fine-grain.
 466         SparsePRTEntry *sprt_entry = _sparse_table.get_entry(from_hrm_ind);
 467         assert(sprt_entry != NULL, "There should have been an entry");
 468         for (int i = 0; i < SparsePRTEntry::cards_num(); i++) {
 469           CardIdx_t c = sprt_entry->card(i);
 470           if (c != SparsePRTEntry::NullEntry) {
 471             prt->add_card(c);
 472           }
 473         }
 474         // Now we can delete the sparse entry.
 475         bool res = _sparse_table.delete_entry(from_hrm_ind);
 476         assert(res, "It should have been there.");
 477       }
 478     }
 479     assert(prt != NULL && prt->hr() == from_hr, "consequence");
 480   }
 481   // Note that we can't assert "prt->hr() == from_hr", because of the
 482   // possibility of concurrent reuse.  But see head comment of
 483   // OtherRegionsTable for why this is OK.
 484   assert(prt != NULL, "Inv");
 485 
 486   prt->add_reference(from);
 487   assert(contains_reference(from), "We just added it!");
 488 }
 489 
 490 PerRegionTable*
 491 OtherRegionsTable::find_region_table(size_t ind, HeapRegion* hr) const {
 492   assert(ind < _max_fine_entries, "Preconditions.");
 493   PerRegionTable* prt = _fine_grain_regions[ind];
 494   while (prt != NULL && prt->hr() != hr) {
 495     prt = prt->collision_list_next();
 496   }
 497   // Loop postcondition is the method postcondition.
 498   return prt;
 499 }
 500 
 501 jint OtherRegionsTable::_n_coarsenings = 0;
 502 
 503 PerRegionTable* OtherRegionsTable::delete_region_table() {
 504   assert(_m->owned_by_self(), "Precondition");
 505   assert(_n_fine_entries == _max_fine_entries, "Precondition");
 506   PerRegionTable* max = NULL;
 507   jint max_occ = 0;
 508   PerRegionTable** max_prev = NULL;
 509   size_t max_ind;
 510 
 511   size_t i = _fine_eviction_start;
 512   for (size_t k = 0; k < _fine_eviction_sample_size; k++) {
 513     size_t ii = i;
 514     // Make sure we get a non-NULL sample.
 515     while (_fine_grain_regions[ii] == NULL) {
 516       ii++;
 517       if (ii == _max_fine_entries) ii = 0;
 518       guarantee(ii != i, "We must find one.");
 519     }
 520     PerRegionTable** prev = &_fine_grain_regions[ii];
 521     PerRegionTable* cur = *prev;
 522     while (cur != NULL) {
 523       jint cur_occ = cur->occupied();
 524       if (max == NULL || cur_occ > max_occ) {
 525         max = cur;
 526         max_prev = prev;
 527         max_ind = i;
 528         max_occ = cur_occ;
 529       }
 530       prev = cur->collision_list_next_addr();
 531       cur = cur->collision_list_next();
 532     }
 533     i = i + _fine_eviction_stride;
 534     if (i >= _n_fine_entries) i = i - _n_fine_entries;
 535   }
 536 
 537   _fine_eviction_start++;
 538 
 539   if (_fine_eviction_start >= _n_fine_entries) {
 540     _fine_eviction_start -= _n_fine_entries;
 541   }
 542 
 543   guarantee(max != NULL, "Since _n_fine_entries > 0");
 544   guarantee(max_prev != NULL, "Since max != NULL.");
 545 
 546   // Set the corresponding coarse bit.
 547   size_t max_hrm_index = (size_t) max->hr()->hrm_index();
 548   if (!_coarse_map.at(max_hrm_index)) {
 549     _coarse_map.at_put(max_hrm_index, true);
 550     _n_coarse_entries++;
 551   }
 552 
 553   // Unsplice.
 554   *max_prev = max->collision_list_next();
 555   Atomic::inc(&_n_coarsenings);
 556   _n_fine_entries--;
 557   return max;
 558 }
 559 
 560 void OtherRegionsTable::scrub(CardTableModRefBS* ctbs,
 561                               BitMap* region_bm, BitMap* card_bm) {
 562   // First eliminated garbage regions from the coarse map.
 563   if (G1RSScrubVerbose) {
 564     gclog_or_tty->print_cr("Scrubbing region %u:", _hr->hrm_index());
 565   }
 566 
 567   assert(_coarse_map.size() == region_bm->size(), "Precondition");
 568   if (G1RSScrubVerbose) {
 569     gclog_or_tty->print("   Coarse map: before = " SIZE_FORMAT "...",
 570                         _n_coarse_entries);
 571   }
 572   _coarse_map.set_intersection(*region_bm);
 573   _n_coarse_entries = _coarse_map.count_one_bits();
 574   if (G1RSScrubVerbose) {
 575     gclog_or_tty->print_cr("   after = " SIZE_FORMAT ".", _n_coarse_entries);
 576   }
 577 
 578   // Now do the fine-grained maps.
 579   for (size_t i = 0; i < _max_fine_entries; i++) {
 580     PerRegionTable* cur = _fine_grain_regions[i];
 581     PerRegionTable** prev = &_fine_grain_regions[i];
 582     while (cur != NULL) {
 583       PerRegionTable* nxt = cur->collision_list_next();
 584       // If the entire region is dead, eliminate.
 585       if (G1RSScrubVerbose) {
 586         gclog_or_tty->print_cr("     For other region %u:",
 587                                cur->hr()->hrm_index());
 588       }
 589       if (!region_bm->at((size_t) cur->hr()->hrm_index())) {
 590         *prev = nxt;
 591         cur->set_collision_list_next(NULL);
 592         _n_fine_entries--;
 593         if (G1RSScrubVerbose) {
 594           gclog_or_tty->print_cr("          deleted via region map.");
 595         }
 596         unlink_from_all(cur);
 597         PerRegionTable::free(cur);
 598       } else {
 599         // Do fine-grain elimination.
 600         if (G1RSScrubVerbose) {
 601           gclog_or_tty->print("          occ: before = %4d.", cur->occupied());
 602         }
 603         cur->scrub(ctbs, card_bm);
 604         if (G1RSScrubVerbose) {
 605           gclog_or_tty->print_cr("          after = %4d.", cur->occupied());
 606         }
 607         // Did that empty the table completely?
 608         if (cur->occupied() == 0) {
 609           *prev = nxt;
 610           cur->set_collision_list_next(NULL);
 611           _n_fine_entries--;
 612           unlink_from_all(cur);
 613           PerRegionTable::free(cur);
 614         } else {
 615           prev = cur->collision_list_next_addr();
 616         }
 617       }
 618       cur = nxt;
 619     }
 620   }
 621   // Since we may have deleted a from_card_cache entry from the RS, clear
 622   // the FCC.
 623   clear_fcc();
 624 }
 625 
 626 bool OtherRegionsTable::occupancy_less_or_equal_than(size_t limit) const {
 627   if (limit <= (size_t)G1RSetSparseRegionEntries) {
 628     return occ_coarse() == 0 && _first_all_fine_prts == NULL && occ_sparse() <= limit;
 629   } else {
 630     // Current uses of this method may only use values less than G1RSetSparseRegionEntries
 631     // for the limit. The solution, comparing against occupied() would be too slow
 632     // at this time.
 633     Unimplemented();
 634     return false;
 635   }
 636 }
 637 
 638 bool OtherRegionsTable::is_empty() const {
 639   return occ_sparse() == 0 && occ_coarse() == 0 && _first_all_fine_prts == NULL;
 640 }
 641 
 642 size_t OtherRegionsTable::occupied() const {
 643   size_t sum = occ_fine();
 644   sum += occ_sparse();
 645   sum += occ_coarse();
 646   return sum;
 647 }
 648 
 649 size_t OtherRegionsTable::occ_fine() const {
 650   size_t sum = 0;
 651 
 652   size_t num = 0;
 653   PerRegionTable * cur = _first_all_fine_prts;
 654   while (cur != NULL) {
 655     sum += cur->occupied();
 656     cur = cur->next();
 657     num++;
 658   }
 659   guarantee(num == _n_fine_entries, "just checking");
 660   return sum;
 661 }
 662 
 663 size_t OtherRegionsTable::occ_coarse() const {
 664   return (_n_coarse_entries * HeapRegion::CardsPerRegion);
 665 }
 666 
 667 size_t OtherRegionsTable::occ_sparse() const {
 668   return _sparse_table.occupied();
 669 }
 670 
 671 size_t OtherRegionsTable::mem_size() const {
 672   size_t sum = 0;
 673   // all PRTs are of the same size so it is sufficient to query only one of them.
 674   if (_first_all_fine_prts != NULL) {
 675     assert(_last_all_fine_prts != NULL &&
 676       _first_all_fine_prts->mem_size() == _last_all_fine_prts->mem_size(), "check that mem_size() is constant");
 677     sum += _first_all_fine_prts->mem_size() * _n_fine_entries;
 678   }
 679   sum += (sizeof(PerRegionTable*) * _max_fine_entries);
 680   sum += (_coarse_map.size_in_words() * HeapWordSize);
 681   sum += (_sparse_table.mem_size());
 682   sum += sizeof(OtherRegionsTable) - sizeof(_sparse_table); // Avoid double counting above.
 683   return sum;
 684 }
 685 
 686 size_t OtherRegionsTable::static_mem_size() {
 687   return FromCardCache::static_mem_size();
 688 }
 689 
 690 size_t OtherRegionsTable::fl_mem_size() {
 691   return PerRegionTable::fl_mem_size();
 692 }
 693 
 694 void OtherRegionsTable::clear_fcc() {
 695   FromCardCache::clear(_hr->hrm_index());
 696 }
 697 
 698 void OtherRegionsTable::clear() {
 699   // if there are no entries, skip this step
 700   if (_first_all_fine_prts != NULL) {
 701     guarantee(_first_all_fine_prts != NULL && _last_all_fine_prts != NULL, "just checking");
 702     PerRegionTable::bulk_free(_first_all_fine_prts, _last_all_fine_prts);
 703     memset(_fine_grain_regions, 0, _max_fine_entries * sizeof(_fine_grain_regions[0]));
 704   } else {
 705     guarantee(_first_all_fine_prts == NULL && _last_all_fine_prts == NULL, "just checking");
 706   }
 707 
 708   _first_all_fine_prts = _last_all_fine_prts = NULL;
 709   _sparse_table.clear();
 710   _coarse_map.clear();
 711   _n_fine_entries = 0;
 712   _n_coarse_entries = 0;
 713 
 714   clear_fcc();
 715 }
 716 
 717 bool OtherRegionsTable::contains_reference(OopOrNarrowOopStar from) const {
 718   // Cast away const in this case.
 719   MutexLockerEx x((Mutex*)_m, Mutex::_no_safepoint_check_flag);
 720   return contains_reference_locked(from);
 721 }
 722 
 723 bool OtherRegionsTable::contains_reference_locked(OopOrNarrowOopStar from) const {
 724   HeapRegion* hr = _g1h->heap_region_containing(from);
 725   RegionIdx_t hr_ind = (RegionIdx_t) hr->hrm_index();
 726   // Is this region in the coarse map?
 727   if (_coarse_map.at(hr_ind)) return true;
 728 
 729   PerRegionTable* prt = find_region_table(hr_ind & _mod_max_fine_entries_mask,
 730                                      hr);
 731   if (prt != NULL) {
 732     return prt->contains_reference(from);
 733 
 734   } else {
 735     uintptr_t from_card =
 736       (uintptr_t(from) >> CardTableModRefBS::card_shift);
 737     uintptr_t hr_bot_card_index =
 738       uintptr_t(hr->bottom()) >> CardTableModRefBS::card_shift;
 739     assert(from_card >= hr_bot_card_index, "Inv");
 740     CardIdx_t card_index = from_card - hr_bot_card_index;
 741     assert(0 <= card_index && (size_t)card_index < HeapRegion::CardsPerRegion,
 742            "Must be in range.");
 743     return _sparse_table.contains_card(hr_ind, card_index);
 744   }
 745 }
 746 
 747 void
 748 OtherRegionsTable::do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task) {
 749   _sparse_table.do_cleanup_work(hrrs_cleanup_task);
 750 }
 751 
 752 // Determines how many threads can add records to an rset in parallel.
 753 // This can be done by either mutator threads together with the
 754 // concurrent refinement threads or GC threads.
 755 uint HeapRegionRemSet::num_par_rem_sets() {
 756   return MAX2(DirtyCardQueueSet::num_par_ids() + ConcurrentG1Refine::thread_num(), ParallelGCThreads);
 757 }
 758 
 759 HeapRegionRemSet::HeapRegionRemSet(G1BlockOffsetSharedArray* bosa,
 760                                    HeapRegion* hr)
 761   : _bosa(bosa),
 762     _m(Mutex::leaf, FormatBuffer<128>("HeapRegionRemSet lock #%u", hr->hrm_index()), true, Monitor::_safepoint_check_never),
 763     _code_roots(), _other_regions(hr, &_m), _iter_state(Unclaimed), _iter_claimed(0) {
 764   reset_for_par_iteration();
 765 }
 766 
 767 void HeapRegionRemSet::setup_remset_size() {
 768   // Setup sparse and fine-grain tables sizes.
 769   // table_size = base * (log(region_size / 1M) + 1)
 770   const int LOG_M = 20;
 771   int region_size_log_mb = MAX2(HeapRegion::LogOfHRGrainBytes - LOG_M, 0);
 772   if (FLAG_IS_DEFAULT(G1RSetSparseRegionEntries)) {
 773     G1RSetSparseRegionEntries = G1RSetSparseRegionEntriesBase * (region_size_log_mb + 1);
 774   }
 775   if (FLAG_IS_DEFAULT(G1RSetRegionEntries)) {
 776     G1RSetRegionEntries = G1RSetRegionEntriesBase * (region_size_log_mb + 1);
 777   }
 778   guarantee(G1RSetSparseRegionEntries > 0 && G1RSetRegionEntries > 0 , "Sanity");
 779 }
 780 
 781 bool HeapRegionRemSet::claim_iter() {
 782   if (_iter_state != Unclaimed) return false;
 783   jint res = Atomic::cmpxchg(Claimed, (jint*)(&_iter_state), Unclaimed);
 784   return (res == Unclaimed);
 785 }
 786 
 787 void HeapRegionRemSet::set_iter_complete() {
 788   _iter_state = Complete;
 789 }
 790 
 791 bool HeapRegionRemSet::iter_is_complete() {
 792   return _iter_state == Complete;
 793 }
 794 
 795 #ifndef PRODUCT
 796 void HeapRegionRemSet::print() {
 797   HeapRegionRemSetIterator iter(this);
 798   size_t card_index;
 799   while (iter.has_next(card_index)) {
 800     HeapWord* card_start =
 801       G1CollectedHeap::heap()->bot_shared()->address_for_index(card_index);
 802     gclog_or_tty->print_cr("  Card " PTR_FORMAT, p2i(card_start));
 803   }
 804   if (iter.n_yielded() != occupied()) {
 805     gclog_or_tty->print_cr("Yielded disagrees with occupied:");
 806     gclog_or_tty->print_cr("  " SIZE_FORMAT_W(6) " yielded (" SIZE_FORMAT_W(6)
 807                   " coarse, " SIZE_FORMAT_W(6) " fine).",
 808                   iter.n_yielded(),
 809                   iter.n_yielded_coarse(), iter.n_yielded_fine());
 810     gclog_or_tty->print_cr("  " SIZE_FORMAT_W(6) " occ     (" SIZE_FORMAT_W(6)
 811                            " coarse, " SIZE_FORMAT_W(6) " fine).",
 812                   occupied(), occ_coarse(), occ_fine());
 813   }
 814   guarantee(iter.n_yielded() == occupied(),
 815             "We should have yielded all the represented cards.");
 816 }
 817 #endif
 818 
 819 void HeapRegionRemSet::cleanup() {
 820   SparsePRT::cleanup_all();
 821 }
 822 
 823 void HeapRegionRemSet::clear() {
 824   MutexLockerEx x(&_m, Mutex::_no_safepoint_check_flag);
 825   clear_locked();
 826 }
 827 
 828 void HeapRegionRemSet::clear_locked() {
 829   _code_roots.clear();
 830   _other_regions.clear();
 831   assert(occupied_locked() == 0, "Should be clear.");
 832   reset_for_par_iteration();
 833 }
 834 
 835 void HeapRegionRemSet::reset_for_par_iteration() {
 836   _iter_state = Unclaimed;
 837   _iter_claimed = 0;
 838   // It's good to check this to make sure that the two methods are in sync.
 839   assert(verify_ready_for_par_iteration(), "post-condition");
 840 }
 841 
 842 void HeapRegionRemSet::scrub(CardTableModRefBS* ctbs,
 843                              BitMap* region_bm, BitMap* card_bm) {
 844   _other_regions.scrub(ctbs, region_bm, card_bm);
 845 }
 846 
 847 // Code roots support
 848 //
 849 // The code root set is protected by two separate locking schemes
 850 // When at safepoint the per-hrrs lock must be held during modifications
 851 // except when doing a full gc.
 852 // When not at safepoint the CodeCache_lock must be held during modifications.
 853 // When concurrent readers access the contains() function
 854 // (during the evacuation phase) no removals are allowed.
 855 
 856 void HeapRegionRemSet::add_strong_code_root(nmethod* nm) {
 857   assert(nm != NULL, "sanity");
 858   // Optimistic unlocked contains-check
 859   if (!_code_roots.contains(nm)) {
 860     MutexLockerEx ml(&_m, Mutex::_no_safepoint_check_flag);
 861     add_strong_code_root_locked(nm);
 862   }
 863 }
 864 
 865 void HeapRegionRemSet::add_strong_code_root_locked(nmethod* nm) {
 866   assert(nm != NULL, "sanity");
 867   _code_roots.add(nm);
 868 }
 869 
 870 void HeapRegionRemSet::remove_strong_code_root(nmethod* nm) {
 871   assert(nm != NULL, "sanity");
 872   assert_locked_or_safepoint(CodeCache_lock);
 873 
 874   MutexLockerEx ml(CodeCache_lock->owned_by_self() ? NULL : &_m, Mutex::_no_safepoint_check_flag);
 875   _code_roots.remove(nm);
 876 
 877   // Check that there were no duplicates
 878   guarantee(!_code_roots.contains(nm), "duplicate entry found");
 879 }
 880 
 881 void HeapRegionRemSet::strong_code_roots_do(CodeBlobClosure* blk) const {
 882   _code_roots.nmethods_do(blk);
 883 }
 884 
 885 void HeapRegionRemSet::clean_strong_code_roots(HeapRegion* hr) {
 886   _code_roots.clean(hr);
 887 }
 888 
 889 size_t HeapRegionRemSet::strong_code_roots_mem_size() {
 890   return _code_roots.mem_size();
 891 }
 892 
 893 HeapRegionRemSetIterator:: HeapRegionRemSetIterator(HeapRegionRemSet* hrrs) :
 894   _hrrs(hrrs),
 895   _g1h(G1CollectedHeap::heap()),
 896   _coarse_map(&hrrs->_other_regions._coarse_map),
 897   _bosa(hrrs->_bosa),
 898   _is(Sparse),
 899   // Set these values so that we increment to the first region.
 900   _coarse_cur_region_index(-1),
 901   _coarse_cur_region_cur_card(HeapRegion::CardsPerRegion-1),
 902   _cur_card_in_prt(HeapRegion::CardsPerRegion),
 903   _fine_cur_prt(NULL),
 904   _n_yielded_coarse(0),
 905   _n_yielded_fine(0),
 906   _n_yielded_sparse(0),
 907   _sparse_iter(&hrrs->_other_regions._sparse_table) {}
 908 
 909 bool HeapRegionRemSetIterator::coarse_has_next(size_t& card_index) {
 910   if (_hrrs->_other_regions._n_coarse_entries == 0) return false;
 911   // Go to the next card.
 912   _coarse_cur_region_cur_card++;
 913   // Was the last the last card in the current region?
 914   if (_coarse_cur_region_cur_card == HeapRegion::CardsPerRegion) {
 915     // Yes: find the next region.  This may leave _coarse_cur_region_index
 916     // Set to the last index, in which case there are no more coarse
 917     // regions.
 918     _coarse_cur_region_index =
 919       (int) _coarse_map->get_next_one_offset(_coarse_cur_region_index + 1);
 920     if ((size_t)_coarse_cur_region_index < _coarse_map->size()) {
 921       _coarse_cur_region_cur_card = 0;
 922       HeapWord* r_bot =
 923         _g1h->region_at((uint) _coarse_cur_region_index)->bottom();
 924       _cur_region_card_offset = _bosa->index_for(r_bot);
 925     } else {
 926       return false;
 927     }
 928   }
 929   // If we didn't return false above, then we can yield a card.
 930   card_index = _cur_region_card_offset + _coarse_cur_region_cur_card;
 931   return true;
 932 }
 933 
 934 bool HeapRegionRemSetIterator::fine_has_next(size_t& card_index) {
 935   if (fine_has_next()) {
 936     _cur_card_in_prt =
 937       _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
 938   }
 939   if (_cur_card_in_prt == HeapRegion::CardsPerRegion) {
 940     // _fine_cur_prt may still be NULL in case if there are not PRTs at all for
 941     // the remembered set.
 942     if (_fine_cur_prt == NULL || _fine_cur_prt->next() == NULL) {
 943       return false;
 944     }
 945     PerRegionTable* next_prt = _fine_cur_prt->next();
 946     switch_to_prt(next_prt);
 947     _cur_card_in_prt = _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
 948   }
 949 
 950   card_index = _cur_region_card_offset + _cur_card_in_prt;
 951   guarantee(_cur_card_in_prt < HeapRegion::CardsPerRegion,
 952             "Card index " SIZE_FORMAT " must be within the region", _cur_card_in_prt);
 953   return true;
 954 }
 955 
 956 bool HeapRegionRemSetIterator::fine_has_next() {
 957   return _cur_card_in_prt != HeapRegion::CardsPerRegion;
 958 }
 959 
 960 void HeapRegionRemSetIterator::switch_to_prt(PerRegionTable* prt) {
 961   assert(prt != NULL, "Cannot switch to NULL prt");
 962   _fine_cur_prt = prt;
 963 
 964   HeapWord* r_bot = _fine_cur_prt->hr()->bottom();
 965   _cur_region_card_offset = _bosa->index_for(r_bot);
 966 
 967   // The bitmap scan for the PRT always scans from _cur_region_cur_card + 1.
 968   // To avoid special-casing this start case, and not miss the first bitmap
 969   // entry, initialize _cur_region_cur_card with -1 instead of 0.
 970   _cur_card_in_prt = (size_t)-1;
 971 }
 972 
 973 bool HeapRegionRemSetIterator::has_next(size_t& card_index) {
 974   switch (_is) {
 975   case Sparse: {
 976     if (_sparse_iter.has_next(card_index)) {
 977       _n_yielded_sparse++;
 978       return true;
 979     }
 980     // Otherwise, deliberate fall-through
 981     _is = Fine;
 982     PerRegionTable* initial_fine_prt = _hrrs->_other_regions._first_all_fine_prts;
 983     if (initial_fine_prt != NULL) {
 984       switch_to_prt(_hrrs->_other_regions._first_all_fine_prts);
 985     }
 986   }
 987   case Fine:
 988     if (fine_has_next(card_index)) {
 989       _n_yielded_fine++;
 990       return true;
 991     }
 992     // Otherwise, deliberate fall-through
 993     _is = Coarse;
 994   case Coarse:
 995     if (coarse_has_next(card_index)) {
 996       _n_yielded_coarse++;
 997       return true;
 998     }
 999     // Otherwise...
1000     break;
1001   }
1002   assert(ParallelGCThreads > 1 ||
1003          n_yielded() == _hrrs->occupied(),
1004          "Should have yielded all the cards in the rem set "
1005          "(in the non-par case).");
1006   return false;
1007 }
1008 
1009 void HeapRegionRemSet::reset_for_cleanup_tasks() {
1010   SparsePRT::reset_for_cleanup_tasks();
1011 }
1012 
1013 void HeapRegionRemSet::do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task) {
1014   _other_regions.do_cleanup_work(hrrs_cleanup_task);
1015 }
1016 
1017 void
1018 HeapRegionRemSet::finish_cleanup_task(HRRSCleanupTask* hrrs_cleanup_task) {
1019   SparsePRT::finish_cleanup_task(hrrs_cleanup_task);
1020 }
1021 
1022 #ifndef PRODUCT
1023 void HeapRegionRemSet::test() {
1024   os::sleep(Thread::current(), (jlong)5000, false);
1025   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1026 
1027   // Run with "-XX:G1LogRSetRegionEntries=2", so that 1 and 5 end up in same
1028   // hash bucket.
1029   HeapRegion* hr0 = g1h->region_at(0);
1030   HeapRegion* hr1 = g1h->region_at(1);
1031   HeapRegion* hr2 = g1h->region_at(5);
1032   HeapRegion* hr3 = g1h->region_at(6);
1033   HeapRegion* hr4 = g1h->region_at(7);
1034   HeapRegion* hr5 = g1h->region_at(8);
1035 
1036   HeapWord* hr1_start = hr1->bottom();
1037   HeapWord* hr1_mid = hr1_start + HeapRegion::GrainWords/2;
1038   HeapWord* hr1_last = hr1->end() - 1;
1039 
1040   HeapWord* hr2_start = hr2->bottom();
1041   HeapWord* hr2_mid = hr2_start + HeapRegion::GrainWords/2;
1042   HeapWord* hr2_last = hr2->end() - 1;
1043 
1044   HeapWord* hr3_start = hr3->bottom();
1045   HeapWord* hr3_mid = hr3_start + HeapRegion::GrainWords/2;
1046   HeapWord* hr3_last = hr3->end() - 1;
1047 
1048   HeapRegionRemSet* hrrs = hr0->rem_set();
1049 
1050   // Make three references from region 0x101...
1051   hrrs->add_reference((OopOrNarrowOopStar)hr1_start);
1052   hrrs->add_reference((OopOrNarrowOopStar)hr1_mid);
1053   hrrs->add_reference((OopOrNarrowOopStar)hr1_last);
1054 
1055   hrrs->add_reference((OopOrNarrowOopStar)hr2_start);
1056   hrrs->add_reference((OopOrNarrowOopStar)hr2_mid);
1057   hrrs->add_reference((OopOrNarrowOopStar)hr2_last);
1058 
1059   hrrs->add_reference((OopOrNarrowOopStar)hr3_start);
1060   hrrs->add_reference((OopOrNarrowOopStar)hr3_mid);
1061   hrrs->add_reference((OopOrNarrowOopStar)hr3_last);
1062 
1063   // Now cause a coarsening.
1064   hrrs->add_reference((OopOrNarrowOopStar)hr4->bottom());
1065   hrrs->add_reference((OopOrNarrowOopStar)hr5->bottom());
1066 
1067   // Now, does iteration yield these three?
1068   HeapRegionRemSetIterator iter(hrrs);
1069   size_t sum = 0;
1070   size_t card_index;
1071   while (iter.has_next(card_index)) {
1072     HeapWord* card_start =
1073       G1CollectedHeap::heap()->bot_shared()->address_for_index(card_index);
1074     gclog_or_tty->print_cr("  Card " PTR_FORMAT ".", p2i(card_start));
1075     sum++;
1076   }
1077   guarantee(sum == 11 - 3 + 2048, "Failure");
1078   guarantee(sum == hrrs->occupied(), "Failure");
1079 }
1080 #endif