1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <deque>
17 
18 #include "bump_pointer_space-inl.h"
19 #include "bump_pointer_space.h"
20 #include "base/dumpable.h"
21 #include "base/logging.h"
22 #include "gc/accounting/read_barrier_table.h"
23 #include "mirror/class-inl.h"
24 #include "mirror/object-inl.h"
25 #include "thread_list.h"
26 
27 namespace art HIDDEN {
28 namespace gc {
29 namespace space {
30 
31 // If a region has live objects whose size is less than this percent
32 // value of the region size, evaculate the region.
33 static constexpr uint kEvacuateLivePercentThreshold = 75U;
34 
35 // Whether we protect the unused and cleared regions.
36 static constexpr bool kProtectClearedRegions = kIsDebugBuild;
37 
38 // Wether we poison memory areas occupied by dead objects in unevacuated regions.
39 static constexpr bool kPoisonDeadObjectsInUnevacuatedRegions = kIsDebugBuild;
40 
41 // Special 32-bit value used to poison memory areas occupied by dead
42 // objects in unevacuated regions. Dereferencing this value is expected
43 // to trigger a memory protection fault, as it is unlikely that it
44 // points to a valid, non-protected memory area.
45 static constexpr uint32_t kPoisonDeadObject = 0xBADDB01D;  // "BADDROID"
46 
47 // Whether we check a region's live bytes count against the region bitmap.
48 static constexpr bool kCheckLiveBytesAgainstRegionBitmap = kIsDebugBuild;
49 
CreateMemMap(const std::string & name,size_t capacity,uint8_t * requested_begin)50 MemMap RegionSpace::CreateMemMap(const std::string& name,
51                                  size_t capacity,
52                                  uint8_t* requested_begin) {
53   CHECK_ALIGNED(capacity, kRegionSize);
54   std::string error_msg;
55   // Ask for the capacity of an additional kRegionSize so that we can align the map by kRegionSize
56   // even if we get unaligned base address. This is necessary for the ReadBarrierTable to work.
57   MemMap mem_map;
58   while (true) {
59     mem_map = MemMap::MapAnonymous(name.c_str(),
60                                    requested_begin,
61                                    capacity + kRegionSize,
62                                    PROT_READ | PROT_WRITE,
63                                    /*low_4gb=*/ true,
64                                    /*reuse=*/ false,
65                                    /*reservation=*/ nullptr,
66                                    &error_msg);
67     if (mem_map.IsValid() || requested_begin == nullptr) {
68       break;
69     }
70     // Retry with no specified request begin.
71     requested_begin = nullptr;
72   }
73   if (!mem_map.IsValid()) {
74     LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
75         << PrettySize(capacity) << " with message " << error_msg;
76     PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
77     MemMap::DumpMaps(LOG_STREAM(ERROR));
78     return MemMap::Invalid();
79   }
80   CHECK_EQ(mem_map.Size(), capacity + kRegionSize);
81   CHECK_EQ(mem_map.Begin(), mem_map.BaseBegin());
82   CHECK_EQ(mem_map.Size(), mem_map.BaseSize());
83   if (IsAlignedParam(mem_map.Begin(), kRegionSize)) {
84     // Got an aligned map. Since we requested a map that's kRegionSize larger. Shrink by
85     // kRegionSize at the end.
86     mem_map.SetSize(capacity);
87   } else {
88     // Got an unaligned map. Align the both ends.
89     mem_map.AlignBy(kRegionSize);
90   }
91   CHECK_ALIGNED(mem_map.Begin(), kRegionSize);
92   CHECK_ALIGNED(mem_map.End(), kRegionSize);
93   CHECK_EQ(mem_map.Size(), capacity);
94   return mem_map;
95 }
96 
Create(const std::string & name,MemMap && mem_map,bool use_generational_cc)97 RegionSpace* RegionSpace::Create(
98     const std::string& name, MemMap&& mem_map, bool use_generational_cc) {
99   return new RegionSpace(name, std::move(mem_map), use_generational_cc);
100 }
101 
RegionSpace(const std::string & name,MemMap && mem_map,bool use_generational_cc)102 RegionSpace::RegionSpace(const std::string& name, MemMap&& mem_map, bool use_generational_cc)
103     : ContinuousMemMapAllocSpace(name,
104                                  std::move(mem_map),
105                                  mem_map.Begin(),
106                                  mem_map.End(),
107                                  mem_map.End(),
108                                  kGcRetentionPolicyAlwaysCollect),
109       region_lock_("Region lock", kRegionSpaceRegionLock),
110       use_generational_cc_(use_generational_cc),
111       time_(1U),
112       num_regions_(mem_map_.Size() / kRegionSize),
113       madvise_time_(0U),
114       num_non_free_regions_(0U),
115       num_evac_regions_(0U),
116       max_peak_num_non_free_regions_(0U),
117       non_free_region_index_limit_(0U),
118       current_region_(&full_region_),
119       evac_region_(nullptr),
120       cyclic_alloc_region_index_(0U) {
121   CHECK_ALIGNED(mem_map_.Size(), kRegionSize);
122   CHECK_ALIGNED(mem_map_.Begin(), kRegionSize);
123   DCHECK_GT(num_regions_, 0U);
124   regions_.reset(new Region[num_regions_]);
125   uint8_t* region_addr = mem_map_.Begin();
126   for (size_t i = 0; i < num_regions_; ++i, region_addr += kRegionSize) {
127     regions_[i].Init(i, region_addr, region_addr + kRegionSize);
128   }
129   mark_bitmap_ =
130       accounting::ContinuousSpaceBitmap::Create("region space live bitmap", Begin(), Capacity());
131   if (kIsDebugBuild) {
132     CHECK_EQ(regions_[0].Begin(), Begin());
133     for (size_t i = 0; i < num_regions_; ++i) {
134       CHECK(regions_[i].IsFree());
135       CHECK_EQ(static_cast<size_t>(regions_[i].End() - regions_[i].Begin()), kRegionSize);
136       if (i + 1 < num_regions_) {
137         CHECK_EQ(regions_[i].End(), regions_[i + 1].Begin());
138       }
139     }
140     CHECK_EQ(regions_[num_regions_ - 1].End(), Limit());
141   }
142   DCHECK(!full_region_.IsFree());
143   DCHECK(full_region_.IsAllocated());
144   size_t ignored;
145   DCHECK(full_region_.Alloc(kAlignment, &ignored, nullptr, &ignored) == nullptr);
146   // Protect the whole region space from the start.
147   Protect();
148 }
149 
FromSpaceSize()150 size_t RegionSpace::FromSpaceSize() {
151   uint64_t num_regions = 0;
152   MutexLock mu(Thread::Current(), region_lock_);
153   for (size_t i = 0; i < num_regions_; ++i) {
154     Region* r = &regions_[i];
155     if (r->IsInFromSpace()) {
156       ++num_regions;
157     }
158   }
159   return num_regions * kRegionSize;
160 }
161 
UnevacFromSpaceSize()162 size_t RegionSpace::UnevacFromSpaceSize() {
163   uint64_t num_regions = 0;
164   MutexLock mu(Thread::Current(), region_lock_);
165   for (size_t i = 0; i < num_regions_; ++i) {
166     Region* r = &regions_[i];
167     if (r->IsInUnevacFromSpace()) {
168       ++num_regions;
169     }
170   }
171   return num_regions * kRegionSize;
172 }
173 
ToSpaceSize()174 size_t RegionSpace::ToSpaceSize() {
175   uint64_t num_regions = 0;
176   MutexLock mu(Thread::Current(), region_lock_);
177   for (size_t i = 0; i < num_regions_; ++i) {
178     Region* r = &regions_[i];
179     if (r->IsInToSpace()) {
180       ++num_regions;
181     }
182   }
183   return num_regions * kRegionSize;
184 }
185 
SetAsUnevacFromSpace(bool clear_live_bytes)186 void RegionSpace::Region::SetAsUnevacFromSpace(bool clear_live_bytes) {
187   // Live bytes are only preserved (i.e. not cleared) during sticky-bit CC collections.
188   DCHECK(GetUseGenerationalCC() || clear_live_bytes);
189   DCHECK(!IsFree() && IsInToSpace());
190   type_ = RegionType::kRegionTypeUnevacFromSpace;
191   if (IsNewlyAllocated()) {
192     // A newly allocated region set as unevac from-space must be
193     // a large or large tail region.
194     DCHECK(IsLarge() || IsLargeTail()) << static_cast<uint>(state_);
195     // Always clear the live bytes of a newly allocated (large or
196     // large tail) region.
197     clear_live_bytes = true;
198     // Clear the "newly allocated" status here, as we do not want the
199     // GC to see it when encountering (and processing) references in the
200     // from-space.
201     //
202     // Invariant: There should be no newly-allocated region in the
203     // from-space (when the from-space exists, which is between the calls
204     // to RegionSpace::SetFromSpace and RegionSpace::ClearFromSpace).
205     is_newly_allocated_ = false;
206   }
207   if (clear_live_bytes) {
208     // Reset the live bytes, as we have made a non-evacuation
209     // decision (possibly based on the percentage of live bytes).
210     live_bytes_ = 0;
211   }
212 }
213 
GetUseGenerationalCC()214 bool RegionSpace::Region::GetUseGenerationalCC() {
215   // We are retrieving the info from Heap, instead of the cached version in
216   // RegionSpace, because accessing the Heap from a Region object is easier
217   // than accessing the RegionSpace.
218   return art::Runtime::Current()->GetHeap()->GetUseGenerationalCC();
219 }
220 
ShouldBeEvacuated(EvacMode evac_mode)221 inline bool RegionSpace::Region::ShouldBeEvacuated(EvacMode evac_mode) {
222   // Evacuation mode `kEvacModeNewlyAllocated` is only used during sticky-bit CC collections.
223   DCHECK(GetUseGenerationalCC() || (evac_mode != kEvacModeNewlyAllocated));
224   DCHECK((IsAllocated() || IsLarge()) && IsInToSpace());
225   // The region should be evacuated if:
226   // - the evacuation is forced (!large && `evac_mode == kEvacModeForceAll`); or
227   // - the region was allocated after the start of the previous GC (newly allocated region); or
228   // - !large and the live ratio is below threshold (`kEvacuateLivePercentThreshold`).
229   if (IsLarge()) {
230     // It makes no sense to evacuate in the large case, since the region only contains zero or
231     // one object. If the regions is completely empty, we'll reclaim it anyhow. If its one object
232     // is live, we would just be moving around region-aligned memory.
233     return false;
234   }
235   if (UNLIKELY(evac_mode == kEvacModeForceAll)) {
236     return true;
237   }
238   DCHECK(IsAllocated());
239   if (is_newly_allocated_) {
240     // Invariant: newly allocated regions have an undefined live bytes count.
241     DCHECK_EQ(live_bytes_, static_cast<size_t>(-1));
242     // We always evacuate newly-allocated non-large regions as we
243     // believe they contain many dead objects (a very simple form of
244     // the generational hypothesis, even before the Sticky-Bit CC
245     // approach).
246     //
247     // TODO: Verify that assertion by collecting statistics on the
248     // number/proportion of live objects in newly allocated regions
249     // in RegionSpace::ClearFromSpace.
250     //
251     // Note that a side effect of evacuating a newly-allocated
252     // non-large region is that the "newly allocated" status will
253     // later be removed, as its live objects will be copied to an
254     // evacuation region, which won't be marked as "newly
255     // allocated" (see RegionSpace::AllocateRegion).
256     return true;
257   } else if (evac_mode == kEvacModeLivePercentNewlyAllocated) {
258     bool is_live_percent_valid = (live_bytes_ != static_cast<size_t>(-1));
259     if (is_live_percent_valid) {
260       DCHECK(IsInToSpace());
261       DCHECK_NE(live_bytes_, static_cast<size_t>(-1));
262       DCHECK_LE(live_bytes_, BytesAllocated());
263       const size_t bytes_allocated = RoundUp(BytesAllocated(), kRegionSize);
264       DCHECK_LE(live_bytes_, bytes_allocated);
265       // Side node: live_percent == 0 does not necessarily mean
266       // there's no live objects due to rounding (there may be a
267       // few).
268       return live_bytes_ * 100U < kEvacuateLivePercentThreshold * bytes_allocated;
269     }
270   }
271   return false;
272 }
273 
ZeroLiveBytesForLargeObject(mirror::Object * obj)274 void RegionSpace::ZeroLiveBytesForLargeObject(mirror::Object* obj) {
275   // This method is only used when Generational CC collection is enabled.
276   DCHECK(use_generational_cc_);
277 
278   // This code uses a logic similar to the one used in RegionSpace::FreeLarge
279   // to traverse the regions supporting `obj`.
280   // TODO: Refactor.
281   DCHECK(IsLargeObject(obj));
282   DCHECK_ALIGNED(obj, kRegionSize);
283   size_t obj_size = obj->SizeOf<kDefaultVerifyFlags>();
284   DCHECK_GT(obj_size, space::RegionSpace::kRegionSize);
285   // Size of the memory area allocated for `obj`.
286   size_t obj_alloc_size = RoundUp(obj_size, space::RegionSpace::kRegionSize);
287   uint8_t* begin_addr = reinterpret_cast<uint8_t*>(obj);
288   uint8_t* end_addr = begin_addr + obj_alloc_size;
289   DCHECK_ALIGNED(end_addr, kRegionSize);
290 
291   // Zero the live bytes of the large region and large tail regions containing the object.
292   MutexLock mu(Thread::Current(), region_lock_);
293   for (uint8_t* addr = begin_addr; addr < end_addr; addr += kRegionSize) {
294     Region* region = RefToRegionLocked(reinterpret_cast<mirror::Object*>(addr));
295     if (addr == begin_addr) {
296       DCHECK(region->IsLarge());
297     } else {
298       DCHECK(region->IsLargeTail());
299     }
300     region->ZeroLiveBytes();
301   }
302   if (kIsDebugBuild && end_addr < Limit()) {
303     // If we aren't at the end of the space, check that the next region is not a large tail.
304     Region* following_region = RefToRegionLocked(reinterpret_cast<mirror::Object*>(end_addr));
305     DCHECK(!following_region->IsLargeTail());
306   }
307 }
308 
309 // Determine which regions to evacuate and mark them as
310 // from-space. Mark the rest as unevacuated from-space.
SetFromSpace(accounting::ReadBarrierTable * rb_table,EvacMode evac_mode,bool clear_live_bytes)311 void RegionSpace::SetFromSpace(accounting::ReadBarrierTable* rb_table,
312                                EvacMode evac_mode,
313                                bool clear_live_bytes) {
314   // Live bytes are only preserved (i.e. not cleared) during sticky-bit CC collections.
315   DCHECK(use_generational_cc_ || clear_live_bytes);
316   ++time_;
317   if (kUseTableLookupReadBarrier) {
318     DCHECK(rb_table->IsAllCleared());
319     rb_table->SetAll();
320   }
321   MutexLock mu(Thread::Current(), region_lock_);
322   // We cannot use the partially utilized TLABs across a GC. Therefore, revoke
323   // them during the thread-flip.
324   partial_tlabs_.clear();
325 
326   // Counter for the number of expected large tail regions following a large region.
327   size_t num_expected_large_tails = 0U;
328   // Flag to store whether the previously seen large region has been evacuated.
329   // This is used to apply the same evacuation policy to related large tail regions.
330   bool prev_large_evacuated = false;
331   VerifyNonFreeRegionLimit();
332   const size_t iter_limit = kUseTableLookupReadBarrier
333       ? num_regions_
334       : std::min(num_regions_, non_free_region_index_limit_);
335   for (size_t i = 0; i < iter_limit; ++i) {
336     Region* r = &regions_[i];
337     RegionState state = r->State();
338     RegionType type = r->Type();
339     if (!r->IsFree()) {
340       DCHECK(r->IsInToSpace());
341       if (LIKELY(num_expected_large_tails == 0U)) {
342         DCHECK((state == RegionState::kRegionStateAllocated ||
343                 state == RegionState::kRegionStateLarge) &&
344                type == RegionType::kRegionTypeToSpace);
345         bool should_evacuate = r->ShouldBeEvacuated(evac_mode);
346         bool is_newly_allocated = r->IsNewlyAllocated();
347         if (should_evacuate) {
348           r->SetAsFromSpace();
349           DCHECK(r->IsInFromSpace());
350         } else {
351           r->SetAsUnevacFromSpace(clear_live_bytes);
352           DCHECK(r->IsInUnevacFromSpace());
353         }
354         if (UNLIKELY(state == RegionState::kRegionStateLarge &&
355                      type == RegionType::kRegionTypeToSpace)) {
356           prev_large_evacuated = should_evacuate;
357           // In 2-phase full heap GC, this function is called after marking is
358           // done. So, it is possible that some newly allocated large object is
359           // marked but its live_bytes is still -1. We need to clear the
360           // mark-bit otherwise the live_bytes will not be updated in
361           // ConcurrentCopying::ProcessMarkStackRef() and hence will break the
362           // logic.
363           if (use_generational_cc_ && !should_evacuate && is_newly_allocated) {
364             GetMarkBitmap()->Clear(reinterpret_cast<mirror::Object*>(r->Begin()));
365           }
366           num_expected_large_tails = RoundUp(r->BytesAllocated(), kRegionSize) / kRegionSize - 1;
367           DCHECK_GT(num_expected_large_tails, 0U);
368         }
369       } else {
370         DCHECK(state == RegionState::kRegionStateLargeTail &&
371                type == RegionType::kRegionTypeToSpace);
372         if (prev_large_evacuated) {
373           r->SetAsFromSpace();
374           DCHECK(r->IsInFromSpace());
375         } else {
376           r->SetAsUnevacFromSpace(clear_live_bytes);
377           DCHECK(r->IsInUnevacFromSpace());
378         }
379         --num_expected_large_tails;
380       }
381     } else {
382       DCHECK_EQ(num_expected_large_tails, 0U);
383       if (kUseTableLookupReadBarrier) {
384         // Clear the rb table for to-space regions.
385         rb_table->Clear(r->Begin(), r->End());
386       }
387     }
388     // Invariant: There should be no newly-allocated region in the from-space.
389     DCHECK(!r->is_newly_allocated_);
390   }
391   DCHECK_EQ(num_expected_large_tails, 0U);
392   current_region_ = &full_region_;
393   evac_region_ = &full_region_;
394 }
395 
ZeroAndProtectRegion(uint8_t * begin,uint8_t * end,bool release_eagerly)396 static void ZeroAndProtectRegion(uint8_t* begin, uint8_t* end, bool release_eagerly) {
397   ZeroMemory(begin, end - begin, release_eagerly);
398   if (kProtectClearedRegions) {
399     CheckedCall(mprotect, __FUNCTION__, begin, end - begin, PROT_NONE);
400   }
401 }
402 
ReleaseFreeRegions()403 void RegionSpace::ReleaseFreeRegions() {
404   MutexLock mu(Thread::Current(), region_lock_);
405   for (size_t i = 0u; i < num_regions_; ++i) {
406     if (regions_[i].IsFree()) {
407       uint8_t* begin = regions_[i].Begin();
408       DCHECK_ALIGNED_PARAM(begin, gPageSize);
409       DCHECK_ALIGNED_PARAM(regions_[i].End(), gPageSize);
410       bool res = madvise(begin, regions_[i].End() - begin, MADV_DONTNEED);
411       CHECK_NE(res, -1) << "madvise failed";
412     }
413   }
414 }
415 
ClearFromSpace(uint64_t * cleared_bytes,uint64_t * cleared_objects,const bool clear_bitmap,const bool release_eagerly)416 void RegionSpace::ClearFromSpace(/* out */ uint64_t* cleared_bytes,
417                                  /* out */ uint64_t* cleared_objects,
418                                  const bool clear_bitmap,
419                                  const bool release_eagerly) {
420   DCHECK(cleared_bytes != nullptr);
421   DCHECK(cleared_objects != nullptr);
422   *cleared_bytes = 0;
423   *cleared_objects = 0;
424   size_t new_non_free_region_index_limit = 0;
425   // We should avoid calling madvise syscalls while holding region_lock_.
426   // Therefore, we split the working of this function into 2 loops. The first
427   // loop gathers memory ranges that must be madvised. Then we release the lock
428   // and perform madvise on the gathered memory ranges. Finally, we reacquire
429   // the lock and loop over the regions to clear the from-space regions and make
430   // them availabe for allocation.
431   std::deque<std::pair<uint8_t*, uint8_t*>> madvise_list;
432   // Gather memory ranges that need to be madvised.
433   {
434     MutexLock mu(Thread::Current(), region_lock_);
435     // Lambda expression `expand_madvise_range` adds a region to the "clear block".
436     //
437     // As we iterate over from-space regions, we maintain a "clear block", composed of
438     // adjacent to-be-cleared regions and whose bounds are `clear_block_begin` and
439     // `clear_block_end`. When processing a new region which is not adjacent to
440     // the clear block (discontinuity in cleared regions), the clear block
441     // is added to madvise_list and the clear block is reset (to the most recent
442     // to-be-cleared region).
443     //
444     // This is done in order to combine zeroing and releasing pages to reduce how
445     // often madvise is called. This helps reduce contention on the mmap semaphore
446     // (see b/62194020).
447     uint8_t* clear_block_begin = nullptr;
448     uint8_t* clear_block_end = nullptr;
449     auto expand_madvise_range = [&madvise_list, &clear_block_begin, &clear_block_end] (Region* r) {
450       if (clear_block_end != r->Begin()) {
451         if (clear_block_begin != nullptr) {
452           DCHECK(clear_block_end != nullptr);
453           madvise_list.push_back(std::pair(clear_block_begin, clear_block_end));
454         }
455         clear_block_begin = r->Begin();
456       }
457       clear_block_end = r->End();
458     };
459     for (size_t i = 0; i < std::min(num_regions_, non_free_region_index_limit_); ++i) {
460       Region* r = &regions_[i];
461       // The following check goes through objects in the region, therefore it
462       // must be performed before madvising the region. Therefore, it can't be
463       // executed in the following loop.
464       if (kCheckLiveBytesAgainstRegionBitmap) {
465         CheckLiveBytesAgainstRegionBitmap(r);
466       }
467       if (r->IsInFromSpace()) {
468         expand_madvise_range(r);
469       } else if (r->IsInUnevacFromSpace()) {
470         // We must skip tails of live large objects.
471         if (r->LiveBytes() == 0 && !r->IsLargeTail()) {
472           // Special case for 0 live bytes, this means all of the objects in the region are
473           // dead and we can to clear it. This is important for large objects since we must
474           // not visit dead ones in RegionSpace::Walk because they may contain dangling
475           // references to invalid objects. It is also better to clear these regions now
476           // instead of at the end of the next GC to save RAM. If we don't clear the regions
477           // here, they will be cleared in next GC by the normal live percent evacuation logic.
478           expand_madvise_range(r);
479           // Also release RAM for large tails.
480           while (i + 1 < num_regions_ && regions_[i + 1].IsLargeTail()) {
481             expand_madvise_range(&regions_[i + 1]);
482             i++;
483           }
484         }
485       }
486     }
487     // There is a small probability that we may reach here with
488     // clear_block_{begin, end} = nullptr. If all the regions allocated since
489     // last GC have been for large objects and all of them survive till this GC
490     // cycle, then there will be no regions in from-space.
491     if (LIKELY(clear_block_begin != nullptr)) {
492       DCHECK(clear_block_end != nullptr);
493       madvise_list.push_back(std::pair(clear_block_begin, clear_block_end));
494     }
495   }
496 
497   // Madvise the memory ranges.
498   uint64_t start_time = NanoTime();
499   for (const auto &iter : madvise_list) {
500     ZeroAndProtectRegion(iter.first, iter.second, release_eagerly);
501   }
502   madvise_time_ += NanoTime() - start_time;
503 
504   for (const auto &iter : madvise_list) {
505     if (clear_bitmap) {
506       GetLiveBitmap()->ClearRange(
507           reinterpret_cast<mirror::Object*>(iter.first),
508           reinterpret_cast<mirror::Object*>(iter.second));
509     }
510   }
511   madvise_list.clear();
512 
513   // Iterate over regions again and actually make the from space regions
514   // available for allocation.
515   MutexLock mu(Thread::Current(), region_lock_);
516   VerifyNonFreeRegionLimit();
517 
518   // Update max of peak non free region count before reclaiming evacuated regions.
519   max_peak_num_non_free_regions_ = std::max(max_peak_num_non_free_regions_,
520                                             num_non_free_regions_);
521 
522   for (size_t i = 0; i < std::min(num_regions_, non_free_region_index_limit_); ++i) {
523     Region* r = &regions_[i];
524     if (r->IsInFromSpace()) {
525       DCHECK(!r->IsTlab());
526       *cleared_bytes += r->BytesAllocated();
527       *cleared_objects += r->ObjectsAllocated();
528       --num_non_free_regions_;
529       r->Clear(/*zero_and_release_pages=*/false);
530     } else if (r->IsInUnevacFromSpace()) {
531       if (r->LiveBytes() == 0) {
532         DCHECK(!r->IsLargeTail());
533         *cleared_bytes += r->BytesAllocated();
534         *cleared_objects += r->ObjectsAllocated();
535         r->Clear(/*zero_and_release_pages=*/false);
536         size_t free_regions = 1;
537         // Also release RAM for large tails.
538         while (i + free_regions < num_regions_ && regions_[i + free_regions].IsLargeTail()) {
539           regions_[i + free_regions].Clear(/*zero_and_release_pages=*/false);
540           ++free_regions;
541         }
542         num_non_free_regions_ -= free_regions;
543         // When clear_bitmap is true, this clearing of bitmap is taken care in
544         // clear_region().
545         if (!clear_bitmap) {
546           GetLiveBitmap()->ClearRange(
547               reinterpret_cast<mirror::Object*>(r->Begin()),
548               reinterpret_cast<mirror::Object*>(r->Begin() + free_regions * kRegionSize));
549         }
550         continue;
551       }
552       r->SetUnevacFromSpaceAsToSpace();
553       if (r->AllAllocatedBytesAreLive()) {
554         // Try to optimize the number of ClearRange calls by checking whether the next regions
555         // can also be cleared.
556         size_t regions_to_clear_bitmap = 1;
557         while (i + regions_to_clear_bitmap < num_regions_) {
558           Region* const cur = &regions_[i + regions_to_clear_bitmap];
559           if (!cur->AllAllocatedBytesAreLive()) {
560             DCHECK(!cur->IsLargeTail());
561             break;
562           }
563           CHECK(cur->IsInUnevacFromSpace());
564           cur->SetUnevacFromSpaceAsToSpace();
565           ++regions_to_clear_bitmap;
566         }
567 
568         // Optimization (for full CC only): If the live bytes are *all* live
569         // in a region then the live-bit information for these objects is
570         // superfluous:
571         // - We can determine that these objects are all live by using
572         //   Region::AllAllocatedBytesAreLive (which just checks whether
573         //   `LiveBytes() == static_cast<size_t>(Top() - Begin())`.
574         // - We can visit the objects in this region using
575         //   RegionSpace::GetNextObject, i.e. without resorting to the
576         //   live bits (see RegionSpace::WalkInternal).
577         // Therefore, we can clear the bits for these objects in the
578         // (live) region space bitmap (and release the corresponding pages).
579         //
580         // This optimization is incompatible with Generational CC, because:
581         // - minor (young-generation) collections need to know which objects
582         //   where marked during the previous GC cycle, meaning all mark bitmaps
583         //   (this includes the region space bitmap) need to be preserved
584         //   between a (minor or major) collection N and a following minor
585         //   collection N+1;
586         // - at this stage (in the current GC cycle), we cannot determine
587         //   whether the next collection will be a minor or a major one;
588         // This means that we need to be conservative and always preserve the
589         // region space bitmap when using Generational CC.
590         // Note that major collections do not require the previous mark bitmaps
591         // to be preserved, and as matter of fact they do clear the region space
592         // bitmap. But they cannot do so before we know the next GC cycle will
593         // be a major one, so this operation happens at the beginning of such a
594         // major collection, before marking starts.
595         if (!use_generational_cc_) {
596           GetLiveBitmap()->ClearRange(
597               reinterpret_cast<mirror::Object*>(r->Begin()),
598               reinterpret_cast<mirror::Object*>(r->Begin()
599                                                 + regions_to_clear_bitmap * kRegionSize));
600         }
601         // Skip over extra regions for which we cleared the bitmaps: we shall not clear them,
602         // as they are unevac regions that are live.
603         // Subtract one for the for-loop.
604         i += regions_to_clear_bitmap - 1;
605       } else {
606         // TODO: Explain why we do not poison dead objects in region
607         // `r` when it has an undefined live bytes count (i.e. when
608         // `r->LiveBytes() == static_cast<size_t>(-1)`) with
609         // Generational CC.
610         if (!use_generational_cc_ || (r->LiveBytes() != static_cast<size_t>(-1))) {
611           // Only some allocated bytes are live in this unevac region.
612           // This should only happen for an allocated non-large region.
613           DCHECK(r->IsAllocated()) << r->State();
614           if (kPoisonDeadObjectsInUnevacuatedRegions) {
615             PoisonDeadObjectsInUnevacuatedRegion(r);
616           }
617         }
618       }
619     }
620     // Note r != last_checked_region if r->IsInUnevacFromSpace() was true above.
621     Region* last_checked_region = &regions_[i];
622     if (!last_checked_region->IsFree()) {
623       new_non_free_region_index_limit = std::max(new_non_free_region_index_limit,
624                                                  last_checked_region->Idx() + 1);
625     }
626   }
627   // Update non_free_region_index_limit_.
628   SetNonFreeRegionLimit(new_non_free_region_index_limit);
629   evac_region_ = nullptr;
630   num_non_free_regions_ += num_evac_regions_;
631   num_evac_regions_ = 0;
632 }
633 
CheckLiveBytesAgainstRegionBitmap(Region * r)634 void RegionSpace::CheckLiveBytesAgainstRegionBitmap(Region* r) {
635   if (r->LiveBytes() == static_cast<size_t>(-1)) {
636     // Live bytes count is undefined for `r`; nothing to check here.
637     return;
638   }
639 
640   // Functor walking the region space bitmap for the range corresponding
641   // to region `r` and calculating the sum of live bytes.
642   size_t live_bytes_recount = 0u;
643   auto recount_live_bytes =
644       [&r, &live_bytes_recount](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
645     DCHECK_ALIGNED(obj, kAlignment);
646     if (r->IsLarge()) {
647       // If `r` is a large region, then it contains at most one
648       // object, which must start at the beginning of the
649       // region. The live byte count in that case is equal to the
650       // allocated regions (large region + large tails regions).
651       DCHECK_EQ(reinterpret_cast<uint8_t*>(obj), r->Begin());
652       DCHECK_EQ(live_bytes_recount, 0u);
653       live_bytes_recount = r->Top() - r->Begin();
654     } else {
655       DCHECK(r->IsAllocated())
656           << "r->State()=" << r->State() << " r->LiveBytes()=" << r->LiveBytes();
657       size_t obj_size = obj->SizeOf<kDefaultVerifyFlags>();
658       size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
659       live_bytes_recount += alloc_size;
660     }
661   };
662   // Visit live objects in `r` and recount the live bytes.
663   GetLiveBitmap()->VisitMarkedRange(reinterpret_cast<uintptr_t>(r->Begin()),
664                                     reinterpret_cast<uintptr_t>(r->Top()),
665                                     recount_live_bytes);
666   // Check that this recount matches the region's current live bytes count.
667   DCHECK_EQ(live_bytes_recount, r->LiveBytes());
668 }
669 
670 // Poison the memory area in range [`begin`, `end`) with value `kPoisonDeadObject`.
PoisonUnevacuatedRange(uint8_t * begin,uint8_t * end)671 static void PoisonUnevacuatedRange(uint8_t* begin, uint8_t* end) {
672   static constexpr size_t kPoisonDeadObjectSize = sizeof(kPoisonDeadObject);
673   static_assert(IsPowerOfTwo(kPoisonDeadObjectSize) &&
674                 IsPowerOfTwo(RegionSpace::kAlignment) &&
675                 (kPoisonDeadObjectSize < RegionSpace::kAlignment),
676                 "RegionSpace::kAlignment should be a multiple of kPoisonDeadObjectSize"
677                 " and both should be powers of 2");
678   DCHECK_ALIGNED(begin, kPoisonDeadObjectSize);
679   DCHECK_ALIGNED(end, kPoisonDeadObjectSize);
680   uint32_t* begin_addr = reinterpret_cast<uint32_t*>(begin);
681   uint32_t* end_addr = reinterpret_cast<uint32_t*>(end);
682   std::fill(begin_addr, end_addr, kPoisonDeadObject);
683 }
684 
PoisonDeadObjectsInUnevacuatedRegion(Region * r)685 void RegionSpace::PoisonDeadObjectsInUnevacuatedRegion(Region* r) {
686   // The live byte count of `r` should be different from -1, as this
687   // region should neither be a newly allocated region nor an
688   // evacuated region.
689   DCHECK_NE(r->LiveBytes(), static_cast<size_t>(-1))
690       << "Unexpected live bytes count of -1 in " << Dumpable<Region>(*r);
691 
692   // Past-the-end address of the previously visited (live) object (or
693   // the beginning of the region, if `maybe_poison` has not run yet).
694   uint8_t* prev_obj_end = reinterpret_cast<uint8_t*>(r->Begin());
695 
696   // Functor poisoning the space between `obj` and the previously
697   // visited (live) object (or the beginng of the region), if any.
698   auto maybe_poison = [&prev_obj_end](mirror::Object* obj) REQUIRES(Locks::mutator_lock_) {
699     DCHECK_ALIGNED(obj, kAlignment);
700     uint8_t* cur_obj_begin = reinterpret_cast<uint8_t*>(obj);
701     if (cur_obj_begin != prev_obj_end) {
702       // There is a gap (dead object(s)) between the previously
703       // visited (live) object (or the beginning of the region) and
704       // `obj`; poison that space.
705       PoisonUnevacuatedRange(prev_obj_end, cur_obj_begin);
706     }
707     prev_obj_end = reinterpret_cast<uint8_t*>(GetNextObject(obj));
708   };
709 
710   // Visit live objects in `r` and poison gaps (dead objects) between them.
711   GetLiveBitmap()->VisitMarkedRange(reinterpret_cast<uintptr_t>(r->Begin()),
712                                     reinterpret_cast<uintptr_t>(r->Top()),
713                                     maybe_poison);
714   // Poison memory between the last live object and the end of the region, if any.
715   if (prev_obj_end < r->Top()) {
716     PoisonUnevacuatedRange(prev_obj_end, r->Top());
717   }
718 }
719 
LogFragmentationAllocFailure(std::ostream & os,size_t failed_alloc_bytes)720 bool RegionSpace::LogFragmentationAllocFailure(std::ostream& os,
721                                                size_t failed_alloc_bytes) {
722   size_t max_contiguous_allocation = 0;
723   MutexLock mu(Thread::Current(), region_lock_);
724 
725   if (current_region_->End() - current_region_->Top() > 0) {
726     max_contiguous_allocation = current_region_->End() - current_region_->Top();
727   }
728 
729   size_t max_contiguous_free_regions = 0;
730   size_t num_contiguous_free_regions = 0;
731   bool prev_free_region = false;
732   for (size_t i = 0; i < num_regions_; ++i) {
733     Region* r = &regions_[i];
734     if (r->IsFree()) {
735       if (!prev_free_region) {
736         CHECK_EQ(num_contiguous_free_regions, 0U);
737         prev_free_region = true;
738       }
739       ++num_contiguous_free_regions;
740     } else if (prev_free_region) {
741       CHECK_NE(num_contiguous_free_regions, 0U);
742       max_contiguous_free_regions = std::max(max_contiguous_free_regions,
743                                              num_contiguous_free_regions);
744       num_contiguous_free_regions = 0U;
745       prev_free_region = false;
746     }
747   }
748   max_contiguous_allocation = std::max(max_contiguous_allocation,
749                                        max_contiguous_free_regions * kRegionSize);
750 
751   // Calculate how many regions are available for allocations as we have to ensure
752   // that enough regions are left for evacuation.
753   size_t regions_free_for_alloc = num_regions_ / 2 - num_non_free_regions_;
754 
755   max_contiguous_allocation = std::min(max_contiguous_allocation,
756                                        regions_free_for_alloc * kRegionSize);
757   if (failed_alloc_bytes > max_contiguous_allocation) {
758     // Region space does not normally fragment in the conventional sense. However we can run out
759     // of region space prematurely if we have many threads, each with a partially committed TLAB.
760     // The whole TLAB uses up region address space, but we only count the section that was
761     // actually given to the thread so far as allocated. For unlikely allocation request sequences
762     // involving largish objects that don't qualify for large objects space, we may also be unable
763     // to fully utilize entire TLABs, and thus generate enough actual fragmentation to get
764     // here. This appears less likely, since we usually reuse sufficiently large TLAB "tails"
765     // that are no longer needed.
766     os << "; failed due to fragmentation (largest possible contiguous allocation "
767        << max_contiguous_allocation << " bytes). Number of " << PrettySize(kRegionSize)
768        << " sized free regions are: " << regions_free_for_alloc
769        << ". Likely cause: (1) Too much memory in use, and "
770        << "(2) many threads or many larger objects of the wrong kind";
771     return true;
772   }
773   // Caller's job to print failed_alloc_bytes.
774   return false;
775 }
776 
Clear()777 void RegionSpace::Clear() {
778   MutexLock mu(Thread::Current(), region_lock_);
779   for (size_t i = 0; i < num_regions_; ++i) {
780     Region* r = &regions_[i];
781     if (!r->IsFree()) {
782       --num_non_free_regions_;
783     }
784     r->Clear(/*zero_and_release_pages=*/true);
785   }
786   SetNonFreeRegionLimit(0);
787   DCHECK_EQ(num_non_free_regions_, 0u);
788   current_region_ = &full_region_;
789   evac_region_ = &full_region_;
790 }
791 
Protect()792 void RegionSpace::Protect() {
793   if (kProtectClearedRegions) {
794     CheckedCall(mprotect, __FUNCTION__, Begin(), Size(), PROT_NONE);
795   }
796 }
797 
Unprotect()798 void RegionSpace::Unprotect() {
799   if (kProtectClearedRegions) {
800     CheckedCall(mprotect, __FUNCTION__, Begin(), Size(), PROT_READ | PROT_WRITE);
801   }
802 }
803 
ClampGrowthLimit(size_t new_capacity)804 void RegionSpace::ClampGrowthLimit(size_t new_capacity) {
805   MutexLock mu(Thread::Current(), region_lock_);
806   CHECK_LE(new_capacity, NonGrowthLimitCapacity());
807   size_t new_num_regions = new_capacity / kRegionSize;
808   if (non_free_region_index_limit_ > new_num_regions) {
809     LOG(WARNING) << "Couldn't clamp region space as there are regions in use beyond growth limit.";
810     return;
811   }
812   num_regions_ = new_num_regions;
813   if (kCyclicRegionAllocation && cyclic_alloc_region_index_ >= num_regions_) {
814     cyclic_alloc_region_index_ = 0u;
815   }
816   SetLimit(Begin() + new_capacity);
817   if (Size() > new_capacity) {
818     SetEnd(Limit());
819   }
820   GetMarkBitmap()->SetHeapSize(new_capacity);
821   GetMemMap()->SetSize(new_capacity);
822 }
823 
Dump(std::ostream & os) const824 void RegionSpace::Dump(std::ostream& os) const {
825   os << GetName() << " "
826      << reinterpret_cast<void*>(Begin()) << "-" << reinterpret_cast<void*>(Limit());
827 }
828 
DumpRegionForObject(std::ostream & os,mirror::Object * obj)829 void RegionSpace::DumpRegionForObject(std::ostream& os, mirror::Object* obj) {
830   CHECK(HasAddress(obj));
831   MutexLock mu(Thread::Current(), region_lock_);
832   RefToRegionUnlocked(obj)->Dump(os);
833 }
834 
DumpRegions(std::ostream & os)835 void RegionSpace::DumpRegions(std::ostream& os) {
836   MutexLock mu(Thread::Current(), region_lock_);
837   for (size_t i = 0; i < num_regions_; ++i) {
838     regions_[i].Dump(os);
839   }
840 }
841 
DumpNonFreeRegions(std::ostream & os)842 void RegionSpace::DumpNonFreeRegions(std::ostream& os) {
843   MutexLock mu(Thread::Current(), region_lock_);
844   for (size_t i = 0; i < num_regions_; ++i) {
845     Region* reg = &regions_[i];
846     if (!reg->IsFree()) {
847       reg->Dump(os);
848     }
849   }
850 }
851 
RecordAlloc(mirror::Object * ref)852 void RegionSpace::RecordAlloc(mirror::Object* ref) {
853   CHECK(ref != nullptr);
854   Region* r = RefToRegion(ref);
855   r->objects_allocated_.fetch_add(1, std::memory_order_relaxed);
856 }
857 
AllocNewTlab(Thread * self,const size_t tlab_size,size_t * bytes_tl_bulk_allocated)858 bool RegionSpace::AllocNewTlab(Thread* self,
859                                const size_t tlab_size,
860                                size_t* bytes_tl_bulk_allocated) {
861   MutexLock mu(self, region_lock_);
862   RevokeThreadLocalBuffersLocked(self, /*reuse=*/ gc::Heap::kUsePartialTlabs);
863   Region* r = nullptr;
864   uint8_t* pos = nullptr;
865   *bytes_tl_bulk_allocated = tlab_size;
866   // First attempt to get a partially used TLAB, if available.
867   if (tlab_size < kRegionSize) {
868     // Fetch the largest partial TLAB. The multimap is ordered in decreasing
869     // size.
870     auto largest_partial_tlab = partial_tlabs_.begin();
871     if (largest_partial_tlab != partial_tlabs_.end() && largest_partial_tlab->first >= tlab_size) {
872       r = largest_partial_tlab->second;
873       pos = r->End() - largest_partial_tlab->first;
874       partial_tlabs_.erase(largest_partial_tlab);
875       DCHECK_GT(r->End(), pos);
876       DCHECK_LE(r->Begin(), pos);
877       DCHECK_GE(r->Top(), pos);
878       *bytes_tl_bulk_allocated -= r->Top() - pos;
879     }
880   }
881   if (r == nullptr) {
882     // Fallback to allocating an entire region as TLAB.
883     r = AllocateRegion(/*for_evac=*/ false);
884   }
885   if (r != nullptr) {
886     uint8_t* start = pos != nullptr ? pos : r->Begin();
887     DCHECK_ALIGNED(start, kObjectAlignment);
888     r->is_a_tlab_ = true;
889     r->thread_ = self;
890     r->SetTop(r->End());
891     self->SetTlab(start, start + tlab_size, r->End());
892     return true;
893   }
894   return false;
895 }
896 
RevokeThreadLocalBuffers(Thread * thread)897 size_t RegionSpace::RevokeThreadLocalBuffers(Thread* thread) {
898   MutexLock mu(Thread::Current(), region_lock_);
899   RevokeThreadLocalBuffersLocked(thread, /*reuse=*/ gc::Heap::kUsePartialTlabs);
900   return 0U;
901 }
902 
RevokeThreadLocalBuffers(Thread * thread,const bool reuse)903 size_t RegionSpace::RevokeThreadLocalBuffers(Thread* thread, const bool reuse) {
904   MutexLock mu(Thread::Current(), region_lock_);
905   RevokeThreadLocalBuffersLocked(thread, reuse);
906   return 0U;
907 }
908 
RevokeThreadLocalBuffersLocked(Thread * thread,bool reuse)909 void RegionSpace::RevokeThreadLocalBuffersLocked(Thread* thread, bool reuse) {
910   uint8_t* tlab_start = thread->GetTlabStart();
911   DCHECK_EQ(thread->HasTlab(), tlab_start != nullptr);
912   if (tlab_start != nullptr) {
913     Region* r = RefToRegionLocked(reinterpret_cast<mirror::Object*>(tlab_start));
914     r->is_a_tlab_ = false;
915     r->thread_ = nullptr;
916     DCHECK(r->IsAllocated());
917     DCHECK_LE(thread->GetThreadLocalBytesAllocated(), kRegionSize);
918     r->RecordThreadLocalAllocations(thread->GetThreadLocalObjectsAllocated(),
919                                     thread->GetTlabEnd() - r->Begin());
920     DCHECK_GE(r->End(), thread->GetTlabPos());
921     DCHECK_LE(r->Begin(), thread->GetTlabPos());
922     size_t remaining_bytes = r->End() - thread->GetTlabPos();
923     if (reuse && remaining_bytes >= gc::Heap::kPartialTlabSize) {
924       partial_tlabs_.insert(std::make_pair(remaining_bytes, r));
925     }
926   }
927   thread->ResetTlab();
928 }
929 
RevokeAllThreadLocalBuffers()930 size_t RegionSpace::RevokeAllThreadLocalBuffers() {
931   Thread* self = Thread::Current();
932   MutexLock mu(self, *Locks::runtime_shutdown_lock_);
933   MutexLock mu2(self, *Locks::thread_list_lock_);
934   std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
935   for (Thread* thread : thread_list) {
936     RevokeThreadLocalBuffers(thread);
937   }
938   return 0U;
939 }
940 
AssertThreadLocalBuffersAreRevoked(Thread * thread)941 void RegionSpace::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
942   if (kIsDebugBuild) {
943     DCHECK(!thread->HasTlab());
944   }
945 }
946 
AssertAllThreadLocalBuffersAreRevoked()947 void RegionSpace::AssertAllThreadLocalBuffersAreRevoked() {
948   if (kIsDebugBuild) {
949     Thread* self = Thread::Current();
950     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
951     MutexLock mu2(self, *Locks::thread_list_lock_);
952     std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
953     for (Thread* thread : thread_list) {
954       AssertThreadLocalBuffersAreRevoked(thread);
955     }
956   }
957 }
958 
Dump(std::ostream & os) const959 void RegionSpace::Region::Dump(std::ostream& os) const {
960   os << "Region[" << idx_ << "]="
961      << reinterpret_cast<void*>(begin_)
962      << "-" << reinterpret_cast<void*>(Top())
963      << "-" << reinterpret_cast<void*>(end_)
964      << " state=" << state_
965      << " type=" << type_
966      << " objects_allocated=" << objects_allocated_
967      << " alloc_time=" << alloc_time_
968      << " live_bytes=" << live_bytes_;
969 
970   if (live_bytes_ != static_cast<size_t>(-1)) {
971     os << " ratio over allocated bytes="
972        << (static_cast<float>(live_bytes_) / RoundUp(BytesAllocated(), kRegionSize));
973     uint64_t longest_consecutive_free_bytes = GetLongestConsecutiveFreeBytes();
974     os << " longest_consecutive_free_bytes=" << longest_consecutive_free_bytes
975        << " (" << PrettySize(longest_consecutive_free_bytes) << ")";
976   }
977 
978   os << " is_newly_allocated=" << std::boolalpha << is_newly_allocated_ << std::noboolalpha
979      << " is_a_tlab=" << std::boolalpha << is_a_tlab_ << std::noboolalpha
980      << " thread=" << thread_ << '\n';
981 }
982 
GetLongestConsecutiveFreeBytes() const983 uint64_t RegionSpace::Region::GetLongestConsecutiveFreeBytes() const {
984   if (IsFree()) {
985     return kRegionSize;
986   }
987   if (IsLarge() || IsLargeTail()) {
988     return 0u;
989   }
990   uintptr_t max_gap = 0u;
991   uintptr_t prev_object_end = reinterpret_cast<uintptr_t>(Begin());
992   // Iterate through all live objects and find the largest free gap.
993   auto visitor = [&max_gap, &prev_object_end](mirror::Object* obj)
994     REQUIRES_SHARED(Locks::mutator_lock_) {
995     uintptr_t current = reinterpret_cast<uintptr_t>(obj);
996     uintptr_t diff = current - prev_object_end;
997     max_gap = std::max(diff, max_gap);
998     uintptr_t object_end = reinterpret_cast<uintptr_t>(obj) + obj->SizeOf();
999     prev_object_end = RoundUp(object_end, kAlignment);
1000   };
1001   space::RegionSpace* region_space = art::Runtime::Current()->GetHeap()->GetRegionSpace();
1002   region_space->WalkNonLargeRegion(visitor, this);
1003   return static_cast<uint64_t>(max_gap);
1004 }
1005 
1006 
AllocationSizeNonvirtual(mirror::Object * obj,size_t * usable_size)1007 size_t RegionSpace::AllocationSizeNonvirtual(mirror::Object* obj, size_t* usable_size) {
1008   size_t num_bytes = obj->SizeOf();
1009   if (usable_size != nullptr) {
1010     if (LIKELY(num_bytes <= kRegionSize)) {
1011       DCHECK(RefToRegion(obj)->IsAllocated());
1012       *usable_size = RoundUp(num_bytes, kAlignment);
1013     } else {
1014       DCHECK(RefToRegion(obj)->IsLarge());
1015       *usable_size = RoundUp(num_bytes, kRegionSize);
1016     }
1017   }
1018   return num_bytes;
1019 }
1020 
Clear(bool zero_and_release_pages)1021 void RegionSpace::Region::Clear(bool zero_and_release_pages) {
1022   top_.store(begin_, std::memory_order_relaxed);
1023   state_ = RegionState::kRegionStateFree;
1024   type_ = RegionType::kRegionTypeNone;
1025   objects_allocated_.store(0, std::memory_order_relaxed);
1026   alloc_time_ = 0;
1027   live_bytes_ = static_cast<size_t>(-1);
1028   if (zero_and_release_pages) {
1029     ZeroAndProtectRegion(begin_, end_, /* release_eagerly= */ true);
1030   }
1031   is_newly_allocated_ = false;
1032   is_a_tlab_ = false;
1033   thread_ = nullptr;
1034 }
1035 
TraceHeapSize()1036 void RegionSpace::TraceHeapSize() {
1037   Heap* heap = Runtime::Current()->GetHeap();
1038   heap->TraceHeapSize(heap->GetBytesAllocated() + EvacBytes());
1039 }
1040 
AllocateRegion(bool for_evac)1041 RegionSpace::Region* RegionSpace::AllocateRegion(bool for_evac) {
1042   if (!for_evac && (num_non_free_regions_ + 1) * 2 > num_regions_) {
1043     return nullptr;
1044   }
1045   for (size_t i = 0; i < num_regions_; ++i) {
1046     // When using the cyclic region allocation strategy, try to
1047     // allocate a region starting from the last cyclic allocated
1048     // region marker. Otherwise, try to allocate a region starting
1049     // from the beginning of the region space.
1050     size_t region_index = kCyclicRegionAllocation
1051         ? ((cyclic_alloc_region_index_ + i) % num_regions_)
1052         : i;
1053     Region* r = &regions_[region_index];
1054     if (r->IsFree()) {
1055       r->Unfree(this, time_);
1056       if (use_generational_cc_) {
1057         // TODO: Add an explanation for this assertion.
1058         DCHECK_IMPLIES(for_evac, !r->is_newly_allocated_);
1059       }
1060       if (for_evac) {
1061         ++num_evac_regions_;
1062         TraceHeapSize();
1063         // Evac doesn't count as newly allocated.
1064       } else {
1065         r->SetNewlyAllocated();
1066         ++num_non_free_regions_;
1067       }
1068       if (kCyclicRegionAllocation) {
1069         // Move the cyclic allocation region marker to the region
1070         // following the one that was just allocated.
1071         cyclic_alloc_region_index_ = (region_index + 1) % num_regions_;
1072       }
1073       return r;
1074     }
1075   }
1076   return nullptr;
1077 }
1078 
MarkAsAllocated(RegionSpace * region_space,uint32_t alloc_time)1079 void RegionSpace::Region::MarkAsAllocated(RegionSpace* region_space, uint32_t alloc_time) {
1080   DCHECK(IsFree());
1081   alloc_time_ = alloc_time;
1082   region_space->AdjustNonFreeRegionLimit(idx_);
1083   type_ = RegionType::kRegionTypeToSpace;
1084   if (kProtectClearedRegions) {
1085     CheckedCall(mprotect, __FUNCTION__, Begin(), kRegionSize, PROT_READ | PROT_WRITE);
1086   }
1087 }
1088 
Unfree(RegionSpace * region_space,uint32_t alloc_time)1089 void RegionSpace::Region::Unfree(RegionSpace* region_space, uint32_t alloc_time) {
1090   MarkAsAllocated(region_space, alloc_time);
1091   state_ = RegionState::kRegionStateAllocated;
1092 }
1093 
UnfreeLarge(RegionSpace * region_space,uint32_t alloc_time)1094 void RegionSpace::Region::UnfreeLarge(RegionSpace* region_space, uint32_t alloc_time) {
1095   MarkAsAllocated(region_space, alloc_time);
1096   state_ = RegionState::kRegionStateLarge;
1097 }
1098 
UnfreeLargeTail(RegionSpace * region_space,uint32_t alloc_time)1099 void RegionSpace::Region::UnfreeLargeTail(RegionSpace* region_space, uint32_t alloc_time) {
1100   MarkAsAllocated(region_space, alloc_time);
1101   state_ = RegionState::kRegionStateLargeTail;
1102 }
1103 
1104 }  // namespace space
1105 }  // namespace gc
1106 }  // namespace art
1107