1 /*
   2  * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoaderDataGraph.hpp"
  27 #include "gc/shared/cardTableRS.hpp"
  28 #include "gc/shared/genCollectedHeap.hpp"
  29 #include "gc/shared/genOopClosures.hpp"
  30 #include "gc/shared/generation.hpp"
  31 #include "gc/shared/space.inline.hpp"
  32 #include "memory/allocation.inline.hpp"
  33 #include "memory/iterator.inline.hpp"
  34 #include "oops/access.inline.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "runtime/atomic.hpp"
  37 #include "runtime/java.hpp"
  38 #include "runtime/os.hpp"
  39 #include "utilities/macros.hpp"
  40 
  41 class HasAccumulatedModifiedOopsClosure : public CLDClosure {
  42   bool _found;
  43  public:
  44   HasAccumulatedModifiedOopsClosure() : _found(false) {}
  45   void do_cld(ClassLoaderData* cld) {
  46     if (_found) {
  47       return;
  48     }
  49 
  50     if (cld->has_accumulated_modified_oops()) {
  51       _found = true;
  52     }
  53   }
  54   bool found() {
  55     return _found;
  56   }
  57 };
  58 
  59 bool CLDRemSet::mod_union_is_clear() {
  60   HasAccumulatedModifiedOopsClosure closure;
  61   ClassLoaderDataGraph::cld_do(&closure);
  62 
  63   return !closure.found();
  64 }
  65 
  66 
  67 class ClearCLDModUnionClosure : public CLDClosure {
  68  public:
  69   void do_cld(ClassLoaderData* cld) {
  70     if (cld->has_accumulated_modified_oops()) {
  71       cld->clear_accumulated_modified_oops();
  72     }
  73   }
  74 };
  75 
  76 void CLDRemSet::clear_mod_union() {
  77   ClearCLDModUnionClosure closure;
  78   ClassLoaderDataGraph::cld_do(&closure);
  79 }
  80 
  81 CardTable::CardValue CardTableRS::find_unused_youngergenP_card_value() {
  82   for (CardValue v = youngergenP1_card;
  83        v < cur_youngergen_and_prev_nonclean_card;
  84        v++) {
  85     bool seen = false;
  86     for (int g = 0; g < _regions_to_iterate; g++) {
  87       if (_last_cur_val_in_gen[g] == v) {
  88         seen = true;
  89         break;
  90       }
  91     }
  92     if (!seen) {
  93       return v;
  94     }
  95   }
  96   ShouldNotReachHere();
  97   return 0;
  98 }
  99 
 100 void CardTableRS::prepare_for_younger_refs_iterate(bool parallel) {
 101   // Parallel or sequential, we must always set the prev to equal the
 102   // last one written.
 103   if (parallel) {
 104     // Find a parallel value to be used next.
 105     jbyte next_val = find_unused_youngergenP_card_value();
 106     set_cur_youngergen_card_val(next_val);
 107 
 108   } else {
 109     // In an sequential traversal we will always write youngergen, so that
 110     // the inline barrier is  correct.
 111     set_cur_youngergen_card_val(youngergen_card);
 112   }
 113 }
 114 
 115 void CardTableRS::younger_refs_iterate(Generation* g,
 116                                        OopsInGenClosure* blk,
 117                                        uint n_threads) {
 118   // The indexing in this array is slightly odd. We want to access
 119   // the old generation record here, which is at index 2.
 120   _last_cur_val_in_gen[2] = cur_youngergen_card_val();
 121   g->younger_refs_iterate(blk, n_threads);
 122 }
 123 
 124 inline bool ClearNoncleanCardWrapper::clear_card(CardValue* entry) {
 125   if (_is_par) {
 126     return clear_card_parallel(entry);
 127   } else {
 128     return clear_card_serial(entry);
 129   }
 130 }
 131 
 132 inline bool ClearNoncleanCardWrapper::clear_card_parallel(CardValue* entry) {
 133   while (true) {
 134     // In the parallel case, we may have to do this several times.
 135     CardValue entry_val = *entry;
 136     assert(entry_val != CardTableRS::clean_card_val(),
 137            "We shouldn't be looking at clean cards, and this should "
 138            "be the only place they get cleaned.");
 139     if (CardTableRS::card_is_dirty_wrt_gen_iter(entry_val)
 140         || _ct->is_prev_youngergen_card_val(entry_val)) {
 141       CardValue res =
 142         Atomic::cmpxchg(entry, entry_val, CardTableRS::clean_card_val());
 143       if (res == entry_val) {
 144         break;
 145       } else {
 146         assert(res == CardTableRS::cur_youngergen_and_prev_nonclean_card,
 147                "The CAS above should only fail if another thread did "
 148                "a GC write barrier.");
 149       }
 150     } else if (entry_val ==
 151                CardTableRS::cur_youngergen_and_prev_nonclean_card) {
 152       // Parallelism shouldn't matter in this case.  Only the thread
 153       // assigned to scan the card should change this value.
 154       *entry = _ct->cur_youngergen_card_val();
 155       break;
 156     } else {
 157       assert(entry_val == _ct->cur_youngergen_card_val(),
 158              "Should be the only possibility.");
 159       // In this case, the card was clean before, and become
 160       // cur_youngergen only because of processing of a promoted object.
 161       // We don't have to look at the card.
 162       return false;
 163     }
 164   }
 165   return true;
 166 }
 167 
 168 
 169 inline bool ClearNoncleanCardWrapper::clear_card_serial(CardValue* entry) {
 170   CardValue entry_val = *entry;
 171   assert(entry_val != CardTableRS::clean_card_val(),
 172          "We shouldn't be looking at clean cards, and this should "
 173          "be the only place they get cleaned.");
 174   assert(entry_val != CardTableRS::cur_youngergen_and_prev_nonclean_card,
 175          "This should be possible in the sequential case.");
 176   *entry = CardTableRS::clean_card_val();
 177   return true;
 178 }
 179 
 180 ClearNoncleanCardWrapper::ClearNoncleanCardWrapper(
 181   DirtyCardToOopClosure* dirty_card_closure, CardTableRS* ct, bool is_par) :
 182     _dirty_card_closure(dirty_card_closure), _ct(ct), _is_par(is_par) {
 183 }
 184 
 185 bool ClearNoncleanCardWrapper::is_word_aligned(CardTable::CardValue* entry) {
 186   return (((intptr_t)entry) & (BytesPerWord-1)) == 0;
 187 }
 188 
 189 // The regions are visited in *decreasing* address order.
 190 // This order aids with imprecise card marking, where a dirty
 191 // card may cause scanning, and summarization marking, of objects
 192 // that extend onto subsequent cards.
 193 void ClearNoncleanCardWrapper::do_MemRegion(MemRegion mr) {
 194   assert(mr.word_size() > 0, "Error");
 195   assert(_ct->is_aligned(mr.start()), "mr.start() should be card aligned");
 196   // mr.end() may not necessarily be card aligned.
 197   CardValue* cur_entry = _ct->byte_for(mr.last());
 198   const CardValue* limit = _ct->byte_for(mr.start());
 199   HeapWord* end_of_non_clean = mr.end();
 200   HeapWord* start_of_non_clean = end_of_non_clean;
 201   while (cur_entry >= limit) {
 202     HeapWord* cur_hw = _ct->addr_for(cur_entry);
 203     if ((*cur_entry != CardTableRS::clean_card_val()) && clear_card(cur_entry)) {
 204       // Continue the dirty range by opening the
 205       // dirty window one card to the left.
 206       start_of_non_clean = cur_hw;
 207     } else {
 208       // We hit a "clean" card; process any non-empty
 209       // "dirty" range accumulated so far.
 210       if (start_of_non_clean < end_of_non_clean) {
 211         const MemRegion mrd(start_of_non_clean, end_of_non_clean);
 212         _dirty_card_closure->do_MemRegion(mrd);
 213       }
 214 
 215       // fast forward through potential continuous whole-word range of clean cards beginning at a word-boundary
 216       if (is_word_aligned(cur_entry)) {
 217         CardValue* cur_row = cur_entry - BytesPerWord;
 218         while (cur_row >= limit && *((intptr_t*)cur_row) ==  CardTableRS::clean_card_row_val()) {
 219           cur_row -= BytesPerWord;
 220         }
 221         cur_entry = cur_row + BytesPerWord;
 222         cur_hw = _ct->addr_for(cur_entry);
 223       }
 224 
 225       // Reset the dirty window, while continuing to look
 226       // for the next dirty card that will start a
 227       // new dirty window.
 228       end_of_non_clean = cur_hw;
 229       start_of_non_clean = cur_hw;
 230     }
 231     // Note that "cur_entry" leads "start_of_non_clean" in
 232     // its leftward excursion after this point
 233     // in the loop and, when we hit the left end of "mr",
 234     // will point off of the left end of the card-table
 235     // for "mr".
 236     cur_entry--;
 237   }
 238   // If the first card of "mr" was dirty, we will have
 239   // been left with a dirty window, co-initial with "mr",
 240   // which we now process.
 241   if (start_of_non_clean < end_of_non_clean) {
 242     const MemRegion mrd(start_of_non_clean, end_of_non_clean);
 243     _dirty_card_closure->do_MemRegion(mrd);
 244   }
 245 }
 246 
 247 void CardTableRS::younger_refs_in_space_iterate(Space* sp,
 248                                                 OopsInGenClosure* cl,
 249                                                 uint n_threads) {
 250   verify_used_region_at_save_marks(sp);
 251 
 252   const MemRegion urasm = sp->used_region_at_save_marks();
 253   non_clean_card_iterate_possibly_parallel(sp, urasm, cl, this, n_threads);
 254 }
 255 
 256 #ifdef ASSERT
 257 void CardTableRS::verify_used_region_at_save_marks(Space* sp) const {
 258   MemRegion ur    = sp->used_region();
 259   MemRegion urasm = sp->used_region_at_save_marks();
 260 
 261   assert(ur.contains(urasm),
 262          "Did you forget to call save_marks()? "
 263          "[" PTR_FORMAT ", " PTR_FORMAT ") is not contained in "
 264          "[" PTR_FORMAT ", " PTR_FORMAT ")",
 265          p2i(urasm.start()), p2i(urasm.end()), p2i(ur.start()), p2i(ur.end()));
 266 }
 267 #endif
 268 
 269 void CardTableRS::clear_into_younger(Generation* old_gen) {
 270   assert(GenCollectedHeap::heap()->is_old_gen(old_gen),
 271          "Should only be called for the old generation");
 272   // The card tables for the youngest gen need never be cleared.
 273   // There's a bit of subtlety in the clear() and invalidate()
 274   // methods that we exploit here and in invalidate_or_clear()
 275   // below to avoid missing cards at the fringes. If clear() or
 276   // invalidate() are changed in the future, this code should
 277   // be revisited. 20040107.ysr
 278   clear(old_gen->prev_used_region());
 279 }
 280 
 281 void CardTableRS::invalidate_or_clear(Generation* old_gen) {
 282   assert(GenCollectedHeap::heap()->is_old_gen(old_gen),
 283          "Should only be called for the old generation");
 284   // Invalidate the cards for the currently occupied part of
 285   // the old generation and clear the cards for the
 286   // unoccupied part of the generation (if any, making use
 287   // of that generation's prev_used_region to determine that
 288   // region). No need to do anything for the youngest
 289   // generation. Also see note#20040107.ysr above.
 290   MemRegion used_mr = old_gen->used_region();
 291   MemRegion to_be_cleared_mr = old_gen->prev_used_region().minus(used_mr);
 292   if (!to_be_cleared_mr.is_empty()) {
 293     clear(to_be_cleared_mr);
 294   }
 295   invalidate(used_mr);
 296 }
 297 
 298 
 299 class VerifyCleanCardClosure: public BasicOopIterateClosure {
 300 private:
 301   HeapWord* _boundary;
 302   HeapWord* _begin;
 303   HeapWord* _end;
 304 protected:
 305   template <class T> void do_oop_work(T* p) {
 306     HeapWord* jp = (HeapWord*)p;
 307     assert(jp >= _begin && jp < _end,
 308            "Error: jp " PTR_FORMAT " should be within "
 309            "[_begin, _end) = [" PTR_FORMAT "," PTR_FORMAT ")",
 310            p2i(jp), p2i(_begin), p2i(_end));
 311     oop obj = RawAccess<>::oop_load(p);
 312     guarantee(obj == NULL || cast_from_oop<HeapWord*>(obj) >= _boundary,
 313               "pointer " PTR_FORMAT " at " PTR_FORMAT " on "
 314               "clean card crosses boundary" PTR_FORMAT,
 315               p2i(obj), p2i(jp), p2i(_boundary));
 316   }
 317 
 318 public:
 319   VerifyCleanCardClosure(HeapWord* b, HeapWord* begin, HeapWord* end) :
 320     _boundary(b), _begin(begin), _end(end) {
 321     assert(b <= begin,
 322            "Error: boundary " PTR_FORMAT " should be at or below begin " PTR_FORMAT,
 323            p2i(b), p2i(begin));
 324     assert(begin <= end,
 325            "Error: begin " PTR_FORMAT " should be strictly below end " PTR_FORMAT,
 326            p2i(begin), p2i(end));
 327   }
 328 
 329   virtual void do_oop(oop* p)       { VerifyCleanCardClosure::do_oop_work(p); }
 330   virtual void do_oop(narrowOop* p) { VerifyCleanCardClosure::do_oop_work(p); }
 331 };
 332 
 333 class VerifyCTSpaceClosure: public SpaceClosure {
 334 private:
 335   CardTableRS* _ct;
 336   HeapWord* _boundary;
 337 public:
 338   VerifyCTSpaceClosure(CardTableRS* ct, HeapWord* boundary) :
 339     _ct(ct), _boundary(boundary) {}
 340   virtual void do_space(Space* s) { _ct->verify_space(s, _boundary); }
 341 };
 342 
 343 class VerifyCTGenClosure: public GenCollectedHeap::GenClosure {
 344   CardTableRS* _ct;
 345 public:
 346   VerifyCTGenClosure(CardTableRS* ct) : _ct(ct) {}
 347   void do_generation(Generation* gen) {
 348     // Skip the youngest generation.
 349     if (GenCollectedHeap::heap()->is_young_gen(gen)) {
 350       return;
 351     }
 352     // Normally, we're interested in pointers to younger generations.
 353     VerifyCTSpaceClosure blk(_ct, gen->reserved().start());
 354     gen->space_iterate(&blk, true);
 355   }
 356 };
 357 
 358 void CardTableRS::verify_space(Space* s, HeapWord* gen_boundary) {
 359   // We don't need to do young-gen spaces.
 360   if (s->end() <= gen_boundary) return;
 361   MemRegion used = s->used_region();
 362 
 363   CardValue* cur_entry = byte_for(used.start());
 364   CardValue* limit = byte_after(used.last());
 365   while (cur_entry < limit) {
 366     if (*cur_entry == clean_card_val()) {
 367       CardValue* first_dirty = cur_entry+1;
 368       while (first_dirty < limit &&
 369              *first_dirty == clean_card_val()) {
 370         first_dirty++;
 371       }
 372       // If the first object is a regular object, and it has a
 373       // young-to-old field, that would mark the previous card.
 374       HeapWord* boundary = addr_for(cur_entry);
 375       HeapWord* end = (first_dirty >= limit) ? used.end() : addr_for(first_dirty);
 376       HeapWord* boundary_block = s->block_start(boundary);
 377       HeapWord* begin = boundary;             // Until proven otherwise.
 378       HeapWord* start_block = boundary_block; // Until proven otherwise.
 379       if (boundary_block < boundary) {
 380         if (s->block_is_obj(boundary_block) && s->obj_is_alive(boundary_block)) {
 381           oop boundary_obj = oop(boundary_block);
 382           if (!boundary_obj->is_objArray() &&
 383               !boundary_obj->is_typeArray()) {
 384             guarantee(cur_entry > byte_for(used.start()),
 385                       "else boundary would be boundary_block");
 386             if (*byte_for(boundary_block) != clean_card_val()) {
 387               begin = boundary_block + s->block_size(boundary_block);
 388               start_block = begin;
 389             }
 390           }
 391         }
 392       }
 393       // Now traverse objects until end.
 394       if (begin < end) {
 395         MemRegion mr(begin, end);
 396         VerifyCleanCardClosure verify_blk(gen_boundary, begin, end);
 397         for (HeapWord* cur = start_block; cur < end; cur += s->block_size(cur)) {
 398           if (s->block_is_obj(cur) && s->obj_is_alive(cur)) {
 399             oop(cur)->oop_iterate(&verify_blk, mr);
 400           }
 401         }
 402       }
 403       cur_entry = first_dirty;
 404     } else {
 405       // We'd normally expect that cur_youngergen_and_prev_nonclean_card
 406       // is a transient value, that cannot be in the card table
 407       // except during GC, and thus assert that:
 408       // guarantee(*cur_entry != cur_youngergen_and_prev_nonclean_card,
 409       //        "Illegal CT value");
 410       // That however, need not hold, as will become clear in the
 411       // following...
 412 
 413       // We'd normally expect that if we are in the parallel case,
 414       // we can't have left a prev value (which would be different
 415       // from the current value) in the card table, and so we'd like to
 416       // assert that:
 417       // guarantee(cur_youngergen_card_val() == youngergen_card
 418       //           || !is_prev_youngergen_card_val(*cur_entry),
 419       //           "Illegal CT value");
 420       // That, however, may not hold occasionally, because of
 421       // CMS or MSC in the old gen. To wit, consider the
 422       // following two simple illustrative scenarios:
 423       // (a) CMS: Consider the case where a large object L
 424       //     spanning several cards is allocated in the old
 425       //     gen, and has a young gen reference stored in it, dirtying
 426       //     some interior cards. A young collection scans the card,
 427       //     finds a young ref and installs a youngergenP_n value.
 428       //     L then goes dead. Now a CMS collection starts,
 429       //     finds L dead and sweeps it up. Assume that L is
 430       //     abutting _unallocated_blk, so _unallocated_blk is
 431       //     adjusted down to (below) L. Assume further that
 432       //     no young collection intervenes during this CMS cycle.
 433       //     The next young gen cycle will not get to look at this
 434       //     youngergenP_n card since it lies in the unoccupied
 435       //     part of the space.
 436       //     Some young collections later the blocks on this
 437       //     card can be re-allocated either due to direct allocation
 438       //     or due to absorbing promotions. At this time, the
 439       //     before-gc verification will fail the above assert.
 440       // (b) MSC: In this case, an object L with a young reference
 441       //     is on a card that (therefore) holds a youngergen_n value.
 442       //     Suppose also that L lies towards the end of the used
 443       //     the used space before GC. An MSC collection
 444       //     occurs that compacts to such an extent that this
 445       //     card is no longer in the occupied part of the space.
 446       //     Since current code in MSC does not always clear cards
 447       //     in the unused part of old gen, this stale youngergen_n
 448       //     value is left behind and can later be covered by
 449       //     an object when promotion or direct allocation
 450       //     re-allocates that part of the heap.
 451       //
 452       // Fortunately, the presence of such stale card values is
 453       // "only" a minor annoyance in that subsequent young collections
 454       // might needlessly scan such cards, but would still never corrupt
 455       // the heap as a result. However, it's likely not to be a significant
 456       // performance inhibitor in practice. For instance,
 457       // some recent measurements with unoccupied cards eagerly cleared
 458       // out to maintain this invariant, showed next to no
 459       // change in young collection times; of course one can construct
 460       // degenerate examples where the cost can be significant.)
 461       // Note, in particular, that if the "stale" card is modified
 462       // after re-allocation, it would be dirty, not "stale". Thus,
 463       // we can never have a younger ref in such a card and it is
 464       // safe not to scan that card in any collection. [As we see
 465       // below, we do some unnecessary scanning
 466       // in some cases in the current parallel scanning algorithm.]
 467       //
 468       // The main point below is that the parallel card scanning code
 469       // deals correctly with these stale card values. There are two main
 470       // cases to consider where we have a stale "young gen" value and a
 471       // "derivative" case to consider, where we have a stale
 472       // "cur_younger_gen_and_prev_non_clean" value, as will become
 473       // apparent in the case analysis below.
 474       // o Case 1. If the stale value corresponds to a younger_gen_n
 475       //   value other than the cur_younger_gen value then the code
 476       //   treats this as being tantamount to a prev_younger_gen
 477       //   card. This means that the card may be unnecessarily scanned.
 478       //   There are two sub-cases to consider:
 479       //   o Case 1a. Let us say that the card is in the occupied part
 480       //     of the generation at the time the collection begins. In
 481       //     that case the card will be either cleared when it is scanned
 482       //     for young pointers, or will be set to cur_younger_gen as a
 483       //     result of promotion. (We have elided the normal case where
 484       //     the scanning thread and the promoting thread interleave
 485       //     possibly resulting in a transient
 486       //     cur_younger_gen_and_prev_non_clean value before settling
 487       //     to cur_younger_gen. [End Case 1a.]
 488       //   o Case 1b. Consider now the case when the card is in the unoccupied
 489       //     part of the space which becomes occupied because of promotions
 490       //     into it during the current young GC. In this case the card
 491       //     will never be scanned for young references. The current
 492       //     code will set the card value to either
 493       //     cur_younger_gen_and_prev_non_clean or leave
 494       //     it with its stale value -- because the promotions didn't
 495       //     result in any younger refs on that card. Of these two
 496       //     cases, the latter will be covered in Case 1a during
 497       //     a subsequent scan. To deal with the former case, we need
 498       //     to further consider how we deal with a stale value of
 499       //     cur_younger_gen_and_prev_non_clean in our case analysis
 500       //     below. This we do in Case 3 below. [End Case 1b]
 501       //   [End Case 1]
 502       // o Case 2. If the stale value corresponds to cur_younger_gen being
 503       //   a value not necessarily written by a current promotion, the
 504       //   card will not be scanned by the younger refs scanning code.
 505       //   (This is OK since as we argued above such cards cannot contain
 506       //   any younger refs.) The result is that this value will be
 507       //   treated as a prev_younger_gen value in a subsequent collection,
 508       //   which is addressed in Case 1 above. [End Case 2]
 509       // o Case 3. We here consider the "derivative" case from Case 1b. above
 510       //   because of which we may find a stale
 511       //   cur_younger_gen_and_prev_non_clean card value in the table.
 512       //   Once again, as in Case 1, we consider two subcases, depending
 513       //   on whether the card lies in the occupied or unoccupied part
 514       //   of the space at the start of the young collection.
 515       //   o Case 3a. Let us say the card is in the occupied part of
 516       //     the old gen at the start of the young collection. In that
 517       //     case, the card will be scanned by the younger refs scanning
 518       //     code which will set it to cur_younger_gen. In a subsequent
 519       //     scan, the card will be considered again and get its final
 520       //     correct value. [End Case 3a]
 521       //   o Case 3b. Now consider the case where the card is in the
 522       //     unoccupied part of the old gen, and is occupied as a result
 523       //     of promotions during thus young gc. In that case,
 524       //     the card will not be scanned for younger refs. The presence
 525       //     of newly promoted objects on the card will then result in
 526       //     its keeping the value cur_younger_gen_and_prev_non_clean
 527       //     value, which we have dealt with in Case 3 here. [End Case 3b]
 528       //   [End Case 3]
 529       //
 530       // (Please refer to the code in the helper class
 531       // ClearNonCleanCardWrapper and in CardTable for details.)
 532       //
 533       // The informal arguments above can be tightened into a formal
 534       // correctness proof and it behooves us to write up such a proof,
 535       // or to use model checking to prove that there are no lingering
 536       // concerns.
 537       //
 538       // Clearly because of Case 3b one cannot bound the time for
 539       // which a card will retain what we have called a "stale" value.
 540       // However, one can obtain a Loose upper bound on the redundant
 541       // work as a result of such stale values. Note first that any
 542       // time a stale card lies in the occupied part of the space at
 543       // the start of the collection, it is scanned by younger refs
 544       // code and we can define a rank function on card values that
 545       // declines when this is so. Note also that when a card does not
 546       // lie in the occupied part of the space at the beginning of a
 547       // young collection, its rank can either decline or stay unchanged.
 548       // In this case, no extra work is done in terms of redundant
 549       // younger refs scanning of that card.
 550       // Then, the case analysis above reveals that, in the worst case,
 551       // any such stale card will be scanned unnecessarily at most twice.
 552       //
 553       // It is nonetheless advisable to try and get rid of some of this
 554       // redundant work in a subsequent (low priority) re-design of
 555       // the card-scanning code, if only to simplify the underlying
 556       // state machine analysis/proof. ysr 1/28/2002. XXX
 557       cur_entry++;
 558     }
 559   }
 560 }
 561 
 562 void CardTableRS::verify() {
 563   // At present, we only know how to verify the card table RS for
 564   // generational heaps.
 565   VerifyCTGenClosure blk(this);
 566   GenCollectedHeap::heap()->generation_iterate(&blk, false);
 567   CardTable::verify();
 568 }
 569 
 570 CardTableRS::CardTableRS(MemRegion whole_heap, bool scanned_concurrently) :
 571   CardTable(whole_heap, scanned_concurrently),
 572   _cur_youngergen_card_val(youngergenP1_card),
 573   // LNC functionality
 574   _lowest_non_clean(NULL),
 575   _lowest_non_clean_chunk_size(NULL),
 576   _lowest_non_clean_base_chunk_index(NULL),
 577   _last_LNC_resizing_collection(NULL)
 578 {
 579   // max_gens is really GenCollectedHeap::heap()->gen_policy()->number_of_generations()
 580   // (which is always 2, young & old), but GenCollectedHeap has not been initialized yet.
 581   uint max_gens = 2;
 582   _last_cur_val_in_gen = NEW_C_HEAP_ARRAY3(CardValue, max_gens + 1,
 583                          mtGC, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 584   if (_last_cur_val_in_gen == NULL) {
 585     vm_exit_during_initialization("Could not create last_cur_val_in_gen array.");
 586   }
 587   for (uint i = 0; i < max_gens + 1; i++) {
 588     _last_cur_val_in_gen[i] = clean_card_val();
 589   }
 590 }
 591 
 592 CardTableRS::~CardTableRS() {
 593   FREE_C_HEAP_ARRAY(CardValue, _last_cur_val_in_gen);
 594   FREE_C_HEAP_ARRAY(CardArr, _lowest_non_clean);
 595   FREE_C_HEAP_ARRAY(size_t, _lowest_non_clean_chunk_size);
 596   FREE_C_HEAP_ARRAY(uintptr_t, _lowest_non_clean_base_chunk_index);
 597   FREE_C_HEAP_ARRAY(int, _last_LNC_resizing_collection);
 598 }
 599 
 600 void CardTableRS::initialize() {
 601   CardTable::initialize();
 602   _lowest_non_clean =
 603     NEW_C_HEAP_ARRAY(CardArr, _max_covered_regions, mtGC);
 604   _lowest_non_clean_chunk_size =
 605     NEW_C_HEAP_ARRAY(size_t, _max_covered_regions, mtGC);
 606   _lowest_non_clean_base_chunk_index =
 607     NEW_C_HEAP_ARRAY(uintptr_t, _max_covered_regions, mtGC);
 608   _last_LNC_resizing_collection =
 609     NEW_C_HEAP_ARRAY(int, _max_covered_regions, mtGC);
 610 
 611   for (int i = 0; i < _max_covered_regions; i++) {
 612     _lowest_non_clean[i] = NULL;
 613     _lowest_non_clean_chunk_size[i] = 0;
 614     _last_LNC_resizing_collection[i] = -1;
 615   }
 616 }
 617 
 618 bool CardTableRS::card_will_be_scanned(CardValue cv) {
 619   return card_is_dirty_wrt_gen_iter(cv) || is_prev_nonclean_card_val(cv);
 620 }
 621 
 622 bool CardTableRS::card_may_have_been_dirty(CardValue cv) {
 623   return
 624     cv != clean_card &&
 625     (card_is_dirty_wrt_gen_iter(cv) ||
 626      CardTableRS::youngergen_may_have_been_dirty(cv));
 627 }
 628 
 629 void CardTableRS::non_clean_card_iterate_possibly_parallel(
 630   Space* sp,
 631   MemRegion mr,
 632   OopsInGenClosure* cl,
 633   CardTableRS* ct,
 634   uint n_threads)
 635 {
 636   if (!mr.is_empty()) {
 637     if (n_threads > 0) {
 638       non_clean_card_iterate_parallel_work(sp, mr, cl, ct, n_threads);
 639     } else {
 640       // clear_cl finds contiguous dirty ranges of cards to process and clear.
 641 
 642       // This is the single-threaded version used by DefNew.
 643       const bool parallel = false;
 644 
 645       DirtyCardToOopClosure* dcto_cl = sp->new_dcto_cl(cl, precision(), cl->gen_boundary(), parallel);
 646       ClearNoncleanCardWrapper clear_cl(dcto_cl, ct, parallel);
 647 
 648       clear_cl.do_MemRegion(mr);
 649     }
 650   }
 651 }
 652 
 653 void CardTableRS::non_clean_card_iterate_parallel_work(Space* sp, MemRegion mr,
 654                                                        OopsInGenClosure* cl, CardTableRS* ct,
 655                                                        uint n_threads) {
 656   fatal("Parallel gc not supported here.");
 657 }
 658 
 659 bool CardTableRS::is_in_young(oop obj) const {
 660   return GenCollectedHeap::heap()->is_in_young(obj);
 661 }