1 /*
   2  * Copyright (c) 2001, 2018, 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_VM_GC_G1_HEAPREGIONREMSET_HPP
  26 #define SHARE_VM_GC_G1_HEAPREGIONREMSET_HPP
  27 
  28 #include "gc/g1/g1CodeCacheRemSet.hpp"
  29 #include "gc/g1/g1FromCardCache.hpp"
  30 #include "gc/g1/sparsePRT.hpp"
  31 
  32 // Remembered set for a heap region.  Represent a set of "cards" that
  33 // contain pointers into the owner heap region.  Cards are defined somewhat
  34 // abstractly, in terms of what the "BlockOffsetTable" in use can parse.
  35 
  36 class G1CollectedHeap;
  37 class G1BlockOffsetTable;
  38 class G1CardLiveData;
  39 class HeapRegion;
  40 class HeapRegionRemSetIterator;
  41 class PerRegionTable;
  42 class SparsePRT;
  43 class nmethod;
  44 
  45 // The "_coarse_map" is a bitmap with one bit for each region, where set
  46 // bits indicate that the corresponding region may contain some pointer
  47 // into the owning region.
  48 
  49 // The "_fine_grain_entries" array is an open hash table of PerRegionTables
  50 // (PRTs), indicating regions for which we're keeping the RS as a set of
  51 // cards.  The strategy is to cap the size of the fine-grain table,
  52 // deleting an entry and setting the corresponding coarse-grained bit when
  53 // we would overflow this cap.
  54 
  55 // We use a mixture of locking and lock-free techniques here.  We allow
  56 // threads to locate PRTs without locking, but threads attempting to alter
  57 // a bucket list obtain a lock.  This means that any failing attempt to
  58 // find a PRT must be retried with the lock.  It might seem dangerous that
  59 // a read can find a PRT that is concurrently deleted.  This is all right,
  60 // because:
  61 //
  62 //   1) We only actually free PRT's at safe points (though we reuse them at
  63 //      other times).
  64 //   2) We find PRT's in an attempt to add entries.  If a PRT is deleted,
  65 //      it's _coarse_map bit is set, so the that we were attempting to add
  66 //      is represented.  If a deleted PRT is re-used, a thread adding a bit,
  67 //      thinking the PRT is for a different region, does no harm.
  68 
  69 class OtherRegionsTable {
  70   friend class HeapRegionRemSetIterator;
  71 
  72   G1CollectedHeap* _g1h;
  73   Mutex*           _m;
  74 
  75   // These are protected by "_m".
  76   CHeapBitMap _coarse_map;
  77   size_t      _n_coarse_entries;
  78   static jint _n_coarsenings;
  79 
  80   PerRegionTable** _fine_grain_regions;
  81   size_t           _n_fine_entries;
  82 
  83   // The fine grain remembered sets are doubly linked together using
  84   // their 'next' and 'prev' fields.
  85   // This allows fast bulk freeing of all the fine grain remembered
  86   // set entries, and fast finding of all of them without iterating
  87   // over the _fine_grain_regions table.
  88   PerRegionTable * _first_all_fine_prts;
  89   PerRegionTable * _last_all_fine_prts;
  90 
  91   // Used to sample a subset of the fine grain PRTs to determine which
  92   // PRT to evict and coarsen.
  93   size_t        _fine_eviction_start;
  94   static size_t _fine_eviction_stride;
  95   static size_t _fine_eviction_sample_size;
  96 
  97   SparsePRT   _sparse_table;
  98 
  99   // These are static after init.
 100   static size_t _max_fine_entries;
 101   static size_t _mod_max_fine_entries_mask;
 102 
 103   // Requires "prt" to be the first element of the bucket list appropriate
 104   // for "hr".  If this list contains an entry for "hr", return it,
 105   // otherwise return "NULL".
 106   PerRegionTable* find_region_table(size_t ind, HeapRegion* hr) const;
 107 
 108   // Find, delete, and return a candidate PerRegionTable, if any exists,
 109   // adding the deleted region to the coarse bitmap.  Requires the caller
 110   // to hold _m, and the fine-grain table to be full.
 111   PerRegionTable* delete_region_table();
 112 
 113   // link/add the given fine grain remembered set into the "all" list
 114   void link_to_all(PerRegionTable * prt);
 115   // unlink/remove the given fine grain remembered set into the "all" list
 116   void unlink_from_all(PerRegionTable * prt);
 117 
 118   bool contains_reference_locked(OopOrNarrowOopStar from) const;
 119 
 120   size_t occ_fine() const;
 121   size_t occ_coarse() const;
 122   size_t occ_sparse() const;
 123 
 124 public:
 125   // Create a new remembered set. The given mutex is used to ensure consistency.
 126   OtherRegionsTable(Mutex* m);
 127 
 128   // Returns the card index of the given within_region pointer relative to the bottom
 129   // of the given heap region.
 130   static CardIdx_t card_within_region(OopOrNarrowOopStar within_region, HeapRegion* hr);
 131   // Adds the reference from "from to this remembered set.
 132   void add_reference(OopOrNarrowOopStar from, uint tid);
 133 
 134   // Returns whether the remembered set contains the given reference.
 135   bool contains_reference(OopOrNarrowOopStar from) const;
 136 
 137   // Returns whether this remembered set (and all sub-sets) have an occupancy
 138   // that is less or equal than the given occupancy.
 139   bool occupancy_less_or_equal_than(size_t limit) const;
 140 
 141   // Returns whether this remembered set (and all sub-sets) does not contain any entry.
 142   bool is_empty() const;
 143 
 144   // Returns the number of cards contained in this remembered set.
 145   size_t occupied() const;
 146 
 147   static jint n_coarsenings() { return _n_coarsenings; }
 148 
 149   // Returns size of the actual remembered set containers in bytes.
 150   size_t mem_size() const;
 151   // Returns the size of static data in bytes.
 152   static size_t static_mem_size();
 153   // Returns the size of the free list content in bytes.
 154   static size_t fl_mem_size();
 155 
 156   // Clear the entire contents of this remembered set.
 157   void clear();
 158 };
 159 
 160 class HeapRegionRemSet : public CHeapObj<mtGC> {
 161   friend class VMStructs;
 162   friend class HeapRegionRemSetIterator;
 163 
 164 private:
 165   G1BlockOffsetTable* _bot;
 166 
 167   // A set of code blobs (nmethods) whose code contains pointers into
 168   // the region that owns this RSet.
 169   G1CodeRootSet _code_roots;
 170 
 171   Mutex _m;
 172 
 173   OtherRegionsTable _other_regions;
 174 
 175   HeapRegion* _hr;
 176 
 177   void clear_fcc();
 178 
 179 public:
 180   HeapRegionRemSet(G1BlockOffsetTable* bot, HeapRegion* hr);
 181 
 182   static void setup_remset_size();
 183 
 184   bool cardset_is_empty() const {
 185     return _other_regions.is_empty();
 186   }
 187 
 188   bool is_empty() const {
 189     return (strong_code_roots_list_length() == 0) && cardset_is_empty();
 190   }
 191 
 192   bool occupancy_less_or_equal_than(size_t occ) const {
 193     return (strong_code_roots_list_length() == 0) && _other_regions.occupancy_less_or_equal_than(occ);
 194   }
 195 
 196   size_t occupied() {
 197     MutexLockerEx x(&_m, Mutex::_no_safepoint_check_flag);
 198     return occupied_locked();
 199   }
 200   size_t occupied_locked() {
 201     return _other_regions.occupied();
 202   }
 203 
 204   static jint n_coarsenings() { return OtherRegionsTable::n_coarsenings(); }
 205 
 206 private:
 207   enum RemSetState {
 208     Untracked,
 209     Updating,
 210     Complete
 211   };
 212 
 213   RemSetState _state;
 214 
 215   static const char* _state_strings[];
 216   static const char* _short_state_strings[];
 217 public:
 218 
 219   const char* get_state_str() const { return _state_strings[_state]; }
 220   const char* get_short_state_str() const { return _short_state_strings[_state]; }
 221 
 222   bool is_tracked() { return _state != Untracked; }
 223   bool is_updating() { return _state == Updating; }
 224   bool is_complete() { return _state == Complete; }
 225 
 226   void set_state_empty() {
 227     guarantee(SafepointSynchronize::is_at_safepoint() || !is_tracked(), "Should only set to Untracked during safepoint but is %s.", get_state_str());
 228     if (_state == Untracked) {
 229       return;
 230     }
 231     clear_fcc();
 232     _state = Untracked;
 233   }
 234 
 235   void set_state_updating() {
 236     guarantee(SafepointSynchronize::is_at_safepoint() && !is_tracked(), "Should only set to Updating from Untracked during safepoint but is %s", get_state_str());
 237     clear_fcc();
 238     _state = Updating;
 239   }
 240 
 241   void set_state_complete() {
 242     clear_fcc();
 243     _state = Complete;
 244   }
 245 
 246   // Used in the sequential case.
 247   void add_reference(OopOrNarrowOopStar from) {
 248     add_reference(from, 0);
 249   }
 250 
 251   // Used in the parallel case.
 252   void add_reference(OopOrNarrowOopStar from, uint tid) {
 253     RemSetState state = _state;
 254     if (state == Untracked) {
 255       return;
 256     }
 257 
 258     uint cur_idx = _hr->hrm_index();
 259     uintptr_t from_card = uintptr_t(from) >> CardTable::card_shift;
 260 
 261     if (G1FromCardCache::contains_or_replace(tid, cur_idx, from_card)) {
 262       assert(contains_reference(from), "We just found " PTR_FORMAT " in the FromCardCache", p2i(from));
 263       return;
 264     }
 265 
 266     _other_regions.add_reference(from, tid);
 267   }
 268 
 269   // The region is being reclaimed; clear its remset, and any mention of
 270   // entries for this region in other remsets.
 271   void clear(bool only_cardset = false);
 272   void clear_locked(bool only_cardset = false);
 273 
 274   // The actual # of bytes this hr_remset takes up.
 275   // Note also includes the strong code root set.
 276   size_t mem_size() {
 277     MutexLockerEx x(&_m, Mutex::_no_safepoint_check_flag);
 278     return _other_regions.mem_size()
 279       // This correction is necessary because the above includes the second
 280       // part.
 281       + (sizeof(HeapRegionRemSet) - sizeof(OtherRegionsTable))
 282       + strong_code_roots_mem_size();
 283   }
 284 
 285   // Returns the memory occupancy of all static data structures associated
 286   // with remembered sets.
 287   static size_t static_mem_size() {
 288     return OtherRegionsTable::static_mem_size() + G1CodeRootSet::static_mem_size();
 289   }
 290 
 291   // Returns the memory occupancy of all free_list data structures associated
 292   // with remembered sets.
 293   static size_t fl_mem_size() {
 294     return OtherRegionsTable::fl_mem_size();
 295   }
 296 
 297   bool contains_reference(OopOrNarrowOopStar from) const {
 298     return _other_regions.contains_reference(from);
 299   }
 300 
 301   // Routines for managing the list of code roots that point into
 302   // the heap region that owns this RSet.
 303   void add_strong_code_root(nmethod* nm);
 304   void add_strong_code_root_locked(nmethod* nm);
 305   void remove_strong_code_root(nmethod* nm);
 306 
 307   // Applies blk->do_code_blob() to each of the entries in
 308   // the strong code roots list
 309   void strong_code_roots_do(CodeBlobClosure* blk) const;
 310 
 311   void clean_strong_code_roots(HeapRegion* hr);
 312 
 313   // Returns the number of elements in the strong code roots list
 314   size_t strong_code_roots_list_length() const {
 315     return _code_roots.length();
 316   }
 317 
 318   // Returns true if the strong code roots contains the given
 319   // nmethod.
 320   bool strong_code_roots_list_contains(nmethod* nm) {
 321     return _code_roots.contains(nm);
 322   }
 323 
 324   // Returns the amount of memory, in bytes, currently
 325   // consumed by the strong code roots.
 326   size_t strong_code_roots_mem_size();
 327 
 328   static void invalidate_from_card_cache(uint start_idx, size_t num_regions) {
 329     G1FromCardCache::invalidate(start_idx, num_regions);
 330   }
 331 
 332 #ifndef PRODUCT
 333   static void print_from_card_cache() {
 334     G1FromCardCache::print();
 335   }
 336 
 337   static void test();
 338 #endif
 339 };
 340 
 341 class HeapRegionRemSetIterator : public StackObj {
 342 private:
 343   // The region RSet over which we are iterating.
 344   HeapRegionRemSet* _hrrs;
 345 
 346   // Local caching of HRRS fields.
 347   const BitMap*             _coarse_map;
 348 
 349   G1BlockOffsetTable*       _bot;
 350   G1CollectedHeap*          _g1h;
 351 
 352   // The number of cards yielded since initialization.
 353   size_t _n_yielded_fine;
 354   size_t _n_yielded_coarse;
 355   size_t _n_yielded_sparse;
 356 
 357   // Indicates what granularity of table that we are currently iterating over.
 358   // We start iterating over the sparse table, progress to the fine grain
 359   // table, and then finish with the coarse table.
 360   enum IterState {
 361     Sparse,
 362     Fine,
 363     Coarse
 364   };
 365   IterState _is;
 366 
 367   // For both Coarse and Fine remembered set iteration this contains the
 368   // first card number of the heap region we currently iterate over.
 369   size_t _cur_region_card_offset;
 370 
 371   // Current region index for the Coarse remembered set iteration.
 372   int    _coarse_cur_region_index;
 373   size_t _coarse_cur_region_cur_card;
 374 
 375   bool coarse_has_next(size_t& card_index);
 376 
 377   // The PRT we are currently iterating over.
 378   PerRegionTable* _fine_cur_prt;
 379   // Card offset within the current PRT.
 380   size_t _cur_card_in_prt;
 381 
 382   // Update internal variables when switching to the given PRT.
 383   void switch_to_prt(PerRegionTable* prt);
 384   bool fine_has_next();
 385   bool fine_has_next(size_t& card_index);
 386 
 387   // The Sparse remembered set iterator.
 388   SparsePRTIter _sparse_iter;
 389 
 390 public:
 391   HeapRegionRemSetIterator(HeapRegionRemSet* hrrs);
 392 
 393   // If there remains one or more cards to be yielded, returns true and
 394   // sets "card_index" to one of those cards (which is then considered
 395   // yielded.)   Otherwise, returns false (and leaves "card_index"
 396   // undefined.)
 397   bool has_next(size_t& card_index);
 398 
 399   size_t n_yielded_fine() { return _n_yielded_fine; }
 400   size_t n_yielded_coarse() { return _n_yielded_coarse; }
 401   size_t n_yielded_sparse() { return _n_yielded_sparse; }
 402   size_t n_yielded() {
 403     return n_yielded_fine() + n_yielded_coarse() + n_yielded_sparse();
 404   }
 405 };
 406 
 407 #endif // SHARE_VM_GC_G1_HEAPREGIONREMSET_HPP