rev 11045 : 8155233: Lazy coarse map clear
Summary: Only clear the coarse bitmaps of the remembered sets if they were dirtied.
Reviewed-by:

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