1 /*
   2  * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "gc/shared/cardTableRS.hpp"
  27 #include "gc/shared/genCollectedHeap.hpp"
  28 #include "gc/shared/genOopClosures.hpp"
  29 #include "gc/shared/generation.hpp"
  30 #include "gc/shared/space.inline.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/iterator.inline.hpp"
  33 #include "oops/access.inline.hpp"
  34 #include "oops/oop.inline.hpp"
  35 #include "runtime/atomic.hpp"
  36 #include "runtime/java.hpp"
  37 #include "runtime/os.hpp"
  38 #include "utilities/macros.hpp"
  39 
  40 class HasAccumulatedModifiedOopsClosure : public CLDClosure {
  41   bool _found;
  42  public:
  43   HasAccumulatedModifiedOopsClosure() : _found(false) {}
  44   void do_cld(ClassLoaderData* cld) {
  45     if (_found) {
  46       return;
  47     }
  48 
  49     if (cld->has_accumulated_modified_oops()) {
  50       _found = true;
  51     }
  52   }
  53   bool found() {
  54     return _found;
  55   }
  56 };
  57 
  58 bool CLDRemSet::mod_union_is_clear() {
  59   HasAccumulatedModifiedOopsClosure closure;
  60   ClassLoaderDataGraph::cld_do(&closure);
  61 
  62   return !closure.found();
  63 }
  64 
  65 
  66 class ClearCLDModUnionClosure : public CLDClosure {
  67  public:
  68   void do_cld(ClassLoaderData* cld) {
  69     if (cld->has_accumulated_modified_oops()) {
  70       cld->clear_accumulated_modified_oops();
  71     }
  72   }
  73 };
  74 
  75 void CLDRemSet::clear_mod_union() {
  76   ClearCLDModUnionClosure closure;
  77   ClassLoaderDataGraph::cld_do(&closure);
  78 }
  79 
  80 
  81 jbyte CardTableRS::find_unused_youngergenP_card_value() {
  82   for (jbyte 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(jbyte* 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(jbyte* entry) {
 133   while (true) {
 134     // In the parallel case, we may have to do this several times.
 135     jbyte 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       jbyte res =
 142         Atomic::cmpxchg(CardTableRS::clean_card_val(), entry, entry_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(jbyte* entry) {
 170   jbyte 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(jbyte* 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   jbyte* cur_entry = _ct->byte_for(mr.last());
 198   const jbyte* 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         jbyte* 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 // clean (by dirty->clean before) ==> cur_younger_gen
 248 // dirty                          ==> cur_youngergen_and_prev_nonclean_card
 249 // precleaned                     ==> cur_youngergen_and_prev_nonclean_card
 250 // prev-younger-gen               ==> cur_youngergen_and_prev_nonclean_card
 251 // cur-younger-gen                ==> cur_younger_gen
 252 // cur_youngergen_and_prev_nonclean_card ==> no change.
 253 void CardTableRS::write_ref_field_gc_par(void* field, oop new_val) {
 254   volatile jbyte* entry = byte_for(field);
 255   do {
 256     jbyte entry_val = *entry;
 257     // We put this first because it's probably the most common case.
 258     if (entry_val == clean_card_val()) {
 259       // No threat of contention with cleaning threads.
 260       *entry = cur_youngergen_card_val();
 261       return;
 262     } else if (card_is_dirty_wrt_gen_iter(entry_val)
 263                || is_prev_youngergen_card_val(entry_val)) {
 264       // Mark it as both cur and prev youngergen; card cleaning thread will
 265       // eventually remove the previous stuff.
 266       jbyte new_val = cur_youngergen_and_prev_nonclean_card;
 267       jbyte res = Atomic::cmpxchg(new_val, entry, entry_val);
 268       // Did the CAS succeed?
 269       if (res == entry_val) return;
 270       // Otherwise, retry, to see the new value.
 271       continue;
 272     } else {
 273       assert(entry_val == cur_youngergen_and_prev_nonclean_card
 274              || entry_val == cur_youngergen_card_val(),
 275              "should be only possibilities.");
 276       return;
 277     }
 278   } while (true);
 279 }
 280 
 281 void CardTableRS::younger_refs_in_space_iterate(Space* sp,
 282                                                 OopsInGenClosure* cl,
 283                                                 uint n_threads) {
 284   verify_used_region_at_save_marks(sp);
 285 
 286   const MemRegion urasm = sp->used_region_at_save_marks();
 287   non_clean_card_iterate_possibly_parallel(sp, urasm, cl, this, n_threads);
 288 }
 289 
 290 #ifdef ASSERT
 291 void CardTableRS::verify_used_region_at_save_marks(Space* sp) const {
 292   MemRegion ur    = sp->used_region();
 293   MemRegion urasm = sp->used_region_at_save_marks();
 294 
 295   assert(ur.contains(urasm),
 296          "Did you forget to call save_marks()? "
 297          "[" PTR_FORMAT ", " PTR_FORMAT ") is not contained in "
 298          "[" PTR_FORMAT ", " PTR_FORMAT ")",
 299          p2i(urasm.start()), p2i(urasm.end()), p2i(ur.start()), p2i(ur.end()));
 300 }
 301 #endif
 302 
 303 void CardTableRS::clear_into_younger(Generation* old_gen) {
 304   assert(GenCollectedHeap::heap()->is_old_gen(old_gen),
 305          "Should only be called for the old generation");
 306   // The card tables for the youngest gen need never be cleared.
 307   // There's a bit of subtlety in the clear() and invalidate()
 308   // methods that we exploit here and in invalidate_or_clear()
 309   // below to avoid missing cards at the fringes. If clear() or
 310   // invalidate() are changed in the future, this code should
 311   // be revisited. 20040107.ysr
 312   clear(old_gen->prev_used_region());
 313 }
 314 
 315 void CardTableRS::invalidate_or_clear(Generation* old_gen) {
 316   assert(GenCollectedHeap::heap()->is_old_gen(old_gen),
 317          "Should only be called for the old generation");
 318   // Invalidate the cards for the currently occupied part of
 319   // the old generation and clear the cards for the
 320   // unoccupied part of the generation (if any, making use
 321   // of that generation's prev_used_region to determine that
 322   // region). No need to do anything for the youngest
 323   // generation. Also see note#20040107.ysr above.
 324   MemRegion used_mr = old_gen->used_region();
 325   MemRegion to_be_cleared_mr = old_gen->prev_used_region().minus(used_mr);
 326   if (!to_be_cleared_mr.is_empty()) {
 327     clear(to_be_cleared_mr);
 328   }
 329   invalidate(used_mr);
 330 }
 331 
 332 
 333 class VerifyCleanCardClosure: public BasicOopIterateClosure {
 334 private:
 335   HeapWord* _boundary;
 336   HeapWord* _begin;
 337   HeapWord* _end;
 338 protected:
 339   template <class T> void do_oop_work(T* p) {
 340     HeapWord* jp = (HeapWord*)p;
 341     assert(jp >= _begin && jp < _end,
 342            "Error: jp " PTR_FORMAT " should be within "
 343            "[_begin, _end) = [" PTR_FORMAT "," PTR_FORMAT ")",
 344            p2i(jp), p2i(_begin), p2i(_end));
 345     oop obj = RawAccess<>::oop_load(p);
 346     guarantee(obj == NULL || (HeapWord*)obj >= _boundary,
 347               "pointer " PTR_FORMAT " at " PTR_FORMAT " on "
 348               "clean card crosses boundary" PTR_FORMAT,
 349               p2i(obj), p2i(jp), p2i(_boundary));
 350   }
 351 
 352 public:
 353   VerifyCleanCardClosure(HeapWord* b, HeapWord* begin, HeapWord* end) :
 354     _boundary(b), _begin(begin), _end(end) {
 355     assert(b <= begin,
 356            "Error: boundary " PTR_FORMAT " should be at or below begin " PTR_FORMAT,
 357            p2i(b), p2i(begin));
 358     assert(begin <= end,
 359            "Error: begin " PTR_FORMAT " should be strictly below end " PTR_FORMAT,
 360            p2i(begin), p2i(end));
 361   }
 362 
 363   virtual void do_oop(oop* p)       { VerifyCleanCardClosure::do_oop_work(p); }
 364   virtual void do_oop(narrowOop* p) { VerifyCleanCardClosure::do_oop_work(p); }
 365 };
 366 
 367 class VerifyCTSpaceClosure: public SpaceClosure {
 368 private:
 369   CardTableRS* _ct;
 370   HeapWord* _boundary;
 371 public:
 372   VerifyCTSpaceClosure(CardTableRS* ct, HeapWord* boundary) :
 373     _ct(ct), _boundary(boundary) {}
 374   virtual void do_space(Space* s) { _ct->verify_space(s, _boundary); }
 375 };
 376 
 377 class VerifyCTGenClosure: public GenCollectedHeap::GenClosure {
 378   CardTableRS* _ct;
 379 public:
 380   VerifyCTGenClosure(CardTableRS* ct) : _ct(ct) {}
 381   void do_generation(Generation* gen) {
 382     // Skip the youngest generation.
 383     if (GenCollectedHeap::heap()->is_young_gen(gen)) {
 384       return;
 385     }
 386     // Normally, we're interested in pointers to younger generations.
 387     VerifyCTSpaceClosure blk(_ct, gen->reserved().start());
 388     gen->space_iterate(&blk, true);
 389   }
 390 };
 391 
 392 void CardTableRS::verify_space(Space* s, HeapWord* gen_boundary) {
 393   // We don't need to do young-gen spaces.
 394   if (s->end() <= gen_boundary) return;
 395   MemRegion used = s->used_region();
 396 
 397   jbyte* cur_entry = byte_for(used.start());
 398   jbyte* limit = byte_after(used.last());
 399   while (cur_entry < limit) {
 400     if (*cur_entry == clean_card_val()) {
 401       jbyte* first_dirty = cur_entry+1;
 402       while (first_dirty < limit &&
 403              *first_dirty == clean_card_val()) {
 404         first_dirty++;
 405       }
 406       // If the first object is a regular object, and it has a
 407       // young-to-old field, that would mark the previous card.
 408       HeapWord* boundary = addr_for(cur_entry);
 409       HeapWord* end = (first_dirty >= limit) ? used.end() : addr_for(first_dirty);
 410       HeapWord* boundary_block = s->block_start(boundary);
 411       HeapWord* begin = boundary;             // Until proven otherwise.
 412       HeapWord* start_block = boundary_block; // Until proven otherwise.
 413       if (boundary_block < boundary) {
 414         if (s->block_is_obj(boundary_block) && s->obj_is_alive(boundary_block)) {
 415           oop boundary_obj = oop(boundary_block);
 416           if (!boundary_obj->is_objArray() &&
 417               !boundary_obj->is_typeArray()) {
 418             guarantee(cur_entry > byte_for(used.start()),
 419                       "else boundary would be boundary_block");
 420             if (*byte_for(boundary_block) != clean_card_val()) {
 421               begin = boundary_block + s->block_size(boundary_block);
 422               start_block = begin;
 423             }
 424           }
 425         }
 426       }
 427       // Now traverse objects until end.
 428       if (begin < end) {
 429         MemRegion mr(begin, end);
 430         VerifyCleanCardClosure verify_blk(gen_boundary, begin, end);
 431         for (HeapWord* cur = start_block; cur < end; cur += s->block_size(cur)) {
 432           if (s->block_is_obj(cur) && s->obj_is_alive(cur)) {
 433             oop(cur)->oop_iterate(&verify_blk, mr);
 434           }
 435         }
 436       }
 437       cur_entry = first_dirty;
 438     } else {
 439       // We'd normally expect that cur_youngergen_and_prev_nonclean_card
 440       // is a transient value, that cannot be in the card table
 441       // except during GC, and thus assert that:
 442       // guarantee(*cur_entry != cur_youngergen_and_prev_nonclean_card,
 443       //        "Illegal CT value");
 444       // That however, need not hold, as will become clear in the
 445       // following...
 446 
 447       // We'd normally expect that if we are in the parallel case,
 448       // we can't have left a prev value (which would be different
 449       // from the current value) in the card table, and so we'd like to
 450       // assert that:
 451       // guarantee(cur_youngergen_card_val() == youngergen_card
 452       //           || !is_prev_youngergen_card_val(*cur_entry),
 453       //           "Illegal CT value");
 454       // That, however, may not hold occasionally, because of
 455       // CMS or MSC in the old gen. To wit, consider the
 456       // following two simple illustrative scenarios:
 457       // (a) CMS: Consider the case where a large object L
 458       //     spanning several cards is allocated in the old
 459       //     gen, and has a young gen reference stored in it, dirtying
 460       //     some interior cards. A young collection scans the card,
 461       //     finds a young ref and installs a youngergenP_n value.
 462       //     L then goes dead. Now a CMS collection starts,
 463       //     finds L dead and sweeps it up. Assume that L is
 464       //     abutting _unallocated_blk, so _unallocated_blk is
 465       //     adjusted down to (below) L. Assume further that
 466       //     no young collection intervenes during this CMS cycle.
 467       //     The next young gen cycle will not get to look at this
 468       //     youngergenP_n card since it lies in the unoccupied
 469       //     part of the space.
 470       //     Some young collections later the blocks on this
 471       //     card can be re-allocated either due to direct allocation
 472       //     or due to absorbing promotions. At this time, the
 473       //     before-gc verification will fail the above assert.
 474       // (b) MSC: In this case, an object L with a young reference
 475       //     is on a card that (therefore) holds a youngergen_n value.
 476       //     Suppose also that L lies towards the end of the used
 477       //     the used space before GC. An MSC collection
 478       //     occurs that compacts to such an extent that this
 479       //     card is no longer in the occupied part of the space.
 480       //     Since current code in MSC does not always clear cards
 481       //     in the unused part of old gen, this stale youngergen_n
 482       //     value is left behind and can later be covered by
 483       //     an object when promotion or direct allocation
 484       //     re-allocates that part of the heap.
 485       //
 486       // Fortunately, the presence of such stale card values is
 487       // "only" a minor annoyance in that subsequent young collections
 488       // might needlessly scan such cards, but would still never corrupt
 489       // the heap as a result. However, it's likely not to be a significant
 490       // performance inhibitor in practice. For instance,
 491       // some recent measurements with unoccupied cards eagerly cleared
 492       // out to maintain this invariant, showed next to no
 493       // change in young collection times; of course one can construct
 494       // degenerate examples where the cost can be significant.)
 495       // Note, in particular, that if the "stale" card is modified
 496       // after re-allocation, it would be dirty, not "stale". Thus,
 497       // we can never have a younger ref in such a card and it is
 498       // safe not to scan that card in any collection. [As we see
 499       // below, we do some unnecessary scanning
 500       // in some cases in the current parallel scanning algorithm.]
 501       //
 502       // The main point below is that the parallel card scanning code
 503       // deals correctly with these stale card values. There are two main
 504       // cases to consider where we have a stale "young gen" value and a
 505       // "derivative" case to consider, where we have a stale
 506       // "cur_younger_gen_and_prev_non_clean" value, as will become
 507       // apparent in the case analysis below.
 508       // o Case 1. If the stale value corresponds to a younger_gen_n
 509       //   value other than the cur_younger_gen value then the code
 510       //   treats this as being tantamount to a prev_younger_gen
 511       //   card. This means that the card may be unnecessarily scanned.
 512       //   There are two sub-cases to consider:
 513       //   o Case 1a. Let us say that the card is in the occupied part
 514       //     of the generation at the time the collection begins. In
 515       //     that case the card will be either cleared when it is scanned
 516       //     for young pointers, or will be set to cur_younger_gen as a
 517       //     result of promotion. (We have elided the normal case where
 518       //     the scanning thread and the promoting thread interleave
 519       //     possibly resulting in a transient
 520       //     cur_younger_gen_and_prev_non_clean value before settling
 521       //     to cur_younger_gen. [End Case 1a.]
 522       //   o Case 1b. Consider now the case when the card is in the unoccupied
 523       //     part of the space which becomes occupied because of promotions
 524       //     into it during the current young GC. In this case the card
 525       //     will never be scanned for young references. The current
 526       //     code will set the card value to either
 527       //     cur_younger_gen_and_prev_non_clean or leave
 528       //     it with its stale value -- because the promotions didn't
 529       //     result in any younger refs on that card. Of these two
 530       //     cases, the latter will be covered in Case 1a during
 531       //     a subsequent scan. To deal with the former case, we need
 532       //     to further consider how we deal with a stale value of
 533       //     cur_younger_gen_and_prev_non_clean in our case analysis
 534       //     below. This we do in Case 3 below. [End Case 1b]
 535       //   [End Case 1]
 536       // o Case 2. If the stale value corresponds to cur_younger_gen being
 537       //   a value not necessarily written by a current promotion, the
 538       //   card will not be scanned by the younger refs scanning code.
 539       //   (This is OK since as we argued above such cards cannot contain
 540       //   any younger refs.) The result is that this value will be
 541       //   treated as a prev_younger_gen value in a subsequent collection,
 542       //   which is addressed in Case 1 above. [End Case 2]
 543       // o Case 3. We here consider the "derivative" case from Case 1b. above
 544       //   because of which we may find a stale
 545       //   cur_younger_gen_and_prev_non_clean card value in the table.
 546       //   Once again, as in Case 1, we consider two subcases, depending
 547       //   on whether the card lies in the occupied or unoccupied part
 548       //   of the space at the start of the young collection.
 549       //   o Case 3a. Let us say the card is in the occupied part of
 550       //     the old gen at the start of the young collection. In that
 551       //     case, the card will be scanned by the younger refs scanning
 552       //     code which will set it to cur_younger_gen. In a subsequent
 553       //     scan, the card will be considered again and get its final
 554       //     correct value. [End Case 3a]
 555       //   o Case 3b. Now consider the case where the card is in the
 556       //     unoccupied part of the old gen, and is occupied as a result
 557       //     of promotions during thus young gc. In that case,
 558       //     the card will not be scanned for younger refs. The presence
 559       //     of newly promoted objects on the card will then result in
 560       //     its keeping the value cur_younger_gen_and_prev_non_clean
 561       //     value, which we have dealt with in Case 3 here. [End Case 3b]
 562       //   [End Case 3]
 563       //
 564       // (Please refer to the code in the helper class
 565       // ClearNonCleanCardWrapper and in CardTable for details.)
 566       //
 567       // The informal arguments above can be tightened into a formal
 568       // correctness proof and it behooves us to write up such a proof,
 569       // or to use model checking to prove that there are no lingering
 570       // concerns.
 571       //
 572       // Clearly because of Case 3b one cannot bound the time for
 573       // which a card will retain what we have called a "stale" value.
 574       // However, one can obtain a Loose upper bound on the redundant
 575       // work as a result of such stale values. Note first that any
 576       // time a stale card lies in the occupied part of the space at
 577       // the start of the collection, it is scanned by younger refs
 578       // code and we can define a rank function on card values that
 579       // declines when this is so. Note also that when a card does not
 580       // lie in the occupied part of the space at the beginning of a
 581       // young collection, its rank can either decline or stay unchanged.
 582       // In this case, no extra work is done in terms of redundant
 583       // younger refs scanning of that card.
 584       // Then, the case analysis above reveals that, in the worst case,
 585       // any such stale card will be scanned unnecessarily at most twice.
 586       //
 587       // It is nonetheless advisable to try and get rid of some of this
 588       // redundant work in a subsequent (low priority) re-design of
 589       // the card-scanning code, if only to simplify the underlying
 590       // state machine analysis/proof. ysr 1/28/2002. XXX
 591       cur_entry++;
 592     }
 593   }
 594 }
 595 
 596 void CardTableRS::verify() {
 597   // At present, we only know how to verify the card table RS for
 598   // generational heaps.
 599   VerifyCTGenClosure blk(this);
 600   GenCollectedHeap::heap()->generation_iterate(&blk, false);
 601   CardTable::verify();
 602 }
 603 
 604 CardTableRS::CardTableRS(MemRegion whole_heap, bool scanned_concurrently) :
 605   CardTable(whole_heap, scanned_concurrently),
 606   _cur_youngergen_card_val(youngergenP1_card),
 607   // LNC functionality
 608   _lowest_non_clean(NULL),
 609   _lowest_non_clean_chunk_size(NULL),
 610   _lowest_non_clean_base_chunk_index(NULL),
 611   _last_LNC_resizing_collection(NULL)
 612 {
 613   // max_gens is really GenCollectedHeap::heap()->gen_policy()->number_of_generations()
 614   // (which is always 2, young & old), but GenCollectedHeap has not been initialized yet.
 615   uint max_gens = 2;
 616   _last_cur_val_in_gen = NEW_C_HEAP_ARRAY3(jbyte, max_gens + 1,
 617                          mtGC, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 618   if (_last_cur_val_in_gen == NULL) {
 619     vm_exit_during_initialization("Could not create last_cur_val_in_gen array.");
 620   }
 621   for (uint i = 0; i < max_gens + 1; i++) {
 622     _last_cur_val_in_gen[i] = clean_card_val();
 623   }
 624 }
 625 
 626 CardTableRS::~CardTableRS() {
 627   if (_last_cur_val_in_gen) {
 628     FREE_C_HEAP_ARRAY(jbyte, _last_cur_val_in_gen);
 629     _last_cur_val_in_gen = NULL;
 630   }
 631   if (_lowest_non_clean) {
 632     FREE_C_HEAP_ARRAY(CardArr, _lowest_non_clean);
 633     _lowest_non_clean = NULL;
 634   }
 635   if (_lowest_non_clean_chunk_size) {
 636     FREE_C_HEAP_ARRAY(size_t, _lowest_non_clean_chunk_size);
 637     _lowest_non_clean_chunk_size = NULL;
 638   }
 639   if (_lowest_non_clean_base_chunk_index) {
 640     FREE_C_HEAP_ARRAY(uintptr_t, _lowest_non_clean_base_chunk_index);
 641     _lowest_non_clean_base_chunk_index = NULL;
 642   }
 643   if (_last_LNC_resizing_collection) {
 644     FREE_C_HEAP_ARRAY(int, _last_LNC_resizing_collection);
 645     _last_LNC_resizing_collection = NULL;
 646   }
 647 }
 648 
 649 void CardTableRS::initialize() {
 650   CardTable::initialize();
 651   _lowest_non_clean =
 652     NEW_C_HEAP_ARRAY(CardArr, _max_covered_regions, mtGC);
 653   _lowest_non_clean_chunk_size =
 654     NEW_C_HEAP_ARRAY(size_t, _max_covered_regions, mtGC);
 655   _lowest_non_clean_base_chunk_index =
 656     NEW_C_HEAP_ARRAY(uintptr_t, _max_covered_regions, mtGC);
 657   _last_LNC_resizing_collection =
 658     NEW_C_HEAP_ARRAY(int, _max_covered_regions, mtGC);
 659   if (_lowest_non_clean == NULL
 660       || _lowest_non_clean_chunk_size == NULL
 661       || _lowest_non_clean_base_chunk_index == NULL
 662       || _last_LNC_resizing_collection == NULL)
 663     vm_exit_during_initialization("couldn't allocate an LNC array.");
 664   for (int i = 0; i < _max_covered_regions; i++) {
 665     _lowest_non_clean[i] = NULL;
 666     _lowest_non_clean_chunk_size[i] = 0;
 667     _last_LNC_resizing_collection[i] = -1;
 668   }
 669 }
 670 
 671 bool CardTableRS::card_will_be_scanned(jbyte cv) {
 672   return card_is_dirty_wrt_gen_iter(cv) || is_prev_nonclean_card_val(cv);
 673 }
 674 
 675 bool CardTableRS::card_may_have_been_dirty(jbyte cv) {
 676   return
 677     cv != clean_card &&
 678     (card_is_dirty_wrt_gen_iter(cv) ||
 679      CardTableRS::youngergen_may_have_been_dirty(cv));
 680 }
 681 
 682 void CardTableRS::non_clean_card_iterate_possibly_parallel(
 683   Space* sp,
 684   MemRegion mr,
 685   OopsInGenClosure* cl,
 686   CardTableRS* ct,
 687   uint n_threads)
 688 {
 689   if (!mr.is_empty()) {
 690     if (n_threads > 0) {
 691       non_clean_card_iterate_parallel_work(sp, mr, cl, ct, n_threads);
 692     } else {
 693       // clear_cl finds contiguous dirty ranges of cards to process and clear.
 694 
 695       // This is the single-threaded version used by DefNew.
 696       const bool parallel = false;
 697 
 698       DirtyCardToOopClosure* dcto_cl = sp->new_dcto_cl(cl, precision(), cl->gen_boundary(), parallel);
 699       ClearNoncleanCardWrapper clear_cl(dcto_cl, ct, parallel);
 700 
 701       clear_cl.do_MemRegion(mr);
 702     }
 703   }
 704 }
 705 
 706 void CardTableRS::non_clean_card_iterate_parallel_work(Space* sp, MemRegion mr,
 707                                                        OopsInGenClosure* cl, CardTableRS* ct,
 708                                                        uint n_threads) {
 709   fatal("Parallel gc not supported here.");
 710 }
 711 
 712 bool CardTableRS::is_in_young(oop obj) const {
 713   return GenCollectedHeap::heap()->is_in_young(obj);
 714 }