1 /*
   2  * Copyright Amazon.com Inc. 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_SHENANDOAH_SHENANDOAHSCANREMEMBERED_HPP
  26 #define SHARE_GC_SHENANDOAH_SHENANDOAHSCANREMEMBERED_HPP
  27 
  28 // Terminology used within this source file:
  29 //
  30 // Card Entry:   This is the information that identifies whether a
  31 //               particular card-table entry is Clean or Dirty.  A clean
  32 //               card entry denotes that the associated memory does not
  33 //               hold references to young-gen memory.
  34 //
  35 // Card Region, aka
  36 // Card Memory:  This is the region of memory that is assocated with a
  37 //               particular card entry.
  38 //
  39 // Card Cluster: A card cluster represents 64 card entries.  A card
  40 //               cluster is the minimal amount of work performed at a
  41 //               time by a parallel thread.  Note that the work required
  42 //               to scan a card cluster is somewhat variable in that the
  43 //               required effort depends on how many cards are dirty, how
  44 //               many references are held within the objects that span a
  45 //               DIRTY card's memory, and on the size of the object
  46 //               that spans the end of a DIRTY card's memory (because
  47 //               that object, if it's not an array, may need to be scanned in
  48 //               its entirety, when the object is imprecisely dirtied. Imprecise
  49 //               dirtying is when the card corresponding to the object header
  50 //               is dirtied, rather than the card on which the updated field lives).
  51 //               To better balance work amongst them, parallel worker threads dynamically
  52 //               claim clusters and are flexible in the number of clusters they
  53 //               process.
  54 //
  55 // A cluster represents a "natural" quantum of work to be performed by
  56 // a parallel GC thread's background remembered set scanning efforts.
  57 // The notion of cluster is similar to the notion of stripe in the
  58 // implementation of parallel GC card scanning.  However, a cluster is
  59 // typically smaller than a stripe, enabling finer grain division of
  60 // labor between multiple threads, and potentially better load balancing
  61 // when dirty cards are not uniformly distributed in the heap, as is often
  62 // the case with generational workloads where more recently promoted objects
  63 // may be dirtied more frequently that older objects.
  64 //
  65 // For illustration, consider the following possible JVM configurations:
  66 //
  67 //   Scenario 1:
  68 //     RegionSize is 128 MB
  69 //     Span of a card entry is 512 B
  70 //     Each card table entry consumes 1 B
  71 //     Assume one long word (8 B)of the card table represents a cluster.
  72 //       This long word holds 8 card table entries, spanning a
  73 //       total of 8*512 B = 4 KB of the heap
  74 //     The number of clusters per region is 128 MB / 4 KB = 32 K
  75 //
  76 //   Scenario 2:
  77 //     RegionSize is 128 MB
  78 //     Span of each card entry is 128 B
  79 //     Each card table entry consumes 1 bit
  80 //     Assume one int word (4 B) of the card table represents a cluster.
  81 //       This int word holds 32 b/1 b = 32 card table entries, spanning a
  82 //       total of 32 * 128 B = 4 KB of the heap
  83 //     The number of clusters per region is 128 MB / 4 KB = 32 K
  84 //
  85 //   Scenario 3:
  86 //     RegionSize is 128 MB
  87 //     Span of each card entry is 512 B
  88 //     Each card table entry consumes 1 bit
  89 //     Assume one long word (8 B) of card table represents a cluster.
  90 //       This long word holds 64 b/ 1 b = 64 card table entries, spanning a
  91 //       total of 64 * 512 B = 32 KB of the heap
  92 //     The number of clusters per region is 128 MB / 32 KB = 4 K
  93 //
  94 // At the start of a new young-gen concurrent mark pass, the gang of
  95 // Shenandoah worker threads collaborate in performing the following
  96 // actions:
  97 //
  98 //  Let old_regions = number of ShenandoahHeapRegion comprising
  99 //    old-gen memory
 100 //  Let region_size = ShenandoahHeapRegion::region_size_bytes()
 101 //    represent the number of bytes in each region
 102 //  Let clusters_per_region = region_size / 512
 103 //  Let rs represent the ShenandoahDirectCardMarkRememberedSet
 104 //
 105 //  for each ShenandoahHeapRegion old_region in the whole heap
 106 //    determine the cluster number of the first cluster belonging
 107 //      to that region
 108 //    for each cluster contained within that region
 109 //      Assure that exactly one worker thread processes each
 110 //      cluster, each thread making a series of invocations of the
 111 //      following:
 112 //
 113 //        rs->process_clusters(worker_id, ReferenceProcessor *,
 114 //                             ShenandoahConcurrentMark *, cluster_no, cluster_count,
 115 //                             HeapWord *end_of_range, OopClosure *oops);
 116 //
 117 //  For efficiency, divide up the clusters so that different threads
 118 //  are responsible for processing different clusters.  Processing costs
 119 //  may vary greatly between clusters for the following reasons:
 120 //
 121 //        a) some clusters contain mostly dirty cards and other
 122 //           clusters contain mostly clean cards
 123 //        b) some clusters contain mostly primitive data and other
 124 //           clusters contain mostly reference data
 125 //        c) some clusters are spanned by very large non-array objects that
 126 //           begin in some other cluster.  When a large non-array object
 127 //           beginning in a preceding cluster spans large portions of
 128 //           this cluster, then because of imprecise dirtying, the
 129 //           portion of the object in this cluster may be clean, but
 130 //           will need to be processed by the worker responsible for
 131 //           this cluster, potentially increasing its work.
 132 //        d) in the case that the end of this cluster is spanned by a
 133 //           very large non-array object, the worker for this cluster will
 134 //           be responsible for processing the portion of the object
 135 //           in this cluster.
 136 //
 137 // Though an initial division of labor between marking threads may
 138 // assign equal numbers of clusters to be scanned by each thread, it
 139 // should be expected that some threads will finish their assigned
 140 // work before others.  Therefore, some amount of the full remembered
 141 // set scanning effort should be held back and assigned incrementally
 142 // to the threads that end up with excess capacity.  Consider the
 143 // following strategy for dividing labor:
 144 //
 145 //        1. Assume there are 8 marking threads and 1024 remembered
 146 //           set clusters to be scanned.
 147 //        2. Assign each thread to scan 64 clusters.  This leaves
 148 //           512 (1024 - (8*64)) clusters to still be scanned.
 149 //        3. As the 8 server threads complete previous cluster
 150 //           scanning assignments, issue each of the next 8 scanning
 151 //           assignments as units of 32 additional cluster each.
 152 //           In the case that there is high variance in effort
 153 //           associated with previous cluster scanning assignments,
 154 //           multiples of these next assignments may be serviced by
 155 //           the server threads that were previously assigned lighter
 156 //           workloads.
 157 //        4. Make subsequent scanning assignments as follows:
 158 //             a) 8 assignments of size 16 clusters
 159 //             b) 8 assignments of size 8 clusters
 160 //             c) 16 assignments of size 4 clusters
 161 //
 162 //    When there is no more remembered set processing work to be
 163 //    assigned to a newly idled worker thread, that thread can move
 164 //    on to work on other tasks associated with root scanning until such
 165 //    time as all clusters have been examined.
 166 //
 167 // Remembered set scanning is designed to run concurrently with
 168 // mutator threads, with multiple concurrent workers. Furthermore, the
 169 // current implementation of remembered set scanning never clears a
 170 // card once it has been marked.
 171 //
 172 // These limitations will be addressed in future enhancements to the
 173 // existing implementation.
 174 
 175 #include "gc/shared/workerThread.hpp"
 176 #include "gc/shenandoah/shenandoahCardStats.hpp"
 177 #include "gc/shenandoah/shenandoahCardTable.hpp"
 178 #include "gc/shenandoah/shenandoahNumberSeq.hpp"
 179 #include "gc/shenandoah/shenandoahTaskqueue.hpp"
 180 #include "memory/iterator.hpp"
 181 #include "utilities/globalDefinitions.hpp"
 182 
 183 class ShenandoahReferenceProcessor;
 184 class ShenandoahConcurrentMark;
 185 class ShenandoahHeap;
 186 class ShenandoahHeapRegion;
 187 class ShenandoahRegionIterator;
 188 class ShenandoahMarkingContext;
 189 
 190 class CardTable;
 191 typedef CardTable::CardValue CardValue;
 192 
 193 class ShenandoahDirectCardMarkRememberedSet: public CHeapObj<mtGC> {
 194 
 195 private:
 196 
 197   // Use symbolic constants defined in cardTable.hpp
 198   //  CardTable::card_shift = 9;
 199   //  CardTable::card_size = 512;
 200   //  CardTable::card_size_in_words = 64;
 201   //  CardTable::clean_card_val()
 202   //  CardTable::dirty_card_val()
 203 
 204   const size_t LogCardValsPerIntPtr;    // the number of card values (entries) in an intptr_t
 205   const size_t LogCardSizeInWords;      // the size of a card in heap word units
 206 
 207   ShenandoahHeap* _heap;
 208   ShenandoahCardTable* _card_table;
 209   size_t _card_shift;
 210   size_t _total_card_count;
 211   HeapWord* _whole_heap_base;   // Points to first HeapWord of data contained within heap memory
 212   CardValue* _byte_map;         // Points to first entry within the card table
 213   CardValue* _byte_map_base;    // Points to byte_map minus the bias computed from address of heap memory
 214 
 215 public:
 216 
 217   // count is the number of cards represented by the card table.
 218   ShenandoahDirectCardMarkRememberedSet(ShenandoahCardTable* card_table, size_t total_card_count);
 219 
 220   // Card index is zero-based relative to _byte_map.
 221   size_t last_valid_index() const;
 222   size_t total_cards() const;
 223   size_t card_index_for_addr(HeapWord* p) const;
 224   HeapWord* addr_for_card_index(size_t card_index) const;
 225   inline const CardValue* get_card_table_byte_map(bool use_write_table) const {
 226     return use_write_table ? _card_table->write_byte_map() : _card_table->read_byte_map();
 227   }
 228 
 229   inline bool is_card_dirty(size_t card_index) const;
 230   inline bool is_write_card_dirty(size_t card_index) const;
 231   inline void mark_card_as_dirty(size_t card_index);
 232   inline void mark_range_as_dirty(size_t card_index, size_t num_cards);
 233   inline void mark_card_as_clean(size_t card_index);
 234   inline void mark_range_as_clean(size_t card_index, size_t num_cards);
 235   inline bool is_card_dirty(HeapWord* p) const;
 236   inline bool is_write_card_dirty(HeapWord* p) const;
 237   inline void mark_card_as_dirty(HeapWord* p);
 238   inline void mark_range_as_dirty(HeapWord* p, size_t num_heap_words);
 239   inline void mark_card_as_clean(HeapWord* p);
 240   inline void mark_range_as_clean(HeapWord* p, size_t num_heap_words);
 241 
 242   // Merge any dirty values from write table into the read table, while leaving
 243   // the write table unchanged.
 244   void merge_write_table(HeapWord* start, size_t word_count);
 245 
 246   // Destructively copy the write table to the read table, and clean the write table.
 247   void reset_remset(HeapWord* start, size_t word_count);
 248 };
 249 
 250 // A ShenandoahCardCluster represents the minimal unit of work
 251 // performed by independent parallel GC threads during scanning of
 252 // remembered sets.
 253 //
 254 // The GC threads that perform card-table remembered set scanning may
 255 // overwrite card-table entries to mark them as clean in the case that
 256 // the associated memory no longer holds references to young-gen
 257 // memory.  Rather than access the card-table entries directly, all GC
 258 // thread access to card-table information is made by way of the
 259 // ShenandoahCardCluster data abstraction.  This abstraction
 260 // effectively manages access to multiple possible underlying
 261 // remembered set implementations, including a traditional card-table
 262 // approach and a SATB-based approach.
 263 //
 264 // The API services represent a compromise between efficiency and
 265 // convenience.
 266 //
 267 // Multiple GC threads that scan the remembered set
 268 // in parallel.  The desire is to divide the complete scanning effort
 269 // into multiple clusters of work that can be independently processed
 270 // by individual threads without need for synchronizing efforts
 271 // between the work performed by each task.  The term "cluster" of
 272 // work is similar to the term "stripe" as used in the implementation
 273 // of Parallel GC.
 274 //
 275 // Complexity arises when an object to be scanned crosses the boundary
 276 // between adjacent cluster regions.  Here is the protocol that we currently
 277 // follow:
 278 //
 279 //  1. The thread responsible for scanning the cards in a cluster modifies
 280 //     the associated card-table entries. Only cards that are dirty are
 281 //     processed, except as described below for the case of objects that
 282 //     straddle more than one card.
 283 //  2. Object Arrays are precisely dirtied, so only the portion of the obj-array
 284 //     that overlaps the range of dirty cards in its cluster are scanned
 285 //     by each worker thread. This holds for portions of obj-arrays that extend
 286 //     over clusters processed by different workers, with each worked responsible
 287 //     for scanning the portion of the obj-array overlapping the dirty cards in
 288 //     its cluster.
 289 //  3. Non-array objects are precisely dirtied by the interpreter and the compilers
 290 //     For such objects that extend over multiple cards, or even multiple clusters,
 291 //     the entire object is scanned by the worker that processes the (dirty) card on
 292 //     which the object's header lies. (However, GC workers should precisely dirty the
 293 //     cards with inter-regional/inter-generational pointers in the body of this object,
 294 //     thus making subsequent scans potentially less expensive.) Such larger non-array
 295 //     objects are relatively rare.
 296 //
 297 //  A possible criticism:
 298 //  C. The representation of pointer location descriptive information
 299 //     within Klass representations is not designed for efficient
 300 //     "random access".  An alternative approach to this design would
 301 //     be to scan very large objects multiple times, once for each
 302 //     cluster that is spanned by the object's range.  This reduces
 303 //     unnecessary overscan, but it introduces different sorts of
 304 //     overhead effort:
 305 //       i) For each spanned cluster, we have to look up the start of
 306 //          the crossing object.
 307 //      ii) Each time we scan the very large object, we have to
 308 //          sequentially walk through its pointer location
 309 //          descriptors, skipping over all of the pointers that
 310 //          precede the start of the range of addresses that we
 311 //          consider relevant.
 312 
 313 
 314 // Because old-gen heap memory is not necessarily contiguous, and
 315 // because cards are not necessarily maintained for young-gen memory,
 316 // consecutive card numbers do not necessarily correspond to consecutive
 317 // address ranges.  For the traditional direct-card-marking
 318 // implementation of this interface, consecutive card numbers are
 319 // likely to correspond to contiguous regions of memory, but this
 320 // should not be assumed.  Instead, rely only upon the following:
 321 //
 322 //  1. All card numbers for cards pertaining to the same
 323 //     ShenandoahHeapRegion are consecutively numbered.
 324 //  2. In the case that neighboring ShenandoahHeapRegions both
 325 //     represent old-gen memory, the card regions that span the
 326 //     boundary between these neighboring heap regions will be
 327 //     consecutively numbered.
 328 //  3. (A corollary) In the case that an old-gen object straddles the
 329 //     boundary between two heap regions, the card regions that
 330 //     correspond to the span of this object will be consecutively
 331 //     numbered.
 332 //
 333 // ShenandoahCardCluster abstracts access to the remembered set
 334 // and also keeps track of crossing map information to allow efficient
 335 // resolution of object start addresses.
 336 //
 337 // ShenandoahCardCluster supports all of the services of
 338 // DirectCardMarkRememberedSet, plus it supports register_object() and lookup_object().
 339 // Note that we only need to register the start addresses of the object that
 340 // overlays the first address of a card; we need to do this for every card.
 341 // In other words, register_object() checks if the object crosses a card boundary,
 342 // and updates the offset value for each card that the object crosses into.
 343 // For objects that don't straddle cards, nothing needs to be done.
 344 //
 345 class ShenandoahCardCluster: public CHeapObj<mtGC> {
 346 
 347 private:
 348   ShenandoahDirectCardMarkRememberedSet* _rs;
 349 
 350 public:
 351   static const size_t CardsPerCluster = 64;
 352 
 353 private:
 354   typedef struct cross_map { uint8_t first; uint8_t last; } xmap;
 355   typedef union crossing_info { uint16_t short_word; xmap offsets; } crossing_info;
 356 
 357   // ObjectStartsInCardRegion bit is set within a crossing_info.offsets.start iff at least one object starts within
 358   // a particular card region.  We pack this bit into start byte under assumption that start byte is accessed less
 359   // frequently than last byte.  This is true when number of clean cards is greater than number of dirty cards.
 360   static const uint8_t ObjectStartsInCardRegion = 0x80;
 361   static const uint8_t FirstStartBits           = 0x7f;
 362 
 363   // Check that we have enough bits to store the largest possible offset into a card for an object start.
 364   // The value for maximum card size is based on the constraints for GCCardSizeInBytes in gc_globals.hpp.
 365   static const int MaxCardSize = NOT_LP64(512) LP64_ONLY(1024);
 366   STATIC_ASSERT((MaxCardSize / HeapWordSize) - 1 <= FirstStartBits);
 367 
 368   crossing_info* _object_starts;
 369 
 370 public:
 371   // If we're setting first_start, assume the card has an object.
 372   inline void set_first_start(size_t card_index, uint8_t value) {
 373     _object_starts[card_index].offsets.first = ObjectStartsInCardRegion | value;
 374   }
 375 
 376   inline void set_last_start(size_t card_index, uint8_t value) {
 377     _object_starts[card_index].offsets.last = value;
 378   }
 379 
 380   inline void set_starts_object_bit(size_t card_index) {
 381     _object_starts[card_index].offsets.first |= ObjectStartsInCardRegion;
 382   }
 383 
 384   inline void clear_starts_object_bit(size_t card_index) {
 385     _object_starts[card_index].offsets.first &= ~ObjectStartsInCardRegion;
 386   }
 387 
 388   // Returns true iff an object is known to start within the card memory associated with card card_index.
 389   inline bool starts_object(size_t card_index) const {
 390     return (_object_starts[card_index].offsets.first & ObjectStartsInCardRegion) != 0;
 391   }
 392 
 393   inline void clear_objects_in_range(HeapWord* addr, size_t num_words) {
 394     size_t card_index = _rs->card_index_for_addr(addr);
 395     size_t last_card_index = _rs->card_index_for_addr(addr + num_words - 1);
 396     while (card_index <= last_card_index)
 397       _object_starts[card_index++].short_word = 0;
 398   }
 399 
 400   ShenandoahCardCluster(ShenandoahDirectCardMarkRememberedSet* rs) {
 401     _rs = rs;
 402     _object_starts = NEW_C_HEAP_ARRAY(crossing_info, rs->total_cards(), mtGC);
 403     for (size_t i = 0; i < rs->total_cards(); i++) {
 404       _object_starts[i].short_word = 0;
 405     }
 406   }
 407 
 408   ~ShenandoahCardCluster() {
 409     FREE_C_HEAP_ARRAY(crossing_info, _object_starts);
 410     _object_starts = nullptr;
 411   }
 412 
 413   // There is one entry within the object_starts array for each card entry.
 414   //
 415   //  Suppose multiple garbage objects are coalesced during GC sweep
 416   //  into a single larger "free segment".  As each two objects are
 417   //  coalesced together, the start information pertaining to the second
 418   //  object must be removed from the objects_starts array.  If the
 419   //  second object had been the first object within card memory,
 420   //  the new first object is the object that follows that object if
 421   //  that starts within the same card memory, or NoObject if the
 422   //  following object starts within the following cluster.  If the
 423   //  second object had been the last object in the card memory,
 424   //  replace this entry with the newly coalesced object if it starts
 425   //  within the same card memory, or with NoObject if it starts in a
 426   //  preceding card's memory.
 427   //
 428   //  Suppose a large free segment is divided into a smaller free
 429   //  segment and a new object.  The second part of the newly divided
 430   //  memory must be registered as a new object, overwriting at most
 431   //  one first_start and one last_start entry.  Note that one of the
 432   //  newly divided two objects might be a new GCLAB.
 433   //
 434   //  Suppose postprocessing of a GCLAB finds that the original GCLAB
 435   //  has been divided into N objects.  Each of the N newly allocated
 436   //  objects will be registered, overwriting at most one first_start
 437   //  and one last_start entries.
 438   //
 439   //  No object registration operations are linear in the length of
 440   //  the registered objects.
 441   //
 442   // Consider further the following observations regarding object
 443   // registration costs:
 444   //
 445   //   1. The cost is paid once for each old-gen object (Except when
 446   //      an object is demoted and repromoted, in which case we would
 447   //      pay the cost again).
 448   //   2. The cost can be deferred so that there is no urgency during
 449   //      mutator copy-on-first-access promotion.  Background GC
 450   //      threads will update the object_starts array by post-
 451   //      processing the contents of retired PLAB buffers.
 452   //   3. The bet is that these costs are paid relatively rarely
 453   //      because:
 454   //      a) Most objects die young and objects that die in young-gen
 455   //         memory never need to be registered with the object_starts
 456   //         array.
 457   //      b) Most objects that are promoted into old-gen memory live
 458   //         there without further relocation for a relatively long
 459   //         time, so we get a lot of benefit from each investment
 460   //         in registering an object.
 461 
 462 public:
 463 
 464   // The starting locations of objects contained within old-gen memory
 465   // are registered as part of the remembered set implementation.  This
 466   // information is required when scanning dirty card regions that are
 467   // spanned by objects beginning within preceding card regions.  It
 468   // is necessary to find the first and last objects that begin within
 469   // this card region.  Starting addresses of objects are required to
 470   // find the object headers, and object headers provide information
 471   // about which fields within the object hold addresses.
 472   //
 473   // The old-gen memory allocator invokes register_object() for any
 474   // object that is allocated within old-gen memory.  This identifies
 475   // the starting addresses of objects that span boundaries between
 476   // card regions.
 477   //
 478   // It is not necessary to invoke register_object at the very instant
 479   // an object is allocated.  It is only necessary to invoke it
 480   // prior to the next start of a garbage collection concurrent mark
 481   // or concurrent update-references phase.  An "ideal" time to register
 482   // objects is during post-processing of a GCLAB after the GCLAB is
 483   // retired due to depletion of its memory.
 484   //
 485   // register_object() does not perform synchronization.  In the case
 486   // that multiple threads are registering objects whose starting
 487   // addresses are within the same cluster, races between these
 488   // threads may result in corruption of the object-start data
 489   // structures.  Parallel GC threads should avoid registering objects
 490   // residing within the same cluster by adhering to the following
 491   // coordination protocols:
 492   //
 493   //  1. Align thread-local GCLAB buffers with some TBD multiple of
 494   //     card clusters.  The card cluster size is 32 KB.  If the
 495   //     desired GCLAB size is 128 KB, align the buffer on a multiple
 496   //     of 4 card clusters.
 497   //  2. Post-process the contents of GCLAB buffers to register the
 498   //     objects allocated therein.  Allow one GC thread at a
 499   //     time to do the post-processing of each GCLAB.
 500   //  3. Since only one GC thread at a time is registering objects
 501   //     belonging to a particular allocation buffer, no locking
 502   //     is performed when registering these objects.
 503   //  4. Any remnant of unallocated memory within an expended GC
 504   //     allocation buffer is not returned to the old-gen allocation
 505   //     pool until after the GC allocation buffer has been post
 506   //     processed.  Before any remnant memory is returned to the
 507   //     old-gen allocation pool, the GC thread that scanned this GC
 508   //     allocation buffer performs a write-commit memory barrier.
 509   //  5. Background GC threads that perform tenuring of young-gen
 510   //     objects without a GCLAB use a CAS lock before registering
 511   //     each tenured object.  The CAS lock assures both mutual
 512   //     exclusion and memory coherency/visibility.  Note that an
 513   //     object tenured by a background GC thread will not overlap
 514   //     with any of the clusters that are receiving tenured objects
 515   //     by way of GCLAB buffers.  Multiple independent GC threads may
 516   //     attempt to tenure objects into a shared cluster.  This is why
 517   //     sychronization may be necessary.  Consider the following
 518   //     scenarios:
 519   //
 520   //     a) If two objects are tenured into the same card region, each
 521   //        registration may attempt to modify the first-start or
 522   //        last-start information associated with that card region.
 523   //        Furthermore, because the representations of first-start
 524   //        and last-start information within the object_starts array
 525   //        entry uses different bits of a shared uint_16 to represent
 526   //        each, it is necessary to lock the entire card entry
 527   //        before modifying either the first-start or last-start
 528   //        information within the entry.
 529   //     b) Suppose GC thread X promotes a tenured object into
 530   //        card region A and this tenured object spans into
 531   //        neighboring card region B.  Suppose GC thread Y (not equal
 532   //        to X) promotes a tenured object into cluster B.  GC thread X
 533   //        will update the object_starts information for card A.  No
 534   //        synchronization is required.
 535   //     c) In summary, when background GC threads register objects
 536   //        newly tenured into old-gen memory, they must acquire a
 537   //        mutual exclusion lock on the card that holds the starting
 538   //        address of the newly tenured object.  This can be achieved
 539   //        by using a CAS instruction to assure that the previous
 540   //        values of first-offset and last-offset have not been
 541   //        changed since the same thread inquired as to their most
 542   //        current values.
 543   //
 544   //     One way to minimize the need for synchronization between
 545   //     background tenuring GC threads is for each tenuring GC thread
 546   //     to promote young-gen objects into distinct dedicated cluster
 547   //     ranges.
 548   //  6. The object_starts information is only required during the
 549   //     starting of concurrent marking and concurrent evacuation
 550   //     phases of GC.  Before we start either of these GC phases, the
 551   //     JVM enters a safe point and all GC threads perform
 552   //     commit-write barriers to assure that access to the
 553   //     object_starts information is coherent.
 554 
 555 
 556   // Notes on synchronization of register_object():
 557   //
 558   //  1. For efficiency, there is no locking in the implementation of register_object()
 559   //  2. Thus, it is required that users of this service assure that concurrent/parallel invocations of
 560   //     register_object() do pertain to the same card's memory range.  See discussion below to understand
 561   //     the risks.
 562   //  3. When allocating from a TLAB or GCLAB, the mutual exclusion can be guaranteed by assuring that each
 563   //     LAB's start and end are aligned on card memory boundaries.
 564   //  4. Use the same lock that guarantees exclusivity when performing free-list allocation within heap regions.
 565   //
 566   // Register the newly allocated object while we're holding the global lock since there's no synchronization
 567   // built in to the implementation of register_object().  There are potential races when multiple independent
 568   // threads are allocating objects, some of which might span the same card region.  For example, consider
 569   // a card table's memory region within which three objects are being allocated by three different threads:
 570   //
 571   // objects being "concurrently" allocated:
 572   //    [-----a------][-----b-----][--------------c------------------]
 573   //            [---- card table memory range --------------]
 574   //
 575   // Before any objects are allocated, this card's memory range holds no objects.  Note that:
 576   //   allocation of object a wants to set the has-object, first-start, and last-start attributes of the preceding card region.
 577   //   allocation of object b wants to set the has-object, first-start, and last-start attributes of this card region.
 578   //   allocation of object c also wants to set the has-object, first-start, and last-start attributes of this card region.
 579   //
 580   // The thread allocating b and the thread allocating c can "race" in various ways, resulting in confusion, such as last-start
 581   // representing object b while first-start represents object c.  This is why we need to require all register_object()
 582   // invocations associated with objects that are allocated from "free lists" to provide their own mutual exclusion locking
 583   // mechanism.
 584 
 585   // Reset the starts_object() information to false for all cards in the range between from and to.
 586   void reset_object_range(HeapWord* from, HeapWord* to);
 587 
 588   // register_object() requires that the caller hold the heap lock
 589   // before calling it.
 590   void register_object(HeapWord* address);
 591 
 592   // register_object_without_lock() does not require that the caller hold
 593   // the heap lock before calling it, under the assumption that the
 594   // caller has assured no other thread will endeavor to concurrently
 595   // register objects that start within the same card's memory region
 596   // as address.
 597   void register_object_without_lock(HeapWord* address);
 598 
 599   // During the reference updates phase of GC, we walk through each old-gen memory region that was
 600   // not part of the collection set and we invalidate all unmarked objects.  As part of this effort,
 601   // we coalesce neighboring dead objects in order to make future remembered set scanning more
 602   // efficient (since future remembered set scanning of any card region containing consecutive
 603   // dead objects can skip over all of them at once by reading only a single dead object header
 604   // instead of having to read the header of each of the coalesced dead objects.
 605   //
 606   // At some future time, we may implement a further optimization: satisfy future allocation requests
 607   // by carving new objects out of the range of memory that represents the coalesced dead objects.
 608   //
 609   // Suppose we want to combine several dead objects into a single coalesced object.  How does this
 610   // impact our representation of crossing map information?
 611   //  1. If the newly coalesced range is contained entirely within a card range, that card's last
 612   //     start entry either remains the same or it is changed to the start of the coalesced region.
 613   //  2. For the card that holds the start of the coalesced object, it will not impact the first start
 614   //     but it may impact the last start.
 615   //  3. For following cards spanned entirely by the newly coalesced object, it will change starts_object
 616   //     to false (and make first-start and last-start "undefined").
 617   //  4. For a following card that is spanned patially by the newly coalesced object, it may change
 618   //     first-start value, but it will not change the last-start value.
 619   //
 620   // The range of addresses represented by the arguments to coalesce_objects() must represent a range
 621   // of memory that was previously occupied exactly by one or more previously registered objects.  For
 622   // convenience, it is legal to invoke coalesce_objects() with arguments that span a single previously
 623   // registered object.
 624   //
 625   // The role of coalesce_objects is to change the crossing map information associated with all of the coalesced
 626   // objects.
 627   void coalesce_objects(HeapWord* address, size_t length_in_words);
 628 
 629   // The typical use case is going to look something like this:
 630   //   for each heapregion that comprises old-gen memory
 631   //     for each card number that corresponds to this heap region
 632   //       scan the objects contained therein if the card is dirty
 633   // To avoid excessive lookups in a sparse array, the API queries
 634   // the card number pertaining to a particular address and then uses the
 635   // card number for subsequent information lookups and stores.
 636 
 637   // If starts_object(card_index), this returns the word offset within this card
 638   // memory at which the first object begins.  If !starts_object(card_index), the
 639   // result is a don't care value -- asserts in a debug build.
 640   size_t get_first_start(size_t card_index) const;
 641 
 642   // If starts_object(card_index), this returns the word offset within this card
 643   // memory at which the last object begins.  If !starts_object(card_index), the
 644   // result is a don't care value.
 645   size_t get_last_start(size_t card_index) const;
 646 
 647 
 648   // Given a card_index, return the starting address of the first block in the heap
 649   // that straddles into the card. If the card is co-initial with an object, then
 650   // this would return the starting address of the heap that this card covers.
 651   // Expects to be called for a card affiliated with the old generation in
 652   // generational mode.
 653   HeapWord* block_start(size_t card_index) const;
 654 };
 655 
 656 // ShenandoahScanRemembered is a concrete class representing the
 657 // ability to scan the old-gen remembered set for references to
 658 // objects residing in young-gen memory.
 659 //
 660 // Scanning normally begins with an invocation of numRegions and ends
 661 // after all clusters of all regions have been scanned.
 662 //
 663 // Throughout the scanning effort, the number of regions does not
 664 // change.
 665 //
 666 // Even though the regions that comprise old-gen memory are not
 667 // necessarily contiguous, the abstraction represented by this class
 668 // identifies each of the old-gen regions with an integer value
 669 // in the range from 0 to (numRegions() - 1) inclusive.
 670 //
 671 
 672 class ShenandoahScanRemembered: public CHeapObj<mtGC> {
 673 
 674 private:
 675   ShenandoahDirectCardMarkRememberedSet* _rs;
 676   ShenandoahCardCluster* _scc;
 677 
 678   // Global card stats (cumulative)
 679   HdrSeq _card_stats_scan_rs[MAX_CARD_STAT_TYPE];
 680   HdrSeq _card_stats_update_refs[MAX_CARD_STAT_TYPE];
 681   // Per worker card stats (multiplexed by phase)
 682   HdrSeq** _card_stats;
 683 
 684   // The types of card metrics that we gather
 685   const char* _card_stats_name[MAX_CARD_STAT_TYPE] = {
 686    "dirty_run", "clean_run",
 687    "dirty_cards", "clean_cards",
 688    "max_dirty_run", "max_clean_run",
 689    "dirty_scan_objs",
 690    "alternations"
 691   };
 692 
 693   // The statistics are collected and logged separately for
 694   // card-scans for initial marking, and for updating refs.
 695   const char* _card_stat_log_type[MAX_CARD_STAT_LOG_TYPE] = {
 696    "Scan Remembered Set", "Update Refs"
 697   };
 698 
 699   int _card_stats_log_counter[2] = {0, 0};
 700 
 701 public:
 702   ShenandoahScanRemembered(ShenandoahDirectCardMarkRememberedSet* rs) {
 703     _rs = rs;
 704     _scc = new ShenandoahCardCluster(rs);
 705 
 706     // We allocate ParallelGCThreads worth even though we usually only
 707     // use up to ConcGCThreads, because degenerate collections may employ
 708     // ParallelGCThreads for remembered set scanning.
 709     if (ShenandoahEnableCardStats) {
 710       _card_stats = NEW_C_HEAP_ARRAY(HdrSeq*, ParallelGCThreads, mtGC);
 711       for (uint i = 0; i < ParallelGCThreads; i++) {
 712         _card_stats[i] = new HdrSeq[MAX_CARD_STAT_TYPE];
 713       }
 714     } else {
 715       _card_stats = nullptr;
 716     }
 717   }
 718 
 719   ~ShenandoahScanRemembered() {
 720     delete _scc;
 721     if (ShenandoahEnableCardStats) {
 722       for (uint i = 0; i < ParallelGCThreads; i++) {
 723         delete _card_stats[i];
 724       }
 725       FREE_C_HEAP_ARRAY(HdrSeq*, _card_stats);
 726       _card_stats = nullptr;
 727     }
 728     assert(_card_stats == nullptr, "Error");
 729   }
 730 
 731   HdrSeq* card_stats(uint worker_id) {
 732     assert(worker_id < ParallelGCThreads, "Error");
 733     assert(ShenandoahEnableCardStats == (_card_stats != nullptr), "Error");
 734     return ShenandoahEnableCardStats ? _card_stats[worker_id] : nullptr;
 735   }
 736 
 737   HdrSeq* card_stats_for_phase(CardStatLogType t) {
 738     switch (t) {
 739       case CARD_STAT_SCAN_RS:
 740         return _card_stats_scan_rs;
 741       case CARD_STAT_UPDATE_REFS:
 742         return _card_stats_update_refs;
 743       default:
 744         guarantee(false, "No such CardStatLogType");
 745     }
 746     return nullptr; // Quiet compiler
 747   }
 748 
 749   // Card index is zero-based relative to first spanned card region.
 750   size_t card_index_for_addr(HeapWord* p);
 751   HeapWord* addr_for_card_index(size_t card_index);
 752   bool is_card_dirty(size_t card_index);
 753   bool is_write_card_dirty(size_t card_index);
 754   bool is_card_dirty(HeapWord* p);
 755   bool is_write_card_dirty(HeapWord* p);
 756   void mark_card_as_dirty(HeapWord* p);
 757   void mark_range_as_dirty(HeapWord* p, size_t num_heap_words);
 758   void mark_card_as_clean(HeapWord* p);
 759   void mark_range_as_clean(HeapWord* p, size_t num_heap_words);
 760 
 761   void reset_remset(HeapWord* start, size_t word_count) { _rs->reset_remset(start, word_count); }
 762 
 763   void merge_write_table(HeapWord* start, size_t word_count) { _rs->merge_write_table(start, word_count); }
 764 
 765   size_t cluster_for_addr(HeapWord* addr);
 766   HeapWord* addr_for_cluster(size_t cluster_no);
 767 
 768   void reset_object_range(HeapWord* from, HeapWord* to);
 769   void register_object(HeapWord* addr);
 770   void register_object_without_lock(HeapWord* addr);
 771   void coalesce_objects(HeapWord* addr, size_t length_in_words);
 772 
 773   HeapWord* first_object_in_card(size_t card_index) {
 774     if (_scc->starts_object(card_index)) {
 775       return addr_for_card_index(card_index) + _scc->get_first_start(card_index);
 776     } else {
 777       return nullptr;
 778     }
 779   }
 780 
 781   // Return true iff this object is "properly" registered.
 782   bool verify_registration(HeapWord* address, ShenandoahMarkingContext* ctx);
 783 
 784   // clear the cards to clean, and clear the object_starts info to no objects
 785   void mark_range_as_empty(HeapWord* addr, size_t length_in_words);
 786 
 787   // process_clusters() scans a portion of the remembered set
 788   // for references from old gen into young. Several worker threads
 789   // scan different portions of the remembered set by making parallel invocations
 790   // of process_clusters() with each invocation scanning different
 791   // "clusters" of the remembered set.
 792   //
 793   // An invocation of process_clusters() examines all of the
 794   // intergenerational references spanned by `count` clusters starting
 795   // with `first_cluster`.  The `oops` argument is a worker-thread-local
 796   // OopClosure that is applied to all "valid" references in the remembered set.
 797   //
 798   // A side-effect of executing process_clusters() is to update the remembered
 799   // set entries (e.g. marking dirty cards clean if they no longer
 800   // hold references to young-gen memory).
 801   //
 802   // An implementation of process_clusters() may choose to efficiently
 803   // address more typical scenarios in the structure of remembered sets. E.g.
 804   // in the generational setting, one might expect remembered sets to be very sparse
 805   // (low mutation rates in the old generation leading to sparse dirty cards,
 806   // each with very few intergenerational pointers). Specific implementations
 807   // may choose to degrade gracefully as the sparsity assumption fails to hold,
 808   // such as when there are sudden spikes in (premature) promotion or in the
 809   // case of an underprovisioned, poorly-tuned, or poorly-shaped heap.
 810   //
 811   // At the start of a concurrent young generation marking cycle, we invoke process_clusters
 812   // with ClosureType ShenandoahInitMarkRootsClosure.
 813   //
 814   // At the start of a concurrent evacuation phase, we invoke process_clusters with
 815   // ClosureType ShenandoahEvacuateUpdateRootsClosure.
 816 
 817   template <typename ClosureType>
 818   void process_clusters(size_t first_cluster, size_t count, HeapWord* end_of_range, ClosureType* oops,
 819                         bool use_write_table, uint worker_id);
 820 
 821   template <typename ClosureType>
 822   void process_humongous_clusters(ShenandoahHeapRegion* r, size_t first_cluster, size_t count,
 823                                   HeapWord* end_of_range, ClosureType* oops, bool use_write_table);
 824 
 825   template <typename ClosureType>
 826   void process_region_slice(ShenandoahHeapRegion* region, size_t offset, size_t clusters, HeapWord* end_of_range,
 827                             ClosureType* cl, bool use_write_table, uint worker_id);
 828 
 829   // To Do:
 830   //  Create subclasses of ShenandoahInitMarkRootsClosure and
 831   //  ShenandoahEvacuateUpdateRootsClosure and any other closures
 832   //  that need to participate in remembered set scanning.  Within the
 833   //  subclasses, add a (probably templated) instance variable that
 834   //  refers to the associated ShenandoahCardCluster object.  Use this
 835   //  ShenandoahCardCluster instance to "enhance" the do_oops
 836   //  processing so that we can:
 837   //
 838   //   1. Avoid processing references that correspond to clean card
 839   //      regions, and
 840   //   2. Set card status to CLEAN when the associated card region no
 841   //      longer holds inter-generatioanal references.
 842   //
 843   //  To enable efficient implementation of these behaviors, we
 844   //  probably also want to add a few fields into the
 845   //  ShenandoahCardCluster object that allow us to precompute and
 846   //  remember the addresses at which card status is going to change
 847   //  from dirty to clean and clean to dirty.  The do_oops
 848   //  implementations will want to update this value each time they
 849   //  cross one of these boundaries.
 850   void roots_do(OopIterateClosure* cl);
 851 
 852   // Log stats related to card/RS stats for given phase t
 853   void log_card_stats(uint nworkers, CardStatLogType t) PRODUCT_RETURN;
 854 private:
 855   // Log stats for given worker id related into given summary card/RS stats
 856   void log_worker_card_stats(uint worker_id, HdrSeq* sum_stats) PRODUCT_RETURN;
 857 
 858   // Log given stats
 859   void log_card_stats(HdrSeq* stats) PRODUCT_RETURN;
 860 
 861   // Merge the stats from worked_id into the given summary stats, and clear the worker_id's stats.
 862   void merge_worker_card_stats_cumulative(HdrSeq* worker_stats, HdrSeq* sum_stats) PRODUCT_RETURN;
 863 };
 864 
 865 
 866 // A ShenandoahRegionChunk represents a contiguous interval of a ShenandoahHeapRegion, typically representing
 867 // work to be done by a worker thread.
 868 struct ShenandoahRegionChunk {
 869   ShenandoahHeapRegion* _r;      // The region of which this represents a chunk
 870   size_t _chunk_offset;          // HeapWordSize offset
 871   size_t _chunk_size;            // HeapWordSize qty
 872 };
 873 
 874 // ShenandoahRegionChunkIterator divides the total remembered set scanning effort into ShenandoahRegionChunks
 875 // that are assigned one at a time to worker threads. (Here, we use the terms `assignments` and `chunks`
 876 // interchangeably.) Note that the effort required to scan a range of memory is not necessarily a linear
 877 // function of the size of the range.  Some memory ranges hold only a small number of live objects.
 878 // Some ranges hold primarily primitive (non-pointer) data.  We start with larger chunk sizes because larger chunks
 879 // reduce coordination overhead.  We expect that the GC worker threads that receive more difficult assignments
 880 // will work longer on those chunks.  Meanwhile, other worker threads will repeatedly accept and complete multiple
 881 // easier chunks.  As the total amount of work remaining to be completed decreases, we decrease the size of chunks
 882 // given to individual threads.  This reduces the likelihood of significant imbalance between worker thread assignments
 883 // when there is less meaningful work to be performed by the remaining worker threads while they wait for
 884 // worker threads with difficult assignments to finish, reducing the overall duration of the phase.
 885 
 886 class ShenandoahRegionChunkIterator : public StackObj {
 887 private:
 888   // The largest chunk size is 4 MiB, measured in words.  Otherwise, remembered set scanning may become too unbalanced.
 889   // If the largest chunk size is too small, there is too much overhead sifting out assignments to individual worker threads.
 890   static const size_t _maximum_chunk_size_words = (4 * 1024 * 1024) / HeapWordSize;
 891 
 892   static const size_t _clusters_in_smallest_chunk = 4;
 893 
 894   // smallest_chunk_size is 4 clusters.  Each cluster spans 128 KiB.
 895   // This is computed from CardTable::card_size_in_words() * ShenandoahCardCluster::CardsPerCluster;
 896   static size_t smallest_chunk_size_words() {
 897       return _clusters_in_smallest_chunk * CardTable::card_size_in_words() *
 898              ShenandoahCardCluster::CardsPerCluster;
 899   }
 900 
 901   // The total remembered set scanning effort is divided into chunks of work that are assigned to individual worker tasks.
 902   // The chunks of assigned work are divided into groups, where the size of the typical group (_regular_group_size) is half the
 903   // total number of regions.  The first group may be larger than
 904   // _regular_group_size in the case that the first group's chunk
 905   // size is less than the region size.  The last group may be larger
 906   // than _regular_group_size because no group is allowed to
 907   // have smaller assignments than _smallest_chunk_size, which is 128 KB.
 908 
 909   // Under normal circumstances, no configuration needs more than _maximum_groups (default value of 16).
 910   // The first group "effectively" processes chunks of size 1 MiB (or smaller for smaller region sizes).
 911   // The last group processes chunks of size 128 KiB.  There are four groups total.
 912 
 913   // group[0] is 4 MiB chunk size (_maximum_chunk_size_words)
 914   // group[1] is 2 MiB chunk size
 915   // group[2] is 1 MiB chunk size
 916   // group[3] is 512 KiB chunk size
 917   // group[4] is 256 KiB chunk size
 918   // group[5] is 128 Kib shunk size (_smallest_chunk_size_words = 4 * 64 * 64
 919   static const size_t _maximum_groups = 6;
 920 
 921   const ShenandoahHeap* _heap;
 922 
 923   const size_t _regular_group_size;                        // Number of chunks in each group
 924   const size_t _first_group_chunk_size_b4_rebalance;
 925   const size_t _num_groups;                        // Number of groups in this configuration
 926   const size_t _total_chunks;
 927 
 928   shenandoah_padding(0);
 929   volatile size_t _index;
 930   shenandoah_padding(1);
 931 
 932   size_t _region_index[_maximum_groups];           // The region index for the first region spanned by this group
 933   size_t _group_offset[_maximum_groups];           // The offset at which group begins within first region spanned by this group
 934   size_t _group_chunk_size[_maximum_groups];       // The size of each chunk within this group
 935   size_t _group_entries[_maximum_groups];          // Total chunks spanned by this group and the ones before it.
 936 
 937   // No implicit copying: iterators should be passed by reference to capture the state
 938   NONCOPYABLE(ShenandoahRegionChunkIterator);
 939 
 940   // Makes use of _heap.
 941   size_t calc_regular_group_size();
 942 
 943   // Makes use of _regular_group_size, which must be initialized before call.
 944   size_t calc_first_group_chunk_size_b4_rebalance();
 945 
 946   // Makes use of _regular_group_size and _first_group_chunk_size_b4_rebalance, both of which must be initialized before call.
 947   size_t calc_num_groups();
 948 
 949   // Makes use of _regular_group_size, _first_group_chunk_size_b4_rebalance, which must be initialized before call.
 950   size_t calc_total_chunks();
 951 
 952 public:
 953   ShenandoahRegionChunkIterator(size_t worker_count);
 954   ShenandoahRegionChunkIterator(ShenandoahHeap* heap, size_t worker_count);
 955 
 956   // Reset iterator to default state
 957   void reset();
 958 
 959   // Fills in assignment with next chunk of work and returns true iff there is more work.
 960   // Otherwise, returns false.  This is multi-thread-safe.
 961   inline bool next(struct ShenandoahRegionChunk* assignment);
 962 
 963   // This is *not* MT safe. However, in the absence of multithreaded access, it
 964   // can be used to determine if there is more work to do.
 965   inline bool has_next() const;
 966 };
 967 
 968 
 969 class ShenandoahScanRememberedTask : public WorkerTask {
 970  private:
 971   ShenandoahObjToScanQueueSet* _queue_set;
 972   ShenandoahObjToScanQueueSet* _old_queue_set;
 973   ShenandoahReferenceProcessor* _rp;
 974   ShenandoahRegionChunkIterator* _work_list;
 975   bool _is_concurrent;
 976 
 977  public:
 978   ShenandoahScanRememberedTask(ShenandoahObjToScanQueueSet* queue_set,
 979                                ShenandoahObjToScanQueueSet* old_queue_set,
 980                                ShenandoahReferenceProcessor* rp,
 981                                ShenandoahRegionChunkIterator* work_list,
 982                                bool is_concurrent);
 983 
 984   void work(uint worker_id);
 985   void do_work(uint worker_id);
 986 };
 987 
 988 // After Full GC is done, reconstruct the remembered set by iterating over OLD regions,
 989 // registering all objects between bottom() and top(), and dirtying the cards containing
 990 // cross-generational pointers.
 991 class ShenandoahReconstructRememberedSetTask : public WorkerTask {
 992 private:
 993   ShenandoahRegionIterator* _regions;
 994 
 995 public:
 996   explicit ShenandoahReconstructRememberedSetTask(ShenandoahRegionIterator* regions);
 997 
 998   void work(uint worker_id) override;
 999 };
1000 
1001 #endif // SHARE_GC_SHENANDOAH_SHENANDOAHSCANREMEMBERED_HPP