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 #ifndef SHARE_GC_G1_HEAPREGIONREMSET_HPP
  26 #define SHARE_GC_G1_HEAPREGIONREMSET_HPP
  27 
  28 #include "gc/g1/g1CodeCacheRemSet.hpp"
  29 #include "gc/g1/g1FromCardCache.hpp"
  30 #include "gc/g1/sparsePRT.hpp"
  31 #include "runtime/mutexLocker.inline.hpp"
  32 #include "utilities/bitMap.hpp"
  33 
  34 // Remembered set for a heap region.  Represent a set of "cards" that
  35 // contain pointers into the owner heap region.  Cards are defined somewhat
  36 // abstractly, in terms of what the "BlockOffsetTable" in use can parse.
  37 
  38 class G1CollectedHeap;
  39 class G1BlockOffsetTable;
  40 class G1CardLiveData;
  41 class HeapRegion;
  42 class PerRegionTable;
  43 class SparsePRT;
  44 class nmethod;
  45 
  46 // The "_coarse_map" is a bitmap with one bit for each region, where set
  47 // bits indicate that the corresponding region may contain some pointer
  48 // into the owning region.
  49 
  50 // The "_fine_grain_entries" array is an open hash table of PerRegionTables
  51 // (PRTs), indicating regions for which we're keeping the RS as a set of
  52 // cards.  The strategy is to cap the size of the fine-grain table,
  53 // deleting an entry and setting the corresponding coarse-grained bit when
  54 // we would overflow this cap.
  55 
  56 // We use a mixture of locking and lock-free techniques here.  We allow
  57 // threads to locate PRTs without locking, but threads attempting to alter
  58 // a bucket list obtain a lock.  This means that any failing attempt to
  59 // find a PRT must be retried with the lock.  It might seem dangerous that
  60 // a read can find a PRT that is concurrently deleted.  This is all right,
  61 // because:
  62 //
  63 //   1) We only actually free PRT's at safe points (though we reuse them at
  64 //      other times).
  65 //   2) We find PRT's in an attempt to add entries.  If a PRT is deleted,
  66 //      it's _coarse_map bit is set, so the that we were attempting to add
  67 //      is represented.  If a deleted PRT is re-used, a thread adding a bit,
  68 //      thinking the PRT is for a different region, does no harm.
  69 
  70 class OtherRegionsTable {
  71   G1CollectedHeap* _g1h;
  72   Mutex*           _m;
  73 
  74   // These are protected by "_m".
  75   CHeapBitMap _coarse_map;
  76   size_t      _n_coarse_entries;
  77   static jint _n_coarsenings;
  78 
  79   PerRegionTable** _fine_grain_regions;
  80   size_t           _n_fine_entries;
  81 
  82   // The fine grain remembered sets are doubly linked together using
  83   // their 'next' and 'prev' fields.
  84   // This allows fast bulk freeing of all the fine grain remembered
  85   // set entries, and fast finding of all of them without iterating
  86   // over the _fine_grain_regions table.
  87   PerRegionTable * _first_all_fine_prts;
  88   PerRegionTable * _last_all_fine_prts;
  89 
  90   // Used to sample a subset of the fine grain PRTs to determine which
  91   // PRT to evict and coarsen.
  92   size_t        _fine_eviction_start;
  93   static size_t _fine_eviction_stride;
  94   static size_t _fine_eviction_sample_size;
  95 
  96   SparsePRT   _sparse_table;
  97 
  98   // These are static after init.
  99   static size_t _max_fine_entries;
 100   static size_t _mod_max_fine_entries_mask;
 101 
 102   // Requires "prt" to be the first element of the bucket list appropriate
 103   // for "hr".  If this list contains an entry for "hr", return it,
 104   // otherwise return "NULL".
 105   PerRegionTable* find_region_table(size_t ind, HeapRegion* hr) const;
 106 
 107   // Find, delete, and return a candidate PerRegionTable, if any exists,
 108   // adding the deleted region to the coarse bitmap.  Requires the caller
 109   // to hold _m, and the fine-grain table to be full.
 110   PerRegionTable* delete_region_table();
 111 
 112   // link/add the given fine grain remembered set into the "all" list
 113   void link_to_all(PerRegionTable * prt);
 114   // unlink/remove the given fine grain remembered set into the "all" list
 115   void unlink_from_all(PerRegionTable * prt);
 116 
 117   bool contains_reference_locked(OopOrNarrowOopStar from) const;
 118 
 119   size_t occ_fine() const;
 120   size_t occ_coarse() const;
 121   size_t occ_sparse() const;
 122 
 123 public:
 124   // Create a new remembered set. The given mutex is used to ensure consistency.
 125   OtherRegionsTable(Mutex* m);
 126 
 127   template <class Closure>
 128   void iterate(Closure& v);
 129 
 130   // Returns the card index of the given within_region pointer relative to the bottom
 131   // of the given heap region.
 132   static CardIdx_t card_within_region(OopOrNarrowOopStar within_region, HeapRegion* hr);
 133   // Adds the reference from "from to this remembered set.
 134   void add_reference(OopOrNarrowOopStar from, uint tid);
 135 
 136   // Returns whether the remembered set contains the given reference.
 137   bool contains_reference(OopOrNarrowOopStar from) const;
 138 
 139   // Returns whether this remembered set (and all sub-sets) have an occupancy
 140   // that is less or equal than the given occupancy.
 141   bool occupancy_less_or_equal_than(size_t limit) const;
 142 
 143   // Returns whether this remembered set (and all sub-sets) does not contain any entry.
 144   bool is_empty() const;
 145 
 146   // Returns the number of cards contained in this remembered set.
 147   size_t occupied() const;
 148 
 149   static jint n_coarsenings() { return _n_coarsenings; }
 150 
 151   // Returns size of the actual remembered set containers in bytes.
 152   size_t mem_size() const;
 153   // Returns the size of static data in bytes.
 154   static size_t static_mem_size();
 155   // Returns the size of the free list content in bytes.
 156   static size_t fl_mem_size();
 157 
 158   // Clear the entire contents of this remembered set.
 159   void clear();
 160 };
 161 
 162 class PerRegionTable: public CHeapObj<mtGC> {
 163   friend class OtherRegionsTable;
 164 
 165   HeapRegion*     _hr;
 166   CHeapBitMap     _bm;
 167   jint            _occupied;
 168 
 169   // next pointer for free/allocated 'all' list
 170   PerRegionTable* _next;
 171 
 172   // prev pointer for the allocated 'all' list
 173   PerRegionTable* _prev;
 174 
 175   // next pointer in collision list
 176   PerRegionTable * _collision_list_next;
 177 
 178   // Global free list of PRTs
 179   static PerRegionTable* volatile _free_list;
 180 
 181 protected:
 182   PerRegionTable(HeapRegion* hr) :
 183     _hr(hr),
 184     _bm(HeapRegion::CardsPerRegion, mtGC),
 185     _occupied(0),
 186     _next(NULL), _prev(NULL),
 187     _collision_list_next(NULL)
 188   {}
 189 
 190   inline void add_card_work(CardIdx_t from_card, bool par);
 191 
 192   inline void add_reference_work(OopOrNarrowOopStar from, bool par);
 193 
 194 public:
 195   // We need access in order to union things into the base table.
 196   BitMap* bm() { return &_bm; }
 197 
 198   HeapRegion* hr() const { return OrderAccess::load_acquire(&_hr); }
 199 
 200   jint occupied() const {
 201     // Overkill, but if we ever need it...
 202     // guarantee(_occupied == _bm.count_one_bits(), "Check");
 203     return _occupied;
 204   }
 205 
 206   void init(HeapRegion* hr, bool clear_links_to_all_list);
 207 
 208   inline void add_reference(OopOrNarrowOopStar from);
 209 
 210   inline void seq_add_reference(OopOrNarrowOopStar from);
 211 
 212   inline void add_card(CardIdx_t from_card_index);
 213 
 214   void seq_add_card(CardIdx_t from_card_index);
 215 
 216   // (Destructively) union the bitmap of the current table into the given
 217   // bitmap (which is assumed to be of the same size.)
 218   void union_bitmap_into(BitMap* bm) {
 219     bm->set_union(_bm);
 220   }
 221 
 222   // Mem size in bytes.
 223   size_t mem_size() const {
 224     return sizeof(PerRegionTable) + _bm.size_in_words() * HeapWordSize;
 225   }
 226 
 227   // Requires "from" to be in "hr()".
 228   bool contains_reference(OopOrNarrowOopStar from) const {
 229     assert(hr()->is_in_reserved(from), "Precondition.");
 230     size_t card_ind = pointer_delta(from, hr()->bottom(),
 231                                     G1CardTable::card_size);
 232     return _bm.at(card_ind);
 233   }
 234 
 235   // Bulk-free the PRTs from prt to last, assumes that they are
 236   // linked together using their _next field.
 237   static void bulk_free(PerRegionTable* prt, PerRegionTable* last) {
 238     while (true) {
 239       PerRegionTable* fl = _free_list;
 240       last->set_next(fl);
 241       PerRegionTable* res = Atomic::cmpxchg(prt, &_free_list, fl);
 242       if (res == fl) {
 243         return;
 244       }
 245     }
 246     ShouldNotReachHere();
 247   }
 248 
 249   static void free(PerRegionTable* prt) {
 250     bulk_free(prt, prt);
 251   }
 252 
 253   // Returns an initialized PerRegionTable instance.
 254   static PerRegionTable* alloc(HeapRegion* hr);
 255 
 256   PerRegionTable* next() const { return _next; }
 257   void set_next(PerRegionTable* next) { _next = next; }
 258   PerRegionTable* prev() const { return _prev; }
 259   void set_prev(PerRegionTable* prev) { _prev = prev; }
 260 
 261   // Accessor and Modification routines for the pointer for the
 262   // singly linked collision list that links the PRTs within the
 263   // OtherRegionsTable::_fine_grain_regions hash table.
 264   //
 265   // It might be useful to also make the collision list doubly linked
 266   // to avoid iteration over the collisions list during scrubbing/deletion.
 267   // OTOH there might not be many collisions.
 268 
 269   PerRegionTable* collision_list_next() const {
 270     return _collision_list_next;
 271   }
 272 
 273   void set_collision_list_next(PerRegionTable* next) {
 274     _collision_list_next = next;
 275   }
 276 
 277   PerRegionTable** collision_list_next_addr() {
 278     return &_collision_list_next;
 279   }
 280 
 281   static size_t fl_mem_size() {
 282     PerRegionTable* cur = _free_list;
 283     size_t res = 0;
 284     while (cur != NULL) {
 285       res += cur->mem_size();
 286       cur = cur->next();
 287     }
 288     return res;
 289   }
 290 
 291   static void test_fl_mem_size();
 292 };
 293 
 294 class HeapRegionRemSet : public CHeapObj<mtGC> {
 295   friend class VMStructs;
 296 
 297 private:
 298   G1BlockOffsetTable* _bot;
 299 
 300   // A set of code blobs (nmethods) whose code contains pointers into
 301   // the region that owns this RSet.
 302   G1CodeRootSet _code_roots;
 303 
 304   Mutex _m;
 305 
 306   OtherRegionsTable _other_regions;
 307 
 308   HeapRegion* _hr;
 309 
 310   void clear_fcc();
 311 
 312 public:
 313   HeapRegionRemSet(G1BlockOffsetTable* bot, HeapRegion* hr);
 314 
 315   // Setup sparse and fine-grain tables sizes.
 316   static void setup_remset_size();
 317 
 318   bool is_empty() const {
 319     return (strong_code_roots_list_length() == 0) && _other_regions.is_empty();
 320   }
 321 
 322   bool occupancy_less_or_equal_than(size_t occ) const {
 323     return (strong_code_roots_list_length() == 0) && _other_regions.occupancy_less_or_equal_than(occ);
 324   }
 325 
 326   // For each PRT in the card (remembered) set call one of the following methods
 327   // of the given closure:
 328   //
 329   // set_full_region_dirty(uint region_idx) - pass the region index for coarse PRTs
 330   // set_bitmap_dirty(uint region_idx, BitMap* bitmap) - pass the region index and bitmap for fine PRTs
 331   // set_cards_dirty(uint region_idx, elem_t* cards, uint num_cards) - pass region index and cards for sparse PRTs
 332   template <class Closure>
 333   inline void iterate_prts(Closure& cl);
 334 
 335   size_t occupied() {
 336     MutexLocker x(&_m, Mutex::_no_safepoint_check_flag);
 337     return occupied_locked();
 338   }
 339   size_t occupied_locked() {
 340     return _other_regions.occupied();
 341   }
 342 
 343   static jint n_coarsenings() { return OtherRegionsTable::n_coarsenings(); }
 344 
 345 private:
 346   enum RemSetState {
 347     Untracked,
 348     Updating,
 349     Complete
 350   };
 351 
 352   RemSetState _state;
 353 
 354   static const char* _state_strings[];
 355   static const char* _short_state_strings[];
 356 public:
 357 
 358   const char* get_state_str() const { return _state_strings[_state]; }
 359   const char* get_short_state_str() const { return _short_state_strings[_state]; }
 360 
 361   bool is_tracked() { return _state != Untracked; }
 362   bool is_updating() { return _state == Updating; }
 363   bool is_complete() { return _state == Complete; }
 364 
 365   void set_state_empty() {
 366     guarantee(SafepointSynchronize::is_at_safepoint() || !is_tracked(), "Should only set to Untracked during safepoint but is %s.", get_state_str());
 367     if (_state == Untracked) {
 368       return;
 369     }
 370     clear_fcc();
 371     _state = Untracked;
 372   }
 373 
 374   void set_state_updating() {
 375     guarantee(SafepointSynchronize::is_at_safepoint() && !is_tracked(), "Should only set to Updating from Untracked during safepoint but is %s", get_state_str());
 376     clear_fcc();
 377     _state = Updating;
 378   }
 379 
 380   void set_state_complete() {
 381     clear_fcc();
 382     _state = Complete;
 383   }
 384 
 385   // Used in the sequential case.
 386   void add_reference(OopOrNarrowOopStar from) {
 387     add_reference(from, 0);
 388   }
 389 
 390   // Used in the parallel case.
 391   void add_reference(OopOrNarrowOopStar from, uint tid) {
 392     RemSetState state = _state;
 393     if (state == Untracked) {
 394       return;
 395     }
 396 
 397     uint cur_idx = _hr->hrm_index();
 398     uintptr_t from_card = uintptr_t(from) >> CardTable::card_shift;
 399 
 400     if (G1FromCardCache::contains_or_replace(tid, cur_idx, from_card)) {
 401       assert(contains_reference(from), "We just found " PTR_FORMAT " in the FromCardCache", p2i(from));
 402       return;
 403     }
 404 
 405     _other_regions.add_reference(from, tid);
 406   }
 407 
 408   // The region is being reclaimed; clear its remset, and any mention of
 409   // entries for this region in other remsets.
 410   void clear(bool only_cardset = false);
 411   void clear_locked(bool only_cardset = false);
 412 
 413   // The actual # of bytes this hr_remset takes up.
 414   // Note also includes the strong code root set.
 415   size_t mem_size() {
 416     MutexLocker x(&_m, Mutex::_no_safepoint_check_flag);
 417     return _other_regions.mem_size()
 418       // This correction is necessary because the above includes the second
 419       // part.
 420       + (sizeof(HeapRegionRemSet) - sizeof(OtherRegionsTable))
 421       + strong_code_roots_mem_size();
 422   }
 423 
 424   // Returns the memory occupancy of all static data structures associated
 425   // with remembered sets.
 426   static size_t static_mem_size() {
 427     return OtherRegionsTable::static_mem_size() + G1CodeRootSet::static_mem_size();
 428   }
 429 
 430   // Returns the memory occupancy of all free_list data structures associated
 431   // with remembered sets.
 432   static size_t fl_mem_size() {
 433     return OtherRegionsTable::fl_mem_size();
 434   }
 435 
 436   bool contains_reference(OopOrNarrowOopStar from) const {
 437     return _other_regions.contains_reference(from);
 438   }
 439 
 440   // Routines for managing the list of code roots that point into
 441   // the heap region that owns this RSet.
 442   void add_strong_code_root(nmethod* nm);
 443   void add_strong_code_root_locked(nmethod* nm);
 444   void remove_strong_code_root(nmethod* nm);
 445 
 446   // Applies blk->do_code_blob() to each of the entries in
 447   // the strong code roots list
 448   void strong_code_roots_do(CodeBlobClosure* blk) const;
 449 
 450   void clean_strong_code_roots(HeapRegion* hr);
 451 
 452   // Returns the number of elements in the strong code roots list
 453   size_t strong_code_roots_list_length() const {
 454     return _code_roots.length();
 455   }
 456 
 457   // Returns true if the strong code roots contains the given
 458   // nmethod.
 459   bool strong_code_roots_list_contains(nmethod* nm) {
 460     return _code_roots.contains(nm);
 461   }
 462 
 463   // Returns the amount of memory, in bytes, currently
 464   // consumed by the strong code roots.
 465   size_t strong_code_roots_mem_size();
 466 
 467   static void invalidate_from_card_cache(uint start_idx, size_t num_regions) {
 468     G1FromCardCache::invalidate(start_idx, num_regions);
 469   }
 470 
 471 #ifndef PRODUCT
 472   static void print_from_card_cache() {
 473     G1FromCardCache::print();
 474   }
 475 
 476   static void test();
 477 #endif
 478 };
 479 
 480 #endif // SHARE_GC_G1_HEAPREGIONREMSET_HPP