1 /*
   2  * Copyright (c) 2001, 2018, 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/g1BlockOffsetTable.inline.hpp"
  27 #include "gc/g1/g1CollectedHeap.inline.hpp"
  28 #include "gc/g1/g1ConcurrentRefine.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.hpp"
  36 #include "utilities/bitMap.inline.hpp"
  37 #include "utilities/debug.hpp"
  38 #include "utilities/formatBuffer.hpp"
  39 #include "utilities/globalDefinitions.hpp"
  40 #include "utilities/growableArray.hpp"
  41 
  42 const char* HeapRegionRemSet::_state_strings[] =  {"Untracked", "Updating", "Complete"};
  43 const char* HeapRegionRemSet::_short_state_strings[] =  {"UNTRA", "UPDAT", "CMPLT"};
  44 
  45 class PerRegionTable: public CHeapObj<mtGC> {
  46   friend class OtherRegionsTable;
  47   friend class HeapRegionRemSetIterator;
  48 
  49   HeapRegion*     _hr;
  50   CHeapBitMap     _bm;
  51   jint            _occupied;
  52 
  53   // next pointer for free/allocated 'all' list
  54   PerRegionTable* _next;
  55 
  56   // prev pointer for the allocated 'all' list
  57   PerRegionTable* _prev;
  58 
  59   // next pointer in collision list
  60   PerRegionTable * _collision_list_next;
  61 
  62   // Global free list of PRTs
  63   static PerRegionTable* volatile _free_list;
  64 
  65 protected:
  66   // We need access in order to union things into the base table.
  67   BitMap* bm() { return &_bm; }
  68 
  69   PerRegionTable(HeapRegion* hr) :
  70     _hr(hr),
  71     _bm(HeapRegion::CardsPerRegion, mtGC),
  72     _occupied(0),
  73     _next(NULL), _prev(NULL),
  74     _collision_list_next(NULL)
  75   {}
  76 
  77   void add_card_work(CardIdx_t from_card, bool par) {
  78     if (!_bm.at(from_card)) {
  79       if (par) {
  80         if (_bm.par_at_put(from_card, 1)) {
  81           Atomic::inc(&_occupied);
  82         }
  83       } else {
  84         _bm.at_put(from_card, 1);
  85         _occupied++;
  86       }
  87     }
  88   }
  89 
  90   void add_reference_work(OopOrNarrowOopStar from, bool par) {
  91     // Must make this robust in case "from" is not in "_hr", because of
  92     // concurrency.
  93 
  94     HeapRegion* loc_hr = hr();
  95     // If the test below fails, then this table was reused concurrently
  96     // with this operation.  This is OK, since the old table was coarsened,
  97     // and adding a bit to the new table is never incorrect.
  98     if (loc_hr->is_in_reserved(from)) {
  99       CardIdx_t from_card = OtherRegionsTable::card_within_region(from, loc_hr);
 100       add_card_work(from_card, par);
 101     }
 102   }
 103 
 104 public:
 105 
 106   HeapRegion* hr() const { return OrderAccess::load_acquire(&_hr); }
 107 
 108   jint occupied() const {
 109     // Overkill, but if we ever need it...
 110     // guarantee(_occupied == _bm.count_one_bits(), "Check");
 111     return _occupied;
 112   }
 113 
 114   void init(HeapRegion* hr, bool clear_links_to_all_list) {
 115     if (clear_links_to_all_list) {
 116       set_next(NULL);
 117       set_prev(NULL);
 118     }
 119     _collision_list_next = NULL;
 120     _occupied = 0;
 121     _bm.clear();
 122     // Make sure that the bitmap clearing above has been finished before publishing
 123     // this PRT to concurrent threads.
 124     OrderAccess::release_store(&_hr, hr);
 125   }
 126 
 127   void add_reference(OopOrNarrowOopStar from) {
 128     add_reference_work(from, /*parallel*/ true);
 129   }
 130 
 131   void seq_add_reference(OopOrNarrowOopStar from) {
 132     add_reference_work(from, /*parallel*/ false);
 133   }
 134 
 135   void add_card(CardIdx_t from_card_index) {
 136     add_card_work(from_card_index, /*parallel*/ true);
 137   }
 138 
 139   void seq_add_card(CardIdx_t from_card_index) {
 140     add_card_work(from_card_index, /*parallel*/ false);
 141   }
 142 
 143   // (Destructively) union the bitmap of the current table into the given
 144   // bitmap (which is assumed to be of the same size.)
 145   void union_bitmap_into(BitMap* bm) {
 146     bm->set_union(_bm);
 147   }
 148 
 149   // Mem size in bytes.
 150   size_t mem_size() const {
 151     return sizeof(PerRegionTable) + _bm.size_in_words() * HeapWordSize;
 152   }
 153 
 154   // Requires "from" to be in "hr()".
 155   bool contains_reference(OopOrNarrowOopStar from) const {
 156     assert(hr()->is_in_reserved(from), "Precondition.");
 157     size_t card_ind = pointer_delta(from, hr()->bottom(),
 158                                     G1CardTable::card_size);
 159     return _bm.at(card_ind);
 160   }
 161 
 162   // Bulk-free the PRTs from prt to last, assumes that they are
 163   // linked together using their _next field.
 164   static void bulk_free(PerRegionTable* prt, PerRegionTable* last) {
 165     while (true) {
 166       PerRegionTable* fl = _free_list;
 167       last->set_next(fl);
 168       PerRegionTable* res = Atomic::cmpxchg(prt, &_free_list, fl);
 169       if (res == fl) {
 170         return;
 171       }
 172     }
 173     ShouldNotReachHere();
 174   }
 175 
 176   static void free(PerRegionTable* prt) {
 177     bulk_free(prt, prt);
 178   }
 179 
 180   // Returns an initialized PerRegionTable instance.
 181   static PerRegionTable* alloc(HeapRegion* hr) {
 182     PerRegionTable* fl = _free_list;
 183     while (fl != NULL) {
 184       PerRegionTable* nxt = fl->next();
 185       PerRegionTable* res = Atomic::cmpxchg(nxt, &_free_list, fl);
 186       if (res == fl) {
 187         fl->init(hr, true);
 188         return fl;
 189       } else {
 190         fl = _free_list;
 191       }
 192     }
 193     assert(fl == NULL, "Loop condition.");
 194     return new PerRegionTable(hr);
 195   }
 196 
 197   PerRegionTable* next() const { return _next; }
 198   void set_next(PerRegionTable* next) { _next = next; }
 199   PerRegionTable* prev() const { return _prev; }
 200   void set_prev(PerRegionTable* prev) { _prev = prev; }
 201 
 202   // Accessor and Modification routines for the pointer for the
 203   // singly linked collision list that links the PRTs within the
 204   // OtherRegionsTable::_fine_grain_regions hash table.
 205   //
 206   // It might be useful to also make the collision list doubly linked
 207   // to avoid iteration over the collisions list during scrubbing/deletion.
 208   // OTOH there might not be many collisions.
 209 
 210   PerRegionTable* collision_list_next() const {
 211     return _collision_list_next;
 212   }
 213 
 214   void set_collision_list_next(PerRegionTable* next) {
 215     _collision_list_next = next;
 216   }
 217 
 218   PerRegionTable** collision_list_next_addr() {
 219     return &_collision_list_next;
 220   }
 221 
 222   static size_t fl_mem_size() {
 223     PerRegionTable* cur = _free_list;
 224     size_t res = 0;
 225     while (cur != NULL) {
 226       res += cur->mem_size();
 227       cur = cur->next();
 228     }
 229     return res;
 230   }
 231 
 232   static void test_fl_mem_size();
 233 };
 234 
 235 PerRegionTable* volatile PerRegionTable::_free_list = NULL;
 236 
 237 size_t OtherRegionsTable::_max_fine_entries = 0;
 238 size_t OtherRegionsTable::_mod_max_fine_entries_mask = 0;
 239 size_t OtherRegionsTable::_fine_eviction_stride = 0;
 240 size_t OtherRegionsTable::_fine_eviction_sample_size = 0;
 241 
 242 OtherRegionsTable::OtherRegionsTable(Mutex* m) :
 243   _g1h(G1CollectedHeap::heap()),
 244   _m(m),
 245   _coarse_map(G1CollectedHeap::heap()->max_regions(), mtGC),
 246   _n_coarse_entries(0),
 247   _fine_grain_regions(NULL),
 248   _n_fine_entries(0),
 249   _first_all_fine_prts(NULL),
 250   _last_all_fine_prts(NULL),
 251   _fine_eviction_start(0),
 252   _sparse_table()
 253 {
 254   typedef PerRegionTable* PerRegionTablePtr;
 255 
 256   if (_max_fine_entries == 0) {
 257     assert(_mod_max_fine_entries_mask == 0, "Both or none.");
 258     size_t max_entries_log = (size_t)log2_long((jlong)G1RSetRegionEntries);
 259     _max_fine_entries = (size_t)1 << max_entries_log;
 260     _mod_max_fine_entries_mask = _max_fine_entries - 1;
 261 
 262     assert(_fine_eviction_sample_size == 0
 263            && _fine_eviction_stride == 0, "All init at same time.");
 264     _fine_eviction_sample_size = MAX2((size_t)4, max_entries_log);
 265     _fine_eviction_stride = _max_fine_entries / _fine_eviction_sample_size;
 266   }
 267 
 268   _fine_grain_regions = NEW_C_HEAP_ARRAY3(PerRegionTablePtr, _max_fine_entries,
 269                         mtGC, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 270 
 271   if (_fine_grain_regions == NULL) {
 272     vm_exit_out_of_memory(sizeof(void*)*_max_fine_entries, OOM_MALLOC_ERROR,
 273                           "Failed to allocate _fine_grain_entries.");
 274   }
 275 
 276   for (size_t i = 0; i < _max_fine_entries; i++) {
 277     _fine_grain_regions[i] = NULL;
 278   }
 279 }
 280 
 281 void OtherRegionsTable::link_to_all(PerRegionTable* prt) {
 282   // We always append to the beginning of the list for convenience;
 283   // the order of entries in this list does not matter.
 284   if (_first_all_fine_prts != NULL) {
 285     assert(_first_all_fine_prts->prev() == NULL, "invariant");
 286     _first_all_fine_prts->set_prev(prt);
 287     prt->set_next(_first_all_fine_prts);
 288   } else {
 289     // this is the first element we insert. Adjust the "last" pointer
 290     _last_all_fine_prts = prt;
 291     assert(prt->next() == NULL, "just checking");
 292   }
 293   // the new element is always the first element without a predecessor
 294   prt->set_prev(NULL);
 295   _first_all_fine_prts = prt;
 296 
 297   assert(prt->prev() == NULL, "just checking");
 298   assert(_first_all_fine_prts == prt, "just checking");
 299   assert((_first_all_fine_prts == NULL && _last_all_fine_prts == NULL) ||
 300          (_first_all_fine_prts != NULL && _last_all_fine_prts != NULL),
 301          "just checking");
 302   assert(_last_all_fine_prts == NULL || _last_all_fine_prts->next() == NULL,
 303          "just checking");
 304   assert(_first_all_fine_prts == NULL || _first_all_fine_prts->prev() == NULL,
 305          "just checking");
 306 }
 307 
 308 void OtherRegionsTable::unlink_from_all(PerRegionTable* prt) {
 309   if (prt->prev() != NULL) {
 310     assert(_first_all_fine_prts != prt, "just checking");
 311     prt->prev()->set_next(prt->next());
 312     // removing the last element in the list?
 313     if (_last_all_fine_prts == prt) {
 314       _last_all_fine_prts = prt->prev();
 315     }
 316   } else {
 317     assert(_first_all_fine_prts == prt, "just checking");
 318     _first_all_fine_prts = prt->next();
 319     // list is empty now?
 320     if (_first_all_fine_prts == NULL) {
 321       _last_all_fine_prts = NULL;
 322     }
 323   }
 324 
 325   if (prt->next() != NULL) {
 326     prt->next()->set_prev(prt->prev());
 327   }
 328 
 329   prt->set_next(NULL);
 330   prt->set_prev(NULL);
 331 
 332   assert((_first_all_fine_prts == NULL && _last_all_fine_prts == NULL) ||
 333          (_first_all_fine_prts != NULL && _last_all_fine_prts != NULL),
 334          "just checking");
 335   assert(_last_all_fine_prts == NULL || _last_all_fine_prts->next() == NULL,
 336          "just checking");
 337   assert(_first_all_fine_prts == NULL || _first_all_fine_prts->prev() == NULL,
 338          "just checking");
 339 }
 340 
 341 CardIdx_t OtherRegionsTable::card_within_region(OopOrNarrowOopStar within_region, HeapRegion* hr) {
 342   assert(hr->is_in_reserved(within_region),
 343          "HeapWord " PTR_FORMAT " is outside of region %u [" PTR_FORMAT ", " PTR_FORMAT ")",
 344          p2i(within_region), hr->hrm_index(), p2i(hr->bottom()), p2i(hr->end()));
 345   CardIdx_t result = (CardIdx_t)(pointer_delta((HeapWord*)within_region, hr->bottom()) >> (CardTable::card_shift - LogHeapWordSize));
 346   return result;
 347 }
 348 
 349 void OtherRegionsTable::add_reference(OopOrNarrowOopStar from, uint tid) {
 350   // Note that this may be a continued H region.
 351   HeapRegion* from_hr = _g1h->heap_region_containing(from);
 352   RegionIdx_t from_hrm_ind = (RegionIdx_t) from_hr->hrm_index();
 353 
 354   // If the region is already coarsened, return.
 355   if (_coarse_map.at(from_hrm_ind)) {
 356     assert(contains_reference(from), "We just found " PTR_FORMAT " in the Coarse table", p2i(from));
 357     return;
 358   }
 359 
 360   // Otherwise find a per-region table to add it to.
 361   size_t ind = from_hrm_ind & _mod_max_fine_entries_mask;
 362   PerRegionTable* prt = find_region_table(ind, from_hr);
 363   if (prt == NULL) {
 364     MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
 365     // Confirm that it's really not there...
 366     prt = find_region_table(ind, from_hr);
 367     if (prt == NULL) {
 368 
 369       CardIdx_t card_index = card_within_region(from, from_hr);
 370 
 371       if (G1HRRSUseSparseTable &&
 372           _sparse_table.add_card(from_hrm_ind, card_index)) {
 373         assert(contains_reference_locked(from), "We just added " PTR_FORMAT " to the Sparse table", p2i(from));
 374         return;
 375       }
 376 
 377       if (_n_fine_entries == _max_fine_entries) {
 378         prt = delete_region_table();
 379         // There is no need to clear the links to the 'all' list here:
 380         // prt will be reused immediately, i.e. remain in the 'all' list.
 381         prt->init(from_hr, false /* clear_links_to_all_list */);
 382       } else {
 383         prt = PerRegionTable::alloc(from_hr);
 384         link_to_all(prt);
 385       }
 386 
 387       PerRegionTable* first_prt = _fine_grain_regions[ind];
 388       prt->set_collision_list_next(first_prt);
 389       // The assignment into _fine_grain_regions allows the prt to
 390       // start being used concurrently. In addition to
 391       // collision_list_next which must be visible (else concurrent
 392       // parsing of the list, if any, may fail to see other entries),
 393       // the content of the prt must be visible (else for instance
 394       // some mark bits may not yet seem cleared or a 'later' update
 395       // performed by a concurrent thread could be undone when the
 396       // zeroing becomes visible). This requires store ordering.
 397       OrderAccess::release_store(&_fine_grain_regions[ind], prt);
 398       _n_fine_entries++;
 399 
 400       if (G1HRRSUseSparseTable) {
 401         // Transfer from sparse to fine-grain.
 402         SparsePRTEntry *sprt_entry = _sparse_table.get_entry(from_hrm_ind);
 403         assert(sprt_entry != NULL, "There should have been an entry");
 404         for (int i = 0; i < sprt_entry->num_valid_cards(); i++) {
 405           CardIdx_t c = sprt_entry->card(i);
 406           prt->add_card(c);
 407         }
 408         // Now we can delete the sparse entry.
 409         bool res = _sparse_table.delete_entry(from_hrm_ind);
 410         assert(res, "It should have been there.");
 411       }
 412     }
 413     assert(prt != NULL && prt->hr() == from_hr, "consequence");
 414   }
 415   // Note that we can't assert "prt->hr() == from_hr", because of the
 416   // possibility of concurrent reuse.  But see head comment of
 417   // OtherRegionsTable for why this is OK.
 418   assert(prt != NULL, "Inv");
 419 
 420   prt->add_reference(from);
 421   assert(contains_reference(from), "We just added " PTR_FORMAT " to the PRT (%d)", p2i(from), prt->contains_reference(from));
 422 }
 423 
 424 PerRegionTable*
 425 OtherRegionsTable::find_region_table(size_t ind, HeapRegion* hr) const {
 426   assert(ind < _max_fine_entries, "Preconditions.");
 427   PerRegionTable* prt = _fine_grain_regions[ind];
 428   while (prt != NULL && prt->hr() != hr) {
 429     prt = prt->collision_list_next();
 430   }
 431   // Loop postcondition is the method postcondition.
 432   return prt;
 433 }
 434 
 435 jint OtherRegionsTable::_n_coarsenings = 0;
 436 
 437 PerRegionTable* OtherRegionsTable::delete_region_table() {
 438   assert(_m->owned_by_self(), "Precondition");
 439   assert(_n_fine_entries == _max_fine_entries, "Precondition");
 440   PerRegionTable* max = NULL;
 441   jint max_occ = 0;
 442   PerRegionTable** max_prev = NULL;
 443   size_t max_ind;
 444 
 445   size_t i = _fine_eviction_start;
 446   for (size_t k = 0; k < _fine_eviction_sample_size; k++) {
 447     size_t ii = i;
 448     // Make sure we get a non-NULL sample.
 449     while (_fine_grain_regions[ii] == NULL) {
 450       ii++;
 451       if (ii == _max_fine_entries) ii = 0;
 452       guarantee(ii != i, "We must find one.");
 453     }
 454     PerRegionTable** prev = &_fine_grain_regions[ii];
 455     PerRegionTable* cur = *prev;
 456     while (cur != NULL) {
 457       jint cur_occ = cur->occupied();
 458       if (max == NULL || cur_occ > max_occ) {
 459         max = cur;
 460         max_prev = prev;
 461         max_ind = i;
 462         max_occ = cur_occ;
 463       }
 464       prev = cur->collision_list_next_addr();
 465       cur = cur->collision_list_next();
 466     }
 467     i = i + _fine_eviction_stride;
 468     if (i >= _n_fine_entries) i = i - _n_fine_entries;
 469   }
 470 
 471   _fine_eviction_start++;
 472 
 473   if (_fine_eviction_start >= _n_fine_entries) {
 474     _fine_eviction_start -= _n_fine_entries;
 475   }
 476 
 477   guarantee(max != NULL, "Since _n_fine_entries > 0");
 478   guarantee(max_prev != NULL, "Since max != NULL.");
 479 
 480   // Set the corresponding coarse bit.
 481   size_t max_hrm_index = (size_t) max->hr()->hrm_index();
 482   if (!_coarse_map.at(max_hrm_index)) {
 483     _coarse_map.at_put(max_hrm_index, true);
 484     _n_coarse_entries++;
 485   }
 486 
 487   // Unsplice.
 488   *max_prev = max->collision_list_next();
 489   Atomic::inc(&_n_coarsenings);
 490   _n_fine_entries--;
 491   return max;
 492 }
 493 
 494 bool OtherRegionsTable::occupancy_less_or_equal_than(size_t limit) const {
 495   if (limit <= (size_t)G1RSetSparseRegionEntries) {
 496     return occ_coarse() == 0 && _first_all_fine_prts == NULL && occ_sparse() <= limit;
 497   } else {
 498     // Current uses of this method may only use values less than G1RSetSparseRegionEntries
 499     // for the limit. The solution, comparing against occupied() would be too slow
 500     // at this time.
 501     Unimplemented();
 502     return false;
 503   }
 504 }
 505 
 506 bool OtherRegionsTable::is_empty() const {
 507   return occ_sparse() == 0 && occ_coarse() == 0 && _first_all_fine_prts == NULL;
 508 }
 509 
 510 size_t OtherRegionsTable::occupied() const {
 511   size_t sum = occ_fine();
 512   sum += occ_sparse();
 513   sum += occ_coarse();
 514   return sum;
 515 }
 516 
 517 size_t OtherRegionsTable::occ_fine() const {
 518   size_t sum = 0;
 519 
 520   size_t num = 0;
 521   PerRegionTable * cur = _first_all_fine_prts;
 522   while (cur != NULL) {
 523     sum += cur->occupied();
 524     cur = cur->next();
 525     num++;
 526   }
 527   guarantee(num == _n_fine_entries, "just checking");
 528   return sum;
 529 }
 530 
 531 size_t OtherRegionsTable::occ_coarse() const {
 532   return (_n_coarse_entries * HeapRegion::CardsPerRegion);
 533 }
 534 
 535 size_t OtherRegionsTable::occ_sparse() const {
 536   return _sparse_table.occupied();
 537 }
 538 
 539 size_t OtherRegionsTable::mem_size() const {
 540   size_t sum = 0;
 541   // all PRTs are of the same size so it is sufficient to query only one of them.
 542   if (_first_all_fine_prts != NULL) {
 543     assert(_last_all_fine_prts != NULL &&
 544       _first_all_fine_prts->mem_size() == _last_all_fine_prts->mem_size(), "check that mem_size() is constant");
 545     sum += _first_all_fine_prts->mem_size() * _n_fine_entries;
 546   }
 547   sum += (sizeof(PerRegionTable*) * _max_fine_entries);
 548   sum += (_coarse_map.size_in_words() * HeapWordSize);
 549   sum += (_sparse_table.mem_size());
 550   sum += sizeof(OtherRegionsTable) - sizeof(_sparse_table); // Avoid double counting above.
 551   return sum;
 552 }
 553 
 554 size_t OtherRegionsTable::static_mem_size() {
 555   return G1FromCardCache::static_mem_size();
 556 }
 557 
 558 size_t OtherRegionsTable::fl_mem_size() {
 559   return PerRegionTable::fl_mem_size();
 560 }
 561 
 562 void OtherRegionsTable::clear() {
 563   // if there are no entries, skip this step
 564   if (_first_all_fine_prts != NULL) {
 565     guarantee(_first_all_fine_prts != NULL && _last_all_fine_prts != NULL, "just checking");
 566     PerRegionTable::bulk_free(_first_all_fine_prts, _last_all_fine_prts);
 567     memset(_fine_grain_regions, 0, _max_fine_entries * sizeof(_fine_grain_regions[0]));
 568   } else {
 569     guarantee(_first_all_fine_prts == NULL && _last_all_fine_prts == NULL, "just checking");
 570   }
 571 
 572   _first_all_fine_prts = _last_all_fine_prts = NULL;
 573   _sparse_table.clear();
 574   if (_n_coarse_entries > 0) {
 575     _coarse_map.clear();
 576   }
 577   _n_fine_entries = 0;
 578   _n_coarse_entries = 0;
 579 }
 580 
 581 bool OtherRegionsTable::contains_reference(OopOrNarrowOopStar from) const {
 582   // Cast away const in this case.
 583   MutexLockerEx x((Mutex*)_m, Mutex::_no_safepoint_check_flag);
 584   return contains_reference_locked(from);
 585 }
 586 
 587 bool OtherRegionsTable::contains_reference_locked(OopOrNarrowOopStar from) const {
 588   HeapRegion* hr = _g1h->heap_region_containing(from);
 589   RegionIdx_t hr_ind = (RegionIdx_t) hr->hrm_index();
 590   // Is this region in the coarse map?
 591   if (_coarse_map.at(hr_ind)) return true;
 592 
 593   PerRegionTable* prt = find_region_table(hr_ind & _mod_max_fine_entries_mask,
 594                                           hr);
 595   if (prt != NULL) {
 596     return prt->contains_reference(from);
 597 
 598   } else {
 599     CardIdx_t card_index = card_within_region(from, hr);
 600     return _sparse_table.contains_card(hr_ind, card_index);
 601   }
 602 }
 603 
 604 void
 605 OtherRegionsTable::do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task) {
 606   _sparse_table.do_cleanup_work(hrrs_cleanup_task);
 607 }
 608 
 609 HeapRegionRemSet::HeapRegionRemSet(G1BlockOffsetTable* bot,
 610                                    HeapRegion* hr)
 611   : _bot(bot),
 612     _code_roots(),
 613     _m(Mutex::leaf, FormatBuffer<128>("HeapRegionRemSet lock #%u", hr->hrm_index()), true, Monitor::_safepoint_check_never),
 614     _other_regions(&_m),
 615     _hr(hr),
 616     _state(Untracked)
 617 {
 618 }
 619 
 620 void HeapRegionRemSet::clear_fcc() {
 621   G1FromCardCache::clear(_hr->hrm_index());
 622 }
 623 
 624 void HeapRegionRemSet::setup_remset_size() {
 625   // Setup sparse and fine-grain tables sizes.
 626   // table_size = base * (log(region_size / 1M) + 1)
 627   const int LOG_M = 20;
 628   int region_size_log_mb = MAX2(HeapRegion::LogOfHRGrainBytes - LOG_M, 0);
 629   if (FLAG_IS_DEFAULT(G1RSetSparseRegionEntries)) {
 630     G1RSetSparseRegionEntries = G1RSetSparseRegionEntriesBase * (region_size_log_mb + 1);
 631   }
 632   if (FLAG_IS_DEFAULT(G1RSetRegionEntries)) {
 633     G1RSetRegionEntries = G1RSetRegionEntriesBase * (region_size_log_mb + 1);
 634   }
 635   guarantee(G1RSetSparseRegionEntries > 0 && G1RSetRegionEntries > 0 , "Sanity");
 636 }
 637 
 638 void HeapRegionRemSet::cleanup() {
 639   SparsePRT::cleanup_all();
 640 }
 641 
 642 void HeapRegionRemSet::clear(bool only_cardset) {
 643   MutexLockerEx x(&_m, Mutex::_no_safepoint_check_flag);
 644   clear_locked(only_cardset);
 645 }
 646 
 647 void HeapRegionRemSet::clear_locked(bool only_cardset) {
 648   if (!only_cardset) {
 649     _code_roots.clear();
 650   }
 651   clear_fcc();
 652   _other_regions.clear();
 653   set_state_empty();
 654   assert(occupied_locked() == 0, "Should be clear.");
 655 }
 656 
 657 // Code roots support
 658 //
 659 // The code root set is protected by two separate locking schemes
 660 // When at safepoint the per-hrrs lock must be held during modifications
 661 // except when doing a full gc.
 662 // When not at safepoint the CodeCache_lock must be held during modifications.
 663 // When concurrent readers access the contains() function
 664 // (during the evacuation phase) no removals are allowed.
 665 
 666 void HeapRegionRemSet::add_strong_code_root(nmethod* nm) {
 667   assert(nm != NULL, "sanity");
 668   assert((!CodeCache_lock->owned_by_self() || SafepointSynchronize::is_at_safepoint()),
 669           "should call add_strong_code_root_locked instead. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s",
 670           BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()));
 671   // Optimistic unlocked contains-check
 672   if (!_code_roots.contains(nm)) {
 673     MutexLockerEx ml(&_m, Mutex::_no_safepoint_check_flag);
 674     add_strong_code_root_locked(nm);
 675   }
 676 }
 677 
 678 void HeapRegionRemSet::add_strong_code_root_locked(nmethod* nm) {
 679   assert(nm != NULL, "sanity");
 680   assert((CodeCache_lock->owned_by_self() ||
 681          (SafepointSynchronize::is_at_safepoint() &&
 682           (_m.owned_by_self() || Thread::current()->is_VM_thread()))),
 683           "not safely locked. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s, _m.owned_by_self(): %s, Thread::current()->is_VM_thread(): %s",
 684           BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()),
 685           BOOL_TO_STR(_m.owned_by_self()), BOOL_TO_STR(Thread::current()->is_VM_thread()));
 686   _code_roots.add(nm);
 687 }
 688 
 689 void HeapRegionRemSet::remove_strong_code_root(nmethod* nm) {
 690   assert(nm != NULL, "sanity");
 691   assert_locked_or_safepoint(CodeCache_lock);
 692 
 693   MutexLockerEx ml(CodeCache_lock->owned_by_self() ? NULL : &_m, Mutex::_no_safepoint_check_flag);
 694   _code_roots.remove(nm);
 695 
 696   // Check that there were no duplicates
 697   guarantee(!_code_roots.contains(nm), "duplicate entry found");
 698 }
 699 
 700 void HeapRegionRemSet::strong_code_roots_do(CodeBlobClosure* blk) const {
 701   _code_roots.nmethods_do(blk);
 702 }
 703 
 704 void HeapRegionRemSet::clean_strong_code_roots(HeapRegion* hr) {
 705   _code_roots.clean(hr);
 706 }
 707 
 708 size_t HeapRegionRemSet::strong_code_roots_mem_size() {
 709   return _code_roots.mem_size();
 710 }
 711 
 712 HeapRegionRemSetIterator:: HeapRegionRemSetIterator(HeapRegionRemSet* hrrs) :
 713   _hrrs(hrrs),
 714   _coarse_map(&hrrs->_other_regions._coarse_map),
 715   _bot(hrrs->_bot),
 716   _g1h(G1CollectedHeap::heap()),
 717   _n_yielded_fine(0),
 718   _n_yielded_coarse(0),
 719   _n_yielded_sparse(0),
 720   _is(Sparse),
 721   _cur_region_card_offset(0),
 722   // Set these values so that we increment to the first region.
 723   _coarse_cur_region_index(-1),
 724   _coarse_cur_region_cur_card(HeapRegion::CardsPerRegion-1),
 725   _fine_cur_prt(NULL),
 726   _cur_card_in_prt(HeapRegion::CardsPerRegion),
 727   _sparse_iter(&hrrs->_other_regions._sparse_table) {}
 728 
 729 bool HeapRegionRemSetIterator::coarse_has_next(size_t& card_index) {
 730   if (_hrrs->_other_regions._n_coarse_entries == 0) return false;
 731   // Go to the next card.
 732   _coarse_cur_region_cur_card++;
 733   // Was the last the last card in the current region?
 734   if (_coarse_cur_region_cur_card == HeapRegion::CardsPerRegion) {
 735     // Yes: find the next region.  This may leave _coarse_cur_region_index
 736     // Set to the last index, in which case there are no more coarse
 737     // regions.
 738     _coarse_cur_region_index =
 739       (int) _coarse_map->get_next_one_offset(_coarse_cur_region_index + 1);
 740     if ((size_t)_coarse_cur_region_index < _coarse_map->size()) {
 741       _coarse_cur_region_cur_card = 0;
 742       HeapWord* r_bot =
 743         _g1h->region_at((uint) _coarse_cur_region_index)->bottom();
 744       _cur_region_card_offset = _bot->index_for_raw(r_bot);
 745     } else {
 746       return false;
 747     }
 748   }
 749   // If we didn't return false above, then we can yield a card.
 750   card_index = _cur_region_card_offset + _coarse_cur_region_cur_card;
 751   return true;
 752 }
 753 
 754 bool HeapRegionRemSetIterator::fine_has_next(size_t& card_index) {
 755   if (fine_has_next()) {
 756     _cur_card_in_prt =
 757       _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
 758   }
 759   if (_cur_card_in_prt == HeapRegion::CardsPerRegion) {
 760     // _fine_cur_prt may still be NULL in case if there are not PRTs at all for
 761     // the remembered set.
 762     if (_fine_cur_prt == NULL || _fine_cur_prt->next() == NULL) {
 763       return false;
 764     }
 765     PerRegionTable* next_prt = _fine_cur_prt->next();
 766     switch_to_prt(next_prt);
 767     _cur_card_in_prt = _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
 768   }
 769 
 770   card_index = _cur_region_card_offset + _cur_card_in_prt;
 771   guarantee(_cur_card_in_prt < HeapRegion::CardsPerRegion,
 772             "Card index " SIZE_FORMAT " must be within the region", _cur_card_in_prt);
 773   return true;
 774 }
 775 
 776 bool HeapRegionRemSetIterator::fine_has_next() {
 777   return _cur_card_in_prt != HeapRegion::CardsPerRegion;
 778 }
 779 
 780 void HeapRegionRemSetIterator::switch_to_prt(PerRegionTable* prt) {
 781   assert(prt != NULL, "Cannot switch to NULL prt");
 782   _fine_cur_prt = prt;
 783 
 784   HeapWord* r_bot = _fine_cur_prt->hr()->bottom();
 785   _cur_region_card_offset = _bot->index_for_raw(r_bot);
 786 
 787   // The bitmap scan for the PRT always scans from _cur_region_cur_card + 1.
 788   // To avoid special-casing this start case, and not miss the first bitmap
 789   // entry, initialize _cur_region_cur_card with -1 instead of 0.
 790   _cur_card_in_prt = (size_t)-1;
 791 }
 792 
 793 bool HeapRegionRemSetIterator::has_next(size_t& card_index) {
 794   switch (_is) {
 795   case Sparse: {
 796     if (_sparse_iter.has_next(card_index)) {
 797       _n_yielded_sparse++;
 798       return true;
 799     }
 800     // Otherwise, deliberate fall-through
 801     _is = Fine;
 802     PerRegionTable* initial_fine_prt = _hrrs->_other_regions._first_all_fine_prts;
 803     if (initial_fine_prt != NULL) {
 804       switch_to_prt(_hrrs->_other_regions._first_all_fine_prts);
 805     }
 806   }
 807   case Fine:
 808     if (fine_has_next(card_index)) {
 809       _n_yielded_fine++;
 810       return true;
 811     }
 812     // Otherwise, deliberate fall-through
 813     _is = Coarse;
 814   case Coarse:
 815     if (coarse_has_next(card_index)) {
 816       _n_yielded_coarse++;
 817       return true;
 818     }
 819     // Otherwise...
 820     break;
 821   }
 822   return false;
 823 }
 824 
 825 void HeapRegionRemSet::reset_for_cleanup_tasks() {
 826   SparsePRT::reset_for_cleanup_tasks();
 827 }
 828 
 829 void HeapRegionRemSet::do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task) {
 830   _other_regions.do_cleanup_work(hrrs_cleanup_task);
 831 }
 832 
 833 void HeapRegionRemSet::finish_cleanup_task(HRRSCleanupTask* hrrs_cleanup_task) {
 834   SparsePRT::finish_cleanup_task(hrrs_cleanup_task);
 835 }
 836 
 837 #ifndef PRODUCT
 838 void HeapRegionRemSet::test() {
 839   os::sleep(Thread::current(), (jlong)5000, false);
 840   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 841 
 842   // Run with "-XX:G1LogRSetRegionEntries=2", so that 1 and 5 end up in same
 843   // hash bucket.
 844   HeapRegion* hr0 = g1h->region_at(0);
 845   HeapRegion* hr1 = g1h->region_at(1);
 846   HeapRegion* hr2 = g1h->region_at(5);
 847   HeapRegion* hr3 = g1h->region_at(6);
 848   HeapRegion* hr4 = g1h->region_at(7);
 849   HeapRegion* hr5 = g1h->region_at(8);
 850 
 851   HeapWord* hr1_start = hr1->bottom();
 852   HeapWord* hr1_mid = hr1_start + HeapRegion::GrainWords/2;
 853   HeapWord* hr1_last = hr1->end() - 1;
 854 
 855   HeapWord* hr2_start = hr2->bottom();
 856   HeapWord* hr2_mid = hr2_start + HeapRegion::GrainWords/2;
 857   HeapWord* hr2_last = hr2->end() - 1;
 858 
 859   HeapWord* hr3_start = hr3->bottom();
 860   HeapWord* hr3_mid = hr3_start + HeapRegion::GrainWords/2;
 861   HeapWord* hr3_last = hr3->end() - 1;
 862 
 863   HeapRegionRemSet* hrrs = hr0->rem_set();
 864 
 865   // Make three references from region 0x101...
 866   hrrs->add_reference((OopOrNarrowOopStar)hr1_start);
 867   hrrs->add_reference((OopOrNarrowOopStar)hr1_mid);
 868   hrrs->add_reference((OopOrNarrowOopStar)hr1_last);
 869 
 870   hrrs->add_reference((OopOrNarrowOopStar)hr2_start);
 871   hrrs->add_reference((OopOrNarrowOopStar)hr2_mid);
 872   hrrs->add_reference((OopOrNarrowOopStar)hr2_last);
 873 
 874   hrrs->add_reference((OopOrNarrowOopStar)hr3_start);
 875   hrrs->add_reference((OopOrNarrowOopStar)hr3_mid);
 876   hrrs->add_reference((OopOrNarrowOopStar)hr3_last);
 877 
 878   // Now cause a coarsening.
 879   hrrs->add_reference((OopOrNarrowOopStar)hr4->bottom());
 880   hrrs->add_reference((OopOrNarrowOopStar)hr5->bottom());
 881 
 882   // Now, does iteration yield these three?
 883   HeapRegionRemSetIterator iter(hrrs);
 884   size_t sum = 0;
 885   size_t card_index;
 886   while (iter.has_next(card_index)) {
 887     HeapWord* card_start = g1h->bot()->address_for_index(card_index);
 888     tty->print_cr("  Card " PTR_FORMAT ".", p2i(card_start));
 889     sum++;
 890   }
 891   guarantee(sum == 11 - 3 + 2048, "Failure");
 892   guarantee(sum == hrrs->occupied(), "Failure");
 893 }
 894 #endif