1 /*
   2  * Copyright (c) 2000, 2013, 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 #ifndef SHARE_VM_MEMORY_CARDTABLEMODREFBS_HPP
  26 #define SHARE_VM_MEMORY_CARDTABLEMODREFBS_HPP
  27 
  28 #include "memory/modRefBarrierSet.hpp"
  29 #include "oops/oop.hpp"
  30 #include "oops/oop.inline2.hpp"
  31 
  32 // This kind of "BarrierSet" allows a "CollectedHeap" to detect and
  33 // enumerate ref fields that have been modified (since the last
  34 // enumeration.)
  35 
  36 // As it currently stands, this barrier is *imprecise*: when a ref field in
  37 // an object "o" is modified, the card table entry for the card containing
  38 // the head of "o" is dirtied, not necessarily the card containing the
  39 // modified field itself.  For object arrays, however, the barrier *is*
  40 // precise; only the card containing the modified element is dirtied.
  41 // Any MemRegionClosures used to scan dirty cards should take these
  42 // considerations into account.
  43 
  44 class Generation;
  45 class OopsInGenClosure;
  46 class DirtyCardToOopClosure;
  47 class ClearNoncleanCardWrapper;
  48 
  49 class CardTableModRefBS: public ModRefBarrierSet {
  50   // Some classes get to look at some private stuff.
  51   friend class BytecodeInterpreter;
  52   friend class VMStructs;
  53   friend class CardTableRS;
  54   friend class CheckForUnmarkedOops; // Needs access to raw card bytes.
  55   friend class SharkBuilder;
  56 #ifndef PRODUCT
  57   // For debugging.
  58   friend class GuaranteeNotModClosure;
  59 #endif
  60  protected:
  61 
  62   enum CardValues {
  63     clean_card                  = -1,
  64     // The mask contains zeros in places for all other values.
  65     clean_card_mask             = clean_card - 31,
  66 
  67     dirty_card                  =  0,
  68     precleaned_card             =  1,
  69     claimed_card                =  2,
  70     deferred_card               =  4,
  71     last_card                   =  8,
  72     CT_MR_BS_last_reserved      = 16,
  73     g1_young_gen                = 32
  74   };
  75 
  76   // a word's worth (row) of clean card values
  77   static const intptr_t clean_card_row = (intptr_t)(-1);
  78 
  79   // dirty and precleaned are equivalent wrt younger_refs_iter.
  80   static bool card_is_dirty_wrt_gen_iter(jbyte cv) {
  81     return cv == dirty_card || cv == precleaned_card;
  82   }
  83 
  84   // Returns "true" iff the value "cv" will cause the card containing it
  85   // to be scanned in the current traversal.  May be overridden by
  86   // subtypes.
  87   virtual bool card_will_be_scanned(jbyte cv) {
  88     return CardTableModRefBS::card_is_dirty_wrt_gen_iter(cv);
  89   }
  90 
  91   // Returns "true" iff the value "cv" may have represented a dirty card at
  92   // some point.
  93   virtual bool card_may_have_been_dirty(jbyte cv) {
  94     return card_is_dirty_wrt_gen_iter(cv);
  95   }
  96 
  97   // The declaration order of these const fields is important; see the
  98   // constructor before changing.
  99   const MemRegion _whole_heap;       // the region covered by the card table
 100   const size_t    _guard_index;      // index of very last element in the card
 101                                      // table; it is set to a guard value
 102                                      // (last_card) and should never be modified
 103   const size_t    _last_valid_index; // index of the last valid element
 104   const size_t    _page_size;        // page size used when mapping _byte_map
 105   const size_t    _byte_map_size;    // in bytes
 106   jbyte*          _byte_map;         // the card marking array
 107 
 108   int _cur_covered_regions;
 109   // The covered regions should be in address order.
 110   MemRegion* _covered;
 111   // The committed regions correspond one-to-one to the covered regions.
 112   // They represent the card-table memory that has been committed to service
 113   // the corresponding covered region.  It may be that committed region for
 114   // one covered region corresponds to a larger region because of page-size
 115   // roundings.  Thus, a committed region for one covered region may
 116   // actually extend onto the card-table space for the next covered region.
 117   MemRegion* _committed;
 118 
 119   // The last card is a guard card, and we commit the page for it so
 120   // we can use the card for verification purposes. We make sure we never
 121   // uncommit the MemRegion for that page.
 122   MemRegion _guard_region;
 123 
 124  protected:
 125   // Initialization utilities; covered_words is the size of the covered region
 126   // in, um, words.
 127   inline size_t cards_required(size_t covered_words);
 128   inline size_t compute_byte_map_size();
 129 
 130   // Finds and return the index of the region, if any, to which the given
 131   // region would be contiguous.  If none exists, assign a new region and
 132   // returns its index.  Requires that no more than the maximum number of
 133   // covered regions defined in the constructor are ever in use.
 134   int find_covering_region_by_base(HeapWord* base);
 135 
 136   // Same as above, but finds the region containing the given address
 137   // instead of starting at a given base address.
 138   int find_covering_region_containing(HeapWord* addr);
 139 
 140   // Resize one of the regions covered by the remembered set.
 141   void resize_covered_region(MemRegion new_region);
 142 
 143   // Returns the leftmost end of a committed region corresponding to a
 144   // covered region before covered region "ind", or else "NULL" if "ind" is
 145   // the first covered region.
 146   HeapWord* largest_prev_committed_end(int ind) const;
 147 
 148   // Returns the part of the region mr that doesn't intersect with
 149   // any committed region other than self.  Used to prevent uncommitting
 150   // regions that are also committed by other regions.  Also protects
 151   // against uncommitting the guard region.
 152   MemRegion committed_unique_to_self(int self, MemRegion mr) const;
 153 
 154   // Mapping from address to card marking array entry
 155   jbyte* byte_for(const void* p) const {
 156     assert(_whole_heap.contains(p),
 157            err_msg("Attempt to access p = "PTR_FORMAT" out of bounds of "
 158                    " card marking array's _whole_heap = ["PTR_FORMAT","PTR_FORMAT")",
 159                    p, _whole_heap.start(), _whole_heap.end()));
 160     jbyte* result = &byte_map_base[uintptr_t(p) >> card_shift];
 161     assert(result >= _byte_map && result < _byte_map + _byte_map_size,
 162            "out of bounds accessor for card marking array");
 163     return result;
 164   }
 165 
 166   // The card table byte one after the card marking array
 167   // entry for argument address. Typically used for higher bounds
 168   // for loops iterating through the card table.
 169   jbyte* byte_after(const void* p) const {
 170     return byte_for(p) + 1;
 171   }
 172 
 173   // Iterate over the portion of the card-table which covers the given
 174   // region mr in the given space and apply cl to any dirty sub-regions
 175   // of mr. Dirty cards are _not_ cleared by the iterator method itself,
 176   // but closures may arrange to do so on their own should they so wish.
 177   void non_clean_card_iterate_serial(MemRegion mr, MemRegionClosure* cl);
 178 
 179   // A variant of the above that will operate in a parallel mode if
 180   // worker threads are available, and clear the dirty cards as it
 181   // processes them.
 182   // XXX ??? MemRegionClosure above vs OopsInGenClosure below XXX
 183   // XXX some new_dcto_cl's take OopClosure's, plus as above there are
 184   // some MemRegionClosures. Clean this up everywhere. XXX
 185   void non_clean_card_iterate_possibly_parallel(Space* sp, MemRegion mr,
 186                                                 OopsInGenClosure* cl, CardTableRS* ct);
 187 
 188  private:
 189   // Work method used to implement non_clean_card_iterate_possibly_parallel()
 190   // above in the parallel case.
 191   void non_clean_card_iterate_parallel_work(Space* sp, MemRegion mr,
 192                                             OopsInGenClosure* cl, CardTableRS* ct,
 193                                             int n_threads);
 194 
 195  protected:
 196   // Dirty the bytes corresponding to "mr" (not all of which must be
 197   // covered.)
 198   void dirty_MemRegion(MemRegion mr);
 199 
 200   // Clear (to clean_card) the bytes entirely contained within "mr" (not
 201   // all of which must be covered.)
 202   void clear_MemRegion(MemRegion mr);
 203 
 204   // *** Support for parallel card scanning.
 205 
 206   // This is an array, one element per covered region of the card table.
 207   // Each entry is itself an array, with one element per chunk in the
 208   // covered region.  Each entry of these arrays is the lowest non-clean
 209   // card of the corresponding chunk containing part of an object from the
 210   // previous chunk, or else NULL.
 211   typedef jbyte*  CardPtr;
 212   typedef CardPtr* CardArr;
 213   CardArr* _lowest_non_clean;
 214   size_t*  _lowest_non_clean_chunk_size;
 215   uintptr_t* _lowest_non_clean_base_chunk_index;
 216   int* _last_LNC_resizing_collection;
 217 
 218   // Initializes "lowest_non_clean" to point to the array for the region
 219   // covering "sp", and "lowest_non_clean_base_chunk_index" to the chunk
 220   // index of the corresponding to the first element of that array.
 221   // Ensures that these arrays are of sufficient size, allocating if necessary.
 222   // May be called by several threads concurrently.
 223   void get_LNC_array_for_space(Space* sp,
 224                                jbyte**& lowest_non_clean,
 225                                uintptr_t& lowest_non_clean_base_chunk_index,
 226                                size_t& lowest_non_clean_chunk_size);
 227 
 228   // Returns the number of chunks necessary to cover "mr".
 229   size_t chunks_to_cover(MemRegion mr) {
 230     return (size_t)(addr_to_chunk_index(mr.last()) -
 231                     addr_to_chunk_index(mr.start()) + 1);
 232   }
 233 
 234   // Returns the index of the chunk in a stride which
 235   // covers the given address.
 236   uintptr_t addr_to_chunk_index(const void* addr) {
 237     uintptr_t card = (uintptr_t) byte_for(addr);
 238     return card / ParGCCardsPerStrideChunk;
 239   }
 240 
 241   // Apply cl, which must either itself apply dcto_cl or be dcto_cl,
 242   // to the cards in the stride (of n_strides) within the given space.
 243   void process_stride(Space* sp,
 244                       MemRegion used,
 245                       jint stride, int n_strides,
 246                       OopsInGenClosure* cl,
 247                       CardTableRS* ct,
 248                       jbyte** lowest_non_clean,
 249                       uintptr_t lowest_non_clean_base_chunk_index,
 250                       size_t lowest_non_clean_chunk_size);
 251 
 252   // Makes sure that chunk boundaries are handled appropriately, by
 253   // adjusting the min_done of dcto_cl, and by using a special card-table
 254   // value to indicate how min_done should be set.
 255   void process_chunk_boundaries(Space* sp,
 256                                 DirtyCardToOopClosure* dcto_cl,
 257                                 MemRegion chunk_mr,
 258                                 MemRegion used,
 259                                 jbyte** lowest_non_clean,
 260                                 uintptr_t lowest_non_clean_base_chunk_index,
 261                                 size_t    lowest_non_clean_chunk_size);
 262 
 263 public:
 264   // Constants
 265   enum SomePublicConstants {
 266     card_shift                  = 9,
 267     card_size                   = 1 << card_shift,
 268     card_size_in_words          = card_size / sizeof(HeapWord)
 269   };
 270 
 271   static int clean_card_val()      { return clean_card; }
 272   static int clean_card_mask_val() { return clean_card_mask; }
 273   static int dirty_card_val()      { return dirty_card; }
 274   static int claimed_card_val()    { return claimed_card; }
 275   static int precleaned_card_val() { return precleaned_card; }
 276   static int deferred_card_val()   { return deferred_card; }
 277   static int g1_young_card_val()   { return g1_young_gen; }
 278 
 279   // For RTTI simulation.
 280   bool is_a(BarrierSet::Name bsn) {
 281     return bsn == BarrierSet::CardTableModRef || ModRefBarrierSet::is_a(bsn);
 282   }
 283 
 284   CardTableModRefBS(MemRegion whole_heap, int max_covered_regions);
 285   ~CardTableModRefBS();
 286 
 287   // *** Barrier set functions.
 288 
 289   bool has_write_ref_pre_barrier() { return false; }
 290 
 291   // Record a reference update. Note that these versions are precise!
 292   // The scanning code has to handle the fact that the write barrier may be
 293   // either precise or imprecise. We make non-virtual inline variants of
 294   // these functions here for performance.
 295 protected:
 296   void write_ref_field_work(oop obj, size_t offset, oop newVal);
 297   virtual void write_ref_field_work(void* field, oop newVal);
 298 public:
 299 
 300   bool has_write_ref_array_opt() { return true; }
 301   bool has_write_region_opt() { return true; }
 302 
 303   inline void inline_write_region(MemRegion mr) {
 304     dirty_MemRegion(mr);
 305   }
 306 protected:
 307   void write_region_work(MemRegion mr) {
 308     inline_write_region(mr);
 309   }
 310 public:
 311 
 312   inline void inline_write_ref_array(MemRegion mr) {
 313     dirty_MemRegion(mr);
 314   }
 315 protected:
 316   void write_ref_array_work(MemRegion mr) {
 317     inline_write_ref_array(mr);
 318   }
 319 public:
 320 
 321   bool is_aligned(HeapWord* addr) {
 322     return is_card_aligned(addr);
 323   }
 324 
 325   // *** Card-table-barrier-specific things.
 326 
 327   template <class T> inline void inline_write_ref_field_pre(T* field, oop newVal) {}
 328 
 329   template <class T> inline void inline_write_ref_field(T* field, oop newVal) {
 330     jbyte* byte = byte_for((void*)field);
 331     *byte = dirty_card;
 332   }
 333 
 334   // These are used by G1, when it uses the card table as a temporary data
 335   // structure for card claiming.
 336   bool is_card_dirty(size_t card_index) {
 337     return _byte_map[card_index] == dirty_card_val();
 338   }
 339 
 340   void mark_card_dirty(size_t card_index) {
 341     _byte_map[card_index] = dirty_card_val();
 342   }
 343 
 344   bool is_card_claimed(size_t card_index) {
 345     jbyte val = _byte_map[card_index];
 346     return (val & (clean_card_mask_val() | claimed_card_val())) == claimed_card_val();
 347   }
 348 
 349   void set_card_claimed(size_t card_index) {
 350       jbyte val = _byte_map[card_index];
 351       if (val == clean_card_val()) {
 352         val = (jbyte)claimed_card_val();
 353       } else {
 354         val |= (jbyte)claimed_card_val();
 355       }
 356       _byte_map[card_index] = val;
 357   }
 358 
 359   bool claim_card(size_t card_index);
 360 
 361   bool is_card_clean(size_t card_index) {
 362     return _byte_map[card_index] == clean_card_val();
 363   }
 364 
 365   bool is_card_deferred(size_t card_index) {
 366     jbyte val = _byte_map[card_index];
 367     return (val & (clean_card_mask_val() | deferred_card_val())) == deferred_card_val();
 368   }
 369 
 370   bool mark_card_deferred(size_t card_index);
 371 
 372   // Card marking array base (adjusted for heap low boundary)
 373   // This would be the 0th element of _byte_map, if the heap started at 0x0.
 374   // But since the heap starts at some higher address, this points to somewhere
 375   // before the beginning of the actual _byte_map.
 376   jbyte* byte_map_base;
 377 
 378   // Return true if "p" is at the start of a card.
 379   bool is_card_aligned(HeapWord* p) {
 380     jbyte* pcard = byte_for(p);
 381     return (addr_for(pcard) == p);
 382   }
 383 
 384   HeapWord* align_to_card_boundary(HeapWord* p) {
 385     jbyte* pcard = byte_for(p + card_size_in_words - 1);
 386     return addr_for(pcard);
 387   }
 388 
 389   // The kinds of precision a CardTableModRefBS may offer.
 390   enum PrecisionStyle {
 391     Precise,
 392     ObjHeadPreciseArray
 393   };
 394 
 395   // Tells what style of precision this card table offers.
 396   PrecisionStyle precision() {
 397     return ObjHeadPreciseArray; // Only one supported for now.
 398   }
 399 
 400   // ModRefBS functions.
 401   virtual void invalidate(MemRegion mr, bool whole_heap = false);
 402   void clear(MemRegion mr);
 403   void dirty(MemRegion mr);
 404 
 405   // *** Card-table-RemSet-specific things.
 406 
 407   // Invoke "cl.do_MemRegion" on a set of MemRegions that collectively
 408   // includes all the modified cards (expressing each card as a
 409   // MemRegion).  Thus, several modified cards may be lumped into one
 410   // region.  The regions are non-overlapping, and are visited in
 411   // *decreasing* address order.  (This order aids with imprecise card
 412   // marking, where a dirty card may cause scanning, and summarization
 413   // marking, of objects that extend onto subsequent cards.)
 414   void mod_card_iterate(MemRegionClosure* cl) {
 415     non_clean_card_iterate_serial(_whole_heap, cl);
 416   }
 417 
 418   // Like the "mod_cards_iterate" above, except only invokes the closure
 419   // for cards within the MemRegion "mr" (which is required to be
 420   // card-aligned and sized.)
 421   void mod_card_iterate(MemRegion mr, MemRegionClosure* cl) {
 422     non_clean_card_iterate_serial(mr, cl);
 423   }
 424 
 425   static uintx ct_max_alignment_constraint();
 426 
 427   // Apply closure "cl" to the dirty cards containing some part of
 428   // MemRegion "mr".
 429   void dirty_card_iterate(MemRegion mr, MemRegionClosure* cl);
 430 
 431   // Return the MemRegion corresponding to the first maximal run
 432   // of dirty cards lying completely within MemRegion mr.
 433   // If reset is "true", then sets those card table entries to the given
 434   // value.
 435   MemRegion dirty_card_range_after_reset(MemRegion mr, bool reset,
 436                                          int reset_val);
 437 
 438   // Provide read-only access to the card table array.
 439   const jbyte* byte_for_const(const void* p) const {
 440     return byte_for(p);
 441   }
 442   const jbyte* byte_after_const(const void* p) const {
 443     return byte_after(p);
 444   }
 445 
 446   // Mapping from card marking array entry to address of first word
 447   HeapWord* addr_for(const jbyte* p) const {
 448     assert(p >= _byte_map && p < _byte_map + _byte_map_size,
 449            "out of bounds access to card marking array");
 450     size_t delta = pointer_delta(p, byte_map_base, sizeof(jbyte));
 451     HeapWord* result = (HeapWord*) (delta << card_shift);
 452     assert(_whole_heap.contains(result),
 453            err_msg("Returning result = "PTR_FORMAT" out of bounds of "
 454                    " card marking array's _whole_heap = ["PTR_FORMAT","PTR_FORMAT")",
 455                    result, _whole_heap.start(), _whole_heap.end()));
 456     return result;
 457   }
 458 
 459   // Mapping from address to card marking array index.
 460   size_t index_for(void* p) {
 461     assert(_whole_heap.contains(p),
 462            err_msg("Attempt to access p = "PTR_FORMAT" out of bounds of "
 463                    " card marking array's _whole_heap = ["PTR_FORMAT","PTR_FORMAT")",
 464                    p, _whole_heap.start(), _whole_heap.end()));
 465     return byte_for(p) - _byte_map;
 466   }
 467 
 468   const jbyte* byte_for_index(const size_t card_index) const {
 469     return _byte_map + card_index;
 470   }
 471 
 472   // Print a description of the memory for the barrier set
 473   virtual void print_on(outputStream* st) const;
 474 
 475   void verify();
 476   void verify_guard();
 477 
 478   // val_equals -> it will check that all cards covered by mr equal val
 479   // !val_equals -> it will check that all cards covered by mr do not equal val
 480   void verify_region(MemRegion mr, jbyte val, bool val_equals) PRODUCT_RETURN;
 481   void verify_not_dirty_region(MemRegion mr) PRODUCT_RETURN;
 482   void verify_dirty_region(MemRegion mr) PRODUCT_RETURN;
 483   void verify_g1_young_region(MemRegion mr) PRODUCT_RETURN;
 484 
 485   static size_t par_chunk_heapword_alignment() {
 486     return ParGCCardsPerStrideChunk * card_size_in_words;
 487   }
 488 
 489 };
 490 
 491 class CardTableRS;
 492 
 493 // A specialization for the CardTableRS gen rem set.
 494 class CardTableModRefBSForCTRS: public CardTableModRefBS {
 495   CardTableRS* _rs;
 496 protected:
 497   bool card_will_be_scanned(jbyte cv);
 498   bool card_may_have_been_dirty(jbyte cv);
 499 public:
 500   CardTableModRefBSForCTRS(MemRegion whole_heap,
 501                            int max_covered_regions) :
 502     CardTableModRefBS(whole_heap, max_covered_regions) {}
 503 
 504   void set_CTRS(CardTableRS* rs) { _rs = rs; }
 505 };
 506 
 507 
 508 #endif // SHARE_VM_MEMORY_CARDTABLEMODREFBS_HPP