1 /*
   2  * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "gc/g1/g1BlockOffsetTable.inline.hpp"
  27 #include "gc/g1/g1CollectedHeap.inline.hpp"
  28 #include "gc/g1/g1ConcurrentRefine.hpp"
  29 #include "gc/g1/heapRegionManager.inline.hpp"
  30 #include "gc/g1/heapRegionRemSet.inline.hpp"
  31 #include "gc/g1/sparsePRT.inline.hpp"
  32 #include "memory/allocation.hpp"
  33 #include "memory/padded.inline.hpp"
  34 #include "oops/oop.inline.hpp"
  35 #include "runtime/atomic.hpp"
  36 #include "utilities/bitMap.inline.hpp"
  37 #include "utilities/debug.hpp"
  38 #include "utilities/formatBuffer.hpp"
  39 #include "utilities/globalDefinitions.hpp"
  40 #include "utilities/growableArray.hpp"
  41 
  42 const char* HeapRegionRemSet::_state_strings[] =  {"Untracked", "Updating", "Complete"};
  43 const char* HeapRegionRemSet::_short_state_strings[] =  {"UNTRA", "UPDAT", "CMPLT"};
  44 
  45 PerRegionTable* PerRegionTable::alloc(HeapRegion* hr) {
  46   PerRegionTable* fl = _free_list;
  47   while (fl != NULL) {
  48     PerRegionTable* nxt = fl->next();
  49     PerRegionTable* res = Atomic::cmpxchg(&_free_list, fl, nxt);
  50     if (res == fl) {
  51       fl->init(hr, true);
  52       return fl;
  53     } else {
  54       fl = _free_list;
  55     }
  56   }
  57   assert(fl == NULL, "Loop condition.");
  58   return new PerRegionTable(hr);
  59 }
  60 
  61 PerRegionTable* volatile PerRegionTable::_free_list = NULL;
  62 
  63 size_t OtherRegionsTable::_max_fine_entries = 0;
  64 size_t OtherRegionsTable::_mod_max_fine_entries_mask = 0;
  65 size_t OtherRegionsTable::_fine_eviction_stride = 0;
  66 size_t OtherRegionsTable::_fine_eviction_sample_size = 0;
  67 
  68 OtherRegionsTable::OtherRegionsTable(Mutex* m) :
  69   _g1h(G1CollectedHeap::heap()),
  70   _m(m),
  71   _num_occupied(0),
  72   _coarse_map(G1CollectedHeap::heap()->max_regions(), mtGC),
  73   _n_coarse_entries(0),
  74   _fine_grain_regions(NULL),
  75   _n_fine_entries(0),
  76   _first_all_fine_prts(NULL),
  77   _last_all_fine_prts(NULL),
  78   _fine_eviction_start(0),
  79   _sparse_table()
  80 {
  81   typedef PerRegionTable* PerRegionTablePtr;
  82 
  83   if (_max_fine_entries == 0) {
  84     assert(_mod_max_fine_entries_mask == 0, "Both or none.");
  85     size_t max_entries_log = (size_t)log2_long((jlong)G1RSetRegionEntries);
  86     _max_fine_entries = (size_t)1 << max_entries_log;
  87     _mod_max_fine_entries_mask = _max_fine_entries - 1;
  88 
  89     assert(_fine_eviction_sample_size == 0
  90            && _fine_eviction_stride == 0, "All init at same time.");
  91     _fine_eviction_sample_size = MAX2((size_t)4, max_entries_log);
  92     _fine_eviction_stride = _max_fine_entries / _fine_eviction_sample_size;
  93   }
  94 
  95   _fine_grain_regions = NEW_C_HEAP_ARRAY3(PerRegionTablePtr, _max_fine_entries,
  96                         mtGC, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
  97 
  98   if (_fine_grain_regions == NULL) {
  99     vm_exit_out_of_memory(sizeof(void*)*_max_fine_entries, OOM_MALLOC_ERROR,
 100                           "Failed to allocate _fine_grain_entries.");
 101   }
 102 
 103   for (size_t i = 0; i < _max_fine_entries; i++) {
 104     _fine_grain_regions[i] = NULL;
 105   }
 106 }
 107 
 108 void OtherRegionsTable::link_to_all(PerRegionTable* prt) {
 109   // We always append to the beginning of the list for convenience;
 110   // the order of entries in this list does not matter.
 111   if (_first_all_fine_prts != NULL) {
 112     assert(_first_all_fine_prts->prev() == NULL, "invariant");
 113     _first_all_fine_prts->set_prev(prt);
 114     prt->set_next(_first_all_fine_prts);
 115   } else {
 116     // this is the first element we insert. Adjust the "last" pointer
 117     _last_all_fine_prts = prt;
 118     assert(prt->next() == NULL, "just checking");
 119   }
 120   // the new element is always the first element without a predecessor
 121   prt->set_prev(NULL);
 122   _first_all_fine_prts = prt;
 123 
 124   assert(prt->prev() == NULL, "just checking");
 125   assert(_first_all_fine_prts == prt, "just checking");
 126   assert((_first_all_fine_prts == NULL && _last_all_fine_prts == NULL) ||
 127          (_first_all_fine_prts != NULL && _last_all_fine_prts != NULL),
 128          "just checking");
 129   assert(_last_all_fine_prts == NULL || _last_all_fine_prts->next() == NULL,
 130          "just checking");
 131   assert(_first_all_fine_prts == NULL || _first_all_fine_prts->prev() == NULL,
 132          "just checking");
 133 }
 134 
 135 void OtherRegionsTable::unlink_from_all(PerRegionTable* prt) {
 136   if (prt->prev() != NULL) {
 137     assert(_first_all_fine_prts != prt, "just checking");
 138     prt->prev()->set_next(prt->next());
 139     // removing the last element in the list?
 140     if (_last_all_fine_prts == prt) {
 141       _last_all_fine_prts = prt->prev();
 142     }
 143   } else {
 144     assert(_first_all_fine_prts == prt, "just checking");
 145     _first_all_fine_prts = prt->next();
 146     // list is empty now?
 147     if (_first_all_fine_prts == NULL) {
 148       _last_all_fine_prts = NULL;
 149     }
 150   }
 151 
 152   if (prt->next() != NULL) {
 153     prt->next()->set_prev(prt->prev());
 154   }
 155 
 156   prt->set_next(NULL);
 157   prt->set_prev(NULL);
 158 
 159   assert((_first_all_fine_prts == NULL && _last_all_fine_prts == NULL) ||
 160          (_first_all_fine_prts != NULL && _last_all_fine_prts != NULL),
 161          "just checking");
 162   assert(_last_all_fine_prts == NULL || _last_all_fine_prts->next() == NULL,
 163          "just checking");
 164   assert(_first_all_fine_prts == NULL || _first_all_fine_prts->prev() == NULL,
 165          "just checking");
 166 }
 167 
 168 CardIdx_t OtherRegionsTable::card_within_region(OopOrNarrowOopStar within_region, HeapRegion* hr) {
 169   assert(hr->is_in_reserved(within_region),
 170          "HeapWord " PTR_FORMAT " is outside of region %u [" PTR_FORMAT ", " PTR_FORMAT ")",
 171          p2i(within_region), hr->hrm_index(), p2i(hr->bottom()), p2i(hr->end()));
 172   CardIdx_t result = (CardIdx_t)(pointer_delta((HeapWord*)within_region, hr->bottom()) >> (CardTable::card_shift - LogHeapWordSize));
 173   return result;
 174 }
 175 
 176 void OtherRegionsTable::add_reference(OopOrNarrowOopStar from, uint tid) {
 177   // Note that this may be a continued H region.
 178   HeapRegion* from_hr = _g1h->heap_region_containing(from);
 179   RegionIdx_t from_hrm_ind = (RegionIdx_t) from_hr->hrm_index();
 180 
 181   // If the region is already coarsened, return.
 182   if (_coarse_map.at(from_hrm_ind)) {
 183     assert(contains_reference(from), "We just found " PTR_FORMAT " in the Coarse table", p2i(from));
 184     return;
 185   }
 186 
 187   size_t num_added_by_coarsening = 0;
 188   // Otherwise find a per-region table to add it to.
 189   size_t ind = from_hrm_ind & _mod_max_fine_entries_mask;
 190   PerRegionTable* prt = find_region_table(ind, from_hr);
 191   if (prt == NULL) {
 192     MutexLocker x(_m, Mutex::_no_safepoint_check_flag);
 193     // Confirm that it's really not there...
 194     prt = find_region_table(ind, from_hr);
 195     if (prt == NULL) {
 196 
 197       CardIdx_t card_index = card_within_region(from, from_hr);
 198 
 199       SparsePRT::AddCardResult result = _sparse_table.add_card(from_hrm_ind, card_index);
 200       if (result != SparsePRT::overflow) {
 201         if (result == SparsePRT::added) {
 202           Atomic::inc(&_num_occupied, memory_order_relaxed);
 203         }
 204         assert(contains_reference_locked(from), "We just added " PTR_FORMAT " to the Sparse table", p2i(from));
 205         return;
 206       }
 207 
 208       if (_n_fine_entries == _max_fine_entries) {
 209         prt = delete_region_table(num_added_by_coarsening);
 210         // There is no need to clear the links to the 'all' list here:
 211         // prt will be reused immediately, i.e. remain in the 'all' list.
 212         prt->init(from_hr, false /* clear_links_to_all_list */);
 213       } else {
 214         prt = PerRegionTable::alloc(from_hr);
 215         link_to_all(prt);
 216       }
 217 
 218       PerRegionTable* first_prt = _fine_grain_regions[ind];
 219       prt->set_collision_list_next(first_prt);
 220       // The assignment into _fine_grain_regions allows the prt to
 221       // start being used concurrently. In addition to
 222       // collision_list_next which must be visible (else concurrent
 223       // parsing of the list, if any, may fail to see other entries),
 224       // the content of the prt must be visible (else for instance
 225       // some mark bits may not yet seem cleared or a 'later' update
 226       // performed by a concurrent thread could be undone when the
 227       // zeroing becomes visible). This requires store ordering.
 228       Atomic::release_store(&_fine_grain_regions[ind], prt);
 229       _n_fine_entries++;
 230 
 231       // Transfer from sparse to fine-grain. The cards from the sparse table
 232       // were already added to the total in _num_occupied.
 233       SparsePRTEntry *sprt_entry = _sparse_table.get_entry(from_hrm_ind);
 234       assert(sprt_entry != NULL, "There should have been an entry");
 235       for (int i = 0; i < sprt_entry->num_valid_cards(); i++) {
 236         CardIdx_t c = sprt_entry->card(i);
 237         prt->add_card(c);
 238       }
 239       // Now we can delete the sparse entry.
 240       bool res = _sparse_table.delete_entry(from_hrm_ind);
 241       assert(res, "It should have been there.");
 242     }
 243     assert(prt != NULL && prt->hr() == from_hr, "consequence");
 244   }
 245   // Note that we can't assert "prt->hr() == from_hr", because of the
 246   // possibility of concurrent reuse.  But see head comment of
 247   // OtherRegionsTable for why this is OK.
 248   assert(prt != NULL, "Inv");
 249 
 250   bool added = prt->add_reference(from);
 251   if (prt->add_reference(from)) {
 252     num_added_by_coarsening++;
 253   }
 254   Atomic::add(&_num_occupied, num_added_by_coarsening, memory_order_relaxed);
 255   assert(contains_reference(from), "We just added " PTR_FORMAT " to the PRT (%d)", p2i(from), prt->contains_reference(from));
 256 }
 257 
 258 PerRegionTable*
 259 OtherRegionsTable::find_region_table(size_t ind, HeapRegion* hr) const {
 260   assert(ind < _max_fine_entries, "Preconditions.");
 261   PerRegionTable* prt = _fine_grain_regions[ind];
 262   while (prt != NULL && prt->hr() != hr) {
 263     prt = prt->collision_list_next();
 264   }
 265   // Loop postcondition is the method postcondition.
 266   return prt;
 267 }
 268 
 269 jint OtherRegionsTable::_n_coarsenings = 0;
 270 
 271 PerRegionTable* OtherRegionsTable::delete_region_table(size_t& added_by_deleted) {
 272   assert(_m->owned_by_self(), "Precondition");
 273   assert(_n_fine_entries == _max_fine_entries, "Precondition");
 274   PerRegionTable* max = NULL;
 275   jint max_occ = 0;
 276   PerRegionTable** max_prev = NULL;
 277   size_t max_ind;
 278 
 279   size_t i = _fine_eviction_start;
 280   for (size_t k = 0; k < _fine_eviction_sample_size; k++) {
 281     size_t ii = i;
 282     // Make sure we get a non-NULL sample.
 283     while (_fine_grain_regions[ii] == NULL) {
 284       ii++;
 285       if (ii == _max_fine_entries) ii = 0;
 286       guarantee(ii != i, "We must find one.");
 287     }
 288     PerRegionTable** prev = &_fine_grain_regions[ii];
 289     PerRegionTable* cur = *prev;
 290     while (cur != NULL) {
 291       jint cur_occ = cur->occupied();
 292       if (max == NULL || cur_occ > max_occ) {
 293         max = cur;
 294         max_prev = prev;
 295         max_ind = i;
 296         max_occ = cur_occ;
 297       }
 298       prev = cur->collision_list_next_addr();
 299       cur = cur->collision_list_next();
 300     }
 301     i = i + _fine_eviction_stride;
 302     if (i >= _n_fine_entries) i = i - _n_fine_entries;
 303   }
 304 
 305   _fine_eviction_start++;
 306 
 307   if (_fine_eviction_start >= _n_fine_entries) {
 308     _fine_eviction_start -= _n_fine_entries;
 309   }
 310 
 311   guarantee(max != NULL, "Since _n_fine_entries > 0");
 312   guarantee(max_prev != NULL, "Since max != NULL.");
 313 
 314   // Set the corresponding coarse bit.
 315   size_t max_hrm_index = (size_t) max->hr()->hrm_index();
 316   if (!_coarse_map.at(max_hrm_index)) {
 317     _coarse_map.at_put(max_hrm_index, true);
 318     _n_coarse_entries++;
 319   }
 320 
 321   added_by_deleted = HeapRegion::CardsPerRegion - max_occ;
 322   // Unsplice.
 323   *max_prev = max->collision_list_next();
 324   Atomic::inc(&_n_coarsenings);
 325   _n_fine_entries--;
 326   return max;
 327 }
 328 
 329 bool OtherRegionsTable::occupancy_less_or_equal_than(size_t limit) const {
 330   return occupied() <= limit;
 331 }
 332 
 333 bool OtherRegionsTable::is_empty() const {
 334   return occupied() == 0;
 335 }
 336 
 337 size_t OtherRegionsTable::occupied() const {
 338   return _num_occupied;
 339 }
 340 
 341 size_t OtherRegionsTable::mem_size() const {
 342   size_t sum = 0;
 343   // all PRTs are of the same size so it is sufficient to query only one of them.
 344   if (_first_all_fine_prts != NULL) {
 345     assert(_last_all_fine_prts != NULL &&
 346       _first_all_fine_prts->mem_size() == _last_all_fine_prts->mem_size(), "check that mem_size() is constant");
 347     sum += _first_all_fine_prts->mem_size() * _n_fine_entries;
 348   }
 349   sum += (sizeof(PerRegionTable*) * _max_fine_entries);
 350   sum += (_coarse_map.size_in_words() * HeapWordSize);
 351   sum += (_sparse_table.mem_size());
 352   sum += sizeof(OtherRegionsTable) - sizeof(_sparse_table); // Avoid double counting above.
 353   return sum;
 354 }
 355 
 356 size_t OtherRegionsTable::static_mem_size() {
 357   return G1FromCardCache::static_mem_size();
 358 }
 359 
 360 size_t OtherRegionsTable::fl_mem_size() {
 361   return PerRegionTable::fl_mem_size();
 362 }
 363 
 364 void OtherRegionsTable::clear() {
 365   // if there are no entries, skip this step
 366   if (_first_all_fine_prts != NULL) {
 367     guarantee(_first_all_fine_prts != NULL && _last_all_fine_prts != NULL, "just checking");
 368     PerRegionTable::bulk_free(_first_all_fine_prts, _last_all_fine_prts);
 369     memset(_fine_grain_regions, 0, _max_fine_entries * sizeof(_fine_grain_regions[0]));
 370   } else {
 371     guarantee(_first_all_fine_prts == NULL && _last_all_fine_prts == NULL, "just checking");
 372   }
 373 
 374   _first_all_fine_prts = _last_all_fine_prts = NULL;
 375   _sparse_table.clear();
 376   if (_n_coarse_entries > 0) {
 377     _coarse_map.clear();
 378   }
 379   _n_fine_entries = 0;
 380   _n_coarse_entries = 0;
 381 
 382   _num_occupied = 0;
 383 }
 384 
 385 bool OtherRegionsTable::contains_reference(OopOrNarrowOopStar from) const {
 386   // Cast away const in this case.
 387   MutexLocker x((Mutex*)_m, Mutex::_no_safepoint_check_flag);
 388   return contains_reference_locked(from);
 389 }
 390 
 391 bool OtherRegionsTable::contains_reference_locked(OopOrNarrowOopStar from) const {
 392   HeapRegion* hr = _g1h->heap_region_containing(from);
 393   RegionIdx_t hr_ind = (RegionIdx_t) hr->hrm_index();
 394   // Is this region in the coarse map?
 395   if (_coarse_map.at(hr_ind)) return true;
 396 
 397   PerRegionTable* prt = find_region_table(hr_ind & _mod_max_fine_entries_mask,
 398                                           hr);
 399   if (prt != NULL) {
 400     return prt->contains_reference(from);
 401 
 402   } else {
 403     CardIdx_t card_index = card_within_region(from, hr);
 404     return _sparse_table.contains_card(hr_ind, card_index);
 405   }
 406 }
 407 
 408 HeapRegionRemSet::HeapRegionRemSet(G1BlockOffsetTable* bot,
 409                                    HeapRegion* hr)
 410   : _bot(bot),
 411     _code_roots(),
 412     _m(Mutex::leaf, FormatBuffer<128>("HeapRegionRemSet lock #%u", hr->hrm_index()), true, Mutex::_safepoint_check_never),
 413     _other_regions(&_m),
 414     _hr(hr),
 415     _state(Untracked)
 416 {
 417 }
 418 
 419 void HeapRegionRemSet::clear_fcc() {
 420   G1FromCardCache::clear(_hr->hrm_index());
 421 }
 422 
 423 void HeapRegionRemSet::setup_remset_size() {
 424   const int LOG_M = 20;
 425   guarantee(HeapRegion::LogOfHRGrainBytes >= LOG_M, "Code assumes the region size >= 1M, but is " SIZE_FORMAT "B", HeapRegion::GrainBytes);
 426 
 427   int region_size_log_mb = HeapRegion::LogOfHRGrainBytes - LOG_M;
 428   if (FLAG_IS_DEFAULT(G1RSetSparseRegionEntries)) {
 429     G1RSetSparseRegionEntries = G1RSetSparseRegionEntriesBase * ((size_t)1 << (region_size_log_mb + 1));
 430   }
 431   if (FLAG_IS_DEFAULT(G1RSetRegionEntries)) {
 432     G1RSetRegionEntries = G1RSetRegionEntriesBase * (region_size_log_mb + 1);
 433   }
 434   guarantee(G1RSetSparseRegionEntries > 0 && G1RSetRegionEntries > 0 , "Sanity");
 435 }
 436 
 437 void HeapRegionRemSet::clear(bool only_cardset) {
 438   MutexLocker x(&_m, Mutex::_no_safepoint_check_flag);
 439   clear_locked(only_cardset);
 440 }
 441 
 442 void HeapRegionRemSet::clear_locked(bool only_cardset) {
 443   if (!only_cardset) {
 444     _code_roots.clear();
 445   }
 446   clear_fcc();
 447   _other_regions.clear();
 448   set_state_empty();
 449   assert(occupied() == 0, "Should be clear.");
 450 }
 451 
 452 // Code roots support
 453 //
 454 // The code root set is protected by two separate locking schemes
 455 // When at safepoint the per-hrrs lock must be held during modifications
 456 // except when doing a full gc.
 457 // When not at safepoint the CodeCache_lock must be held during modifications.
 458 // When concurrent readers access the contains() function
 459 // (during the evacuation phase) no removals are allowed.
 460 
 461 void HeapRegionRemSet::add_strong_code_root(nmethod* nm) {
 462   assert(nm != NULL, "sanity");
 463   assert((!CodeCache_lock->owned_by_self() || SafepointSynchronize::is_at_safepoint()),
 464           "should call add_strong_code_root_locked instead. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s",
 465           BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()));
 466   // Optimistic unlocked contains-check
 467   if (!_code_roots.contains(nm)) {
 468     MutexLocker ml(&_m, Mutex::_no_safepoint_check_flag);
 469     add_strong_code_root_locked(nm);
 470   }
 471 }
 472 
 473 void HeapRegionRemSet::add_strong_code_root_locked(nmethod* nm) {
 474   assert(nm != NULL, "sanity");
 475   assert((CodeCache_lock->owned_by_self() ||
 476          (SafepointSynchronize::is_at_safepoint() &&
 477           (_m.owned_by_self() || Thread::current()->is_VM_thread()))),
 478           "not safely locked. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s, _m.owned_by_self(): %s, Thread::current()->is_VM_thread(): %s",
 479           BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()),
 480           BOOL_TO_STR(_m.owned_by_self()), BOOL_TO_STR(Thread::current()->is_VM_thread()));
 481   _code_roots.add(nm);
 482 }
 483 
 484 void HeapRegionRemSet::remove_strong_code_root(nmethod* nm) {
 485   assert(nm != NULL, "sanity");
 486   assert_locked_or_safepoint(CodeCache_lock);
 487 
 488   MutexLocker ml(CodeCache_lock->owned_by_self() ? NULL : &_m, Mutex::_no_safepoint_check_flag);
 489   _code_roots.remove(nm);
 490 
 491   // Check that there were no duplicates
 492   guarantee(!_code_roots.contains(nm), "duplicate entry found");
 493 }
 494 
 495 void HeapRegionRemSet::strong_code_roots_do(CodeBlobClosure* blk) const {
 496   _code_roots.nmethods_do(blk);
 497 }
 498 
 499 void HeapRegionRemSet::clean_strong_code_roots(HeapRegion* hr) {
 500   _code_roots.clean(hr);
 501 }
 502 
 503 size_t HeapRegionRemSet::strong_code_roots_mem_size() {
 504   return _code_roots.mem_size();
 505 }