1 /*
   2  * Copyright (c) 2001, 2014, 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_implementation/g1/heapRegion.hpp"
  27 #include "gc_implementation/g1/heapRegionManager.inline.hpp"
  28 #include "gc_implementation/g1/heapRegionSet.inline.hpp"
  29 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  30 #include "gc_implementation/g1/concurrentG1Refine.hpp"
  31 #include "memory/allocation.hpp"
  32 
  33 void HeapRegionManager::initialize(G1RegionToSpaceMapper* heap_storage,
  34                                G1RegionToSpaceMapper* prev_bitmap,
  35                                G1RegionToSpaceMapper* next_bitmap,
  36                                G1RegionToSpaceMapper* bot,
  37                                G1RegionToSpaceMapper* cardtable,
  38                                G1RegionToSpaceMapper* card_counts) {
  39   _allocated_heapregions_length = 0;
  40 
  41   _heap_mapper = heap_storage;
  42 
  43   _prev_bitmap_mapper = prev_bitmap;
  44   _next_bitmap_mapper = next_bitmap;
  45 
  46   _bot_mapper = bot;
  47   _cardtable_mapper = cardtable;
  48 
  49   _card_counts_mapper = card_counts;
  50 
  51   MemRegion reserved = heap_storage->reserved();
  52   _regions.initialize(reserved.start(), reserved.end(), HeapRegion::GrainBytes);
  53 
  54   _available_map.resize(_regions.length(), false);
  55   _available_map.clear();
  56 }
  57 
  58 bool HeapRegionManager::is_available(uint region) const {
  59   return _available_map.at(region);
  60 }
  61 
  62 #ifdef ASSERT
  63 bool HeapRegionManager::is_free(HeapRegion* hr) const {
  64   return _free_list.contains(hr);
  65 }
  66 #endif
  67 
  68 HeapRegion* HeapRegionManager::new_heap_region(uint hrm_index) {
  69   HeapWord* bottom = G1CollectedHeap::heap()->bottom_addr_for_region(hrm_index);
  70   MemRegion mr(bottom, bottom + HeapRegion::GrainWords);
  71   assert(reserved().contains(mr), "invariant");
  72   return new HeapRegion(hrm_index, G1CollectedHeap::heap()->bot_shared(), mr);
  73 }
  74 
  75 void HeapRegionManager::commit_regions(uint index, size_t num_regions) {
  76   guarantee(num_regions > 0, "Must commit more than zero regions");
  77   guarantee(_num_committed + num_regions <= max_length(), "Cannot commit more than the maximum amount of regions");
  78 
  79   _num_committed += (uint)num_regions;
  80 
  81   _heap_mapper->commit_regions(index, num_regions);
  82 
  83   // Also commit auxiliary data
  84   _prev_bitmap_mapper->commit_regions(index, num_regions);
  85   _next_bitmap_mapper->commit_regions(index, num_regions);
  86 
  87   _bot_mapper->commit_regions(index, num_regions);
  88   _cardtable_mapper->commit_regions(index, num_regions);
  89 
  90   _card_counts_mapper->commit_regions(index, num_regions);
  91 }
  92 
  93 void HeapRegionManager::uncommit_regions(uint start, size_t num_regions) {
  94   guarantee(num_regions >= 1, err_msg("Need to specify at least one region to uncommit, tried to uncommit zero regions at %u", start));
  95   guarantee(_num_committed >= num_regions, "pre-condition");
  96 
  97   // Print before uncommitting.
  98   if (G1CollectedHeap::heap()->hr_printer()->is_active()) {
  99     for (uint i = start; i < start + num_regions; i++) {
 100       HeapRegion* hr = at(i);
 101       G1CollectedHeap::heap()->hr_printer()->uncommit(hr->bottom(), hr->end());
 102     }
 103   }
 104 
 105   _num_committed -= (uint)num_regions;
 106 
 107   _available_map.par_clear_range(start, start + num_regions, BitMap::unknown_range);
 108   _heap_mapper->uncommit_regions(start, num_regions);
 109 
 110   // Also uncommit auxiliary data
 111   _prev_bitmap_mapper->uncommit_regions(start, num_regions);
 112   _next_bitmap_mapper->uncommit_regions(start, num_regions);
 113 
 114   _bot_mapper->uncommit_regions(start, num_regions);
 115   _cardtable_mapper->uncommit_regions(start, num_regions);
 116 
 117   _card_counts_mapper->uncommit_regions(start, num_regions);
 118 }
 119 
 120 void HeapRegionManager::make_regions_available(uint start, uint num_regions) {
 121   guarantee(num_regions > 0, "No point in calling this for zero regions");
 122   commit_regions(start, num_regions);
 123   for (uint i = start; i < start + num_regions; i++) {
 124     if (_regions.get_by_index(i) == NULL) {
 125       HeapRegion* new_hr = new_heap_region(i);
 126       _regions.set_by_index(i, new_hr);
 127       _allocated_heapregions_length = MAX2(_allocated_heapregions_length, i + 1);
 128     }
 129   }
 130 
 131   _available_map.par_set_range(start, start + num_regions, BitMap::unknown_range);
 132 
 133   for (uint i = start; i < start + num_regions; i++) {
 134     assert(is_available(i), err_msg("Just made region %u available but is apparently not.", i));
 135     HeapRegion* hr = at(i);
 136     if (G1CollectedHeap::heap()->hr_printer()->is_active()) {
 137       G1CollectedHeap::heap()->hr_printer()->commit(hr->bottom(), hr->end());
 138     }
 139     HeapWord* bottom = G1CollectedHeap::heap()->bottom_addr_for_region(i);
 140     MemRegion mr(bottom, bottom + HeapRegion::GrainWords);
 141 
 142     hr->initialize(mr);
 143     insert_into_free_list(at(i));
 144   }
 145 }
 146 
 147 uint HeapRegionManager::expand_by(uint num_regions) {
 148   return expand_at(0, num_regions);
 149 }
 150 
 151 uint HeapRegionManager::expand_at(uint start, uint num_regions) {
 152   if (num_regions == 0) {
 153     return 0;
 154   }
 155 
 156   uint cur = start;
 157   uint idx_last_found = 0;
 158   uint num_last_found = 0;
 159 
 160   uint expanded = 0;
 161 
 162   while (expanded < num_regions &&
 163          (num_last_found = find_unavailable_from_idx(cur, &idx_last_found)) > 0) {
 164     uint to_expand = MIN2(num_regions - expanded, num_last_found);
 165     make_regions_available(idx_last_found, to_expand);
 166     expanded += to_expand;
 167     cur = idx_last_found + num_last_found + 1;
 168   }
 169 
 170   verify_optional();
 171   return expanded;
 172 }
 173 
 174 uint HeapRegionManager::find_contiguous(size_t num, bool empty_only) {
 175   uint found = 0;
 176   size_t length_found = 0;
 177   uint cur = 0;
 178 
 179   while (length_found < num && cur < max_length()) {
 180     HeapRegion* hr = _regions.get_by_index(cur);
 181     if ((!empty_only && !is_available(cur)) || (is_available(cur) && hr != NULL && hr->is_empty())) {
 182       // This region is a potential candidate for allocation into.
 183       length_found++;
 184     } else {
 185       // This region is not a candidate. The next region is the next possible one.
 186       found = cur + 1;
 187       length_found = 0;
 188     }
 189     cur++;
 190   }
 191 
 192   if (length_found == num) {
 193     for (uint i = found; i < (found + num); i++) {
 194       HeapRegion* hr = _regions.get_by_index(i);
 195       // sanity check
 196       guarantee((!empty_only && !is_available(i)) || (is_available(i) && hr != NULL && hr->is_empty()),
 197                 err_msg("Found region sequence starting at " UINT32_FORMAT ", length " SIZE_FORMAT
 198                         " that is not empty at " UINT32_FORMAT ". Hr is " PTR_FORMAT, found, num, i, p2i(hr)));
 199     }
 200     return found;
 201   } else {
 202     return G1_NO_HRM_INDEX;
 203   }
 204 }
 205 
 206 HeapRegion* HeapRegionManager::next_region_in_heap(const HeapRegion* r) const {
 207   guarantee(r != NULL, "Start region must be a valid region");
 208   guarantee(is_available(r->hrm_index()), err_msg("Trying to iterate starting from region %u which is not in the heap", r->hrm_index()));
 209   for (uint i = r->hrm_index() + 1; i < _allocated_heapregions_length; i++) {
 210     HeapRegion* hr = _regions.get_by_index(i);
 211     if (is_available(i)) {
 212       return hr;
 213     }
 214   }
 215   return NULL;
 216 }
 217 
 218 void HeapRegionManager::iterate(HeapRegionClosure* blk) const {
 219   uint len = max_length();
 220 
 221   for (uint i = 0; i < len; i++) {
 222     if (!is_available(i)) {
 223       continue;
 224     }
 225     guarantee(at(i) != NULL, err_msg("Tried to access region %u that has a NULL HeapRegion*", i));
 226     bool res = blk->doHeapRegion(at(i));
 227     if (res) {
 228       blk->incomplete();
 229       return;
 230     }
 231   }
 232 }
 233 
 234 uint HeapRegionManager::find_unavailable_from_idx(uint start_idx, uint* res_idx) const {
 235   guarantee(res_idx != NULL, "checking");
 236   guarantee(start_idx <= (max_length() + 1), "checking");
 237 
 238   uint num_regions = 0;
 239 
 240   uint cur = start_idx;
 241   while (cur < max_length() && is_available(cur)) {
 242     cur++;
 243   }
 244   if (cur == max_length()) {
 245     return num_regions;
 246   }
 247   *res_idx = cur;
 248   while (cur < max_length() && !is_available(cur)) {
 249     cur++;
 250   }
 251   num_regions = cur - *res_idx;
 252 #ifdef ASSERT
 253   for (uint i = *res_idx; i < (*res_idx + num_regions); i++) {
 254     assert(!is_available(i), "just checking");
 255   }
 256   assert(cur == max_length() || num_regions == 0 || is_available(cur),
 257          err_msg("The region at the current position %u must be available or at the end of the heap.", cur));
 258 #endif
 259   return num_regions;
 260 }
 261 
 262 void HeapRegionManager::par_iterate(HeapRegionClosure* blk, uint worker_id, HeapRegionClaimer* hrclaimer) const {
 263   const uint start_index = hrclaimer->start_region_for_worker(worker_id);
 264 
 265   // Every worker will actually look at all regions, skipping over regions that
 266   // are currently not committed.
 267   // This also (potentially) iterates over regions newly allocated during GC. This
 268   // is no problem except for some extra work.
 269   const uint n_regions = hrclaimer->n_regions();
 270   for (uint count = 0; count < n_regions; count++) {
 271     const uint index = (start_index + count) % n_regions;
 272     assert(0 <= index && index < n_regions, "sanity");
 273     // Skip over unavailable regions
 274     if (!is_available(index)) {
 275       continue;
 276     }
 277     HeapRegion* r = _regions.get_by_index(index);
 278     // We'll ignore "continues humongous" regions (we'll process them
 279     // when we come across their corresponding "start humongous"
 280     // region) and regions already claimed.
 281     if (hrclaimer->is_region_claimed(index) || r->continuesHumongous()) {
 282       continue;
 283     }
 284     // OK, try to claim it
 285     if (!hrclaimer->claim_region(index)) {
 286       continue;
 287     }
 288     // Success!
 289     if (r->startsHumongous()) {
 290       // If the region is "starts humongous" we'll iterate over its
 291       // "continues humongous" first; in fact we'll do them
 292       // first. The order is important. In one case, calling the
 293       // closure on the "starts humongous" region might de-allocate
 294       // and clear all its "continues humongous" regions and, as a
 295       // result, we might end up processing them twice. So, we'll do
 296       // them first (note: most closures will ignore them anyway) and
 297       // then we'll do the "starts humongous" region.
 298       for (uint ch_index = index + 1; ch_index < index + r->region_num(); ch_index++) {
 299         HeapRegion* chr = _regions.get_by_index(ch_index);
 300 
 301         assert(chr->continuesHumongous(), "Must be humongous region");
 302         assert(chr->humongous_start_region() == r,
 303                err_msg("Must work on humongous continuation of the original start region "
 304                        PTR_FORMAT ", but is " PTR_FORMAT, p2i(r), p2i(chr)));
 305         assert(!hrclaimer->is_region_claimed(ch_index),
 306                "Must not have been claimed yet because claiming of humongous continuation first claims the start region");
 307 
 308         // There's no need to actually claim the continues humongous region, but we can do it in an assert as an extra precaution.
 309         assert(hrclaimer->claim_region(ch_index), "We should always be able to claim the continuesHumongous part of the humongous object");
 310 
 311         bool res2 = blk->doHeapRegion(chr);
 312         if (res2) {
 313           return;
 314         }
 315 
 316         // Right now, this holds (i.e., no closure that actually
 317         // does something with "continues humongous" regions
 318         // clears them). We might have to weaken it in the future,
 319         // but let's leave these two asserts here for extra safety.
 320         assert(chr->continuesHumongous(), "should still be the case");
 321         assert(chr->humongous_start_region() == r, "sanity");
 322       }
 323     }
 324 
 325     bool res = blk->doHeapRegion(r);
 326     if (res) {
 327       return;
 328     }
 329   }
 330 }
 331 
 332 uint HeapRegionManager::shrink_by(uint num_regions_to_remove) {
 333   assert(length() > 0, "the region sequence should not be empty");
 334   assert(length() <= _allocated_heapregions_length, "invariant");
 335   assert(_allocated_heapregions_length > 0, "we should have at least one region committed");
 336   assert(num_regions_to_remove < length(), "We should never remove all regions");
 337 
 338   if (num_regions_to_remove == 0) {
 339     return 0;
 340   }
 341 
 342   uint removed = 0;
 343   uint cur = _allocated_heapregions_length - 1;
 344   uint idx_last_found = 0;
 345   uint num_last_found = 0;
 346 
 347   while ((removed < num_regions_to_remove) &&
 348       (num_last_found = find_empty_from_idx_reverse(cur, &idx_last_found)) > 0) {
 349     uint to_remove = MIN2(num_regions_to_remove - removed, num_last_found);
 350 
 351     uncommit_regions(idx_last_found + num_last_found - to_remove, to_remove);
 352 
 353     cur -= num_last_found;
 354     removed += to_remove;
 355   }
 356 
 357   verify_optional();
 358 
 359   return removed;
 360 }
 361 
 362 uint HeapRegionManager::find_empty_from_idx_reverse(uint start_idx, uint* res_idx) const {
 363   guarantee(start_idx < _allocated_heapregions_length, "checking");
 364   guarantee(res_idx != NULL, "checking");
 365 
 366   uint num_regions_found = 0;
 367 
 368   jlong cur = start_idx;
 369   while (cur != -1 && !(is_available(cur) && at(cur)->is_empty())) {
 370     cur--;
 371   }
 372   if (cur == -1) {
 373     return num_regions_found;
 374   }
 375   jlong old_cur = cur;
 376   // cur indexes the first empty region
 377   while (cur != -1 && is_available(cur) && at(cur)->is_empty()) {
 378     cur--;
 379   }
 380   *res_idx = cur + 1;
 381   num_regions_found = old_cur - cur;
 382 
 383 #ifdef ASSERT
 384   for (uint i = *res_idx; i < (*res_idx + num_regions_found); i++) {
 385     assert(at(i)->is_empty(), "just checking");
 386   }
 387 #endif
 388   return num_regions_found;
 389 }
 390 
 391 void HeapRegionManager::verify() {
 392   guarantee(length() <= _allocated_heapregions_length,
 393             err_msg("invariant: _length: %u _allocated_length: %u",
 394                     length(), _allocated_heapregions_length));
 395   guarantee(_allocated_heapregions_length <= max_length(),
 396             err_msg("invariant: _allocated_length: %u _max_length: %u",
 397                     _allocated_heapregions_length, max_length()));
 398 
 399   bool prev_committed = true;
 400   uint num_committed = 0;
 401   HeapWord* prev_end = heap_bottom();
 402   for (uint i = 0; i < _allocated_heapregions_length; i++) {
 403     if (!is_available(i)) {
 404       prev_committed = false;
 405       continue;
 406     }
 407     num_committed++;
 408     HeapRegion* hr = _regions.get_by_index(i);
 409     guarantee(hr != NULL, err_msg("invariant: i: %u", i));
 410     guarantee(!prev_committed || hr->bottom() == prev_end,
 411               err_msg("invariant i: %u "HR_FORMAT" prev_end: "PTR_FORMAT,
 412                       i, HR_FORMAT_PARAMS(hr), p2i(prev_end)));
 413     guarantee(hr->hrm_index() == i,
 414               err_msg("invariant: i: %u hrm_index(): %u", i, hr->hrm_index()));
 415     // Asserts will fire if i is >= _length
 416     HeapWord* addr = hr->bottom();
 417     guarantee(addr_to_region(addr) == hr, "sanity");
 418     // We cannot check whether the region is part of a particular set: at the time
 419     // this method may be called, we have only completed allocation of the regions,
 420     // but not put into a region set.
 421     prev_committed = true;
 422     if (hr->startsHumongous()) {
 423       prev_end = hr->orig_end();
 424     } else {
 425       prev_end = hr->end();
 426     }
 427   }
 428   for (uint i = _allocated_heapregions_length; i < max_length(); i++) {
 429     guarantee(_regions.get_by_index(i) == NULL, err_msg("invariant i: %u", i));
 430   }
 431 
 432   guarantee(num_committed == _num_committed, err_msg("Found %u committed regions, but should be %u", num_committed, _num_committed));
 433   _free_list.verify();
 434 }
 435 
 436 #ifndef PRODUCT
 437 void HeapRegionManager::verify_optional() {
 438   verify();
 439 }
 440 #endif // PRODUCT
 441 
 442 void HeapRegionClaimer::initialize(uint n_workers) {
 443   assert(n_workers > 0, "Need at least one worker.");
 444   assert(_claims == NULL, "Must initialize only once.");
 445   _n_workers = n_workers;
 446   _n_regions = G1CollectedHeap::heap()->_hrm._allocated_heapregions_length;
 447   _claims = NEW_C_HEAP_ARRAY(uint, _n_regions, mtGC);
 448   memset(_claims, Unclaimed, sizeof(*_claims) * _n_regions);
 449 }
 450 
 451 uint HeapRegionClaimer::start_region_for_worker(uint worker_id) const {
 452   assert(_n_workers != 0, "Must initialize before use.");
 453   assert(worker_id < _n_workers, "Invalid worker_id.");
 454   return _n_regions * worker_id / _n_workers;
 455 }
 456 
 457 bool HeapRegionClaimer::is_region_claimed(uint region_index) const {
 458   assert(_claims != NULL, "Must initialize before use.");
 459   assert(region_index < _n_regions, "Invalid index.");
 460   return _claims[region_index] == Claimed;
 461 }
 462 
 463 bool HeapRegionClaimer::claim_region(uint region_index) {
 464   assert(_claims != NULL, "Must initialize before use.");
 465   assert(region_index < _n_regions, "Invalid index.");
 466   if (Atomic::cmpxchg(Claimed, &_claims[region_index], Unclaimed) == Unclaimed) {
 467     return true;
 468   }
 469   return false;
 470 }