heapRegion.cpp 34.4 KB
Newer Older
1
/*
2
 * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34
#include "precompiled.hpp"
#include "gc_implementation/g1/g1BlockOffsetTable.inline.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
#include "gc_implementation/g1/heapRegion.inline.hpp"
#include "gc_implementation/g1/heapRegionRemSet.hpp"
#include "gc_implementation/g1/heapRegionSeq.inline.hpp"
#include "memory/genOopClosures.inline.hpp"
#include "memory/iterator.hpp"
#include "oops/oop.inline.hpp"
35

36 37 38 39 40
int    HeapRegion::LogOfHRGrainBytes = 0;
int    HeapRegion::LogOfHRGrainWords = 0;
size_t HeapRegion::GrainBytes        = 0;
size_t HeapRegion::GrainWords        = 0;
size_t HeapRegion::CardsPerRegion    = 0;
41

42 43 44 45 46 47
HeapRegionDCTOC::HeapRegionDCTOC(G1CollectedHeap* g1,
                                 HeapRegion* hr, OopClosure* cl,
                                 CardTableModRefBS::PrecisionStyle precision,
                                 FilterKind fk) :
  ContiguousSpaceDCTOC(hr, cl, precision, NULL),
  _hr(hr), _fk(fk), _g1(g1)
48
{ }
49 50 51 52 53 54 55 56

FilterOutOfRegionClosure::FilterOutOfRegionClosure(HeapRegion* r,
                                                   OopClosure* oc) :
  _r_bottom(r->bottom()), _r_end(r->end()),
  _oc(oc), _out_of_region(0)
{}

class VerifyLiveClosure: public OopClosure {
57
private:
58 59 60 61 62
  G1CollectedHeap* _g1h;
  CardTableModRefBS* _bs;
  oop _containing_obj;
  bool _failures;
  int _n_failures;
63
  VerifyOption _vo;
64
public:
65 66 67 68
  // _vo == UsePrevMarking -> use "prev" marking information,
  // _vo == UseNextMarking -> use "next" marking information,
  // _vo == UseMarkWord    -> use mark word from object header.
  VerifyLiveClosure(G1CollectedHeap* g1h, VerifyOption vo) :
69
    _g1h(g1h), _bs(NULL), _containing_obj(NULL),
70
    _failures(false), _n_failures(0), _vo(vo)
71 72 73 74 75 76 77 78 79 80 81 82 83
  {
    BarrierSet* bs = _g1h->barrier_set();
    if (bs->is_a(BarrierSet::CardTableModRef))
      _bs = (CardTableModRefBS*)bs;
  }

  void set_containing_obj(oop obj) {
    _containing_obj = obj;
  }

  bool failures() { return _failures; }
  int n_failures() { return _n_failures; }

84 85
  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
  virtual void do_oop(      oop* p) { do_oop_work(p); }
86

87 88 89 90 91 92 93 94 95 96
  void print_object(outputStream* out, oop obj) {
#ifdef PRODUCT
    klassOop k = obj->klass();
    const char* class_name = instanceKlass::cast(k)->external_name();
    out->print_cr("class name %s", class_name);
#else // PRODUCT
    obj->print_on(out);
#endif // PRODUCT
  }

97 98
  template <class T>
  void do_oop_work(T* p) {
99
    assert(_containing_obj != NULL, "Precondition");
100
    assert(!_g1h->is_obj_dead_cond(_containing_obj, _vo),
101
           "Precondition");
102 103 104
    T heap_oop = oopDesc::load_heap_oop(p);
    if (!oopDesc::is_null(heap_oop)) {
      oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
105
      bool failed = false;
106 107 108 109
      if (!_g1h->is_in_closed_subset(obj) || _g1h->is_obj_dead_cond(obj, _vo)) {
        MutexLockerEx x(ParGCRareEvent_lock,
                        Mutex::_no_safepoint_check_flag);

110 111 112 113 114
        if (!_failures) {
          gclog_or_tty->print_cr("");
          gclog_or_tty->print_cr("----------");
        }
        if (!_g1h->is_in_closed_subset(obj)) {
115
          HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
116
          gclog_or_tty->print_cr("Field "PTR_FORMAT
117 118 119 120 121 122 123
                                 " of live obj "PTR_FORMAT" in region "
                                 "["PTR_FORMAT", "PTR_FORMAT")",
                                 p, (void*) _containing_obj,
                                 from->bottom(), from->end());
          print_object(gclog_or_tty, _containing_obj);
          gclog_or_tty->print_cr("points to obj "PTR_FORMAT" not in the heap",
                                 (void*) obj);
124
        } else {
125 126
          HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
          HeapRegion* to   = _g1h->heap_region_containing((HeapWord*)obj);
127
          gclog_or_tty->print_cr("Field "PTR_FORMAT
128 129 130 131 132 133 134 135 136
                                 " of live obj "PTR_FORMAT" in region "
                                 "["PTR_FORMAT", "PTR_FORMAT")",
                                 p, (void*) _containing_obj,
                                 from->bottom(), from->end());
          print_object(gclog_or_tty, _containing_obj);
          gclog_or_tty->print_cr("points to dead obj "PTR_FORMAT" in region "
                                 "["PTR_FORMAT", "PTR_FORMAT")",
                                 (void*) obj, to->bottom(), to->end());
          print_object(gclog_or_tty, obj);
137 138
        }
        gclog_or_tty->print_cr("----------");
139
        gclog_or_tty->flush();
140 141 142 143 144 145
        _failures = true;
        failed = true;
        _n_failures++;
      }

      if (!_g1h->full_collection()) {
146 147
        HeapRegion* from = _g1h->heap_region_containing((HeapWord*)p);
        HeapRegion* to   = _g1h->heap_region_containing(obj);
148 149 150 151 152 153 154 155 156 157 158 159 160 161
        if (from != NULL && to != NULL &&
            from != to &&
            !to->isHumongous()) {
          jbyte cv_obj = *_bs->byte_for_const(_containing_obj);
          jbyte cv_field = *_bs->byte_for_const(p);
          const jbyte dirty = CardTableModRefBS::dirty_card_val();

          bool is_bad = !(from->is_young()
                          || to->rem_set()->contains_reference(p)
                          || !G1HRRSFlushLogBuffersOnVerify && // buffers were not flushed
                              (_containing_obj->is_objArray() ?
                                  cv_field == dirty
                               : cv_obj == dirty || cv_field == dirty));
          if (is_bad) {
162 163 164
            MutexLockerEx x(ParGCRareEvent_lock,
                            Mutex::_no_safepoint_check_flag);

165 166 167 168 169
            if (!_failures) {
              gclog_or_tty->print_cr("");
              gclog_or_tty->print_cr("----------");
            }
            gclog_or_tty->print_cr("Missing rem set entry:");
170 171 172 173 174
            gclog_or_tty->print_cr("Field "PTR_FORMAT" "
                                   "of obj "PTR_FORMAT", "
                                   "in region "HR_FORMAT,
                                   p, (void*) _containing_obj,
                                   HR_FORMAT_PARAMS(from));
175
            _containing_obj->print_on(gclog_or_tty);
176 177 178 179
            gclog_or_tty->print_cr("points to obj "PTR_FORMAT" "
                                   "in region "HR_FORMAT,
                                   (void*) obj,
                                   HR_FORMAT_PARAMS(to));
180 181 182 183
            obj->print_on(gclog_or_tty);
            gclog_or_tty->print_cr("Obj head CTE = %d, field CTE = %d.",
                          cv_obj, cv_field);
            gclog_or_tty->print_cr("----------");
184
            gclog_or_tty->flush();
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
            _failures = true;
            if (!failed) _n_failures++;
          }
        }
      }
    }
  }
};

template<class ClosureType>
HeapWord* walk_mem_region_loop(ClosureType* cl, G1CollectedHeap* g1h,
                               HeapRegion* hr,
                               HeapWord* cur, HeapWord* top) {
  oop cur_oop = oop(cur);
  int oop_size = cur_oop->size();
  HeapWord* next_obj = cur + oop_size;
  while (next_obj < top) {
    // Keep filtering the remembered set.
    if (!g1h->is_obj_dead(cur_oop, hr)) {
      // Bottom lies entirely below top, so we can call the
      // non-memRegion version of oop_iterate below.
      cur_oop->oop_iterate(cl);
    }
    cur = next_obj;
    cur_oop = oop(cur);
    oop_size = cur_oop->size();
    next_obj = cur + oop_size;
  }
  return cur;
}

void HeapRegionDCTOC::walk_mem_region_with_cl(MemRegion mr,
                                              HeapWord* bottom,
                                              HeapWord* top,
                                              OopClosure* cl) {
  G1CollectedHeap* g1h = _g1;
  int oop_size;
222
  OopClosure* cl2 = NULL;
223

224
  FilterIntoCSClosure intoCSFilt(this, g1h, cl);
225
  FilterOutOfRegionClosure outOfRegionFilt(_hr, cl);
226

227
  switch (_fk) {
228
  case NoFilterKind:          cl2 = cl; break;
229 230
  case IntoCSFilterKind:      cl2 = &intoCSFilt; break;
  case OutOfRegionFilterKind: cl2 = &outOfRegionFilt; break;
231
  default:                    ShouldNotReachHere();
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  }

  // Start filtering what we add to the remembered set. If the object is
  // not considered dead, either because it is marked (in the mark bitmap)
  // or it was allocated after marking finished, then we add it. Otherwise
  // we can safely ignore the object.
  if (!g1h->is_obj_dead(oop(bottom), _hr)) {
    oop_size = oop(bottom)->oop_iterate(cl2, mr);
  } else {
    oop_size = oop(bottom)->size();
  }

  bottom += oop_size;

  if (bottom < top) {
    // We replicate the loop below for several kinds of possible filters.
    switch (_fk) {
    case NoFilterKind:
      bottom = walk_mem_region_loop(cl, g1h, _hr, bottom, top);
      break;
252

253
    case IntoCSFilterKind: {
254
      FilterIntoCSClosure filt(this, g1h, cl);
255 256 257
      bottom = walk_mem_region_loop(&filt, g1h, _hr, bottom, top);
      break;
    }
258

259 260 261 262 263
    case OutOfRegionFilterKind: {
      FilterOutOfRegionClosure filt(_hr, cl);
      bottom = walk_mem_region_loop(&filt, g1h, _hr, bottom, top);
      break;
    }
264

265 266 267 268 269 270 271 272 273 274 275
    default:
      ShouldNotReachHere();
    }

    // Last object. Need to do dead-obj filtering here too.
    if (!g1h->is_obj_dead(oop(bottom), _hr)) {
      oop(bottom)->oop_iterate(cl2, mr);
    }
  }
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
// Minimum region size; we won't go lower than that.
// We might want to decrease this in the future, to deal with small
// heaps a bit more efficiently.
#define MIN_REGION_SIZE  (      1024 * 1024 )

// Maximum region size; we don't go higher than that. There's a good
// reason for having an upper bound. We don't want regions to get too
// large, otherwise cleanup's effectiveness would decrease as there
// will be fewer opportunities to find totally empty regions after
// marking.
#define MAX_REGION_SIZE  ( 32 * 1024 * 1024 )

// The automatic region size calculation will try to have around this
// many regions in the heap (based on the min heap size).
#define TARGET_REGION_NUMBER          2048

void HeapRegion::setup_heap_region_size(uintx min_heap_size) {
  // region_size in bytes
  uintx region_size = G1HeapRegionSize;
  if (FLAG_IS_DEFAULT(G1HeapRegionSize)) {
    // We base the automatic calculation on the min heap size. This
    // can be problematic if the spread between min and max is quite
    // wide, imagine -Xms128m -Xmx32g. But, if we decided it based on
    // the max size, the region size might be way too large for the
    // min size. Either way, some users might have to set the region
    // size manually for some -Xms / -Xmx combos.

    region_size = MAX2(min_heap_size / TARGET_REGION_NUMBER,
                       (uintx) MIN_REGION_SIZE);
  }

  int region_size_log = log2_long((jlong) region_size);
  // Recalculate the region size to make sure it's a power of
  // 2. This means that region_size is the largest power of 2 that's
  // <= what we've calculated so far.
311
  region_size = ((uintx)1 << region_size_log);
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

  // Now make sure that we don't go over or under our limits.
  if (region_size < MIN_REGION_SIZE) {
    region_size = MIN_REGION_SIZE;
  } else if (region_size > MAX_REGION_SIZE) {
    region_size = MAX_REGION_SIZE;
  }

  // And recalculate the log.
  region_size_log = log2_long((jlong) region_size);

  // Now, set up the globals.
  guarantee(LogOfHRGrainBytes == 0, "we should only set it once");
  LogOfHRGrainBytes = region_size_log;

  guarantee(LogOfHRGrainWords == 0, "we should only set it once");
  LogOfHRGrainWords = LogOfHRGrainBytes - LogHeapWordSize;

  guarantee(GrainBytes == 0, "we should only set it once");
  // The cast to int is safe, given that we've bounded region_size by
  // MIN_REGION_SIZE and MAX_REGION_SIZE.
333
  GrainBytes = (size_t)region_size;
334 335 336

  guarantee(GrainWords == 0, "we should only set it once");
  GrainWords = GrainBytes >> LogHeapWordSize;
337
  guarantee((size_t) 1 << LogOfHRGrainWords == GrainWords, "sanity");
338 339 340 341 342

  guarantee(CardsPerRegion == 0, "we should only set it once");
  CardsPerRegion = GrainBytes >> CardTableModRefBS::card_shift;
}

343 344 345 346 347 348 349 350 351
void HeapRegion::reset_after_compaction() {
  G1OffsetTableContigSpace::reset_after_compaction();
  // After a compaction the mark bitmap is invalid, so we must
  // treat all objects as being inside the unmarked area.
  zero_marked_bytes();
  init_top_at_mark_start();
}

void HeapRegion::hr_clear(bool par, bool clear_space) {
352 353 354 355 356 357 358
  assert(_humongous_type == NotHumongous,
         "we should have already filtered out humongous regions");
  assert(_humongous_start_region == NULL,
         "we should have already filtered out humongous regions");
  assert(_end == _orig_end,
         "we should have already filtered out humongous regions");

359 360 361 362 363
  _in_collection_set = false;

  set_young_index_in_cset(-1);
  uninstall_surv_rate_group();
  set_young_type(NotYoung);
364
  reset_pre_dummy_top();
365 366 367 368 369

  if (!par) {
    // If this is parallel, this will be done later.
    HeapRegionRemSet* hrrs = rem_set();
    if (hrrs != NULL) hrrs->clear();
370
    _claimed = InitialClaimValue;
371 372 373 374 375
  }
  zero_marked_bytes();

  _offsets.resize(HeapRegion::GrainWords);
  init_top_at_mark_start();
T
Merge  
tonyp 已提交
376
  if (clear_space) clear(SpaceDecorator::Mangle);
377 378
}

379 380
void HeapRegion::par_clear() {
  assert(used() == 0, "the region should have been already cleared");
381
  assert(capacity() == HeapRegion::GrainBytes, "should be back to normal");
382 383 384 385 386 387 388
  HeapRegionRemSet* hrrs = rem_set();
  hrrs->clear();
  CardTableModRefBS* ct_bs =
                   (CardTableModRefBS*)G1CollectedHeap::heap()->barrier_set();
  ct_bs->clear(MemRegion(bottom(), end()));
}

389 390
void HeapRegion::calc_gc_efficiency() {
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
391 392 393
  G1CollectorPolicy* g1p = g1h->g1_policy();
  _gc_efficiency = (double) reclaimable_bytes() /
                            g1p->predict_region_elapsed_time_ms(this, false);
394 395
}

396
void HeapRegion::set_startsHumongous(HeapWord* new_top, HeapWord* new_end) {
397
  assert(!isHumongous(), "sanity / pre-condition");
398 399 400
  assert(end() == _orig_end,
         "Should be normal before the humongous object allocation");
  assert(top() == bottom(), "should be empty");
401
  assert(bottom() <= new_top && new_top <= new_end, "pre-condition");
402

403
  _humongous_type = StartsHumongous;
404
  _humongous_start_region = this;
405 406

  set_end(new_end);
407
  _offsets.set_for_starts_humongous(new_top);
408 409
}

410
void HeapRegion::set_continuesHumongous(HeapRegion* first_hr) {
411
  assert(!isHumongous(), "sanity / pre-condition");
412 413 414
  assert(end() == _orig_end,
         "Should be normal before the humongous object allocation");
  assert(top() == bottom(), "should be empty");
415
  assert(first_hr->startsHumongous(), "pre-condition");
416 417

  _humongous_type = ContinuesHumongous;
418
  _humongous_start_region = first_hr;
419 420
}

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
void HeapRegion::set_notHumongous() {
  assert(isHumongous(), "pre-condition");

  if (startsHumongous()) {
    assert(top() <= end(), "pre-condition");
    set_end(_orig_end);
    if (top() > end()) {
      // at least one "continues humongous" region after it
      set_top(end());
    }
  } else {
    // continues humongous
    assert(end() == _orig_end, "sanity");
  }

436
  assert(capacity() == HeapRegion::GrainBytes, "pre-condition");
437 438 439 440
  _humongous_type = NotHumongous;
  _humongous_start_region = NULL;
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
bool HeapRegion::claimHeapRegion(jint claimValue) {
  jint current = _claimed;
  if (current != claimValue) {
    jint res = Atomic::cmpxchg(claimValue, &_claimed, current);
    if (res == current) {
      return true;
    }
  }
  return false;
}

HeapWord* HeapRegion::next_block_start_careful(HeapWord* addr) {
  HeapWord* low = addr;
  HeapWord* high = end();
  while (low < high) {
    size_t diff = pointer_delta(high, low);
    // Must add one below to bias toward the high amount.  Otherwise, if
  // "high" were at the desired value, and "low" were one less, we
    // would not converge on "high".  This is not symmetric, because
    // we set "high" to a block start, which might be the right one,
    // which we don't do for "low".
    HeapWord* middle = low + (diff+1)/2;
    if (middle == high) return high;
    HeapWord* mid_bs = block_start_careful(middle);
    if (mid_bs < addr) {
      low = middle;
    } else {
      high = mid_bs;
    }
  }
  assert(low == high && low >= addr, "Didn't work.");
  return low;
}

T
Merge  
tonyp 已提交
475 476
void HeapRegion::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
  G1OffsetTableContigSpace::initialize(mr, false, mangle_space);
477 478 479 480 481 482 483
  hr_clear(false/*par*/, clear_space);
}
#ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
#pragma warning( disable:4355 ) // 'this' : used in base member initializer list
#endif // _MSC_VER


484 485 486 487
HeapRegion::HeapRegion(uint hrs_index,
                       G1BlockOffsetSharedArray* sharedOffsetArray,
                       MemRegion mr, bool is_zeroed) :
    G1OffsetTableContigSpace(sharedOffsetArray, mr, is_zeroed),
488
    _hrs_index(hrs_index),
489
    _humongous_type(NotHumongous), _humongous_start_region(NULL),
490
    _in_collection_set(false),
491
    _next_in_special_set(NULL), _orig_end(NULL),
492
    _claimed(InitialClaimValue), _evacuation_failed(false),
493
    _prev_marked_bytes(0), _next_marked_bytes(0), _gc_efficiency(0.0),
494
    _young_type(NotYoung), _next_young_region(NULL),
495 496 497 498 499 500
    _next_dirty_cards_region(NULL), _next(NULL), _pending_removal(false),
#ifdef ASSERT
    _containing_set(NULL),
#endif // ASSERT
     _young_index_in_cset(-1), _surv_rate_group(NULL), _age_index(-1),
    _rem_set(NULL), _recorded_rs_length(0), _predicted_elapsed_time_ms(0),
501
    _predicted_bytes_to_copy(0)
502 503 504 505
{
  _orig_end = mr.end();
  // Note that initialize() will set the start of the unmarked area of the
  // region.
T
Merge  
tonyp 已提交
506 507 508
  this->initialize(mr, !is_zeroed, SpaceDecorator::Mangle);
  set_top(bottom());
  set_saved_mark();
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

  _rem_set =  new HeapRegionRemSet(sharedOffsetArray, this);

  assert(HeapRegionRemSet::num_par_rem_sets() > 0, "Invariant.");
}

class NextCompactionHeapRegionClosure: public HeapRegionClosure {
  const HeapRegion* _target;
  bool _target_seen;
  HeapRegion* _last;
  CompactibleSpace* _res;
public:
  NextCompactionHeapRegionClosure(const HeapRegion* target) :
    _target(target), _target_seen(false), _res(NULL) {}
  bool doHeapRegion(HeapRegion* cur) {
    if (_target_seen) {
      if (!cur->isHumongous()) {
        _res = cur;
        return true;
      }
    } else if (cur == _target) {
      _target_seen = true;
    }
    return false;
  }
  CompactibleSpace* result() { return _res; }
};

CompactibleSpace* HeapRegion::next_compaction_space() const {
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  // cast away const-ness
  HeapRegion* r = (HeapRegion*) this;
  NextCompactionHeapRegionClosure blk(r);
  g1h->heap_region_iterate_from(r, &blk);
  return blk.result();
}

void HeapRegion::save_marks() {
  set_saved_mark();
}

void HeapRegion::oops_in_mr_iterate(MemRegion mr, OopClosure* cl) {
  HeapWord* p = mr.start();
  HeapWord* e = mr.end();
  oop obj;
  while (p < e) {
    obj = oop(p);
    p += obj->oop_iterate(cl);
  }
  assert(p == e, "bad memregion: doesn't end on obj boundary");
}

#define HeapRegion_OOP_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix) \
void HeapRegion::oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) { \
  ContiguousSpace::oop_since_save_marks_iterate##nv_suffix(cl);              \
}
SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES(HeapRegion_OOP_SINCE_SAVE_MARKS_DEFN)


void HeapRegion::oop_before_save_marks_iterate(OopClosure* cl) {
  oops_in_mr_iterate(MemRegion(bottom(), saved_mark_word()), cl);
}

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
void HeapRegion::note_self_forwarding_removal_start(bool during_initial_mark,
                                                    bool during_conc_mark) {
  // We always recreate the prev marking info and we'll explicitly
  // mark all objects we find to be self-forwarded on the prev
  // bitmap. So all objects need to be below PTAMS.
  _prev_top_at_mark_start = top();
  _prev_marked_bytes = 0;

  if (during_initial_mark) {
    // During initial-mark, we'll also explicitly mark all objects
    // we find to be self-forwarded on the next bitmap. So all
    // objects need to be below NTAMS.
    _next_top_at_mark_start = top();
    _next_marked_bytes = 0;
  } else if (during_conc_mark) {
    // During concurrent mark, all objects in the CSet (including
    // the ones we find to be self-forwarded) are implicitly live.
    // So all objects need to be above NTAMS.
    _next_top_at_mark_start = bottom();
    _next_marked_bytes = 0;
  }
}

void HeapRegion::note_self_forwarding_removal_end(bool during_initial_mark,
                                                  bool during_conc_mark,
                                                  size_t marked_bytes) {
  assert(0 <= marked_bytes && marked_bytes <= used(),
         err_msg("marked: "SIZE_FORMAT" used: "SIZE_FORMAT,
                 marked_bytes, used()));
  _prev_marked_bytes = marked_bytes;
}

604 605 606 607 608 609 610 611 612 613 614 615
HeapWord*
HeapRegion::object_iterate_mem_careful(MemRegion mr,
                                                 ObjectClosure* cl) {
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  // We used to use "block_start_careful" here.  But we're actually happy
  // to update the BOT while we do this...
  HeapWord* cur = block_start(mr.start());
  mr = mr.intersection(used_region());
  if (mr.is_empty()) return NULL;
  // Otherwise, find the obj that extends onto mr.start().

  assert(cur <= mr.start()
616
         && (oop(cur)->klass_or_null() == NULL ||
617 618 619 620 621
             cur + oop(cur)->size() > mr.start()),
         "postcondition of block_start");
  oop obj;
  while (cur < mr.end()) {
    obj = oop(cur);
622
    if (obj->klass_or_null() == NULL) {
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
      // Ran into an unparseable point.
      return cur;
    } else if (!g1h->is_obj_dead(obj)) {
      cl->do_object(obj);
    }
    if (cl->abort()) return cur;
    // The check above must occur before the operation below, since an
    // abort might invalidate the "size" operation.
    cur += obj->size();
  }
  return NULL;
}

HeapWord*
HeapRegion::
oops_on_card_seq_iterate_careful(MemRegion mr,
639
                                 FilterOutOfRegionClosure* cl,
640 641 642 643 644 645 646 647 648
                                 bool filter_young,
                                 jbyte* card_ptr) {
  // Currently, we should only have to clean the card if filter_young
  // is true and vice versa.
  if (filter_young) {
    assert(card_ptr != NULL, "pre-condition");
  } else {
    assert(card_ptr == NULL, "pre-condition");
  }
649 650 651 652 653
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

  // If we're within a stop-world GC, then we might look at a card in a
  // GC alloc region that extends onto a GC LAB, which may not be
  // parseable.  Stop such at the "saved_mark" of the region.
654
  if (g1h->is_gc_active()) {
655 656 657 658 659 660 661
    mr = mr.intersection(used_region_at_save_marks());
  } else {
    mr = mr.intersection(used_region());
  }
  if (mr.is_empty()) return NULL;
  // Otherwise, find the obj that extends onto mr.start().

662 663 664 665 666 667 668 669 670 671
  // The intersection of the incoming mr (for the card) and the
  // allocated part of the region is non-empty. This implies that
  // we have actually allocated into this region. The code in
  // G1CollectedHeap.cpp that allocates a new region sets the
  // is_young tag on the region before allocating. Thus we
  // safely know if this region is young.
  if (is_young() && filter_young) {
    return NULL;
  }

J
johnc 已提交
672 673
  assert(!is_young(), "check value of filter_young");

674 675 676 677 678 679 680 681 682
  // We can only clean the card here, after we make the decision that
  // the card is not young. And we only clean the card if we have been
  // asked to (i.e., card_ptr != NULL).
  if (card_ptr != NULL) {
    *card_ptr = CardTableModRefBS::clean_card_val();
    // We must complete this write before we do any of the reads below.
    OrderAccess::storeload();
  }

683 684 685 686
  // Cache the boundaries of the memory region in some const locals
  HeapWord* const start = mr.start();
  HeapWord* const end = mr.end();

687 688
  // We used to use "block_start_careful" here.  But we're actually happy
  // to update the BOT while we do this...
689 690
  HeapWord* cur = block_start(start);
  assert(cur <= start, "Postcondition");
691

692 693 694 695 696 697 698
  oop obj;

  HeapWord* next = cur;
  while (next <= start) {
    cur = next;
    obj = oop(cur);
    if (obj->klass_or_null() == NULL) {
699 700 701 702
      // Ran into an unparseable point.
      return cur;
    }
    // Otherwise...
703
    next = (cur + obj->size());
704
  }
705 706 707 708 709 710 711 712 713

  // If we finish the above loop...We have a parseable object that
  // begins on or before the start of the memory region, and ends
  // inside or spans the entire region.

  assert(obj == oop(cur), "sanity");
  assert(cur <= start &&
         obj->klass_or_null() != NULL &&
         (cur + obj->size()) > start,
714
         "Loop postcondition");
715

716 717 718 719
  if (!g1h->is_obj_dead(obj)) {
    obj->oop_iterate(cl, mr);
  }

720
  while (cur < end) {
721
    obj = oop(cur);
722
    if (obj->klass_or_null() == NULL) {
723 724 725
      // Ran into an unparseable point.
      return cur;
    };
726

727 728
    // Otherwise:
    next = (cur + obj->size());
729

730
    if (!g1h->is_obj_dead(obj)) {
731 732 733 734
      if (next < end || !obj->is_objArray()) {
        // This object either does not span the MemRegion
        // boundary, or if it does it's not an array.
        // Apply closure to whole object.
735 736
        obj->oop_iterate(cl);
      } else {
737 738 739
        // This obj is an array that spans the boundary.
        // Stop at the boundary.
        obj->oop_iterate(cl, mr);
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
      }
    }
    cur = next;
  }
  return NULL;
}

void HeapRegion::print() const { print_on(gclog_or_tty); }
void HeapRegion::print_on(outputStream* st) const {
  if (isHumongous()) {
    if (startsHumongous())
      st->print(" HS");
    else
      st->print(" HC");
  } else {
    st->print("   ");
  }
  if (in_collection_set())
    st->print(" CS");
  else
    st->print("   ");
  if (is_young())
762
    st->print(is_survivor() ? " SU" : " Y ");
763 764 765 766 767 768
  else
    st->print("   ");
  if (is_empty())
    st->print(" F");
  else
    st->print("  ");
769
  st->print(" TS %5d", _gc_time_stamp);
770 771
  st->print(" PTAMS "PTR_FORMAT" NTAMS "PTR_FORMAT,
            prev_top_at_mark_start(), next_top_at_mark_start());
772 773 774
  G1OffsetTableContigSpace::print_on(st);
}

775
void HeapRegion::verify() const {
776
  bool dummy = false;
777
  verify(VerifyOption_G1UsePrevMarking, /* failures */ &dummy);
778 779
}

780 781 782
// This really ought to be commoned up into OffsetTableContigSpace somehow.
// We would need a mechanism to make that code skip dead objects.

783
void HeapRegion::verify(VerifyOption vo,
784
                        bool* failures) const {
785
  G1CollectedHeap* g1 = G1CollectedHeap::heap();
786
  *failures = false;
787 788
  HeapWord* p = bottom();
  HeapWord* prev_p = NULL;
789
  VerifyLiveClosure vl_cl(g1, vo);
790
  bool is_humongous = isHumongous();
791
  bool do_bot_verify = !is_young();
792
  size_t object_num = 0;
793
  while (p < top()) {
794 795 796 797 798
    oop obj = oop(p);
    size_t obj_size = obj->size();
    object_num += 1;

    if (is_humongous != g1->isHumongous(obj_size)) {
799 800
      gclog_or_tty->print_cr("obj "PTR_FORMAT" is of %shumongous size ("
                             SIZE_FORMAT" words) in a %shumongous region",
801 802
                             p, g1->isHumongous(obj_size) ? "" : "non-",
                             obj_size, is_humongous ? "" : "non-");
803
       *failures = true;
804
       return;
805
    }
806 807 808 809 810 811

    // If it returns false, verify_for_object() will output the
    // appropriate messasge.
    if (do_bot_verify && !_offsets.verify_for_object(p, obj_size)) {
      *failures = true;
      return;
812
    }
813

814
    if (!g1->is_obj_dead_cond(obj, this, vo)) {
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
      if (obj->is_oop()) {
        klassOop klass = obj->klass();
        if (!klass->is_perm()) {
          gclog_or_tty->print_cr("klass "PTR_FORMAT" of object "PTR_FORMAT" "
                                 "not in perm", klass, obj);
          *failures = true;
          return;
        } else if (!klass->is_klass()) {
          gclog_or_tty->print_cr("klass "PTR_FORMAT" of object "PTR_FORMAT" "
                                 "not a klass", klass, obj);
          *failures = true;
          return;
        } else {
          vl_cl.set_containing_obj(obj);
          obj->oop_iterate(&vl_cl);
          if (vl_cl.failures()) {
831
            *failures = true;
832 833 834
          }
          if (G1MaxVerifyFailures >= 0 &&
              vl_cl.n_failures() >= G1MaxVerifyFailures) {
835 836 837
            return;
          }
        }
838 839 840 841
      } else {
        gclog_or_tty->print_cr(PTR_FORMAT" no an oop", obj);
        *failures = true;
        return;
842 843 844
      }
    }
    prev_p = p;
845
    p += obj_size;
846
  }
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

  if (p != top()) {
    gclog_or_tty->print_cr("end of last object "PTR_FORMAT" "
                           "does not match top "PTR_FORMAT, p, top());
    *failures = true;
    return;
  }

  HeapWord* the_end = end();
  assert(p == top(), "it should still hold");
  // Do some extra BOT consistency checking for addresses in the
  // range [top, end). BOT look-ups in this range should yield
  // top. No point in doing that if top == end (there's nothing there).
  if (p < the_end) {
    // Look up top
    HeapWord* addr_1 = p;
    HeapWord* b_start_1 = _offsets.block_start_const(addr_1);
    if (b_start_1 != p) {
      gclog_or_tty->print_cr("BOT look up for top: "PTR_FORMAT" "
                             " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
                             addr_1, b_start_1, p);
      *failures = true;
      return;
    }

    // Look up top + 1
    HeapWord* addr_2 = p + 1;
    if (addr_2 < the_end) {
      HeapWord* b_start_2 = _offsets.block_start_const(addr_2);
      if (b_start_2 != p) {
        gclog_or_tty->print_cr("BOT look up for top + 1: "PTR_FORMAT" "
                               " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
                               addr_2, b_start_2, p);
880 881
        *failures = true;
        return;
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
      }
    }

    // Look up an address between top and end
    size_t diff = pointer_delta(the_end, p) / 2;
    HeapWord* addr_3 = p + diff;
    if (addr_3 < the_end) {
      HeapWord* b_start_3 = _offsets.block_start_const(addr_3);
      if (b_start_3 != p) {
        gclog_or_tty->print_cr("BOT look up for top + diff: "PTR_FORMAT" "
                               " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
                               addr_3, b_start_3, p);
        *failures = true;
        return;
      }
    }

    // Loook up end - 1
    HeapWord* addr_4 = the_end - 1;
    HeapWord* b_start_4 = _offsets.block_start_const(addr_4);
    if (b_start_4 != p) {
      gclog_or_tty->print_cr("BOT look up for end - 1: "PTR_FORMAT" "
                             " yielded "PTR_FORMAT", expecting "PTR_FORMAT,
                             addr_4, b_start_4, p);
      *failures = true;
      return;
908
    }
909
  }
910

911 912 913 914 915
  if (is_humongous && object_num > 1) {
    gclog_or_tty->print_cr("region ["PTR_FORMAT","PTR_FORMAT"] is humongous "
                           "but has "SIZE_FORMAT", objects",
                           bottom(), end(), object_num);
    *failures = true;
916
    return;
917 918 919 920 921 922
  }
}

// G1OffsetTableContigSpace code; copied from space.cpp.  Hope this can go
// away eventually.

T
Merge  
tonyp 已提交
923
void G1OffsetTableContigSpace::initialize(MemRegion mr, bool clear_space, bool mangle_space) {
924
  // false ==> we'll do the clearing if there's clearing to be done.
T
Merge  
tonyp 已提交
925
  ContiguousSpace::initialize(mr, false, mangle_space);
926 927
  _offsets.zero_bottom_entry();
  _offsets.initialize_threshold();
T
Merge  
tonyp 已提交
928
  if (clear_space) clear(mangle_space);
929 930
}

T
Merge  
tonyp 已提交
931 932
void G1OffsetTableContigSpace::clear(bool mangle_space) {
  ContiguousSpace::clear(mangle_space);
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
  _offsets.zero_bottom_entry();
  _offsets.initialize_threshold();
}

void G1OffsetTableContigSpace::set_bottom(HeapWord* new_bottom) {
  Space::set_bottom(new_bottom);
  _offsets.set_bottom(new_bottom);
}

void G1OffsetTableContigSpace::set_end(HeapWord* new_end) {
  Space::set_end(new_end);
  _offsets.resize(new_end - bottom());
}

void G1OffsetTableContigSpace::print() const {
  print_short();
  gclog_or_tty->print_cr(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", "
                INTPTR_FORMAT ", " INTPTR_FORMAT ")",
                bottom(), top(), _offsets.threshold(), end());
}

HeapWord* G1OffsetTableContigSpace::initialize_threshold() {
  return _offsets.initialize_threshold();
}

HeapWord* G1OffsetTableContigSpace::cross_threshold(HeapWord* start,
                                                    HeapWord* end) {
  _offsets.alloc_block(start, end);
  return _offsets.threshold();
}

HeapWord* G1OffsetTableContigSpace::saved_mark_word() const {
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  assert( _gc_time_stamp <= g1h->get_gc_time_stamp(), "invariant" );
  if (_gc_time_stamp < g1h->get_gc_time_stamp())
    return top();
  else
    return ContiguousSpace::saved_mark_word();
}

void G1OffsetTableContigSpace::set_saved_mark() {
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  unsigned curr_gc_time_stamp = g1h->get_gc_time_stamp();

  if (_gc_time_stamp < curr_gc_time_stamp) {
    // The order of these is important, as another thread might be
    // about to start scanning this region. If it does so after
    // set_saved_mark and before _gc_time_stamp = ..., then the latter
    // will be false, and it will pick up top() as the high water mark
    // of region. If it does so after _gc_time_stamp = ..., then it
    // will pick up the right saved_mark_word() as the high water mark
    // of the region. Either way, the behaviour will be correct.
    ContiguousSpace::set_saved_mark();
986
    OrderAccess::storestore();
987
    _gc_time_stamp = curr_gc_time_stamp;
988 989 990 991 992
    // No need to do another barrier to flush the writes above. If
    // this is called in parallel with other threads trying to
    // allocate into the region, the caller should call this while
    // holding a lock and when the lock is released the writes will be
    // flushed.
993 994 995 996 997 998 999 1000 1001 1002 1003
  }
}

G1OffsetTableContigSpace::
G1OffsetTableContigSpace(G1BlockOffsetSharedArray* sharedOffsetArray,
                         MemRegion mr, bool is_zeroed) :
  _offsets(sharedOffsetArray, mr),
  _par_alloc_lock(Mutex::leaf, "OffsetTableContigSpace par alloc lock", true),
  _gc_time_stamp(0)
{
  _offsets.set_space(this);
T
Merge  
tonyp 已提交
1004
  initialize(mr, !is_zeroed, SpaceDecorator::Mangle);
1005
}