1 /*
   2  * Copyright (c) 2021, Amazon.com, Inc. or its affiliates.  All rights reserved.
   3  *
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #ifndef SHARE_GC_SHENANDOAH_SHENANDOAHSCANREMEMBERED_HPP
  27 #define SHARE_GC_SHENANDOAH_SHENANDOAHSCANREMEMBERED_HPP
  28 
  29 // Terminology used within this source file:
  30 //
  31 // Card Entry:   This is the information that identifies whether a
  32 //               particular card-table entry is Clean or Dirty.  A clean
  33 //               card entry denotes that the associated memory does not
  34 //               hold references to young-gen memory.
  35 //
  36 // Card Region, aka
  37 // Card Memory:  This is the region of memory that is assocated with a
  38 //               particular card entry.
  39 //
  40 // Card Cluster: A card cluster represents 64 card entries.  A card
  41 //               cluster is the minimal amount of work performed at a
  42 //               time by a parallel thread.  Note that the work required
  43 //               to scan a card cluster is somewhat variable in that the
  44 //               required effort depends on how many cards are dirty, how
  45 //               many references are held within the objects that span a
  46 //               DIRTY card's memory, and on the size of the object
  47 //               that spans the end of a DIRTY card's memory (because
  48 //               that object will be scanned in its entirety). For these
  49 //               reasons, it is advisable for the multiple worker threads
  50 //               to be flexible in the number of clusters to be
  51 //               processed by each thread.
  52 //
  53 // A cluster represents a "natural" quantum of work to be performed by
  54 // a parallel GC thread's background remembered set scanning efforts.
  55 // The notion of cluster is similar to the notion of stripe in the
  56 // implementation of parallel GC card scanning.  However, a cluster is
  57 // typically smaller than a stripe, enabling finer grain division of
  58 // labor between multiple threads.
  59 //
  60 // For illustration, consider the following possible JVM configurations:
  61 //
  62 //   Scenario 1:
  63 //     RegionSize is 128 MB
  64 //     Span of a card entry is 512 B
  65 //     Each card table entry consumes 1 B
  66 //     Assume one long word of card table entries represents a cluster.
  67 //       This long word holds 8 card table entries, spanning a
  68 //       total of 4KB
  69 //     The number of clusters per region is 128 MB / 4 KB = 32K
  70 //
  71 //   Scenario 2:
  72 //     RegionSize is 128 MB
  73 //     Span of each card entry is 128 B
  74 //     Each card table entry consumes 1 bit
  75 //     Assume one int word of card tables represents a cluster.
  76 //       This int word holds 32 card table entries, spanning a
  77 //       total of 4KB
  78 //     The number of clusters per region is 128 MB / 4 KB = 32K
  79 //
  80 //   Scenario 3:
  81 //     RegionSize is 128 MB
  82 //     Span of each card entry is 512 B
  83 //     Each card table entry consumes 1 bit
  84 //     Assume one long word of card tables represents a cluster.
  85 //       This long word holds 64 card table entries, spanning a
  86 //       total of 32 KB
  87 //     The number of clusters per region is 128 MB / 32 KB = 4K
  88 //
  89 // At the start of a new young-gen concurrent mark pass, the gang of
  90 // Shenandoah worker threads collaborate in performing the following
  91 // actions:
  92 //
  93 //  Let old_regions = number of ShenandoahHeapRegion comprising
  94 //    old-gen memory
  95 //  Let region_size = ShenandoahHeapRegion::region_size_bytes()
  96 //    represent the number of bytes in each region
  97 //  Let clusters_per_region = region_size / 512
  98 //  Let rs represent the relevant RememberedSet implementation
  99 //    (an instance of ShenandoahDirectCardMarkRememberedSet or an instance
 100 //     of a to-be-implemented ShenandoahBufferWithSATBRememberedSet)
 101 //
 102 //  for each ShenandoahHeapRegion old_region in the whole heap
 103 //    determine the cluster number of the first cluster belonging
 104 //      to that region
 105 //    for each cluster contained within that region
 106 //      Assure that exactly one worker thread initializes each
 107 //      cluster of overreach memory by invoking:
 108 //
 109 //        rs->initialize_overreach(cluster_no, cluster_count)
 110 //
 111 //      in separate threads.  (Divide up the clusters so that
 112 //      different threads are responsible for initializing different
 113 //      clusters.  Initialization cost is essentially identical for
 114 //      each cluster.)
 115 //
 116 //  Next, we repeat the process for invocations of process_clusters.
 117 //  for each ShenandoahHeapRegion old_region in the whole heap
 118 //    determine the cluster number of the first cluster belonging
 119 //      to that region
 120 //    for each cluster contained within that region
 121 //      Assure that exactly one worker thread processes each
 122 //      cluster, each thread making a series of invocations of the
 123 //      following:
 124 //
 125 //        rs->process_clusters(worker_id, ReferenceProcessor *,
 126 //                             ShenandoahConcurrentMark *, cluster_no, cluster_count,
 127 //                             HeapWord *end_of_range, OopClosure *oops);
 128 //
 129 //  For efficiency, divide up the clusters so that different threads
 130 //  are responsible for processing different clusters.  Processing costs
 131 //  may vary greatly between clusters for the following reasons:
 132 //
 133 //        a) some clusters contain mostly dirty cards and other
 134 //           clusters contain mostly clean cards
 135 //        b) some clusters contain mostly primitive data and other
 136 //           clusters contain mostly reference data
 137 //        c) some clusters are spanned by very large objects that
 138 //           begin in some other cluster.  When a large object
 139 //           beginning in a preceding cluster spans large portions of
 140 //           this cluster, the processing of this cluster gets a
 141 //           "free ride" because the thread responsible for processing
 142 //           the cluster that holds the object's header does the
 143 //           processing.
 144 //        d) in the case that the end of this cluster is spanned by a
 145 //           very large object, the processing of this cluster will
 146 //           be responsible for examining the entire object,
 147 //           potentially requiring this thread to process large amounts
 148 //           of memory pertaining to other clusters.
 149 //
 150 // Though an initial division of labor between marking threads may
 151 // assign equal numbers of clusters to be scanned by each thread, it
 152 // should be expected that some threads will finish their assigned
 153 // work before others.  Therefore, some amount of the full remembered
 154 // set scanning effort should be held back and assigned incrementally
 155 // to the threads that end up with excess capacity.  Consider the
 156 // following strategy for dividing labor:
 157 //
 158 //        1. Assume there are 8 marking threads and 1024 remembered
 159 //           set clusters to be scanned.
 160 //        2. Assign each thread to scan 64 clusters.  This leaves
 161 //           512 (1024 - (8*64)) clusters to still be scanned.
 162 //        3. As the 8 server threads complete previous cluster
 163 //           scanning assignments, issue each of the next 8 scanning
 164 //           assignments as units of 32 additional cluster each.
 165 //           In the case that there is high variance in effort
 166 //           associated with previous cluster scanning assignments,
 167 //           multiples of these next assignments may be serviced by
 168 //           the server threads that were previously assigned lighter
 169 //           workloads.
 170 //        4. Make subsequent scanning assignments as follows:
 171 //             a) 8 assignments of size 16 clusters
 172 //             b) 8 assignments of size 8 clusters
 173 //             c) 16 assignments of size 4 clusters
 174 //
 175 //    When there is no more remembered set processing work to be
 176 //    assigned to a newly idled worker thread, that thread can move
 177 //    on to work on other tasks associated with root scanning until such
 178 //    time as all clusters have been examined.
 179 //
 180 //  Once all clusters have been processed, the gang of GC worker
 181 //  threads collaborate to merge the overreach data.
 182 //
 183 //  for each ShenandoahHeapRegion old_region in the whole heap
 184 //    determine the cluster number of the first cluster belonging
 185 //      to that region
 186 //    for each cluster contained within that region
 187 //      Assure that exactly one worker thread initializes each
 188 //      cluster of overreach memory by invoking:
 189 //
 190 //        rs->merge_overreach(cluster_no, cluster_count)
 191 //
 192 //      in separate threads.  (Divide up the clusters so that
 193 //      different threads are responsible for merging different
 194 //      clusters.  Merging cost is essentially identical for
 195 //      each cluster.)
 196 //
 197 // Though remembered set scanning is designed to run concurrently with
 198 // mutator threads, the current implementation of remembered set
 199 // scanning runs in parallel during a GC safepoint.  Furthermore, the
 200 // current implementation of remembered set scanning never clears a
 201 // card once it has been marked.  Since the current implementation
 202 // never clears marked pages, the current implementation does not
 203 // invoke initialize_overreach() or merge_overreach().
 204 //
 205 // These limitations will be addressed in future enhancements to the
 206 // existing implementation.
 207 
 208 #include <stdint.h>
 209 #include "memory/iterator.hpp"
 210 #include "gc/shared/workgroup.hpp"
 211 #include "gc/shenandoah/shenandoahCardTable.hpp"
 212 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
 213 #include "gc/shenandoah/shenandoahTaskqueue.hpp"
 214 
 215 class ShenandoahReferenceProcessor;
 216 class ShenandoahConcurrentMark;
 217 class ShenandoahHeap;
 218 class ShenandoahRegionIterator;
 219 class ShenandoahMarkingContext;
 220 
 221 class CardTable;
 222 
 223 class ShenandoahDirectCardMarkRememberedSet: public CHeapObj<mtGC> {
 224 
 225 private:
 226 
 227   // Use symbolic constants defined in cardTable.hpp
 228   //  CardTable::card_shift = 9;
 229   //  CardTable::card_size = 512;
 230   //  CardTable::card_size_in_words = 64;
 231 
 232   //  CardTable::clean_card_val()
 233   //  CardTable::dirty_card_val()
 234 
 235   ShenandoahHeap *_heap;
 236   ShenandoahCardTable *_card_table;
 237   size_t _card_shift;
 238   size_t _total_card_count;
 239   size_t _cluster_count;
 240   HeapWord *_whole_heap_base;   // Points to first HeapWord of data contained within heap memory
 241   HeapWord *_whole_heap_end;
 242   uint8_t *_byte_map;           // Points to first entry within the card table
 243   uint8_t *_byte_map_base;      // Points to byte_map minus the bias computed from address of heap memory
 244   uint8_t *_overreach_map;      // Points to first entry within the overreach card table
 245   uint8_t *_overreach_map_base; // Points to overreach_map minus the bias computed from address of heap memory
 246 
 247   uint64_t _wide_clean_value;
 248 
 249 public:
 250   // count is the number of cards represented by the card table.
 251   ShenandoahDirectCardMarkRememberedSet(ShenandoahCardTable *card_table, size_t total_card_count);
 252   ~ShenandoahDirectCardMarkRememberedSet();
 253 
 254   // Card index is zero-based relative to _byte_map.
 255   size_t total_cards();
 256   size_t card_index_for_addr(HeapWord *p);
 257   HeapWord *addr_for_card_index(size_t card_index);
 258   bool is_card_dirty(size_t card_index);
 259   bool is_write_card_dirty(size_t card_index);
 260   void mark_card_as_dirty(size_t card_index);
 261   void mark_range_as_dirty(size_t card_index, size_t num_cards);
 262   void mark_card_as_clean(size_t card_index);
 263   void mark_read_card_as_clean(size_t card_index);
 264   void mark_range_as_clean(size_t card_index, size_t num_cards);
 265   void mark_overreach_card_as_dirty(size_t card_index);
 266   bool is_card_dirty(HeapWord *p);
 267   void mark_card_as_dirty(HeapWord *p);
 268   void mark_range_as_dirty(HeapWord *p, size_t num_heap_words);
 269   void mark_card_as_clean(HeapWord *p);
 270   void mark_range_as_clean(HeapWord *p, size_t num_heap_words);
 271   void mark_overreach_card_as_dirty(void *p);
 272   size_t cluster_count();
 273 
 274   // Called by multiple GC threads at start of concurrent mark and evacuation phases.  Each parallel GC thread typically
 275   // initializes a different subranges of all overreach entries.
 276   void initialize_overreach(size_t first_cluster, size_t count);
 277 
 278   // Called by GC thread at end of concurrent mark or evacuation phase.  Each parallel GC thread typically merges different
 279   // subranges of all overreach entries.
 280   void merge_overreach(size_t first_cluster, size_t count);
 281 
 282   // Called by GC thread at start of concurrent mark to exchange roles of read and write remembered sets.
 283   // Not currently used because mutator write barrier does not honor changes to the location of card table.
 284   void swap_remset() {  _card_table->swap_card_tables(); }
 285 
 286   HeapWord* whole_heap_base() { return _whole_heap_base; }
 287   HeapWord* whole_heap_end() { return _whole_heap_end; }
 288 
 289   // Instead of swap_remset, the current implementation of concurrent remembered set scanning does reset_remset
 290   // in parallel threads, each invocation processing one entire HeapRegion at a time.  Processing of a region
 291   // consists of copying the write table to the read table and cleaning the write table.
 292   void reset_remset(HeapWord* start, size_t word_count) {
 293     size_t card_index = card_index_for_addr(start);
 294     size_t num_cards = word_count / CardTable::card_size_in_words;
 295     size_t iterations = num_cards / (sizeof (intptr_t) / sizeof (CardTable::CardValue));
 296     intptr_t* read_table_ptr = (intptr_t*) &(_card_table->read_byte_map())[card_index];
 297     intptr_t* write_table_ptr = (intptr_t*) &(_card_table->write_byte_map())[card_index];
 298     for (size_t i = 0; i < iterations; i++) {
 299       *read_table_ptr++ = *write_table_ptr;
 300       *write_table_ptr++ = CardTable::clean_card_row_val();
 301     }
 302   }
 303 
 304   // Called by GC thread after scanning old remembered set in order to prepare for next GC pass
 305   void clear_old_remset() {  _card_table->clear_read_table(); }
 306 
 307 };
 308 
 309 // A ShenandoahCardCluster represents the minimal unit of work
 310 // performed by independent parallel GC threads during scanning of
 311 // remembered sets.
 312 //
 313 // The GC threads that perform card-table remembered set scanning may
 314 // overwrite card-table entries to mark them as clean in the case that
 315 // the associated memory no longer holds references to young-gen
 316 // memory.  Rather than access the card-table entries directly, all GC
 317 // thread access to card-table information is made by way of the
 318 // ShenandoahCardCluster data abstraction.  This abstraction
 319 // effectively manages access to multiple possible underlying
 320 // remembered set implementations, including a traditional card-table
 321 // approach and a SATB-based approach.
 322 //
 323 // The API services represent a compromise between efficiency and
 324 // convenience.
 325 //
 326 // In the initial implementation, we assume that scanning of card
 327 // table entries occurs only while the JVM is at a safe point.  Thus,
 328 // there is no synchronization required between GC threads that are
 329 // scanning card-table entries and marking certain entries that were
 330 // previously dirty as clean, and mutator threads which would possibly
 331 // be marking certain card-table entries as dirty.
 332 //
 333 // There is however a need to implement concurrency control and memory
 334 // coherency between multiple GC threads that scan the remembered set
 335 // in parallel.  The desire is to divide the complete scanning effort
 336 // into multiple clusters of work that can be independently processed
 337 // by individual threads without need for synchronizing efforts
 338 // between the work performed by each task.  The term "cluster" of
 339 // work is similar to the term "stripe" as used in the implementation
 340 // of Parallel GC.
 341 //
 342 // Complexity arises when an object to be scanned crosses the boundary
 343 // between adjacent cluster regions.  Here is the protocol that is
 344 // followed:
 345 //
 346 //  1. We implement a supplemental data structure known as the overreach
 347 //     card table.  The thread that is responsible for scanning each
 348 //     cluster of card-table entries is granted exclusive access to
 349 //     modify the associated card-table entries.  In the case that a
 350 //     thread scans a very large object that reaches into one or more
 351 //     following clusters, that thread has exclusive access to the
 352 //     overreach card table for all of the entries belonging to the
 353 //     following clusters that are spanned by this large object.
 354 //     After all clusters have been scanned, the scanning threads
 355 //     briefly synchronize to merge the contents of the overreach
 356 //     entries with the traditional card table entries using logical-
 357 //     and operations.
 358 //  2. Every object is scanned in its "entirety" by the thread that is
 359 //     responsible for the cluster that holds its starting address.
 360 //     Entirety is in quotes because there are various situations in
 361 //     which some portions of the object will not be scanned by this
 362 //     thread:
 363 //     a) If an object spans multiple card regions, all of which are
 364 //        contained within the same cluster, the scanning thread
 365 //        consults the existing card-table entries and does not scan
 366 //        portions of the object that are not currently dirty.
 367 //     b) For any cluster that is spanned in its entirety by a very
 368 //        large object, the GC thread that scans this object assumes
 369 //        full responsibility for maintenance of the associated
 370 //        card-table entries.
 371 //     c) If a cluster is partially spanned by an object originating
 372 //        in a preceding cluster, the portion of the object that
 373 //        partially spans the following cluster is scanned in its
 374 //        entirety (because the thread that is responsible for
 375 //        scanning the object cannot rely upon the card-table entries
 376 //        associated with the following cluster).  Whenever references
 377 //        to young-gen memory are found within the scanned data, the
 378 //        associated overreach card table entries are marked as dirty
 379 //        by the scanning thread.
 380 //  3. If a cluster is spanned in its entirety by an object that
 381 //     originates within a preceding cluster's memory, the thread
 382 //     assigned to examine this cluster does absolutely nothing.  The
 383 //     thread assigned to scan the cluster that holds the object's
 384 //     starting address takes full responsibility for scanning the
 385 //     entire object and updating the associated card-table entries.
 386 //  4. If a cluster is spanned partially by an object that originates
 387 //     within a preceding cluster's memory, the thread assigned to
 388 //     examine this cluster marks the card-table entry as clean for
 389 //     each card table that is fully spanned by this overreaching
 390 //     object.  If a card-table entry's memory is partially spanned
 391 //     by the overreaching object, the thread sets the card-table
 392 //     entry to clean if it was previously dirty and if the portion
 393 //     of the card-table entry's memory that is not spanned by the
 394 //     overreaching object does not hold pointers to young-gen
 395 //     memory.
 396 //  5. While examining a particular card belonging to a particular
 397 //     cluster, if an object reaches beyond the end of its card
 398 //     memory, the thread "scans" all portions of the object that
 399 //     correspond to DIRTY card entries within the current cluster and
 400 //     all portions of the object that reach into following clustesr.
 401 //     After this object is scanned, continue scanning with the memory
 402 //     that follows this object if this memory pertains to the same
 403 //     cluster.  Otherwise, consider this cluster's memory to have
 404 //     been fully examined.
 405 //
 406 // Discussion:
 407 //  Though this design results from careful consideration of multiple
 408 //  design objectives, it is subject to various criticisms.  Some
 409 //  discussion of the design choices is provided here:
 410 //
 411 //  1. Note that remembered sets are a heuristic technique to avoid
 412 //     the need to scan all of old-gen memory with each young-gen
 413 //     collection.  If we sometimes scan a bit more memory than is
 414 //     absolutely necessary, that should be considered a reasonable
 415 //     compromise.  This compromise is already present in the sizing
 416 //     of card table memory areas.  Note that a single dirty pointer
 417 //     within a 512-byte card region forces the "unnecessary" scanning
 418 //     of 63 = ((512 - 8 = 504) / 8) pointers.
 419 //  2. One undesirable aspect of this design is that we sometimes have
 420 //     to scan large amounts of memory belonging to very large
 421 //     objects, even for parts of the very large object that do not
 422 //     correspond to dirty card table entries.  Note that this design
 423 //     limits the amount of non-dirty scanning that might have to
 424 //     be performed for these very large objects.  In particular, only
 425 //     the last part of the very large object that extends into but
 426 //     does not completely span a particular cluster is unnecessarily
 427 //     scanned.  Thus, for each very large object, the maximum
 428 //     over-scan is the size of memory spanned by a single cluster.
 429 //  3. The representation of pointer location descriptive information
 430 //     within Klass representations is not designed for efficient
 431 //     "random access".  An alternative approach to this design would
 432 //     be to scan very large objects multiple times, once for each
 433 //     cluster that is spanned by the object's range.  This reduces
 434 //     unnecessary overscan, but it introduces different sorts of
 435 //     overhead effort:
 436 //       i) For each spanned cluster, we have to look up the start of
 437 //          the crossing object.
 438 //      ii) Each time we scan the very large object, we have to
 439 //          sequentially walk through its pointer location
 440 //          descriptors, skipping over all of the pointers that
 441 //          precede the start of the range of addresses that we
 442 //          consider relevant.
 443 
 444 
 445 // Because old-gen heap memory is not necessarily contiguous, and
 446 // because cards are not necessarily maintained for young-gen memory,
 447 // consecutive card numbers do not necessarily correspond to consecutive
 448 // address ranges.  For the traditional direct-card-marking
 449 // implementation of this interface, consecutive card numbers are
 450 // likely to correspond to contiguous regions of memory, but this
 451 // should not be assumed.  Instead, rely only upon the following:
 452 //
 453 //  1. All card numbers for cards pertaining to the same
 454 //     ShenandoahHeapRegion are consecutively numbered.
 455 //  2. In the case that neighboring ShenandoahHeapRegions both
 456 //     represent old-gen memory, the card regions that span the
 457 //     boundary between these neighboring heap regions will be
 458 //     consecutively numbered.
 459 //  3. (A corollary) In the case that an old-gen object spans the
 460 //     boundary between two heap regions, the card regions that
 461 //     correspond to the span of this object will be consecutively
 462 //     numbered.
 463 
 464 
 465 // ShenandoahCardCluster abstracts access to the remembered set
 466 // and also keeps track of crossing map information to allow efficient
 467 // resolution of object start addresses.
 468 //
 469 // ShenandoahCardCluster supports all of the services of
 470 // RememberedSet, plus it supports register_object() and lookup_object().
 471 //
 472 // There are two situations under which we need to know the location
 473 // at which the object spanning the start of a particular card-table
 474 // memory region begins:
 475 //
 476 // 1. When we begin to scan dirty card memory that is not the
 477 //    first card region within a cluster, and the object that
 478 //    crosses into this card memory was not previously scanned,
 479 //    we need to find where that object starts so we can scan it.
 480 //    (Asides: if the objects starts within a previous cluster, it
 481 //     has already been scanned.  If the object starts within this
 482 //     cluster and it spans at least one card region that is dirty
 483 //     and precedes this card region within the cluster, then it has
 484 //     already been scanned.)
 485 // 2. When we are otherwise done scanning a complete cluster, if the
 486 //    last object within the cluster reaches into the following
 487 //    cluster, we need to scan this object.  Thus, we need to find
 488 //    its starting location.
 489 //
 490 // The RememberedSet template parameter is intended to represent either
 491 //     ShenandoahDirectCardMarkRememberedSet, or a to-be-implemented
 492 //     ShenandoahBufferWithSATBRememberedSet.
 493 template<typename RememberedSet>
 494 class ShenandoahCardCluster: public CHeapObj<mtGC> {
 495 
 496 private:
 497   RememberedSet *_rs;
 498 
 499 public:
 500   static const size_t CardsPerCluster = 64;
 501 
 502 private:
 503   // This bit is set iff at least one object starts within a
 504   // particular card region.
 505   static const uint16_t ObjectStartsInCardRegion = 0x8000;
 506   static const uint16_t FirstStartBits = 0x003f;
 507   static const uint16_t LastStartBits = 0x0fc0;
 508   static const uint16_t FirstStartShift = 0;
 509   static const uint16_t LastStartShift = 6;
 510 
 511   uint16_t *object_starts;
 512 
 513 public:
 514   inline void set_first_start(size_t card_index, uint8_t value) {
 515     object_starts[card_index] &= ~FirstStartBits;
 516     object_starts[card_index] |= (FirstStartBits & (value << FirstStartShift));
 517   }
 518 
 519   inline void set_last_start(size_t card_index, uint8_t value) {
 520     object_starts[card_index] &= ~LastStartBits;
 521     object_starts[card_index] |= (LastStartBits & (value << LastStartShift));
 522   }
 523 
 524   inline void set_has_object_bit(size_t card_index) {
 525     object_starts[card_index] |= ObjectStartsInCardRegion;
 526   }
 527 
 528   inline void clear_has_object_bit(size_t card_index) {
 529     object_starts[card_index] &= ~ObjectStartsInCardRegion;
 530   }
 531 
 532   inline void clear_objects_in_range(HeapWord *addr, size_t num_words) {
 533     size_t card_index = _rs->card_index_for_addr(addr);
 534     size_t last_card_index = _rs->card_index_for_addr(addr + num_words - 1);
 535     while (card_index <= last_card_index)
 536       object_starts[card_index++] = 0;
 537   }
 538 
 539   ShenandoahCardCluster(RememberedSet *rs) {
 540     _rs = rs;
 541     // TODO: We don't really need object_starts entries for every card entry.  We only need these for
 542     // the card entries that correspond to old-gen memory.  But for now, let's be quick and dirty.
 543     object_starts = (uint16_t *) malloc(rs->total_cards() * sizeof(uint16_t));
 544     if (object_starts == NULL)
 545       fatal("Insufficient memory for initializing heap");
 546     for (size_t i = 0; i < rs->total_cards(); i++)
 547       object_starts[i] = 0;
 548   }
 549 
 550   ~ShenandoahCardCluster() {
 551     if (object_starts != NULL)
 552       free(object_starts);
 553   }
 554 
 555   // There is one entry within the object_starts array for each
 556   // card entry.  The interpretation of the data contained within each
 557   // object_starts entry is described below:
 558   //
 559   // Bits 0x003f: Value ranges from 0-63, which is multiplied by 8
 560   //              to obtain the offset at which the first object
 561   //              beginning within this card region begins.
 562   // Bits 0x0fc0: Value ranges from 0-63, which is multiplied by 8 to
 563   //              obtain the offset at which the last object beginning
 564   //              within this card region begins.
 565   // Bits 0x8000: This bit is on if an object starts within this card
 566   //              region.
 567   // Bits 0x7000: Reserved for future uses
 568   //
 569   // In the most recent implementation of ShenandoahScanRemembered::process_clusters(),
 570   // there is no need for the get_crossing_object_start() method function, so there is no
 571   // need to maintain the following information.  The comment is left in place for now in
 572   // case we find it necessary to add support for this service at a later time.
 573   //
 574   // Bits 0x7fff: If no object starts within this card region, the
 575   //              remaining bits of the object_starts array represent
 576   //              the absolute word offset within the enclosing
 577   //              cluster's memory of the starting address for the
 578   //              object that spans the start of this card region's
 579   //              memory.  If the spanning object begins in memory
 580   //              that precedes this card region's cluster, the value
 581   //              stored in these bits is the special value 0x7fff.
 582   //              (Note that the maximum value required to represent a
 583   //              spanning object from within the current cluster is
 584   //              ((63 * 64) - 8), which equals 0x0fbf.
 585   //
 586   // In the absence of the need to support get_crossing_object_start(),
 587   // here is discussion of performance:
 588   //
 589   //  Suppose multiple garbage objects are coalesced during GC sweep
 590   //  into a single larger "free segment".  As each two objects are
 591   //  coalesced together, the start information pertaining to the second
 592   //  object must be removed from the objects_starts array.  If the
 593   //  second object had been been the first object within card memory,
 594   //  the new first object is the object that follows that object if
 595   //  that starts within the same card memory, or NoObject if the
 596   //  following object starts within the following cluster.  If the
 597   //  second object had been the last object in the card memory,
 598   //  replace this entry with the newly coalesced object if it starts
 599   //  within the same card memory, or with NoObject if it starts in a
 600   //  preceding card's memory.
 601   //
 602   //  Suppose a large free segment is divided into a smaller free
 603   //  segment and a new object.  The second part of the newly divided
 604   //  memory must be registered as a new object, overwriting at most
 605   //  one first_start and one last_start entry.  Note that one of the
 606   //  newly divided two objects might be a new GCLAB.
 607   //
 608   //  Suppose postprocessing of a GCLAB finds that the original GCLAB
 609   //  has been divided into N objects.  Each of the N newly allocated
 610   //  objects will be registered, overwriting at most one first_start
 611   //  and one last_start entries.
 612   //
 613   //  No object registration operations are linear in the length of
 614   //  the registered objects.
 615   //
 616   // Consider further the following observations regarding object
 617   // registration costs:
 618   //
 619   //   1. The cost is paid once for each old-gen object (Except when
 620   //      an object is demoted and repromoted, in which case we would
 621   //      pay the cost again).
 622   //   2. The cost can be deferred so that there is no urgency during
 623   //      mutator copy-on-first-access promotion.  Background GC
 624   //      threads will update the object_starts array by post-
 625   //      processing the contents of retired GCLAB buffers.
 626   //   3. The bet is that these costs are paid relatively rarely
 627   //      because:
 628   //      a) Most objects die young and objects that die in young-gen
 629   //         memory never need to be registered with the object_starts
 630   //         array.
 631   //      b) Most objects that are promoted into old-gen memory live
 632   //         there without further relocation for a relatively long
 633   //         time, so we get a lot of benefit from each investment
 634   //         in registering an object.
 635 
 636 public:
 637 
 638   // The starting locations of objects contained within old-gen memory
 639   // are registered as part of the remembered set implementation.  This
 640   // information is required when scanning dirty card regions that are
 641   // spanned by objects beginning within preceding card regions.  It
 642   // is necessary to find the first and last objects that begin within
 643   // this card region.  Starting addresses of objects are required to
 644   // find the object headers, and object headers provide information
 645   // about which fields within the object hold addresses.
 646   //
 647   // The old-gen memory allocator invokes register_object() for any
 648   // object that is allocated within old-gen memory.  This identifies
 649   // the starting addresses of objects that span boundaries between
 650   // card regions.
 651   //
 652   // It is not necessary to invoke register_object at the very instant
 653   // an object is allocated.  It is only necessary to invoke it
 654   // prior to the next start of a garbage collection concurrent mark
 655   // or concurrent update-references phase.  An "ideal" time to register
 656   // objects is during post-processing of a GCLAB after the GCLAB is
 657   // retired due to depletion of its memory.
 658   //
 659   // register_object() does not perform synchronization.  In the case
 660   // that multiple threads are registering objects whose starting
 661   // addresses are within the same cluster, races between these
 662   // threads may result in corruption of the object-start data
 663   // structures.  Parallel GC threads should avoid registering objects
 664   // residing within the same cluster by adhering to the following
 665   // coordination protocols:
 666   //
 667   //  1. Align thread-local GCLAB buffers with some TBD multiple of
 668   //     card clusters.  The card cluster size is 32 KB.  If the
 669   //     desired GCLAB size is 128 KB, align the buffer on a multiple
 670   //     of 4 card clusters.
 671   //  2. Post-process the contents of GCLAB buffers to register the
 672   //     objects allocated therein.  Allow one GC thread at a
 673   //     time to do the post-processing of each GCLAB.
 674   //  3. Since only one GC thread at a time is registering objects
 675   //     belonging to a particular allocation buffer, no locking
 676   //     is performed when registering these objects.
 677   //  4. Any remnant of unallocated memory within an expended GC
 678   //     allocation buffer is not returned to the old-gen allocation
 679   //     pool until after the GC allocation buffer has been post
 680   //     processed.  Before any remnant memory is returned to the
 681   //     old-gen allocation pool, the GC thread that scanned this GC
 682   //     allocation buffer performs a write-commit memory barrier.
 683   //  5. Background GC threads that perform tenuring of young-gen
 684   //     objects without a GCLAB use a CAS lock before registering
 685   //     each tenured object.  The CAS lock assures both mutual
 686   //     exclusion and memory coherency/visibility.  Note that an
 687   //     object tenured by a background GC thread will not overlap
 688   //     with any of the clusters that are receiving tenured objects
 689   //     by way of GCLAB buffers.  Multiple independent GC threads may
 690   //     attempt to tenure objects into a shared cluster.  This is why
 691   //     sychronization may be necessary.  Consider the following
 692   //     scenarios:
 693   //
 694   //     a) If two objects are tenured into the same card region, each
 695   //        registration may attempt to modify the first-start or
 696   //        last-start information associated with that card region.
 697   //        Furthermore, because the representations of first-start
 698   //        and last-start information within the object_starts array
 699   //        entry uses different bits of a shared uint_16 to represent
 700   //        each, it is necessary to lock the entire card entry
 701   //        before modifying either the first-start or last-start
 702   //        information within the entry.
 703   //     b) Suppose GC thread X promotes a tenured object into
 704   //        card region A and this tenured object spans into
 705   //        neighboring card region B.  Suppose GC thread Y (not equal
 706   //        to X) promotes a tenured object into cluster B.  GC thread X
 707   //        will update the object_starts information for card A.  No
 708   //        synchronization is required.
 709   //     c) In summary, when background GC threads register objects
 710   //        newly tenured into old-gen memory, they must acquire a
 711   //        mutual exclusion lock on the card that holds the starting
 712   //        address of the newly tenured object.  This can be achieved
 713   //        by using a CAS instruction to assure that the previous
 714   //        values of first-offset and last-offset have not been
 715   //        changed since the same thread inquired as to their most
 716   //        current values.
 717   //
 718   //     One way to minimize the need for synchronization between
 719   //     background tenuring GC threads is for each tenuring GC thread
 720   //     to promote young-gen objects into distinct dedicated cluster
 721   //     ranges.
 722   //  6. The object_starts information is only required during the
 723   //     starting of concurrent marking and concurrent evacuation
 724   //     phases of GC.  Before we start either of these GC phases, the
 725   //     JVM enters a safe point and all GC threads perform
 726   //     commit-write barriers to assure that access to the
 727   //     object_starts information is coherent.
 728 
 729 
 730   // Notes on synchronization of register_object():
 731   //
 732   //  1. For efficiency, there is no locking in the implementation of register_object()
 733   //  2. Thus, it is required that users of this service assure that concurrent/parallel invocations of
 734   //     register_object() do pertain to the same card's memory range.  See discussion below to undestand
 735   //     the risks.
 736   //  3. When allocating from a TLAB or GCLAB, the mutual exclusion can be guaranteed by assuring that each
 737   //     LAB's start and end are aligned on card memory boundaries.
 738   //  4. Use the same lock that guarantees exclusivity when performing free-list allocation within heap regions.
 739   //
 740   // Register the newly allocated object while we're holding the global lock since there's no synchronization
 741   // built in to the implementation of register_object().  There are potential races when multiple independent
 742   // threads are allocating objects, some of which might span the same card region.  For example, consider
 743   // a card table's memory region within which three objects are being allocated by three different threads:
 744   //
 745   // objects being "concurrently" allocated:
 746   //    [-----a------][-----b-----][--------------c------------------]
 747   //            [---- card table memory range --------------]
 748   //
 749   // Before any objects are allocated, this card's memory range holds no objects.  Note that:
 750   //   allocation of object a wants to set the has-object, first-start, and last-start attributes of the preceding card region.
 751   //   allocation of object b wants to set the has-object, first-start, and last-start attributes of this card region.
 752   //   allocation of object c also wants to set the has-object, first-start, and last-start attributes of this card region.
 753   //
 754   // The thread allocating b and the thread allocating c can "race" in various ways, resulting in confusion, such as last-start
 755   // representing object b while first-start represents object c.  This is why we need to require all register_object()
 756   // invocations associated with objects that are allocated from "free lists" to provide their own mutual exclusion locking
 757   // mechanism.
 758 
 759   // Reset the has_object() information to false for all cards in the range between from and to.
 760   void reset_object_range(HeapWord *from, HeapWord *to);
 761 
 762   // register_object() requires that the caller hold the heap lock
 763   // before calling it.
 764   void register_object(HeapWord* address);
 765 
 766   // register_object_wo_lock() does not require that the caller hold
 767   // the heap lock before calling it, under the assumption that the
 768   // caller has assure no other thread will endeavor to concurrently
 769   // register objects that start within the same card's memory region
 770   // as address.
 771   void register_object_wo_lock(HeapWord* address);
 772 
 773   // During the reference updates phase of GC, we walk through each old-gen memory region that was
 774   // not part of the collection set and we invalidate all unmarked objects.  As part of this effort,
 775   // we coalesce neighboring dead objects in order to make future remembered set scanning more
 776   // efficient (since future remembered set scanning of any card region containing consecutive
 777   // dead objects can skip over all of them at once by reading only a single dead object header
 778   // instead of having to read the header of each of the coalesced dead objects.
 779   //
 780   // At some future time, we may implement a further optimization: satisfy future allocation requests
 781   // by carving new objects out of the range of memory that represents the coalesced dead objects.
 782   //
 783   // Suppose we want to combine several dead objects into a single coalesced object.  How does this
 784   // impact our representation of crossing map information?
 785   //  1. If the newly coalesced range is contained entirely within a card range, that card's last
 786   //     start entry either remains the same or it is changed to the start of the coalesced region.
 787   //  2. For the card that holds the start of the coalesced object, it will not impact the first start
 788   //     but it may impact the last start.
 789   //  3. For following cards spanned entirely by the newly coalesced object, it will change has_object
 790   //     to false (and make first-start and last-start "undefined").
 791   //  4. For a following card that is spanned patially by the newly coalesced object, it may change
 792   //     first-start value, but it will not change the last-start value.
 793   //
 794   // The range of addresses represented by the arguments to coalesce_objects() must represent a range
 795   // of memory that was previously occupied exactly by one or more previously registered objects.  For
 796   // convenience, it is legal to invoke coalesce_objects() with arguments that span a single previously
 797   // registered object.
 798   //
 799   // The role of coalesce_objects is to change the crossing map information associated with all of the coalesced
 800   // objects.
 801   void coalesce_objects(HeapWord* address, size_t length_in_words);
 802 
 803   // The typical use case is going to look something like this:
 804   //   for each heapregion that comprises old-gen memory
 805   //     for each card number that corresponds to this heap region
 806   //       scan the objects contained therein if the card is dirty
 807   // To avoid excessive lookups in a sparse array, the API queries
 808   // the card number pertaining to a particular address and then uses the
 809   // card noumber for subsequent information lookups and stores.
 810 
 811   // Returns true iff an object is known to start within the card memory
 812   // associated with addr p.
 813   // Returns true iff an object is known to start within the card memory
 814   // associated with addr p.
 815   bool has_object(size_t card_index);
 816 
 817   // If has_object(card_index), this returns the word offset within this card
 818   // memory at which the first object begins.  If !has_object(card_index), the
 819   // result is a don't care value.
 820   size_t get_first_start(size_t card_index);
 821 
 822   // If has_object(card_index), this returns the word offset within this card
 823   // memory at which the last object begins.  If !has_object(card_index), the
 824   // result is a don't care value.
 825   size_t get_last_start(size_t card_index);
 826 
 827 };
 828 
 829 // ShenandoahScanRemembered is a concrete class representing the
 830 // ability to scan the old-gen remembered set for references to
 831 // objects residing in young-gen memory.
 832 //
 833 // Scanning normally begins with an invocation of numRegions and ends
 834 // after all clusters of all regions have been scanned.
 835 //
 836 // Throughout the scanning effort, the number of regions does not
 837 // change.
 838 //
 839 // Even though the regions that comprise old-gen memory are not
 840 // necessarily contiguous, the abstraction represented by this class
 841 // identifies each of the old-gen regions with an integer value
 842 // in the range from 0 to (numRegions() - 1) inclusive.
 843 //
 844 
 845 template<typename RememberedSet>
 846 class ShenandoahScanRemembered: public CHeapObj<mtGC> {
 847 
 848 private:
 849 
 850   RememberedSet* _rs;
 851   ShenandoahCardCluster<RememberedSet>* _scc;
 852 
 853 public:
 854   // How to instantiate this object?
 855   //   ShenandoahDirectCardMarkRememberedSet *rs =
 856   //       new ShenandoahDirectCardMarkRememberedSet();
 857   //   scr = new
 858   //     ShenandoahScanRememberd<ShenandoahDirectCardMarkRememberedSet>(rs);
 859   //
 860   // or, after the planned implementation of
 861   // ShenandoahBufferWithSATBRememberedSet has been completed:
 862   //
 863   //   ShenandoahBufferWithSATBRememberedSet *rs =
 864   //       new ShenandoahBufferWithSATBRememberedSet();
 865   //   scr = new
 866   //     ShenandoahScanRememberd<ShenandoahBufferWithSATBRememberedSet>(rs);
 867 
 868 
 869   ShenandoahScanRemembered(RememberedSet *rs) {
 870     _rs = rs;
 871     _scc = new ShenandoahCardCluster<RememberedSet>(rs);
 872   }
 873 
 874   ~ShenandoahScanRemembered() {
 875     delete _scc;
 876   }
 877 
 878   // TODO:  We really don't want to share all of these APIs with arbitrary consumers of the ShenandoahScanRemembered abstraction.
 879   // 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
 880   // of existing code already depends on having access to these services (because existing code has not been written to honor
 881   // full abstraction of remembered set scanning.  In the not too distant future, we want to try to make most, if not all, of
 882   // these services private.  Two problems with publicizing:
 883   //  1. Allowing arbitrary users to reach beneath the hood allows the users to make assumptions about underlying implementation.
 884   //     This will make it more difficult to change underlying implementation at a future time, such as when we eventually experiment
 885   //     with SATB-based implementation of remembered set representation.
 886   //  2. If we carefully control sharing of certain of these services, we can reduce the overhead of synchronization by assuring
 887   //     that all users follow protocols that avoid contention that might require synchronization.  When we publish these APIs, we
 888   //     lose control over who and how the data is accessed.  As a result, we are required to insert more defensive measures into
 889   //     the implementation, including synchronization locks.
 890 
 891 
 892   // Card index is zero-based relative to first spanned card region.
 893   size_t total_cards();
 894   size_t card_index_for_addr(HeapWord *p);
 895   HeapWord *addr_for_card_index(size_t card_index);
 896   bool is_card_dirty(size_t card_index);
 897   bool is_write_card_dirty(size_t card_index) { return _rs->is_write_card_dirty(card_index); }
 898   void mark_card_as_dirty(size_t card_index);
 899   void mark_range_as_dirty(size_t card_index, size_t num_cards);
 900   void mark_card_as_clean(size_t card_index);
 901   void mark_read_card_as_clean(size_t card_index) { _rs->mark_read_card_clean(card_index); }
 902   void mark_range_as_clean(size_t card_index, size_t num_cards);
 903   void mark_overreach_card_as_dirty(size_t card_index);
 904   bool is_card_dirty(HeapWord *p);
 905   void mark_card_as_dirty(HeapWord *p);
 906   void mark_range_as_dirty(HeapWord *p, size_t num_heap_words);
 907   void mark_card_as_clean(HeapWord *p);
 908   void mark_range_as_clean(HeapWord *p, size_t num_heap_words);
 909   void mark_overreach_card_as_dirty(void *p);
 910   size_t cluster_count();
 911   void initialize_overreach(size_t first_cluster, size_t count);
 912   void merge_overreach(size_t first_cluster, size_t count);
 913 
 914   // Called by GC thread at start of concurrent mark to exchange roles of read and write remembered sets.
 915   void swap_remset() { _rs->swap_remset(); }
 916 
 917   void reset_remset(HeapWord* start, size_t word_count) { _rs->reset_remset(start, word_count); }
 918 
 919   // Called by GC thread after scanning old remembered set in order to prepare for next GC pass
 920   void clear_old_remset() { _rs->clear_old_remset(); }
 921 
 922   size_t cluster_for_addr(HeapWord *addr);
 923 
 924   void reset_object_range(HeapWord *from, HeapWord *to);
 925   void register_object(HeapWord *addr);
 926   void register_object_wo_lock(HeapWord *addr);
 927   void coalesce_objects(HeapWord *addr, size_t length_in_words);
 928 
 929   // Return true iff this object is "properly" registered.
 930   bool verify_registration(HeapWord* address, ShenandoahMarkingContext* ctx);
 931 
 932   // clear the cards to clean, and clear the object_starts info to no objects
 933   void mark_range_as_empty(HeapWord *addr, size_t length_in_words);
 934 
 935   // process_clusters() scans a portion of the remembered set during a JVM
 936   // safepoint as part of the root scanning activities that serve to
 937   // initiate concurrent scanning and concurrent evacuation.  Multiple
 938   // threads may scan different portions of the remembered set by
 939   // making parallel invocations of process_clusters() with each
 940   // invocation scanning different clusters of the remembered set.
 941   //
 942   // An invocation of process_clusters() examines all of the
 943   // intergenerational references spanned by count clusters starting
 944   // with first_cluster.  The oops argument is assumed to represent a
 945   // thread-local OopClosure into which addresses of intergenerational
 946   // pointer values will be accumulated for the purposes of root scanning.
 947   //
 948   // A side effect of executing process_clusters() is to update the card
 949   // table entries, marking dirty cards as clean if they no longer
 950   // hold references to young-gen memory.  (THIS IS NOT YET IMPLEMENTED.)
 951   //
 952   // The implementation of process_clusters() is designed to efficiently
 953   // minimize work in the large majority of cases for which the
 954   // associated cluster has very few dirty card-table entries.
 955   //
 956   // At initialization of concurrent marking, invoke process_clusters with
 957   // ClosureType equal to ShenandoahInitMarkRootsClosure.
 958   //
 959   // At initialization of concurrent evacuation, invoke process_clusters with
 960   // ClosureType equal to ShenandoahEvacuateUpdateRootsClosure.
 961 
 962   // This is big enough it probably shouldn't be in-lined.  On the other hand, there are only a few places this
 963   // code is called from, so it might as well be in-lined.  The "real" reason I'm inlining at the moment is because
 964   // the template expansions were making it difficult for the link/loader to resolve references to the template-
 965   // parameterized implementations of this service.
 966   template <typename ClosureType>
 967   inline void process_clusters(size_t first_cluster, size_t count, HeapWord *end_of_range, ClosureType *oops);
 968 
 969   template <typename ClosureType>
 970   inline void process_clusters(size_t first_cluster, size_t count, HeapWord *end_of_range, ClosureType *oops, bool use_write_table);
 971 
 972   template <typename ClosureType>
 973   inline void process_region(ShenandoahHeapRegion* region, ClosureType *cl);
 974 
 975   template <typename ClosureType>
 976   inline void process_region(ShenandoahHeapRegion* region, ClosureType *cl, bool use_write_table);
 977 
 978   // To Do:
 979   //  Create subclasses of ShenandoahInitMarkRootsClosure and
 980   //  ShenandoahEvacuateUpdateRootsClosure and any other closures
 981   //  that need to participate in remembered set scanning.  Within the
 982   //  subclasses, add a (probably templated) instance variable that
 983   //  refers to the associated ShenandoahCardCluster object.  Use this
 984   //  ShenandoahCardCluster instance to "enhance" the do_oops
 985   //  processing so that we can:
 986   //
 987   //   1. Avoid processing references that correspond to clean card
 988   //      regions, and
 989   //   2. Set card status to CLEAN when the associated card region no
 990   //      longer holds inter-generatioanal references.
 991   //
 992   //  To enable efficient implementation of these behaviors, we
 993   //  probably also want to add a few fields into the
 994   //  ShenandoahCardCluster object that allow us to precompute and
 995   //  remember the addresses at which card status is going to change
 996   //  from dirty to clean and clean to dirty.  The do_oops
 997   //  implementations will want to update this value each time they
 998   //  cross one of these boundaries.
 999   void roots_do(OopIterateClosure* cl);
1000 };
1001 
1002 typedef ShenandoahScanRemembered<ShenandoahDirectCardMarkRememberedSet> RememberedScanner;
1003 
1004 class ShenandoahScanRememberedTask : public AbstractGangTask {
1005  private:
1006   ShenandoahObjToScanQueueSet* _queue_set;
1007   ShenandoahObjToScanQueueSet* _old_queue_set;
1008   ShenandoahReferenceProcessor* _rp;
1009   ShenandoahRegionIterator* _regions;
1010  public:
1011   ShenandoahScanRememberedTask(ShenandoahObjToScanQueueSet* queue_set,
1012                                ShenandoahObjToScanQueueSet* old_queue_set,
1013                                ShenandoahReferenceProcessor* rp,
1014                                ShenandoahRegionIterator* regions);
1015 
1016   void work(uint worker_id);
1017 };
1018 #endif // SHARE_GC_SHENANDOAH_SHENANDOAHSCANREMEMBERED_HPP