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 // Essentially a wrapper around SparsePRTCleanupTask. See
  46 // sparsePRT.hpp for more details.
  47 class HRRSCleanupTask : public SparsePRTCleanupTask {
  48 };
  49 
  50 // The "_coarse_map" is a bitmap with one bit for each region, where set
  51 // bits indicate that the corresponding region may contain some pointer
  52 // into the owning region.
  53 
  54 // The "_fine_grain_entries" array is an open hash table of PerRegionTables
  55 // (PRTs), indicating regions for which we're keeping the RS as a set of
  56 // cards.  The strategy is to cap the size of the fine-grain table,
  57 // deleting an entry and setting the corresponding coarse-grained bit when
  58 // we would overflow this cap.
  59 
  60 // We use a mixture of locking and lock-free techniques here.  We allow
  61 // threads to locate PRTs without locking, but threads attempting to alter
  62 // a bucket list obtain a lock.  This means that any failing attempt to
  63 // find a PRT must be retried with the lock.  It might seem dangerous that
  64 // a read can find a PRT that is concurrently deleted.  This is all right,
  65 // because:
  66 //
  67 //   1) We only actually free PRT's at safe points (though we reuse them at
  68 //      other times).
  69 //   2) We find PRT's in an attempt to add entries.  If a PRT is deleted,
  70 //      it's _coarse_map bit is set, so the that we were attempting to add
  71 //      is represented.  If a deleted PRT is re-used, a thread adding a bit,
  72 //      thinking the PRT is for a different region, does no harm.
  73 
  74 class OtherRegionsTable {
  75   friend class HeapRegionRemSetIterator;
  76 
  77   G1CollectedHeap* _g1h;
  78   Mutex*           _m;
  79   HeapRegion*      _hr;
  80 
  81   // These are protected by "_m".
  82   CHeapBitMap _coarse_map;
  83   size_t      _n_coarse_entries;
  84   static jint _n_coarsenings;
  85 
  86   PerRegionTable** _fine_grain_regions;
  87   size_t           _n_fine_entries;
  88 
  89   // The fine grain remembered sets are doubly linked together using
  90   // their 'next' and 'prev' fields.
  91   // This allows fast bulk freeing of all the fine grain remembered
  92   // set entries, and fast finding of all of them without iterating
  93   // over the _fine_grain_regions table.
  94   PerRegionTable * _first_all_fine_prts;
  95   PerRegionTable * _last_all_fine_prts;
  96 
  97   // Used to sample a subset of the fine grain PRTs to determine which
  98   // PRT to evict and coarsen.
  99   size_t        _fine_eviction_start;
 100   static size_t _fine_eviction_stride;
 101   static size_t _fine_eviction_sample_size;
 102 
 103   SparsePRT   _sparse_table;
 104 
 105   // These are static after init.
 106   static size_t _max_fine_entries;
 107   static size_t _mod_max_fine_entries_mask;
 108 
 109   // Requires "prt" to be the first element of the bucket list appropriate
 110   // for "hr".  If this list contains an entry for "hr", return it,
 111   // otherwise return "NULL".
 112   PerRegionTable* find_region_table(size_t ind, HeapRegion* hr) const;
 113 
 114   // Find, delete, and return a candidate PerRegionTable, if any exists,
 115   // adding the deleted region to the coarse bitmap.  Requires the caller
 116   // to hold _m, and the fine-grain table to be full.
 117   PerRegionTable* delete_region_table();
 118 
 119   // link/add the given fine grain remembered set into the "all" list
 120   void link_to_all(PerRegionTable * prt);
 121   // unlink/remove the given fine grain remembered set into the "all" list
 122   void unlink_from_all(PerRegionTable * prt);
 123 
 124   bool contains_reference_locked(OopOrNarrowOopStar from) const;
 125 
 126 public:
 127   // Clear the from_card_cache entries for this region.
 128   void clear_fcc();
 129   // Create a new remembered set for the given heap region. The given mutex should
 130   // be used to ensure consistency.
 131   OtherRegionsTable(HeapRegion* hr, Mutex* m);
 132 
 133   // Returns the card index of the given within_region pointer relative to the bottom
 134   // of the given heap region.
 135   static CardIdx_t card_within_region(OopOrNarrowOopStar within_region, HeapRegion* hr);
 136   // Adds the reference from "from to this remembered set.
 137   void add_reference(OopOrNarrowOopStar from, uint tid);
 138 
 139   // Returns whether the remembered set contains the given reference.
 140   bool contains_reference(OopOrNarrowOopStar from) const;
 141 
 142   // Returns whether this remembered set (and all sub-sets) have an occupancy
 143   // that is less or equal than the given occupancy.
 144   bool occupancy_less_or_equal_than(size_t limit) const;
 145 
 146   // Returns whether this remembered set (and all sub-sets) does not contain any entry.
 147   bool is_empty() const;
 148 
 149   // Returns the number of cards contained in this remembered set.
 150   size_t occupied() const;
 151   size_t occ_fine() const;
 152   size_t occ_coarse() const;
 153   size_t occ_sparse() const;
 154 
 155   static jint n_coarsenings() { return _n_coarsenings; }
 156 
 157   // Returns size of the actual remembered set containers in bytes.
 158   size_t mem_size() const;
 159   // Returns the size of static data in bytes.
 160   static size_t static_mem_size();
 161   // Returns the size of the free list content in bytes.
 162   static size_t fl_mem_size();
 163 
 164   // Clear the entire contents of this remembered set.
 165   void clear();
 166 
 167   void do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task);
 168 };
 169 
 170 class HeapRegionRemSet : public CHeapObj<mtGC> {
 171   friend class VMStructs;
 172   friend class HeapRegionRemSetIterator;
 173 
 174 private:
 175   G1BlockOffsetTable* _bot;
 176 
 177   // A set of code blobs (nmethods) whose code contains pointers into
 178   // the region that owns this RSet.
 179   G1CodeRootSet _code_roots;
 180 
 181   Mutex _m;
 182 
 183   OtherRegionsTable _other_regions;
 184 
 185 public:
 186   HeapRegionRemSet(G1BlockOffsetTable* bot, HeapRegion* hr);
 187 
 188   static void setup_remset_size();
 189 
 190   bool is_empty() const {
 191     return (strong_code_roots_list_length() == 0) && _other_regions.is_empty();
 192   }
 193 
 194   bool occupancy_less_or_equal_than(size_t occ) const {
 195     return (strong_code_roots_list_length() == 0) && _other_regions.occupancy_less_or_equal_than(occ);
 196   }
 197 
 198   size_t occupied() {
 199     MutexLockerEx x(&_m, Mutex::_no_safepoint_check_flag);
 200     return occupied_locked();
 201   }
 202   size_t occupied_locked() {
 203     return _other_regions.occupied();
 204   }
 205   size_t occ_fine() const {
 206     return _other_regions.occ_fine();
 207   }
 208   size_t occ_coarse() const {
 209     return _other_regions.occ_coarse();
 210   }
 211   size_t occ_sparse() const {
 212     return _other_regions.occ_sparse();
 213   }
 214 
 215   static jint n_coarsenings() { return OtherRegionsTable::n_coarsenings(); }
 216 
 217 private:
 218   enum RemSetState {
 219     Untracked,
 220     Updating,
 221     Complete
 222   };
 223 
 224   RemSetState _state;
 225 
 226   static const char* _state_strings[];
 227 public:
 228 
 229   const char* get_state_str() const { return _state_strings[_state]; }
 230 
 231   bool is_tracked() { return _state != Untracked; }
 232   bool is_updating() { return _state == Updating; }
 233   bool is_complete() { return _state == Complete; }
 234 
 235   void set_state_empty() {
 236     guarantee(SafepointSynchronize::is_at_safepoint() || !is_tracked(), "Should only set to Untracked during safepoint but is %s.", get_state_str());
 237     if (_state == Untracked) {
 238       return;
 239     }
 240     _other_regions.clear_fcc();
 241     _state = Untracked;
 242   }
 243 
 244   void set_state_updating() {
 245     guarantee(SafepointSynchronize::is_at_safepoint() && !is_tracked(), "Should only set to Updating from Untracked during safepoint but is %s", get_state_str());
 246     _other_regions.clear_fcc();
 247     _state = Updating;
 248   }
 249 
 250   void set_state_complete() {
 251     _other_regions.clear_fcc();
 252     _state = Complete;
 253   }
 254 
 255   // Used in the sequential case.
 256   void add_reference(OopOrNarrowOopStar from) {
 257     add_reference(from, 0);
 258   }
 259 
 260   // Used in the parallel case.
 261   void add_reference(OopOrNarrowOopStar from, uint tid) {
 262     RemSetState state = _state;
 263     if (state == Untracked) {
 264       return;
 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   // Called during a stop-world phase to perform any deferred cleanups.
 329   static void cleanup();
 330 
 331   static void invalidate_from_card_cache(uint start_idx, size_t num_regions) {
 332     G1FromCardCache::invalidate(start_idx, num_regions);
 333   }
 334 
 335 #ifndef PRODUCT
 336   static void print_from_card_cache() {
 337     G1FromCardCache::print();
 338   }
 339 #endif
 340 
 341   // These are wrappers for the similarly-named methods on
 342   // SparsePRT. Look at sparsePRT.hpp for more details.
 343   static void reset_for_cleanup_tasks();
 344   void do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task);
 345   static void finish_cleanup_task(HRRSCleanupTask* hrrs_cleanup_task);
 346 
 347   // Run unit tests.
 348 #ifndef PRODUCT
 349   static void test();
 350 #endif
 351 };
 352 
 353 class HeapRegionRemSetIterator : public StackObj {
 354  private:
 355   // The region RSet over which we are iterating.
 356   HeapRegionRemSet* _hrrs;
 357 
 358   // Local caching of HRRS fields.
 359   const BitMap*             _coarse_map;
 360 
 361   G1BlockOffsetTable*       _bot;
 362   G1CollectedHeap*          _g1h;
 363 
 364   // The number of cards yielded since initialization.
 365   size_t _n_yielded_fine;
 366   size_t _n_yielded_coarse;
 367   size_t _n_yielded_sparse;
 368 
 369   // Indicates what granularity of table that we are currently iterating over.
 370   // We start iterating over the sparse table, progress to the fine grain
 371   // table, and then finish with the coarse table.
 372   enum IterState {
 373     Sparse,
 374     Fine,
 375     Coarse
 376   };
 377   IterState _is;
 378 
 379   // For both Coarse and Fine remembered set iteration this contains the
 380   // first card number of the heap region we currently iterate over.
 381   size_t _cur_region_card_offset;
 382 
 383   // Current region index for the Coarse remembered set iteration.
 384   int    _coarse_cur_region_index;
 385   size_t _coarse_cur_region_cur_card;
 386 
 387   bool coarse_has_next(size_t& card_index);
 388 
 389   // The PRT we are currently iterating over.
 390   PerRegionTable* _fine_cur_prt;
 391   // Card offset within the current PRT.
 392   size_t _cur_card_in_prt;
 393 
 394   // Update internal variables when switching to the given PRT.
 395   void switch_to_prt(PerRegionTable* prt);
 396   bool fine_has_next();
 397   bool fine_has_next(size_t& card_index);
 398 
 399   // The Sparse remembered set iterator.
 400   SparsePRTIter _sparse_iter;
 401 
 402  public:
 403   HeapRegionRemSetIterator(HeapRegionRemSet* hrrs);
 404 
 405   // If there remains one or more cards to be yielded, returns true and
 406   // sets "card_index" to one of those cards (which is then considered
 407   // yielded.)   Otherwise, returns false (and leaves "card_index"
 408   // undefined.)
 409   bool has_next(size_t& card_index);
 410 
 411   size_t n_yielded_fine() { return _n_yielded_fine; }
 412   size_t n_yielded_coarse() { return _n_yielded_coarse; }
 413   size_t n_yielded_sparse() { return _n_yielded_sparse; }
 414   size_t n_yielded() {
 415     return n_yielded_fine() + n_yielded_coarse() + n_yielded_sparse();
 416   }
 417 };
 418 
 419 #endif // SHARE_VM_GC_G1_HEAPREGIONREMSET_HPP