1 /*
   2  * Copyright (c) 2000, 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/cardTable.hpp"
  27 #include "gc/shared/collectedHeap.hpp"
  28 #include "gc/shared/space.inline.hpp"
  29 #include "logging/log.hpp"
  30 #include "memory/virtualspace.hpp"
  31 #include "runtime/java.hpp"
  32 #include "runtime/os.hpp"
  33 #include "services/memTracker.hpp"
  34 #include "utilities/align.hpp"
  35 
  36 size_t CardTable::compute_byte_map_size() {
  37   assert(_guard_index == cards_required(_whole_heap.word_size()) - 1,
  38                                         "uninitialized, check declaration order");
  39   assert(_page_size != 0, "uninitialized, check declaration order");
  40   const size_t granularity = os::vm_allocation_granularity();
  41   return align_up(_guard_index + 1, MAX2(_page_size, granularity));
  42 }
  43 
  44 CardTable::CardTable(MemRegion whole_heap, bool conc_scan) :
  45   _scanned_concurrently(conc_scan),
  46   _whole_heap(whole_heap),
  47   _guard_index(0),
  48   _last_valid_index(0),
  49   _page_size(os::vm_page_size()),
  50   _byte_map_size(0),
  51   _byte_map(NULL),
  52   _byte_map_base(NULL),
  53   _cur_covered_regions(0),
  54   _covered(NEW_C_HEAP_ARRAY(MemRegion, _max_covered_regions, mtGC)),
  55   _committed(NEW_C_HEAP_ARRAY(MemRegion, _max_covered_regions, mtGC)),
  56   _guard_region()
  57 {
  58   assert((uintptr_t(_whole_heap.start())  & (card_size - 1))  == 0, "heap must start at card boundary");
  59   assert((uintptr_t(_whole_heap.end()) & (card_size - 1))  == 0, "heap must end at card boundary");
  60 
  61   assert(card_size <= 512, "card_size must be less than 512"); // why?
  62 
  63   for (int i = 0; i < _max_covered_regions; i++) {
  64     ::new (&_covered[i]) MemRegion();
  65     ::new (&_committed[i]) MemRegion();
  66   }
  67 }
  68 
  69 CardTable::~CardTable() {
  70   FREE_C_HEAP_ARRAY(MemRegion, _covered);
  71   FREE_C_HEAP_ARRAY(MemRegion, _committed);
  72 }
  73 
  74 void CardTable::initialize() {
  75   _guard_index = cards_required(_whole_heap.word_size()) - 1;
  76   _last_valid_index = _guard_index - 1;
  77 
  78   _byte_map_size = compute_byte_map_size();
  79 
  80   HeapWord* low_bound  = _whole_heap.start();
  81   HeapWord* high_bound = _whole_heap.end();
  82 
  83   _cur_covered_regions = 0;
  84 
  85   const size_t rs_align = _page_size == (size_t) os::vm_page_size() ? 0 :
  86     MAX2(_page_size, (size_t) os::vm_allocation_granularity());
  87   ReservedSpace heap_rs(_byte_map_size, rs_align, false);
  88 
  89   MemTracker::record_virtual_memory_type((address)heap_rs.base(), mtGC);
  90 
  91   os::trace_page_sizes("Card Table", _guard_index + 1, _guard_index + 1,
  92                        _page_size, heap_rs.base(), heap_rs.size());
  93   if (!heap_rs.is_reserved()) {
  94     vm_exit_during_initialization("Could not reserve enough space for the "
  95                                   "card marking array");
  96   }
  97 
  98   // The assembler store_check code will do an unsigned shift of the oop,
  99   // then add it to _byte_map_base, i.e.
 100   //
 101   //   _byte_map = _byte_map_base + (uintptr_t(low_bound) >> card_shift)
 102   _byte_map = (CardValue*) heap_rs.base();
 103   _byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
 104   assert(byte_for(low_bound) == &_byte_map[0], "Checking start of map");
 105   assert(byte_for(high_bound-1) <= &_byte_map[_last_valid_index], "Checking end of map");
 106 
 107   CardValue* guard_card = &_byte_map[_guard_index];
 108   HeapWord* guard_page = align_down((HeapWord*)guard_card, _page_size);
 109   _guard_region = MemRegion(guard_page, _page_size);
 110   os::commit_memory_or_exit((char*)guard_page, _page_size, _page_size,
 111                             !ExecMem, "card table last card");
 112   *guard_card = last_card;
 113 
 114   log_trace(gc, barrier)("CardTable::CardTable: ");
 115   log_trace(gc, barrier)("    &_byte_map[0]: " INTPTR_FORMAT "  &_byte_map[_last_valid_index]: " INTPTR_FORMAT,
 116                   p2i(&_byte_map[0]), p2i(&_byte_map[_last_valid_index]));
 117   log_trace(gc, barrier)("    _byte_map_base: " INTPTR_FORMAT, p2i(_byte_map_base));
 118 }
 119 
 120 int CardTable::find_covering_region_by_base(HeapWord* base) {
 121   int i;
 122   for (i = 0; i < _cur_covered_regions; i++) {
 123     if (_covered[i].start() == base) return i;
 124     if (_covered[i].start() > base) break;
 125   }
 126   // If we didn't find it, create a new one.
 127   assert(_cur_covered_regions < _max_covered_regions,
 128          "too many covered regions");
 129   // Move the ones above up, to maintain sorted order.
 130   for (int j = _cur_covered_regions; j > i; j--) {
 131     _covered[j] = _covered[j-1];
 132     _committed[j] = _committed[j-1];
 133   }
 134   int res = i;
 135   _cur_covered_regions++;
 136   _covered[res].set_start(base);
 137   _covered[res].set_word_size(0);
 138   CardValue* ct_start = byte_for(base);
 139   HeapWord* ct_start_aligned = align_down((HeapWord*)ct_start, _page_size);
 140   _committed[res].set_start(ct_start_aligned);
 141   _committed[res].set_word_size(0);
 142   return res;
 143 }
 144 
 145 int CardTable::find_covering_region_containing(HeapWord* addr) {
 146   for (int i = 0; i < _cur_covered_regions; i++) {
 147     if (_covered[i].contains(addr)) {
 148       return i;
 149     }
 150   }
 151   assert(0, "address outside of heap?");
 152   return -1;
 153 }
 154 
 155 HeapWord* CardTable::largest_prev_committed_end(int ind) const {
 156   HeapWord* max_end = NULL;
 157   for (int j = 0; j < ind; j++) {
 158     HeapWord* this_end = _committed[j].end();
 159     if (this_end > max_end) max_end = this_end;
 160   }
 161   return max_end;
 162 }
 163 
 164 MemRegion CardTable::committed_unique_to_self(int self, MemRegion mr) const {
 165   MemRegion result = mr;
 166   for (int r = 0; r < _cur_covered_regions; r += 1) {
 167     if (r != self) {
 168       result = result.minus(_committed[r]);
 169     }
 170   }
 171   // Never include the guard page.
 172   result = result.minus(_guard_region);
 173   return result;
 174 }
 175 
 176 void CardTable::resize_covered_region(MemRegion new_region) {
 177   // We don't change the start of a region, only the end.
 178   assert(_whole_heap.contains(new_region),
 179            "attempt to cover area not in reserved area");
 180   debug_only(verify_guard();)
 181   // collided is true if the expansion would push into another committed region
 182   debug_only(bool collided = false;)
 183   int const ind = find_covering_region_by_base(new_region.start());
 184   MemRegion const old_region = _covered[ind];
 185   assert(old_region.start() == new_region.start(), "just checking");
 186   if (new_region.word_size() != old_region.word_size()) {
 187     // Commit new or uncommit old pages, if necessary.
 188     MemRegion cur_committed = _committed[ind];
 189     // Extend the end of this _committed region
 190     // to cover the end of any lower _committed regions.
 191     // This forms overlapping regions, but never interior regions.
 192     HeapWord* const max_prev_end = largest_prev_committed_end(ind);
 193     if (max_prev_end > cur_committed.end()) {
 194       cur_committed.set_end(max_prev_end);
 195     }
 196     // Align the end up to a page size (starts are already aligned).
 197     HeapWord* new_end = (HeapWord*) byte_after(new_region.last());
 198     HeapWord* new_end_aligned = align_up(new_end, _page_size);
 199     assert(new_end_aligned >= new_end, "align up, but less");
 200     // Check the other regions (excludes "ind") to ensure that
 201     // the new_end_aligned does not intrude onto the committed
 202     // space of another region.
 203     int ri = 0;
 204     for (ri = ind + 1; ri < _cur_covered_regions; ri++) {
 205       if (new_end_aligned > _committed[ri].start()) {
 206         assert(new_end_aligned <= _committed[ri].end(),
 207                "An earlier committed region can't cover a later committed region");
 208         // Any region containing the new end
 209         // should start at or beyond the region found (ind)
 210         // for the new end (committed regions are not expected to
 211         // be proper subsets of other committed regions).
 212         assert(_committed[ri].start() >= _committed[ind].start(),
 213                "New end of committed region is inconsistent");
 214         new_end_aligned = _committed[ri].start();
 215         // new_end_aligned can be equal to the start of its
 216         // committed region (i.e., of "ind") if a second
 217         // region following "ind" also start at the same location
 218         // as "ind".
 219         assert(new_end_aligned >= _committed[ind].start(),
 220           "New end of committed region is before start");
 221         debug_only(collided = true;)
 222         // Should only collide with 1 region
 223         break;
 224       }
 225     }
 226 #ifdef ASSERT
 227     for (++ri; ri < _cur_covered_regions; ri++) {
 228       assert(!_committed[ri].contains(new_end_aligned),
 229         "New end of committed region is in a second committed region");
 230     }
 231 #endif
 232     // The guard page is always committed and should not be committed over.
 233     // "guarded" is used for assertion checking below and recalls the fact
 234     // that the would-be end of the new committed region would have
 235     // penetrated the guard page.
 236     HeapWord* new_end_for_commit = new_end_aligned;
 237 
 238     DEBUG_ONLY(bool guarded = false;)
 239     if (new_end_for_commit > _guard_region.start()) {
 240       new_end_for_commit = _guard_region.start();
 241       DEBUG_ONLY(guarded = true;)
 242     }
 243 
 244     if (new_end_for_commit > cur_committed.end()) {
 245       // Must commit new pages.
 246       MemRegion const new_committed =
 247         MemRegion(cur_committed.end(), new_end_for_commit);
 248 
 249       assert(!new_committed.is_empty(), "Region should not be empty here");
 250       os::commit_memory_or_exit((char*)new_committed.start(),
 251                                 new_committed.byte_size(), _page_size,
 252                                 !ExecMem, "card table expansion");
 253     // Use new_end_aligned (as opposed to new_end_for_commit) because
 254     // the cur_committed region may include the guard region.
 255     } else if (new_end_aligned < cur_committed.end()) {
 256       // Must uncommit pages.
 257       MemRegion const uncommit_region =
 258         committed_unique_to_self(ind, MemRegion(new_end_aligned,
 259                                                 cur_committed.end()));
 260       if (!uncommit_region.is_empty()) {
 261         // It is not safe to uncommit cards if the boundary between
 262         // the generations is moving.  A shrink can uncommit cards
 263         // owned by generation A but being used by generation B.
 264         if (!UseAdaptiveGCBoundary) {
 265           if (!os::uncommit_memory((char*)uncommit_region.start(),
 266                                    uncommit_region.byte_size())) {
 267             assert(false, "Card table contraction failed");
 268             // The call failed so don't change the end of the
 269             // committed region.  This is better than taking the
 270             // VM down.
 271             new_end_aligned = _committed[ind].end();
 272           }
 273         } else {
 274           new_end_aligned = _committed[ind].end();
 275         }
 276       }
 277     }
 278     // In any case, we can reset the end of the current committed entry.
 279     _committed[ind].set_end(new_end_aligned);
 280 
 281 #ifdef ASSERT
 282     // Check that the last card in the new region is committed according
 283     // to the tables.
 284     bool covered = false;
 285     for (int cr = 0; cr < _cur_covered_regions; cr++) {
 286       if (_committed[cr].contains(new_end - 1)) {
 287         covered = true;
 288         break;
 289       }
 290     }
 291     assert(covered, "Card for end of new region not committed");
 292 #endif
 293 
 294     // The default of 0 is not necessarily clean cards.
 295     CardValue* entry;
 296     if (old_region.last() < _whole_heap.start()) {
 297       entry = byte_for(_whole_heap.start());
 298     } else {
 299       entry = byte_after(old_region.last());
 300     }
 301     assert(index_for(new_region.last()) <  _guard_index,
 302       "The guard card will be overwritten");
 303     // This line commented out cleans the newly expanded region and
 304     // not the aligned up expanded region.
 305     // CardValue* const end = byte_after(new_region.last());
 306     CardValue* const end = (CardValue*) new_end_for_commit;
 307     assert((end >= byte_after(new_region.last())) || collided || guarded,
 308       "Expect to be beyond new region unless impacting another region");
 309     // do nothing if we resized downward.
 310 #ifdef ASSERT
 311     for (int ri = 0; ri < _cur_covered_regions; ri++) {
 312       if (ri != ind) {
 313         // The end of the new committed region should not
 314         // be in any existing region unless it matches
 315         // the start of the next region.
 316         assert(!_committed[ri].contains(end) ||
 317                (_committed[ri].start() == (HeapWord*) end),
 318                "Overlapping committed regions");
 319       }
 320     }
 321 #endif
 322     if (entry < end) {
 323       memset(entry, clean_card, pointer_delta(end, entry, sizeof(CardValue)));
 324     }
 325   }
 326   // In any case, the covered size changes.
 327   _covered[ind].set_word_size(new_region.word_size());
 328 
 329   log_trace(gc, barrier)("CardTable::resize_covered_region: ");
 330   log_trace(gc, barrier)("    _covered[%d].start(): " INTPTR_FORMAT " _covered[%d].last(): " INTPTR_FORMAT,
 331                          ind, p2i(_covered[ind].start()), ind, p2i(_covered[ind].last()));
 332   log_trace(gc, barrier)("    _committed[%d].start(): " INTPTR_FORMAT "  _committed[%d].last(): " INTPTR_FORMAT,
 333                          ind, p2i(_committed[ind].start()), ind, p2i(_committed[ind].last()));
 334   log_trace(gc, barrier)("    byte_for(start): " INTPTR_FORMAT "  byte_for(last): " INTPTR_FORMAT,
 335                          p2i(byte_for(_covered[ind].start())),  p2i(byte_for(_covered[ind].last())));
 336   log_trace(gc, barrier)("    addr_for(start): " INTPTR_FORMAT "  addr_for(last): " INTPTR_FORMAT,
 337                          p2i(addr_for((CardValue*) _committed[ind].start())),  p2i(addr_for((CardValue*) _committed[ind].last())));
 338 
 339   // Touch the last card of the covered region to show that it
 340   // is committed (or SEGV).
 341   debug_only((void) (*byte_for(_covered[ind].last()));)
 342   debug_only(verify_guard();)
 343 }
 344 
 345 // Note that these versions are precise!  The scanning code has to handle the
 346 // fact that the write barrier may be either precise or imprecise.
 347 void CardTable::dirty_MemRegion(MemRegion mr) {
 348   assert(align_down(mr.start(), HeapWordSize) == mr.start(), "Unaligned start");
 349   assert(align_up  (mr.end(),   HeapWordSize) == mr.end(),   "Unaligned end"  );
 350   CardValue* cur  = byte_for(mr.start());
 351   CardValue* last = byte_after(mr.last());
 352   while (cur < last) {
 353     *cur = dirty_card;
 354     cur++;
 355   }
 356 }
 357 
 358 void CardTable::clear_MemRegion(MemRegion mr) {
 359   // Be conservative: only clean cards entirely contained within the
 360   // region.
 361   CardValue* cur;
 362   if (mr.start() == _whole_heap.start()) {
 363     cur = byte_for(mr.start());
 364   } else {
 365     assert(mr.start() > _whole_heap.start(), "mr is not covered.");
 366     cur = byte_after(mr.start() - 1);
 367   }
 368   CardValue* last = byte_after(mr.last());
 369   memset(cur, clean_card, pointer_delta(last, cur, sizeof(CardValue)));
 370 }
 371 
 372 void CardTable::clear(MemRegion mr) {
 373   for (int i = 0; i < _cur_covered_regions; i++) {
 374     MemRegion mri = mr.intersection(_covered[i]);
 375     if (!mri.is_empty()) clear_MemRegion(mri);
 376   }
 377 }
 378 
 379 void CardTable::dirty(MemRegion mr) {
 380   CardValue* first = byte_for(mr.start());
 381   CardValue* last  = byte_after(mr.last());
 382   memset(first, dirty_card, last-first);
 383 }
 384 
 385 // Unlike several other card table methods, dirty_card_iterate()
 386 // iterates over dirty cards ranges in increasing address order.
 387 void CardTable::dirty_card_iterate(MemRegion mr, MemRegionClosure* cl) {
 388   for (int i = 0; i < _cur_covered_regions; i++) {
 389     MemRegion mri = mr.intersection(_covered[i]);
 390     if (!mri.is_empty()) {
 391       CardValue *cur_entry, *next_entry, *limit;
 392       for (cur_entry = byte_for(mri.start()), limit = byte_for(mri.last());
 393            cur_entry <= limit;
 394            cur_entry  = next_entry) {
 395         next_entry = cur_entry + 1;
 396         if (*cur_entry == dirty_card) {
 397           size_t dirty_cards;
 398           // Accumulate maximal dirty card range, starting at cur_entry
 399           for (dirty_cards = 1;
 400                next_entry <= limit && *next_entry == dirty_card;
 401                dirty_cards++, next_entry++);
 402           MemRegion cur_cards(addr_for(cur_entry),
 403                               dirty_cards*card_size_in_words);
 404           cl->do_MemRegion(cur_cards);
 405         }
 406       }
 407     }
 408   }
 409 }
 410 
 411 MemRegion CardTable::dirty_card_range_after_reset(MemRegion mr,
 412                                                   bool reset,
 413                                                   int reset_val) {
 414   for (int i = 0; i < _cur_covered_regions; i++) {
 415     MemRegion mri = mr.intersection(_covered[i]);
 416     if (!mri.is_empty()) {
 417       CardValue* cur_entry, *next_entry, *limit;
 418       for (cur_entry = byte_for(mri.start()), limit = byte_for(mri.last());
 419            cur_entry <= limit;
 420            cur_entry  = next_entry) {
 421         next_entry = cur_entry + 1;
 422         if (*cur_entry == dirty_card) {
 423           size_t dirty_cards;
 424           // Accumulate maximal dirty card range, starting at cur_entry
 425           for (dirty_cards = 1;
 426                next_entry <= limit && *next_entry == dirty_card;
 427                dirty_cards++, next_entry++);
 428           MemRegion cur_cards(addr_for(cur_entry),
 429                               dirty_cards*card_size_in_words);
 430           if (reset) {
 431             for (size_t i = 0; i < dirty_cards; i++) {
 432               cur_entry[i] = reset_val;
 433             }
 434           }
 435           return cur_cards;
 436         }
 437       }
 438     }
 439   }
 440   return MemRegion(mr.end(), mr.end());
 441 }
 442 
 443 uintx CardTable::ct_max_alignment_constraint() {
 444   return card_size * os::vm_page_size();
 445 }
 446 
 447 void CardTable::verify_guard() {
 448   // For product build verification
 449   guarantee(_byte_map[_guard_index] == last_card,
 450             "card table guard has been modified");
 451 }
 452 
 453 void CardTable::invalidate(MemRegion mr) {
 454   assert(align_down(mr.start(), HeapWordSize) == mr.start(), "Unaligned start");
 455   assert(align_up  (mr.end(),   HeapWordSize) == mr.end(),   "Unaligned end"  );
 456   for (int i = 0; i < _cur_covered_regions; i++) {
 457     MemRegion mri = mr.intersection(_covered[i]);
 458     if (!mri.is_empty()) dirty_MemRegion(mri);
 459   }
 460 }
 461 
 462 void CardTable::verify() {
 463   verify_guard();
 464 }
 465 
 466 #ifndef PRODUCT
 467 void CardTable::verify_region(MemRegion mr, CardValue val, bool val_equals) {
 468   CardValue* start    = byte_for(mr.start());
 469   CardValue* end      = byte_for(mr.last());
 470   bool failures = false;
 471   for (CardValue* curr = start; curr <= end; ++curr) {
 472     CardValue curr_val = *curr;
 473     bool failed = (val_equals) ? (curr_val != val) : (curr_val == val);
 474     if (failed) {
 475       if (!failures) {
 476         log_error(gc, verify)("== CT verification failed: [" INTPTR_FORMAT "," INTPTR_FORMAT "]", p2i(start), p2i(end));
 477         log_error(gc, verify)("==   %sexpecting value: %d", (val_equals) ? "" : "not ", val);
 478         failures = true;
 479       }
 480       log_error(gc, verify)("==   card " PTR_FORMAT " [" PTR_FORMAT "," PTR_FORMAT "], val: %d",
 481                             p2i(curr), p2i(addr_for(curr)),
 482                             p2i((HeapWord*) (((size_t) addr_for(curr)) + card_size)),
 483                             (int) curr_val);
 484     }
 485   }
 486   guarantee(!failures, "there should not have been any failures");
 487 }
 488 
 489 void CardTable::verify_not_dirty_region(MemRegion mr) {
 490   verify_region(mr, dirty_card, false /* val_equals */);
 491 }
 492 
 493 void CardTable::verify_dirty_region(MemRegion mr) {
 494   verify_region(mr, dirty_card, true /* val_equals */);
 495 }
 496 #endif
 497 
 498 void CardTable::print_on(outputStream* st) const {
 499   st->print_cr("Card table byte_map: [" INTPTR_FORMAT "," INTPTR_FORMAT "] _byte_map_base: " INTPTR_FORMAT,
 500                p2i(_byte_map), p2i(_byte_map + _byte_map_size), p2i(_byte_map_base));
 501 }