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