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/shared/space.inline.hpp"
  32 #include "memory/allocation.hpp"
  33 #include "memory/padded.inline.hpp"
  34 #include "oops/oop.inline.hpp"
  35 #include "runtime/atomic.hpp"
  36 #include "utilities/bitMap.inline.hpp"
  37 #include "utilities/debug.hpp"
  38 #include "utilities/formatBuffer.hpp"
  39 #include "utilities/globalDefinitions.hpp"
  40 #include "utilities/growableArray.hpp"
  41 
  42 const char* HeapRegionRemSet::_state_strings[] =  {"Untracked", "Updating", "Complete"};
  43 const char* HeapRegionRemSet::_short_state_strings[] =  {"UNTRA", "UPDAT", "CMPLT"};
  44 
  45 PerRegionTable* PerRegionTable::alloc(HeapRegion* hr) {
  46   PerRegionTable* fl = _free_list;
  47   while (fl != NULL) {
  48     PerRegionTable* nxt = fl->next();
  49     PerRegionTable* res = Atomic::cmpxchg(nxt, &_free_list, fl);
  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       if (_sparse_table.add_card(from_hrm_ind, card_index)) {
 200         Atomic::inc(&_num_occupied, memory_order_relaxed);
 201         assert(contains_reference_locked(from), "We just added " PTR_FORMAT " to the Sparse table", p2i(from));
 202         return;
 203       }
 204 
 205       if (_n_fine_entries == _max_fine_entries) {
 206         prt = delete_region_table(num_added_by_coarsening);
 207         // There is no need to clear the links to the 'all' list here:
 208         // prt will be reused immediately, i.e. remain in the 'all' list.
 209         prt->init(from_hr, false /* clear_links_to_all_list */);
 210       } else {
 211         prt = PerRegionTable::alloc(from_hr);
 212         link_to_all(prt);
 213       }
 214 
 215       PerRegionTable* first_prt = _fine_grain_regions[ind];
 216       prt->set_collision_list_next(first_prt);
 217       // The assignment into _fine_grain_regions allows the prt to
 218       // start being used concurrently. In addition to
 219       // collision_list_next which must be visible (else concurrent
 220       // parsing of the list, if any, may fail to see other entries),
 221       // the content of the prt must be visible (else for instance
 222       // some mark bits may not yet seem cleared or a 'later' update
 223       // performed by a concurrent thread could be undone when the
 224       // zeroing becomes visible). This requires store ordering.
 225       OrderAccess::release_store(&_fine_grain_regions[ind], prt);
 226       _n_fine_entries++;
 227 
 228       // Transfer from sparse to fine-grain. The cards from the sparse table
 229       // were already added to the total in _num_occupied.
 230       SparsePRTEntry *sprt_entry = _sparse_table.get_entry(from_hrm_ind);
 231       assert(sprt_entry != NULL, "There should have been an entry");
 232       for (int i = 0; i < sprt_entry->num_valid_cards(); i++) {
 233         CardIdx_t c = sprt_entry->card(i);
 234         prt->add_card(c);
 235       }
 236       // Now we can delete the sparse entry.
 237       bool res = _sparse_table.delete_entry(from_hrm_ind);
 238       assert(res, "It should have been there.");
 239     }
 240     assert(prt != NULL && prt->hr() == from_hr, "consequence");
 241   }
 242   // Note that we can't assert "prt->hr() == from_hr", because of the
 243   // possibility of concurrent reuse.  But see head comment of
 244   // OtherRegionsTable for why this is OK.
 245   assert(prt != NULL, "Inv");
 246 
 247   bool added = prt->add_reference(from);
 248   Atomic::add(num_added_by_coarsening + (added ? 1 : 0), &_num_occupied, memory_order_relaxed);
 249   assert(contains_reference(from), "We just added " PTR_FORMAT " to the PRT (%d)", p2i(from), prt->contains_reference(from));
 250 }
 251 
 252 PerRegionTable*
 253 OtherRegionsTable::find_region_table(size_t ind, HeapRegion* hr) const {
 254   assert(ind < _max_fine_entries, "Preconditions.");
 255   PerRegionTable* prt = _fine_grain_regions[ind];
 256   while (prt != NULL && prt->hr() != hr) {
 257     prt = prt->collision_list_next();
 258   }
 259   // Loop postcondition is the method postcondition.
 260   return prt;
 261 }
 262 
 263 jint OtherRegionsTable::_n_coarsenings = 0;
 264 
 265 PerRegionTable* OtherRegionsTable::delete_region_table(size_t& added_by_deleted) {
 266   assert(_m->owned_by_self(), "Precondition");
 267   assert(_n_fine_entries == _max_fine_entries, "Precondition");
 268   PerRegionTable* max = NULL;
 269   jint max_occ = 0;
 270   PerRegionTable** max_prev = NULL;
 271   size_t max_ind;
 272 
 273   size_t i = _fine_eviction_start;
 274   for (size_t k = 0; k < _fine_eviction_sample_size; k++) {
 275     size_t ii = i;
 276     // Make sure we get a non-NULL sample.
 277     while (_fine_grain_regions[ii] == NULL) {
 278       ii++;
 279       if (ii == _max_fine_entries) ii = 0;
 280       guarantee(ii != i, "We must find one.");
 281     }
 282     PerRegionTable** prev = &_fine_grain_regions[ii];
 283     PerRegionTable* cur = *prev;
 284     while (cur != NULL) {
 285       jint cur_occ = cur->occupied();
 286       if (max == NULL || cur_occ > max_occ) {
 287         max = cur;
 288         max_prev = prev;
 289         max_ind = i;
 290         max_occ = cur_occ;
 291       }
 292       prev = cur->collision_list_next_addr();
 293       cur = cur->collision_list_next();
 294     }
 295     i = i + _fine_eviction_stride;
 296     if (i >= _n_fine_entries) i = i - _n_fine_entries;
 297   }
 298 
 299   _fine_eviction_start++;
 300 
 301   if (_fine_eviction_start >= _n_fine_entries) {
 302     _fine_eviction_start -= _n_fine_entries;
 303   }
 304 
 305   guarantee(max != NULL, "Since _n_fine_entries > 0");
 306   guarantee(max_prev != NULL, "Since max != NULL.");
 307 
 308   // Set the corresponding coarse bit.
 309   size_t max_hrm_index = (size_t) max->hr()->hrm_index();
 310   if (!_coarse_map.at(max_hrm_index)) {
 311     _coarse_map.at_put(max_hrm_index, true);
 312     _n_coarse_entries++;
 313   }
 314 
 315   added_by_deleted = HeapRegion::CardsPerRegion - max_occ;
 316   // Unsplice.
 317   *max_prev = max->collision_list_next();
 318   Atomic::inc(&_n_coarsenings);
 319   _n_fine_entries--;
 320   return max;
 321 }
 322 
 323 bool OtherRegionsTable::occupancy_less_or_equal_than(size_t limit) const {
 324   return occupied() <= limit;
 325 }
 326 
 327 bool OtherRegionsTable::is_empty() const {
 328   return occupied() == 0;
 329 }
 330 
 331 size_t OtherRegionsTable::occupied() const {
 332   return _num_occupied;
 333 }
 334 
 335 size_t OtherRegionsTable::mem_size() const {
 336   size_t sum = 0;
 337   // all PRTs are of the same size so it is sufficient to query only one of them.
 338   if (_first_all_fine_prts != NULL) {
 339     assert(_last_all_fine_prts != NULL &&
 340       _first_all_fine_prts->mem_size() == _last_all_fine_prts->mem_size(), "check that mem_size() is constant");
 341     sum += _first_all_fine_prts->mem_size() * _n_fine_entries;
 342   }
 343   sum += (sizeof(PerRegionTable*) * _max_fine_entries);
 344   sum += (_coarse_map.size_in_words() * HeapWordSize);
 345   sum += (_sparse_table.mem_size());
 346   sum += sizeof(OtherRegionsTable) - sizeof(_sparse_table); // Avoid double counting above.
 347   return sum;
 348 }
 349 
 350 size_t OtherRegionsTable::static_mem_size() {
 351   return G1FromCardCache::static_mem_size();
 352 }
 353 
 354 size_t OtherRegionsTable::fl_mem_size() {
 355   return PerRegionTable::fl_mem_size();
 356 }
 357 
 358 void OtherRegionsTable::clear() {
 359   // if there are no entries, skip this step
 360   if (_first_all_fine_prts != NULL) {
 361     guarantee(_first_all_fine_prts != NULL && _last_all_fine_prts != NULL, "just checking");
 362     PerRegionTable::bulk_free(_first_all_fine_prts, _last_all_fine_prts);
 363     memset(_fine_grain_regions, 0, _max_fine_entries * sizeof(_fine_grain_regions[0]));
 364   } else {
 365     guarantee(_first_all_fine_prts == NULL && _last_all_fine_prts == NULL, "just checking");
 366   }
 367 
 368   _first_all_fine_prts = _last_all_fine_prts = NULL;
 369   _sparse_table.clear();
 370   if (_n_coarse_entries > 0) {
 371     _coarse_map.clear();
 372   }
 373   _n_fine_entries = 0;
 374   _n_coarse_entries = 0;
 375 
 376   _num_occupied = 0;
 377 }
 378 
 379 bool OtherRegionsTable::contains_reference(OopOrNarrowOopStar from) const {
 380   // Cast away const in this case.
 381   MutexLocker x((Mutex*)_m, Mutex::_no_safepoint_check_flag);
 382   return contains_reference_locked(from);
 383 }
 384 
 385 bool OtherRegionsTable::contains_reference_locked(OopOrNarrowOopStar from) const {
 386   HeapRegion* hr = _g1h->heap_region_containing(from);
 387   RegionIdx_t hr_ind = (RegionIdx_t) hr->hrm_index();
 388   // Is this region in the coarse map?
 389   if (_coarse_map.at(hr_ind)) return true;
 390 
 391   PerRegionTable* prt = find_region_table(hr_ind & _mod_max_fine_entries_mask,
 392                                           hr);
 393   if (prt != NULL) {
 394     return prt->contains_reference(from);
 395 
 396   } else {
 397     CardIdx_t card_index = card_within_region(from, hr);
 398     return _sparse_table.contains_card(hr_ind, card_index);
 399   }
 400 }
 401 
 402 HeapRegionRemSet::HeapRegionRemSet(G1BlockOffsetTable* bot,
 403                                    HeapRegion* hr)
 404   : _bot(bot),
 405     _code_roots(),
 406     _m(Mutex::leaf, FormatBuffer<128>("HeapRegionRemSet lock #%u", hr->hrm_index()), true, Mutex::_safepoint_check_never),
 407     _other_regions(&_m),
 408     _hr(hr),
 409     _state(Untracked)
 410 {
 411 }
 412 
 413 void HeapRegionRemSet::clear_fcc() {
 414   G1FromCardCache::clear(_hr->hrm_index());
 415 }
 416 
 417 void HeapRegionRemSet::setup_remset_size() {
 418   const int LOG_M = 20;
 419   guarantee(HeapRegion::LogOfHRGrainBytes >= LOG_M, "Code assumes the region size >= 1M, but is " SIZE_FORMAT "B", HeapRegion::GrainBytes);
 420 
 421   int region_size_log_mb = HeapRegion::LogOfHRGrainBytes - LOG_M;
 422   if (FLAG_IS_DEFAULT(G1RSetSparseRegionEntries)) {
 423     G1RSetSparseRegionEntries = G1RSetSparseRegionEntriesBase * ((size_t)1 << (region_size_log_mb + 1));
 424   }
 425   if (FLAG_IS_DEFAULT(G1RSetRegionEntries)) {
 426     G1RSetRegionEntries = G1RSetRegionEntriesBase * (region_size_log_mb + 1);
 427   }
 428   guarantee(G1RSetSparseRegionEntries > 0 && G1RSetRegionEntries > 0 , "Sanity");
 429 }
 430 
 431 void HeapRegionRemSet::clear(bool only_cardset) {
 432   MutexLocker x(&_m, Mutex::_no_safepoint_check_flag);
 433   clear_locked(only_cardset);
 434 }
 435 
 436 void HeapRegionRemSet::clear_locked(bool only_cardset) {
 437   if (!only_cardset) {
 438     _code_roots.clear();
 439   }
 440   clear_fcc();
 441   _other_regions.clear();
 442   set_state_empty();
 443   assert(occupied() == 0, "Should be clear.");
 444 }
 445 
 446 // Code roots support
 447 //
 448 // The code root set is protected by two separate locking schemes
 449 // When at safepoint the per-hrrs lock must be held during modifications
 450 // except when doing a full gc.
 451 // When not at safepoint the CodeCache_lock must be held during modifications.
 452 // When concurrent readers access the contains() function
 453 // (during the evacuation phase) no removals are allowed.
 454 
 455 void HeapRegionRemSet::add_strong_code_root(nmethod* nm) {
 456   assert(nm != NULL, "sanity");
 457   assert((!CodeCache_lock->owned_by_self() || SafepointSynchronize::is_at_safepoint()),
 458           "should call add_strong_code_root_locked instead. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s",
 459           BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()));
 460   // Optimistic unlocked contains-check
 461   if (!_code_roots.contains(nm)) {
 462     MutexLocker ml(&_m, Mutex::_no_safepoint_check_flag);
 463     add_strong_code_root_locked(nm);
 464   }
 465 }
 466 
 467 void HeapRegionRemSet::add_strong_code_root_locked(nmethod* nm) {
 468   assert(nm != NULL, "sanity");
 469   assert((CodeCache_lock->owned_by_self() ||
 470          (SafepointSynchronize::is_at_safepoint() &&
 471           (_m.owned_by_self() || Thread::current()->is_VM_thread()))),
 472           "not safely locked. CodeCache_lock->owned_by_self(): %s, is_at_safepoint(): %s, _m.owned_by_self(): %s, Thread::current()->is_VM_thread(): %s",
 473           BOOL_TO_STR(CodeCache_lock->owned_by_self()), BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()),
 474           BOOL_TO_STR(_m.owned_by_self()), BOOL_TO_STR(Thread::current()->is_VM_thread()));
 475   _code_roots.add(nm);
 476 }
 477 
 478 void HeapRegionRemSet::remove_strong_code_root(nmethod* nm) {
 479   assert(nm != NULL, "sanity");
 480   assert_locked_or_safepoint(CodeCache_lock);
 481 
 482   MutexLocker ml(CodeCache_lock->owned_by_self() ? NULL : &_m, Mutex::_no_safepoint_check_flag);
 483   _code_roots.remove(nm);
 484 
 485   // Check that there were no duplicates
 486   guarantee(!_code_roots.contains(nm), "duplicate entry found");
 487 }
 488 
 489 void HeapRegionRemSet::strong_code_roots_do(CodeBlobClosure* blk) const {
 490   _code_roots.nmethods_do(blk);
 491 }
 492 
 493 void HeapRegionRemSet::clean_strong_code_roots(HeapRegion* hr) {
 494   _code_roots.clean(hr);
 495 }
 496 
 497 size_t HeapRegionRemSet::strong_code_roots_mem_size() {
 498   return _code_roots.mem_size();
 499 }