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