1 /*
   2  * Copyright (c) 2001, 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/g1/g1CollectedHeap.inline.hpp"
  27 #include "gc/g1/g1ConcurrentRefine.hpp"
  28 #include "gc/g1/heapRegion.hpp"
  29 #include "gc/g1/heapRegionManager.inline.hpp"
  30 #include "gc/g1/heapRegionSet.inline.hpp"
  31 #include "memory/allocation.hpp"
  32 #include "utilities/bitMap.inline.hpp"
  33 
  34 class MasterFreeRegionListChecker : public HeapRegionSetChecker {
  35 public:
  36   void check_mt_safety() {
  37     // Master Free List MT safety protocol:
  38     // (a) If we're at a safepoint, operations on the master free list
  39     // should be invoked by either the VM thread (which will serialize
  40     // them) or by the GC workers while holding the
  41     // FreeList_lock.
  42     // (b) If we're not at a safepoint, operations on the master free
  43     // list should be invoked while holding the Heap_lock.
  44 
  45     if (SafepointSynchronize::is_at_safepoint()) {
  46       guarantee(Thread::current()->is_VM_thread() ||
  47                 FreeList_lock->owned_by_self(), "master free list MT safety protocol at a safepoint");
  48     } else {
  49       guarantee(Heap_lock->owned_by_self(), "master free list MT safety protocol outside a safepoint");
  50     }
  51   }
  52   bool is_correct_type(HeapRegion* hr) { return hr->is_free(); }
  53   const char* get_description() { return "Free Regions"; }
  54 };
  55 
  56 HeapRegionManager::HeapRegionManager() :
  57   _regions(), _heap_mapper(NULL),
  58   _prev_bitmap_mapper(NULL),
  59   _next_bitmap_mapper(NULL),
  60   _bot_mapper(NULL),
  61   _cardtable_mapper(NULL),
  62   _card_counts_mapper(NULL),
  63   _free_list("Free list", new MasterFreeRegionListChecker()),
  64   _available_map(mtGC),
  65   _num_committed(0),
  66   _allocated_heapregions_length(0)
  67 { }
  68 
  69 void HeapRegionManager::initialize(G1RegionToSpaceMapper* heap_storage,
  70                                G1RegionToSpaceMapper* prev_bitmap,
  71                                G1RegionToSpaceMapper* next_bitmap,
  72                                G1RegionToSpaceMapper* bot,
  73                                G1RegionToSpaceMapper* cardtable,
  74                                G1RegionToSpaceMapper* card_counts) {
  75   _allocated_heapregions_length = 0;
  76 
  77   _heap_mapper = heap_storage;
  78 
  79   _prev_bitmap_mapper = prev_bitmap;
  80   _next_bitmap_mapper = next_bitmap;
  81 
  82   _bot_mapper = bot;
  83   _cardtable_mapper = cardtable;
  84 
  85   _card_counts_mapper = card_counts;
  86 
  87   MemRegion reserved = heap_storage->reserved();
  88   _regions.initialize(reserved.start(), reserved.end(), HeapRegion::GrainBytes);
  89 
  90   _available_map.initialize(_regions.length());
  91 }
  92 
  93 bool HeapRegionManager::is_available(uint region) const {
  94   return _available_map.at(region);
  95 }
  96 
  97 #ifdef ASSERT
  98 bool HeapRegionManager::is_free(HeapRegion* hr) const {
  99   return _free_list.contains(hr);
 100 }
 101 #endif
 102 
 103 HeapRegion* HeapRegionManager::new_heap_region(uint hrm_index) {
 104   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 105   HeapWord* bottom = g1h->bottom_addr_for_region(hrm_index);
 106   MemRegion mr(bottom, bottom + HeapRegion::GrainWords);
 107   assert(reserved().contains(mr), "invariant");
 108   return g1h->new_heap_region(hrm_index, mr);
 109 }
 110 
 111 void HeapRegionManager::commit_regions(uint index, size_t num_regions, WorkGang* pretouch_gang) {
 112   guarantee(num_regions > 0, "Must commit more than zero regions");
 113   guarantee(_num_committed + num_regions <= max_length(), "Cannot commit more than the maximum amount of regions");
 114 
 115   _num_committed += (uint)num_regions;
 116 
 117   _heap_mapper->commit_regions(index, num_regions, pretouch_gang);
 118 
 119   // Also commit auxiliary data
 120   _prev_bitmap_mapper->commit_regions(index, num_regions, pretouch_gang);
 121   _next_bitmap_mapper->commit_regions(index, num_regions, pretouch_gang);
 122 
 123   _bot_mapper->commit_regions(index, num_regions, pretouch_gang);
 124   _cardtable_mapper->commit_regions(index, num_regions, pretouch_gang);
 125 
 126   _card_counts_mapper->commit_regions(index, num_regions, pretouch_gang);
 127 }
 128 
 129 void HeapRegionManager::uncommit_regions(uint start, size_t num_regions) {
 130   guarantee(num_regions >= 1, "Need to specify at least one region to uncommit, tried to uncommit zero regions at %u", start);
 131   guarantee(_num_committed >= num_regions, "pre-condition");
 132 
 133   // Print before uncommitting.
 134   if (G1CollectedHeap::heap()->hr_printer()->is_active()) {
 135     for (uint i = start; i < start + num_regions; i++) {
 136       HeapRegion* hr = at(i);
 137       G1CollectedHeap::heap()->hr_printer()->uncommit(hr);
 138     }
 139   }
 140 
 141   _num_committed -= (uint)num_regions;
 142 
 143   _available_map.par_clear_range(start, start + num_regions, BitMap::unknown_range);
 144   _heap_mapper->uncommit_regions(start, num_regions);
 145 
 146   // Also uncommit auxiliary data
 147   _prev_bitmap_mapper->uncommit_regions(start, num_regions);
 148   _next_bitmap_mapper->uncommit_regions(start, num_regions);
 149 
 150   _bot_mapper->uncommit_regions(start, num_regions);
 151   _cardtable_mapper->uncommit_regions(start, num_regions);
 152 
 153   _card_counts_mapper->uncommit_regions(start, num_regions);
 154 }
 155 
 156 void HeapRegionManager::make_regions_available(uint start, uint num_regions, WorkGang* pretouch_gang) {
 157   guarantee(num_regions > 0, "No point in calling this for zero regions");
 158   commit_regions(start, num_regions, pretouch_gang);
 159   for (uint i = start; i < start + num_regions; i++) {
 160     if (_regions.get_by_index(i) == NULL) {
 161       HeapRegion* new_hr = new_heap_region(i);
 162       OrderAccess::storestore();
 163       _regions.set_by_index(i, new_hr);
 164       _allocated_heapregions_length = MAX2(_allocated_heapregions_length, i + 1);
 165     }
 166   }
 167 
 168   _available_map.par_set_range(start, start + num_regions, BitMap::unknown_range);
 169 
 170   for (uint i = start; i < start + num_regions; i++) {
 171     assert(is_available(i), "Just made region %u available but is apparently not.", i);
 172     HeapRegion* hr = at(i);
 173     if (G1CollectedHeap::heap()->hr_printer()->is_active()) {
 174       G1CollectedHeap::heap()->hr_printer()->commit(hr);
 175     }
 176     HeapWord* bottom = G1CollectedHeap::heap()->bottom_addr_for_region(i);
 177     MemRegion mr(bottom, bottom + HeapRegion::GrainWords);
 178 
 179     hr->initialize(mr);
 180     insert_into_free_list(at(i));
 181   }
 182 }
 183 
 184 MemoryUsage HeapRegionManager::get_auxiliary_data_memory_usage() const {
 185   size_t used_sz =
 186     _prev_bitmap_mapper->committed_size() +
 187     _next_bitmap_mapper->committed_size() +
 188     _bot_mapper->committed_size() +
 189     _cardtable_mapper->committed_size() +
 190     _card_counts_mapper->committed_size();
 191 
 192   size_t committed_sz =
 193     _prev_bitmap_mapper->reserved_size() +
 194     _next_bitmap_mapper->reserved_size() +
 195     _bot_mapper->reserved_size() +
 196     _cardtable_mapper->reserved_size() +
 197     _card_counts_mapper->reserved_size();
 198 
 199   return MemoryUsage(0, used_sz, committed_sz, committed_sz);
 200 }
 201 
 202 uint HeapRegionManager::expand_by(uint num_regions, WorkGang* pretouch_workers) {
 203   return expand_at(0, num_regions, pretouch_workers);
 204 }
 205 
 206 uint HeapRegionManager::expand_at(uint start, uint num_regions, WorkGang* pretouch_workers) {
 207   if (num_regions == 0) {
 208     return 0;
 209   }
 210 
 211   uint cur = start;
 212   uint idx_last_found = 0;
 213   uint num_last_found = 0;
 214 
 215   uint expanded = 0;
 216 
 217   while (expanded < num_regions &&
 218          (num_last_found = find_unavailable_from_idx(cur, &idx_last_found)) > 0) {
 219     uint to_expand = MIN2(num_regions - expanded, num_last_found);
 220     make_regions_available(idx_last_found, to_expand, pretouch_workers);
 221     expanded += to_expand;
 222     cur = idx_last_found + num_last_found + 1;
 223   }
 224 
 225   verify_optional();
 226   return expanded;
 227 }
 228 
 229 uint HeapRegionManager::find_contiguous(size_t num, bool empty_only) {
 230   uint found = 0;
 231   size_t length_found = 0;
 232   uint cur = 0;
 233 
 234   while (length_found < num && cur < max_length()) {
 235     HeapRegion* hr = _regions.get_by_index(cur);
 236     if ((!empty_only && !is_available(cur)) || (is_available(cur) && hr != NULL && hr->is_empty())) {
 237       // This region is a potential candidate for allocation into.
 238       length_found++;
 239     } else {
 240       // This region is not a candidate. The next region is the next possible one.
 241       found = cur + 1;
 242       length_found = 0;
 243     }
 244     cur++;
 245   }
 246 
 247   if (length_found == num) {
 248     for (uint i = found; i < (found + num); i++) {
 249       HeapRegion* hr = _regions.get_by_index(i);
 250       // sanity check
 251       guarantee((!empty_only && !is_available(i)) || (is_available(i) && hr != NULL && hr->is_empty()),
 252                 "Found region sequence starting at " UINT32_FORMAT ", length " SIZE_FORMAT
 253                 " that is not empty at " UINT32_FORMAT ". Hr is " PTR_FORMAT, found, num, i, p2i(hr));
 254     }
 255     return found;
 256   } else {
 257     return G1_NO_HRM_INDEX;
 258   }
 259 }
 260 
 261 HeapRegion* HeapRegionManager::next_region_in_heap(const HeapRegion* r) const {
 262   guarantee(r != NULL, "Start region must be a valid region");
 263   guarantee(is_available(r->hrm_index()), "Trying to iterate starting from region %u which is not in the heap", r->hrm_index());
 264   for (uint i = r->hrm_index() + 1; i < _allocated_heapregions_length; i++) {
 265     HeapRegion* hr = _regions.get_by_index(i);
 266     if (is_available(i)) {
 267       return hr;
 268     }
 269   }
 270   return NULL;
 271 }
 272 
 273 void HeapRegionManager::iterate(HeapRegionClosure* blk) const {
 274   uint len = max_length();
 275 
 276   for (uint i = 0; i < len; i++) {
 277     if (!is_available(i)) {
 278       continue;
 279     }
 280     guarantee(at(i) != NULL, "Tried to access region %u that has a NULL HeapRegion*", i);
 281     bool res = blk->do_heap_region(at(i));
 282     if (res) {
 283       blk->set_incomplete();
 284       return;
 285     }
 286   }
 287 }
 288 
 289 uint HeapRegionManager::find_unavailable_from_idx(uint start_idx, uint* res_idx) const {
 290   guarantee(res_idx != NULL, "checking");
 291   guarantee(start_idx <= (max_length() + 1), "checking");
 292 
 293   uint num_regions = 0;
 294 
 295   uint cur = start_idx;
 296   while (cur < max_length() && is_available(cur)) {
 297     cur++;
 298   }
 299   if (cur == max_length()) {
 300     return num_regions;
 301   }
 302   *res_idx = cur;
 303   while (cur < max_length() && !is_available(cur)) {
 304     cur++;
 305   }
 306   num_regions = cur - *res_idx;
 307 #ifdef ASSERT
 308   for (uint i = *res_idx; i < (*res_idx + num_regions); i++) {
 309     assert(!is_available(i), "just checking");
 310   }
 311   assert(cur == max_length() || num_regions == 0 || is_available(cur),
 312          "The region at the current position %u must be available or at the end of the heap.", cur);
 313 #endif
 314   return num_regions;
 315 }
 316 
 317 uint HeapRegionManager::find_highest_free(bool* expanded) {
 318   // Loop downwards from the highest region index, looking for an
 319   // entry which is either free or not yet committed.  If not yet
 320   // committed, expand_at that index.
 321   uint curr = max_length() - 1;
 322   while (true) {
 323     HeapRegion *hr = _regions.get_by_index(curr);
 324     if (hr == NULL || !is_available(curr)) {
 325       uint res = expand_at(curr, 1, NULL);
 326       if (res == 1) {
 327         *expanded = true;
 328         return curr;
 329       }
 330     } else {
 331       if (hr->is_free()) {
 332         *expanded = false;
 333         return curr;
 334       }
 335     }
 336     if (curr == 0) {
 337       return G1_NO_HRM_INDEX;
 338     }
 339     curr--;
 340   }
 341 }
 342 
 343 bool HeapRegionManager::allocate_containing_regions(MemRegion range, size_t* commit_count, WorkGang* pretouch_workers) {
 344   size_t commits = 0;
 345   uint start_index = (uint)_regions.get_index_by_address(range.start());
 346   uint last_index = (uint)_regions.get_index_by_address(range.last());
 347 
 348   // Ensure that each G1 region in the range is free, returning false if not.
 349   // Commit those that are not yet available, and keep count.
 350   for (uint curr_index = start_index; curr_index <= last_index; curr_index++) {
 351     if (!is_available(curr_index)) {
 352       commits++;
 353       expand_at(curr_index, 1, pretouch_workers);
 354     }
 355     HeapRegion* curr_region  = _regions.get_by_index(curr_index);
 356     if (!curr_region->is_free()) {
 357       return false;
 358     }
 359   }
 360 
 361   allocate_free_regions_starting_at(start_index, (last_index - start_index) + 1);
 362   *commit_count = commits;
 363   return true;
 364 }
 365 
 366 void HeapRegionManager::par_iterate(HeapRegionClosure* blk, HeapRegionClaimer* hrclaimer, const uint start_index) const {
 367   // Every worker will actually look at all regions, skipping over regions that
 368   // are currently not committed.
 369   // This also (potentially) iterates over regions newly allocated during GC. This
 370   // is no problem except for some extra work.
 371   const uint n_regions = hrclaimer->n_regions();
 372   for (uint count = 0; count < n_regions; count++) {
 373     const uint index = (start_index + count) % n_regions;
 374     assert(index < n_regions, "sanity");
 375     // Skip over unavailable regions
 376     if (!is_available(index)) {
 377       continue;
 378     }
 379     HeapRegion* r = _regions.get_by_index(index);
 380     // We'll ignore regions already claimed.
 381     // However, if the iteration is specified as concurrent, the values for
 382     // is_starts_humongous and is_continues_humongous can not be trusted,
 383     // and we should just blindly iterate over regions regardless of their
 384     // humongous status.
 385     if (hrclaimer->is_region_claimed(index)) {
 386       continue;
 387     }
 388     // OK, try to claim it
 389     if (!hrclaimer->claim_region(index)) {
 390       continue;
 391     }
 392     bool res = blk->do_heap_region(r);
 393     if (res) {
 394       return;
 395     }
 396   }
 397 }
 398 
 399 uint HeapRegionManager::shrink_by(uint num_regions_to_remove) {
 400   assert(length() > 0, "the region sequence should not be empty");
 401   assert(length() <= _allocated_heapregions_length, "invariant");
 402   assert(_allocated_heapregions_length > 0, "we should have at least one region committed");
 403   assert(num_regions_to_remove < length(), "We should never remove all regions");
 404 
 405   if (num_regions_to_remove == 0) {
 406     return 0;
 407   }
 408 
 409   uint removed = 0;
 410   uint cur = _allocated_heapregions_length - 1;
 411   uint idx_last_found = 0;
 412   uint num_last_found = 0;
 413 
 414   while ((removed < num_regions_to_remove) &&
 415       (num_last_found = find_empty_from_idx_reverse(cur, &idx_last_found)) > 0) {
 416     uint to_remove = MIN2(num_regions_to_remove - removed, num_last_found);
 417 
 418     shrink_at(idx_last_found + num_last_found - to_remove, to_remove);
 419 
 420     cur = idx_last_found;
 421     removed += to_remove;
 422   }
 423 
 424   verify_optional();
 425 
 426   return removed;
 427 }
 428 
 429 void HeapRegionManager::shrink_at(uint index, size_t num_regions) {
 430 #ifdef ASSERT
 431   for (uint i = index; i < (index + num_regions); i++) {
 432     assert(is_available(i), "Expected available region at index %u", i);
 433     assert(at(i)->is_empty(), "Expected empty region at index %u", i);
 434     assert(at(i)->is_free(), "Expected free region at index %u", i);
 435   }
 436 #endif
 437   uncommit_regions(index, num_regions);
 438 }
 439 
 440 uint HeapRegionManager::find_empty_from_idx_reverse(uint start_idx, uint* res_idx) const {
 441   guarantee(start_idx < _allocated_heapregions_length, "checking");
 442   guarantee(res_idx != NULL, "checking");
 443 
 444   uint num_regions_found = 0;
 445 
 446   jlong cur = start_idx;
 447   while (cur != -1 && !(is_available(cur) && at(cur)->is_empty())) {
 448     cur--;
 449   }
 450   if (cur == -1) {
 451     return num_regions_found;
 452   }
 453   jlong old_cur = cur;
 454   // cur indexes the first empty region
 455   while (cur != -1 && is_available(cur) && at(cur)->is_empty()) {
 456     cur--;
 457   }
 458   *res_idx = cur + 1;
 459   num_regions_found = old_cur - cur;
 460 
 461 #ifdef ASSERT
 462   for (uint i = *res_idx; i < (*res_idx + num_regions_found); i++) {
 463     assert(at(i)->is_empty(), "just checking");
 464   }
 465 #endif
 466   return num_regions_found;
 467 }
 468 
 469 void HeapRegionManager::verify() {
 470   guarantee(length() <= _allocated_heapregions_length,
 471             "invariant: _length: %u _allocated_length: %u",
 472             length(), _allocated_heapregions_length);
 473   guarantee(_allocated_heapregions_length <= max_length(),
 474             "invariant: _allocated_length: %u _max_length: %u",
 475             _allocated_heapregions_length, max_length());
 476 
 477   bool prev_committed = true;
 478   uint num_committed = 0;
 479   HeapWord* prev_end = heap_bottom();
 480   for (uint i = 0; i < _allocated_heapregions_length; i++) {
 481     if (!is_available(i)) {
 482       prev_committed = false;
 483       continue;
 484     }
 485     num_committed++;
 486     HeapRegion* hr = _regions.get_by_index(i);
 487     guarantee(hr != NULL, "invariant: i: %u", i);
 488     guarantee(!prev_committed || hr->bottom() == prev_end,
 489               "invariant i: %u " HR_FORMAT " prev_end: " PTR_FORMAT,
 490               i, HR_FORMAT_PARAMS(hr), p2i(prev_end));
 491     guarantee(hr->hrm_index() == i,
 492               "invariant: i: %u hrm_index(): %u", i, hr->hrm_index());
 493     // Asserts will fire if i is >= _length
 494     HeapWord* addr = hr->bottom();
 495     guarantee(addr_to_region(addr) == hr, "sanity");
 496     // We cannot check whether the region is part of a particular set: at the time
 497     // this method may be called, we have only completed allocation of the regions,
 498     // but not put into a region set.
 499     prev_committed = true;
 500     prev_end = hr->end();
 501   }
 502   for (uint i = _allocated_heapregions_length; i < max_length(); i++) {
 503     guarantee(_regions.get_by_index(i) == NULL, "invariant i: %u", i);
 504   }
 505 
 506   guarantee(num_committed == _num_committed, "Found %u committed regions, but should be %u", num_committed, _num_committed);
 507   _free_list.verify();
 508 }
 509 
 510 #ifndef PRODUCT
 511 void HeapRegionManager::verify_optional() {
 512   verify();
 513 }
 514 #endif // PRODUCT
 515 
 516 HeapRegionClaimer::HeapRegionClaimer(uint n_workers) :
 517     _n_workers(n_workers), _n_regions(G1CollectedHeap::heap()->_hrm->_allocated_heapregions_length), _claims(NULL) {
 518   assert(n_workers > 0, "Need at least one worker.");
 519   uint* new_claims = NEW_C_HEAP_ARRAY(uint, _n_regions, mtGC);
 520   memset(new_claims, Unclaimed, sizeof(*_claims) * _n_regions);
 521   _claims = new_claims;
 522 }
 523 
 524 HeapRegionClaimer::~HeapRegionClaimer() {
 525   if (_claims != NULL) {
 526     FREE_C_HEAP_ARRAY(uint, _claims);
 527   }
 528 }
 529 
 530 uint HeapRegionClaimer::offset_for_worker(uint worker_id) const {
 531   assert(worker_id < _n_workers, "Invalid worker_id.");
 532   return _n_regions * worker_id / _n_workers;
 533 }
 534 
 535 bool HeapRegionClaimer::is_region_claimed(uint region_index) const {
 536   assert(region_index < _n_regions, "Invalid index.");
 537   return _claims[region_index] == Claimed;
 538 }
 539 
 540 bool HeapRegionClaimer::claim_region(uint region_index) {
 541   assert(region_index < _n_regions, "Invalid index.");
 542   uint old_val = Atomic::cmpxchg(Claimed, &_claims[region_index], Unclaimed);
 543   return old_val == Unclaimed;
 544 }