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   log_develop(gc, remset, scrub)("Scrubbing region %u:", _hr->hrm_index());
 564 
 565   assert(_coarse_map.size() == region_bm->size(), "Precondition");
 566   log_develop(gc, remset, scrub)("   Coarse map: before = " SIZE_FORMAT "...", _n_coarse_entries);
 567   _coarse_map.set_intersection(*region_bm);
 568   _n_coarse_entries = _coarse_map.count_one_bits();
 569   log_develop(gc, remset, scrub)("   after = " SIZE_FORMAT ".", _n_coarse_entries);
 570 
 571   // Now do the fine-grained maps.
 572   for (size_t i = 0; i < _max_fine_entries; i++) {
 573     PerRegionTable* cur = _fine_grain_regions[i];
 574     PerRegionTable** prev = &_fine_grain_regions[i];
 575     while (cur != NULL) {
 576       PerRegionTable* nxt = cur->collision_list_next();
 577       // If the entire region is dead, eliminate.
 578       log_develop(gc, remset, scrub)("     For other region %u:", cur->hr()->hrm_index());
 579       if (!region_bm->at((size_t) cur->hr()->hrm_index())) {
 580         *prev = nxt;
 581         cur->set_collision_list_next(NULL);
 582         _n_fine_entries--;
 583         log_develop(gc, remset, scrub)("          deleted via region map.");
 584         unlink_from_all(cur);
 585         PerRegionTable::free(cur);
 586       } else {
 587         // Do fine-grain elimination.
 588         log_develop(gc, remset, scrub)("          occ: before = %4d.", cur->occupied());
 589         cur->scrub(ctbs, card_bm);
 590         log_develop(gc, remset, scrub)("          after = %4d.", cur->occupied());
 591         // Did that empty the table completely?
 592         if (cur->occupied() == 0) {
 593           *prev = nxt;
 594           cur->set_collision_list_next(NULL);
 595           _n_fine_entries--;
 596           unlink_from_all(cur);
 597           PerRegionTable::free(cur);
 598         } else {
 599           prev = cur->collision_list_next_addr();
 600         }
 601       }
 602       cur = nxt;
 603     }
 604   }
 605   // Since we may have deleted a from_card_cache entry from the RS, clear
 606   // the FCC.
 607   clear_fcc();
 608 }
 609 
 610 bool OtherRegionsTable::occupancy_less_or_equal_than(size_t limit) const {
 611   if (limit <= (size_t)G1RSetSparseRegionEntries) {
 612     return occ_coarse() == 0 && _first_all_fine_prts == NULL && occ_sparse() <= limit;
 613   } else {
 614     // Current uses of this method may only use values less than G1RSetSparseRegionEntries
 615     // for the limit. The solution, comparing against occupied() would be too slow
 616     // at this time.
 617     Unimplemented();
 618     return false;
 619   }
 620 }
 621 
 622 bool OtherRegionsTable::is_empty() const {
 623   return occ_sparse() == 0 && occ_coarse() == 0 && _first_all_fine_prts == NULL;
 624 }
 625 
 626 size_t OtherRegionsTable::occupied() const {
 627   size_t sum = occ_fine();
 628   sum += occ_sparse();
 629   sum += occ_coarse();
 630   return sum;
 631 }
 632 
 633 size_t OtherRegionsTable::occ_fine() const {
 634   size_t sum = 0;
 635 
 636   size_t num = 0;
 637   PerRegionTable * cur = _first_all_fine_prts;
 638   while (cur != NULL) {
 639     sum += cur->occupied();
 640     cur = cur->next();
 641     num++;
 642   }
 643   guarantee(num == _n_fine_entries, "just checking");
 644   return sum;
 645 }
 646 
 647 size_t OtherRegionsTable::occ_coarse() const {
 648   return (_n_coarse_entries * HeapRegion::CardsPerRegion);
 649 }
 650 
 651 size_t OtherRegionsTable::occ_sparse() const {
 652   return _sparse_table.occupied();
 653 }
 654 
 655 size_t OtherRegionsTable::mem_size() const {
 656   size_t sum = 0;
 657   // all PRTs are of the same size so it is sufficient to query only one of them.
 658   if (_first_all_fine_prts != NULL) {
 659     assert(_last_all_fine_prts != NULL &&
 660       _first_all_fine_prts->mem_size() == _last_all_fine_prts->mem_size(), "check that mem_size() is constant");
 661     sum += _first_all_fine_prts->mem_size() * _n_fine_entries;
 662   }
 663   sum += (sizeof(PerRegionTable*) * _max_fine_entries);
 664   sum += (_coarse_map.size_in_words() * HeapWordSize);
 665   sum += (_sparse_table.mem_size());
 666   sum += sizeof(OtherRegionsTable) - sizeof(_sparse_table); // Avoid double counting above.
 667   return sum;
 668 }
 669 
 670 size_t OtherRegionsTable::static_mem_size() {
 671   return FromCardCache::static_mem_size();
 672 }
 673 
 674 size_t OtherRegionsTable::fl_mem_size() {
 675   return PerRegionTable::fl_mem_size();
 676 }
 677 
 678 void OtherRegionsTable::clear_fcc() {
 679   FromCardCache::clear(_hr->hrm_index());
 680 }
 681 
 682 void OtherRegionsTable::clear() {
 683   // if there are no entries, skip this step
 684   if (_first_all_fine_prts != NULL) {
 685     guarantee(_first_all_fine_prts != NULL && _last_all_fine_prts != NULL, "just checking");
 686     PerRegionTable::bulk_free(_first_all_fine_prts, _last_all_fine_prts);
 687     memset(_fine_grain_regions, 0, _max_fine_entries * sizeof(_fine_grain_regions[0]));
 688   } else {
 689     guarantee(_first_all_fine_prts == NULL && _last_all_fine_prts == NULL, "just checking");
 690   }
 691 
 692   _first_all_fine_prts = _last_all_fine_prts = NULL;
 693   _sparse_table.clear();
 694   _coarse_map.clear();
 695   _n_fine_entries = 0;
 696   _n_coarse_entries = 0;
 697 
 698   clear_fcc();
 699 }
 700 
 701 bool OtherRegionsTable::contains_reference(OopOrNarrowOopStar from) const {
 702   // Cast away const in this case.
 703   MutexLockerEx x((Mutex*)_m, Mutex::_no_safepoint_check_flag);
 704   return contains_reference_locked(from);
 705 }
 706 
 707 bool OtherRegionsTable::contains_reference_locked(OopOrNarrowOopStar from) const {
 708   HeapRegion* hr = _g1h->heap_region_containing(from);
 709   RegionIdx_t hr_ind = (RegionIdx_t) hr->hrm_index();
 710   // Is this region in the coarse map?
 711   if (_coarse_map.at(hr_ind)) return true;
 712 
 713   PerRegionTable* prt = find_region_table(hr_ind & _mod_max_fine_entries_mask,
 714                                      hr);
 715   if (prt != NULL) {
 716     return prt->contains_reference(from);
 717 
 718   } else {
 719     uintptr_t from_card =
 720       (uintptr_t(from) >> CardTableModRefBS::card_shift);
 721     uintptr_t hr_bot_card_index =
 722       uintptr_t(hr->bottom()) >> CardTableModRefBS::card_shift;
 723     assert(from_card >= hr_bot_card_index, "Inv");
 724     CardIdx_t card_index = from_card - hr_bot_card_index;
 725     assert(0 <= card_index && (size_t)card_index < HeapRegion::CardsPerRegion,
 726            "Must be in range.");
 727     return _sparse_table.contains_card(hr_ind, card_index);
 728   }
 729 }
 730 
 731 void
 732 OtherRegionsTable::do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task) {
 733   _sparse_table.do_cleanup_work(hrrs_cleanup_task);
 734 }
 735 
 736 // Determines how many threads can add records to an rset in parallel.
 737 // This can be done by either mutator threads together with the
 738 // concurrent refinement threads or GC threads.
 739 uint HeapRegionRemSet::num_par_rem_sets() {
 740   return MAX2(DirtyCardQueueSet::num_par_ids() + ConcurrentG1Refine::thread_num(), ParallelGCThreads);
 741 }
 742 
 743 HeapRegionRemSet::HeapRegionRemSet(G1BlockOffsetSharedArray* bosa,
 744                                    HeapRegion* hr)
 745   : _bosa(bosa),
 746     _m(Mutex::leaf, FormatBuffer<128>("HeapRegionRemSet lock #%u", hr->hrm_index()), true, Monitor::_safepoint_check_never),
 747     _code_roots(), _other_regions(hr, &_m), _iter_state(Unclaimed), _iter_claimed(0) {
 748   reset_for_par_iteration();
 749 }
 750 
 751 void HeapRegionRemSet::setup_remset_size() {
 752   // Setup sparse and fine-grain tables sizes.
 753   // table_size = base * (log(region_size / 1M) + 1)
 754   const int LOG_M = 20;
 755   int region_size_log_mb = MAX2(HeapRegion::LogOfHRGrainBytes - LOG_M, 0);
 756   if (FLAG_IS_DEFAULT(G1RSetSparseRegionEntries)) {
 757     G1RSetSparseRegionEntries = G1RSetSparseRegionEntriesBase * (region_size_log_mb + 1);
 758   }
 759   if (FLAG_IS_DEFAULT(G1RSetRegionEntries)) {
 760     G1RSetRegionEntries = G1RSetRegionEntriesBase * (region_size_log_mb + 1);
 761   }
 762   guarantee(G1RSetSparseRegionEntries > 0 && G1RSetRegionEntries > 0 , "Sanity");
 763 }
 764 
 765 bool HeapRegionRemSet::claim_iter() {
 766   if (_iter_state != Unclaimed) return false;
 767   jint res = Atomic::cmpxchg(Claimed, (jint*)(&_iter_state), Unclaimed);
 768   return (res == Unclaimed);
 769 }
 770 
 771 void HeapRegionRemSet::set_iter_complete() {
 772   _iter_state = Complete;
 773 }
 774 
 775 bool HeapRegionRemSet::iter_is_complete() {
 776   return _iter_state == Complete;
 777 }
 778 
 779 #ifndef PRODUCT
 780 void HeapRegionRemSet::print() {
 781   HeapRegionRemSetIterator iter(this);
 782   size_t card_index;
 783   while (iter.has_next(card_index)) {
 784     HeapWord* card_start =
 785       G1CollectedHeap::heap()->bot_shared()->address_for_index(card_index);
 786     tty->print_cr("  Card " PTR_FORMAT, p2i(card_start));
 787   }
 788   if (iter.n_yielded() != occupied()) {
 789     tty->print_cr("Yielded disagrees with occupied:");
 790     tty->print_cr("  " SIZE_FORMAT_W(6) " yielded (" SIZE_FORMAT_W(6)
 791                   " coarse, " SIZE_FORMAT_W(6) " fine).",
 792                   iter.n_yielded(),
 793                   iter.n_yielded_coarse(), iter.n_yielded_fine());
 794     tty->print_cr("  " SIZE_FORMAT_W(6) " occ     (" SIZE_FORMAT_W(6)
 795                            " coarse, " SIZE_FORMAT_W(6) " fine).",
 796                   occupied(), occ_coarse(), occ_fine());
 797   }
 798   guarantee(iter.n_yielded() == occupied(),
 799             "We should have yielded all the represented cards.");
 800 }
 801 #endif
 802 
 803 void HeapRegionRemSet::cleanup() {
 804   SparsePRT::cleanup_all();
 805 }
 806 
 807 void HeapRegionRemSet::clear() {
 808   MutexLockerEx x(&_m, Mutex::_no_safepoint_check_flag);
 809   clear_locked();
 810 }
 811 
 812 void HeapRegionRemSet::clear_locked() {
 813   _code_roots.clear();
 814   _other_regions.clear();
 815   assert(occupied_locked() == 0, "Should be clear.");
 816   reset_for_par_iteration();
 817 }
 818 
 819 void HeapRegionRemSet::reset_for_par_iteration() {
 820   _iter_state = Unclaimed;
 821   _iter_claimed = 0;
 822   // It's good to check this to make sure that the two methods are in sync.
 823   assert(verify_ready_for_par_iteration(), "post-condition");
 824 }
 825 
 826 void HeapRegionRemSet::scrub(CardTableModRefBS* ctbs,
 827                              BitMap* region_bm, BitMap* card_bm) {
 828   _other_regions.scrub(ctbs, region_bm, card_bm);
 829 }
 830 
 831 // Code roots support
 832 //
 833 // The code root set is protected by two separate locking schemes
 834 // When at safepoint the per-hrrs lock must be held during modifications
 835 // except when doing a full gc.
 836 // When not at safepoint the CodeCache_lock must be held during modifications.
 837 // When concurrent readers access the contains() function
 838 // (during the evacuation phase) no removals are allowed.
 839 
 840 void HeapRegionRemSet::add_strong_code_root(nmethod* nm) {
 841   assert(nm != NULL, "sanity");
 842   // Optimistic unlocked contains-check
 843   if (!_code_roots.contains(nm)) {
 844     MutexLockerEx ml(&_m, Mutex::_no_safepoint_check_flag);
 845     add_strong_code_root_locked(nm);
 846   }
 847 }
 848 
 849 void HeapRegionRemSet::add_strong_code_root_locked(nmethod* nm) {
 850   assert(nm != NULL, "sanity");
 851   _code_roots.add(nm);
 852 }
 853 
 854 void HeapRegionRemSet::remove_strong_code_root(nmethod* nm) {
 855   assert(nm != NULL, "sanity");
 856   assert_locked_or_safepoint(CodeCache_lock);
 857 
 858   MutexLockerEx ml(CodeCache_lock->owned_by_self() ? NULL : &_m, Mutex::_no_safepoint_check_flag);
 859   _code_roots.remove(nm);
 860 
 861   // Check that there were no duplicates
 862   guarantee(!_code_roots.contains(nm), "duplicate entry found");
 863 }
 864 
 865 void HeapRegionRemSet::strong_code_roots_do(CodeBlobClosure* blk) const {
 866   _code_roots.nmethods_do(blk);
 867 }
 868 
 869 void HeapRegionRemSet::clean_strong_code_roots(HeapRegion* hr) {
 870   _code_roots.clean(hr);
 871 }
 872 
 873 size_t HeapRegionRemSet::strong_code_roots_mem_size() {
 874   return _code_roots.mem_size();
 875 }
 876 
 877 HeapRegionRemSetIterator:: HeapRegionRemSetIterator(HeapRegionRemSet* hrrs) :
 878   _hrrs(hrrs),
 879   _g1h(G1CollectedHeap::heap()),
 880   _coarse_map(&hrrs->_other_regions._coarse_map),
 881   _bosa(hrrs->_bosa),
 882   _is(Sparse),
 883   // Set these values so that we increment to the first region.
 884   _coarse_cur_region_index(-1),
 885   _coarse_cur_region_cur_card(HeapRegion::CardsPerRegion-1),
 886   _cur_card_in_prt(HeapRegion::CardsPerRegion),
 887   _fine_cur_prt(NULL),
 888   _n_yielded_coarse(0),
 889   _n_yielded_fine(0),
 890   _n_yielded_sparse(0),
 891   _sparse_iter(&hrrs->_other_regions._sparse_table) {}
 892 
 893 bool HeapRegionRemSetIterator::coarse_has_next(size_t& card_index) {
 894   if (_hrrs->_other_regions._n_coarse_entries == 0) return false;
 895   // Go to the next card.
 896   _coarse_cur_region_cur_card++;
 897   // Was the last the last card in the current region?
 898   if (_coarse_cur_region_cur_card == HeapRegion::CardsPerRegion) {
 899     // Yes: find the next region.  This may leave _coarse_cur_region_index
 900     // Set to the last index, in which case there are no more coarse
 901     // regions.
 902     _coarse_cur_region_index =
 903       (int) _coarse_map->get_next_one_offset(_coarse_cur_region_index + 1);
 904     if ((size_t)_coarse_cur_region_index < _coarse_map->size()) {
 905       _coarse_cur_region_cur_card = 0;
 906       HeapWord* r_bot =
 907         _g1h->region_at((uint) _coarse_cur_region_index)->bottom();
 908       _cur_region_card_offset = _bosa->index_for(r_bot);
 909     } else {
 910       return false;
 911     }
 912   }
 913   // If we didn't return false above, then we can yield a card.
 914   card_index = _cur_region_card_offset + _coarse_cur_region_cur_card;
 915   return true;
 916 }
 917 
 918 bool HeapRegionRemSetIterator::fine_has_next(size_t& card_index) {
 919   if (fine_has_next()) {
 920     _cur_card_in_prt =
 921       _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
 922   }
 923   if (_cur_card_in_prt == HeapRegion::CardsPerRegion) {
 924     // _fine_cur_prt may still be NULL in case if there are not PRTs at all for
 925     // the remembered set.
 926     if (_fine_cur_prt == NULL || _fine_cur_prt->next() == NULL) {
 927       return false;
 928     }
 929     PerRegionTable* next_prt = _fine_cur_prt->next();
 930     switch_to_prt(next_prt);
 931     _cur_card_in_prt = _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
 932   }
 933 
 934   card_index = _cur_region_card_offset + _cur_card_in_prt;
 935   guarantee(_cur_card_in_prt < HeapRegion::CardsPerRegion,
 936             "Card index " SIZE_FORMAT " must be within the region", _cur_card_in_prt);
 937   return true;
 938 }
 939 
 940 bool HeapRegionRemSetIterator::fine_has_next() {
 941   return _cur_card_in_prt != HeapRegion::CardsPerRegion;
 942 }
 943 
 944 void HeapRegionRemSetIterator::switch_to_prt(PerRegionTable* prt) {
 945   assert(prt != NULL, "Cannot switch to NULL prt");
 946   _fine_cur_prt = prt;
 947 
 948   HeapWord* r_bot = _fine_cur_prt->hr()->bottom();
 949   _cur_region_card_offset = _bosa->index_for(r_bot);
 950 
 951   // The bitmap scan for the PRT always scans from _cur_region_cur_card + 1.
 952   // To avoid special-casing this start case, and not miss the first bitmap
 953   // entry, initialize _cur_region_cur_card with -1 instead of 0.
 954   _cur_card_in_prt = (size_t)-1;
 955 }
 956 
 957 bool HeapRegionRemSetIterator::has_next(size_t& card_index) {
 958   switch (_is) {
 959   case Sparse: {
 960     if (_sparse_iter.has_next(card_index)) {
 961       _n_yielded_sparse++;
 962       return true;
 963     }
 964     // Otherwise, deliberate fall-through
 965     _is = Fine;
 966     PerRegionTable* initial_fine_prt = _hrrs->_other_regions._first_all_fine_prts;
 967     if (initial_fine_prt != NULL) {
 968       switch_to_prt(_hrrs->_other_regions._first_all_fine_prts);
 969     }
 970   }
 971   case Fine:
 972     if (fine_has_next(card_index)) {
 973       _n_yielded_fine++;
 974       return true;
 975     }
 976     // Otherwise, deliberate fall-through
 977     _is = Coarse;
 978   case Coarse:
 979     if (coarse_has_next(card_index)) {
 980       _n_yielded_coarse++;
 981       return true;
 982     }
 983     // Otherwise...
 984     break;
 985   }
 986   assert(ParallelGCThreads > 1 ||
 987          n_yielded() == _hrrs->occupied(),
 988          "Should have yielded all the cards in the rem set "
 989          "(in the non-par case).");
 990   return false;
 991 }
 992 
 993 void HeapRegionRemSet::reset_for_cleanup_tasks() {
 994   SparsePRT::reset_for_cleanup_tasks();
 995 }
 996 
 997 void HeapRegionRemSet::do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task) {
 998   _other_regions.do_cleanup_work(hrrs_cleanup_task);
 999 }
1000 
1001 void
1002 HeapRegionRemSet::finish_cleanup_task(HRRSCleanupTask* hrrs_cleanup_task) {
1003   SparsePRT::finish_cleanup_task(hrrs_cleanup_task);
1004 }
1005 
1006 #ifndef PRODUCT
1007 void PerRegionTable::test_fl_mem_size() {
1008   PerRegionTable* dummy = alloc(NULL);
1009 
1010   size_t min_prt_size = sizeof(void*) + dummy->bm()->size_in_words() * HeapWordSize;
1011   assert(dummy->mem_size() > min_prt_size,
1012          "PerRegionTable memory usage is suspiciously small, only has " SIZE_FORMAT " bytes. "
1013          "Should be at least " SIZE_FORMAT " bytes.", dummy->mem_size(), min_prt_size);
1014   free(dummy);
1015   guarantee(dummy->mem_size() == fl_mem_size(), "fl_mem_size() does not return the correct element size");
1016   // try to reset the state
1017   _free_list = NULL;
1018   delete dummy;
1019 }
1020 
1021 void HeapRegionRemSet::test_prt() {
1022   PerRegionTable::test_fl_mem_size();
1023 }
1024 
1025 void HeapRegionRemSet::test() {
1026   os::sleep(Thread::current(), (jlong)5000, false);
1027   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1028 
1029   // Run with "-XX:G1LogRSetRegionEntries=2", so that 1 and 5 end up in same
1030   // hash bucket.
1031   HeapRegion* hr0 = g1h->region_at(0);
1032   HeapRegion* hr1 = g1h->region_at(1);
1033   HeapRegion* hr2 = g1h->region_at(5);
1034   HeapRegion* hr3 = g1h->region_at(6);
1035   HeapRegion* hr4 = g1h->region_at(7);
1036   HeapRegion* hr5 = g1h->region_at(8);
1037 
1038   HeapWord* hr1_start = hr1->bottom();
1039   HeapWord* hr1_mid = hr1_start + HeapRegion::GrainWords/2;
1040   HeapWord* hr1_last = hr1->end() - 1;
1041 
1042   HeapWord* hr2_start = hr2->bottom();
1043   HeapWord* hr2_mid = hr2_start + HeapRegion::GrainWords/2;
1044   HeapWord* hr2_last = hr2->end() - 1;
1045 
1046   HeapWord* hr3_start = hr3->bottom();
1047   HeapWord* hr3_mid = hr3_start + HeapRegion::GrainWords/2;
1048   HeapWord* hr3_last = hr3->end() - 1;
1049 
1050   HeapRegionRemSet* hrrs = hr0->rem_set();
1051 
1052   // Make three references from region 0x101...
1053   hrrs->add_reference((OopOrNarrowOopStar)hr1_start);
1054   hrrs->add_reference((OopOrNarrowOopStar)hr1_mid);
1055   hrrs->add_reference((OopOrNarrowOopStar)hr1_last);
1056 
1057   hrrs->add_reference((OopOrNarrowOopStar)hr2_start);
1058   hrrs->add_reference((OopOrNarrowOopStar)hr2_mid);
1059   hrrs->add_reference((OopOrNarrowOopStar)hr2_last);
1060 
1061   hrrs->add_reference((OopOrNarrowOopStar)hr3_start);
1062   hrrs->add_reference((OopOrNarrowOopStar)hr3_mid);
1063   hrrs->add_reference((OopOrNarrowOopStar)hr3_last);
1064 
1065   // Now cause a coarsening.
1066   hrrs->add_reference((OopOrNarrowOopStar)hr4->bottom());
1067   hrrs->add_reference((OopOrNarrowOopStar)hr5->bottom());
1068 
1069   // Now, does iteration yield these three?
1070   HeapRegionRemSetIterator iter(hrrs);
1071   size_t sum = 0;
1072   size_t card_index;
1073   while (iter.has_next(card_index)) {
1074     HeapWord* card_start =
1075       G1CollectedHeap::heap()->bot_shared()->address_for_index(card_index);
1076     tty->print_cr("  Card " PTR_FORMAT ".", p2i(card_start));
1077     sum++;
1078   }
1079   guarantee(sum == 11 - 3 + 2048, "Failure");
1080   guarantee(sum == hrrs->occupied(), "Failure");
1081 }
1082 #endif