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