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