blob: 274d77765e74176b1ac2b9b071aa4cb59e2887fa [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 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 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "space.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070018
Elliott Hughes90a33692011-08-30 13:27:07 -070019#include "UniquePtr.h"
Ian Rogers30fab402012-01-23 15:43:46 -080020#include "dlmalloc.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070021#include "file.h"
22#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070023#include "logging.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070024#include "os.h"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070025#include "space_bitmap.h"
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070026#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "utils.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070028
29namespace art {
30
Ian Rogers30fab402012-01-23 15:43:46 -080031#ifndef NDEBUG
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070032static const bool kDebugSpaces = true;
Mathieu Chartier2fde5332012-09-14 14:51:54 -070033#else
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070034static const bool kDebugSpaces = false;
Ian Rogers30fab402012-01-23 15:43:46 -080035#endif
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070036// Magic padding value that we use to check for buffer overruns.
37static const word kPaddingValue = 0xBAC0BAC0;
Ian Rogers30fab402012-01-23 15:43:46 -080038
Mathieu Chartier2fde5332012-09-14 14:51:54 -070039// TODO: Remove define macro
Ian Rogers30fab402012-01-23 15:43:46 -080040#define CHECK_MEMORY_CALL(call, args, what) \
41 do { \
42 int rc = call args; \
43 if (UNLIKELY(rc != 0)) { \
44 errno = rc; \
45 PLOG(FATAL) << # call << " failed for " << what; \
46 } \
47 } while (false)
48
Mathieu Chartier2fde5332012-09-14 14:51:54 -070049Space::Space(const std::string& name, GcRetentionPolicy gc_retention_policy)
50 : name_(name),
51 gc_retention_policy_(gc_retention_policy) {
52
53}
54
55ContinuousSpace::ContinuousSpace(const std::string& name, byte* begin, byte* end,
56 GcRetentionPolicy gc_retention_policy)
57 : Space(name, gc_retention_policy),
58 begin_(begin),
59 end_(end) {
60
61}
62
63MemMapSpace::MemMapSpace(const std::string& name, MemMap* mem_map, size_t initial_size,
64 GcRetentionPolicy gc_retention_policy)
65 : ContinuousSpace(name, mem_map->Begin(), mem_map->Begin() + initial_size, gc_retention_policy),
66 mem_map_(mem_map)
67{
68
69}
70
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070071size_t AllocSpace::bitmap_index_ = 0;
72
Mathieu Chartier2fde5332012-09-14 14:51:54 -070073AllocSpace::AllocSpace(const std::string& name, MemMap* mem_map, void* mspace, byte* begin,
74 byte* end, size_t growth_limit)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070075 : MemMapSpace(name, mem_map, end - begin, kGcRetentionPolicyAlwaysCollect),
Mathieu Chartier155dfe92012-10-09 14:24:49 -070076 num_bytes_allocated_(0), num_objects_allocated_(0), total_bytes_allocated_(0),
77 total_objects_allocated_(0), lock_("allocation space lock", kAllocSpaceLock), mspace_(mspace),
Ian Rogers15bf2d32012-08-28 17:33:04 -070078 growth_limit_(growth_limit) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070079 CHECK(mspace != NULL);
80
81 size_t bitmap_index = bitmap_index_++;
82
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070083 static const uintptr_t kGcCardSize = static_cast<uintptr_t>(CardTable::kCardSize);
Mathieu Chartier2fde5332012-09-14 14:51:54 -070084 CHECK(reinterpret_cast<uintptr_t>(mem_map->Begin()) % kGcCardSize == 0);
85 CHECK(reinterpret_cast<uintptr_t>(mem_map->End()) % kGcCardSize == 0);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070086 live_bitmap_.reset(SpaceBitmap::Create(
87 StringPrintf("allocspace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
88 Begin(), Capacity()));
89 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace live bitmap #" << bitmap_index;
90
91 mark_bitmap_.reset(SpaceBitmap::Create(
92 StringPrintf("allocspace-%s-mark-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
93 Begin(), Capacity()));
94 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace mark bitmap #" << bitmap_index;
95}
96
Mathieu Chartier2fde5332012-09-14 14:51:54 -070097AllocSpace* AllocSpace::Create(const std::string& name, size_t initial_size, size_t growth_limit,
98 size_t capacity, byte* requested_begin) {
Ian Rogers3bb17a62012-01-27 23:56:44 -080099 // Memory we promise to dlmalloc before it asks for morecore.
100 // Note: making this value large means that large allocations are unlikely to succeed as dlmalloc
101 // will ask for this memory from sys_alloc which will fail as the footprint (this value plus the
102 // size of the large allocation) will be greater than the footprint limit.
103 size_t starting_size = kPageSize;
Ian Rogers30fab402012-01-23 15:43:46 -0800104 uint64_t start_time = 0;
105 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
106 start_time = NanoTime();
107 VLOG(startup) << "Space::CreateAllocSpace entering " << name
Ian Rogers3bb17a62012-01-27 23:56:44 -0800108 << " initial_size=" << PrettySize(initial_size)
109 << " growth_limit=" << PrettySize(growth_limit)
110 << " capacity=" << PrettySize(capacity)
Ian Rogers30fab402012-01-23 15:43:46 -0800111 << " requested_begin=" << reinterpret_cast<void*>(requested_begin);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700112 }
Ian Rogers30fab402012-01-23 15:43:46 -0800113
114 // Sanity check arguments
Ian Rogers3bb17a62012-01-27 23:56:44 -0800115 if (starting_size > initial_size) {
116 initial_size = starting_size;
117 }
Ian Rogers30fab402012-01-23 15:43:46 -0800118 if (initial_size > growth_limit) {
119 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size ("
Ian Rogers3bb17a62012-01-27 23:56:44 -0800120 << PrettySize(initial_size) << ") is larger than its capacity ("
121 << PrettySize(growth_limit) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800122 return NULL;
123 }
124 if (growth_limit > capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800125 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity ("
126 << PrettySize(growth_limit) << ") is larger than the capacity ("
127 << PrettySize(capacity) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800128 return NULL;
129 }
130
131 // Page align growth limit and capacity which will be used to manage mmapped storage
132 growth_limit = RoundUp(growth_limit, kPageSize);
133 capacity = RoundUp(capacity, kPageSize);
134
135 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(name.c_str(), requested_begin,
136 capacity, PROT_READ | PROT_WRITE));
137 if (mem_map.get() == NULL) {
138 LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800139 << PrettySize(capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800140 return NULL;
141 }
142
Ian Rogers3bb17a62012-01-27 23:56:44 -0800143 void* mspace = AllocSpace::CreateMallocSpace(mem_map->Begin(), starting_size, initial_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800144 if (mspace == NULL) {
145 LOG(ERROR) << "Failed to initialize mspace for alloc space (" << name << ")";
146 return NULL;
147 }
148
Ian Rogers3bb17a62012-01-27 23:56:44 -0800149 // Protect memory beyond the initial size.
150 byte* end = mem_map->Begin() + starting_size;
Ian Rogers30fab402012-01-23 15:43:46 -0800151 if (capacity - initial_size > 0) {
152 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name);
153 }
154
155 // Everything is set so record in immutable structure and leave
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700156 MemMap* mem_map_ptr = mem_map.release();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700157 AllocSpace* space = new AllocSpace(name, mem_map_ptr, mspace, mem_map_ptr->Begin(), end,
158 growth_limit);
Ian Rogers30fab402012-01-23 15:43:46 -0800159 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800160 LOG(INFO) << "Space::CreateAllocSpace exiting (" << PrettyDuration(NanoTime() - start_time)
161 << " ) " << *space;
Ian Rogers30fab402012-01-23 15:43:46 -0800162 }
163 return space;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700164}
165
Ian Rogers3bb17a62012-01-27 23:56:44 -0800166void* AllocSpace::CreateMallocSpace(void* begin, size_t morecore_start, size_t initial_size) {
Ian Rogers30fab402012-01-23 15:43:46 -0800167 // clear errno to allow PLOG on error
Carl Shapiro69759ea2011-07-21 18:13:35 -0700168 errno = 0;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800169 // create mspace using our backing storage starting at begin and with a footprint of
170 // morecore_start. Don't use an internal dlmalloc lock (as we already hold heap lock). When
171 // morecore_start bytes of memory is exhaused morecore will be called.
172 void* msp = create_mspace_with_base(begin, morecore_start, false /*locked*/);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700173 if (msp != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800174 // Do not allow morecore requests to succeed beyond the initial size of the heap
Ian Rogers3bb17a62012-01-27 23:56:44 -0800175 mspace_set_footprint_limit(msp, initial_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700176 } else {
Ian Rogers30fab402012-01-23 15:43:46 -0800177 PLOG(ERROR) << "create_mspace_with_base failed";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700178 }
179 return msp;
180}
181
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700182void AllocSpace::SwapBitmaps() {
183 SpaceBitmap* temp_live_bitmap = live_bitmap_.release();
184 live_bitmap_.reset(mark_bitmap_.release());
185 mark_bitmap_.reset(temp_live_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700186 // Swap names to get more descriptive diagnostics.
187 std::string temp_name = live_bitmap_->GetName();
188 live_bitmap_->SetName(mark_bitmap_->GetName());
189 mark_bitmap_->SetName(temp_name);
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700190}
191
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700192Object* AllocSpace::AllocWithoutGrowthLocked(size_t num_bytes) {
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700193 if (kDebugSpaces) {
194 num_bytes += sizeof(word);
195 }
196
Ian Rogers30fab402012-01-23 15:43:46 -0800197 Object* result = reinterpret_cast<Object*>(mspace_calloc(mspace_, 1, num_bytes));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700198 if (kDebugSpaces && result != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800199 CHECK(Contains(result)) << "Allocation (" << reinterpret_cast<void*>(result)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700200 << ") not in bounds of allocation space " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700201 // Put a magic pattern before and after the allocation.
202 *reinterpret_cast<word*>(reinterpret_cast<byte*>(result) + AllocationSize(result)
203 - sizeof(word) - kChunkOverhead) = kPaddingValue;
jeffhaoc1160702011-10-27 15:48:45 -0700204 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700205 size_t allocation_size = AllocationSize(result);
206 num_bytes_allocated_ += allocation_size;
207 total_bytes_allocated_ += allocation_size;
208 ++total_objects_allocated_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700209 ++num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800210 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700211}
212
Ian Rogers50b35e22012-10-04 10:09:15 -0700213Object* AllocSpace::AllocWithoutGrowth(Thread* self, size_t num_bytes) {
214 MutexLock mu(self, lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700215 return AllocWithoutGrowthLocked(num_bytes);
216}
217
Ian Rogers50b35e22012-10-04 10:09:15 -0700218Object* AllocSpace::AllocWithGrowth(Thread* self, size_t num_bytes) {
219 MutexLock mu(self, lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800220 // Grow as much as possible within the mspace.
221 size_t max_allowed = Capacity();
222 mspace_set_footprint_limit(mspace_, max_allowed);
223 // Try the allocation.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 void* ptr = AllocWithoutGrowthLocked(num_bytes);
Ian Rogers30fab402012-01-23 15:43:46 -0800225 // Shrink back down as small as possible.
226 size_t footprint = mspace_footprint(mspace_);
227 mspace_set_footprint_limit(mspace_, footprint);
228 // Return the new allocation or NULL.
229 Object* result = reinterpret_cast<Object*>(ptr);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700230 CHECK(!kDebugSpaces || result == NULL || Contains(result));
Ian Rogers30fab402012-01-23 15:43:46 -0800231 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700232}
233
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700234void AllocSpace::SetGrowthLimit(size_t growth_limit) {
235 growth_limit = RoundUp(growth_limit, kPageSize);
236 growth_limit_ = growth_limit;
237 if (Size() > growth_limit_) {
238 end_ = begin_ + growth_limit;
239 }
240}
241
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700242AllocSpace* AllocSpace::CreateZygoteSpace() {
243 end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700244 DCHECK(IsAligned<CardTable::kCardSize>(begin_));
245 DCHECK(IsAligned<CardTable::kCardSize>(end_));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700246 DCHECK(IsAligned<kPageSize>(begin_));
247 DCHECK(IsAligned<kPageSize>(end_));
248 size_t size = RoundUp(Size(), kPageSize);
249 // Trim the heap so that we minimize the size of the Zygote space.
250 Trim();
251 // Trim our mem-map to free unused pages.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700252 GetMemMap()->UnMapAtEnd(end_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700253 // TODO: Not hardcode these in?
254 const size_t starting_size = kPageSize;
255 const size_t initial_size = 2 * MB;
256 // Remaining size is for the new alloc space.
257 const size_t growth_limit = growth_limit_ - size;
258 const size_t capacity = Capacity() - size;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700259 VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n"
260 << "End " << reinterpret_cast<const void*>(end_) << "\n"
261 << "Size " << size << "\n"
262 << "GrowthLimit " << growth_limit_ << "\n"
263 << "Capacity " << Capacity();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700264 SetGrowthLimit(RoundUp(size, kPageSize));
265 SetFootprintLimit(RoundUp(size, kPageSize));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700266 // FIXME: Do we need reference counted pointers here?
267 // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces.
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700268 VLOG(heap) << "Creating new AllocSpace: ";
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700269 VLOG(heap) << "Size " << GetMemMap()->Size();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700270 VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit);
271 VLOG(heap) << "Capacity " << PrettySize(capacity);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700272 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(GetName().c_str(), End(), capacity, PROT_READ | PROT_WRITE));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700273 void* mspace = CreateMallocSpace(end_, starting_size, initial_size);
274 // Protect memory beyond the initial size.
275 byte* end = mem_map->Begin() + starting_size;
276 if (capacity - initial_size > 0) {
277 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name_.c_str());
278 }
279 AllocSpace* alloc_space = new AllocSpace(name_, mem_map.release(), mspace, end_, end, growth_limit);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700280 live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
281 CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
282 mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
283 CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700284 name_ += "-zygote-transformed";
285 VLOG(heap) << "zygote space creation done";
286 return alloc_space;
287}
288
Ian Rogers50b35e22012-10-04 10:09:15 -0700289void AllocSpace::Free(Thread* self, Object* ptr) {
290 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700291 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700292 CHECK(ptr != NULL);
293 CHECK(Contains(ptr)) << "Free (" << ptr << ") not in bounds of heap " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700294 CHECK_EQ(
295 *reinterpret_cast<word*>(reinterpret_cast<byte*>(ptr) + AllocationSize(ptr) -
296 sizeof(word) - kChunkOverhead), kPaddingValue);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700297 }
298 num_bytes_allocated_ -= AllocationSize(ptr);
299 --num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800300 mspace_free(mspace_, ptr);
301}
302
Ian Rogers50b35e22012-10-04 10:09:15 -0700303void AllocSpace::FreeList(Thread* self, size_t num_ptrs, Object** ptrs) {
304 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700305 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700306 CHECK(ptrs != NULL);
307 size_t num_broken_ptrs = 0;
308 for (size_t i = 0; i < num_ptrs; i++) {
309 if (!Contains(ptrs[i])) {
310 num_broken_ptrs++;
311 LOG(ERROR) << "FreeList[" << i << "] (" << ptrs[i] << ") not in bounds of heap " << *this;
312 } else {
313 size_t size = mspace_usable_size(ptrs[i]);
314 memset(ptrs[i], 0xEF, size);
315 }
Ian Rogers30fab402012-01-23 15:43:46 -0800316 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700317 CHECK_EQ(num_broken_ptrs, 0u);
Ian Rogers30fab402012-01-23 15:43:46 -0800318 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700319 for (size_t i = 0; i < num_ptrs; i++) {
320 num_bytes_allocated_ -= AllocationSize(ptrs[i]);
321 }
322 num_objects_allocated_ -= num_ptrs;
Ian Rogers30fab402012-01-23 15:43:46 -0800323 mspace_bulk_free(mspace_, reinterpret_cast<void**>(ptrs), num_ptrs);
324}
325
326// Callback from dlmalloc when it needs to increase the footprint
327extern "C" void* art_heap_morecore(void* mspace, intptr_t increment) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800328 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700329 DCHECK_EQ(heap->GetAllocSpace()->GetMspace(), mspace);
330 return heap->GetAllocSpace()->MoreCore(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800331}
332
333void* AllocSpace::MoreCore(intptr_t increment) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700334 lock_.AssertHeld(Thread::Current());
Ian Rogers30fab402012-01-23 15:43:46 -0800335 byte* original_end = end_;
336 if (increment != 0) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800337 VLOG(heap) << "AllocSpace::MoreCore " << PrettySize(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800338 byte* new_end = original_end + increment;
339 if (increment > 0) {
340#if DEBUG_SPACES
341 // Should never be asked to increase the allocation beyond the capacity of the space. Enforced
342 // by mspace_set_footprint_limit.
343 CHECK_LE(new_end, Begin() + Capacity());
344#endif
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700345 CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800346 } else {
347#if DEBUG_SPACES
348 // Should never be asked for negative footprint (ie before begin)
349 CHECK_GT(original_end + increment, Begin());
350#endif
351 // Advise we don't need the pages and protect them
Ian Rogers3bb17a62012-01-27 23:56:44 -0800352 // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be
353 // expensive (note the same isn't true for giving permissions to a page as the protected
354 // page shouldn't be in a TLB). We should investigate performance impact of just
355 // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's
356 // likely just a useful debug feature.
Ian Rogers30fab402012-01-23 15:43:46 -0800357 size_t size = -increment;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700358 CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName());
359 CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800360 }
361 // Update end_
362 end_ = new_end;
363 }
364 return original_end;
365}
366
367size_t AllocSpace::AllocationSize(const Object* obj) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700368 return mspace_usable_size(const_cast<void*>(reinterpret_cast<const void*>(obj))) +
369 kChunkOverhead;
Ian Rogers30fab402012-01-23 15:43:46 -0800370}
371
Brian Carlstromb18e77a2012-08-21 14:20:03 -0700372void MspaceMadviseCallback(void* start, void* end, size_t used_bytes, void* /* arg */) {
373 // Is this chunk in use?
374 if (used_bytes != 0) {
375 return;
376 }
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700377 // Do we have any whole pages to give back?
378 start = reinterpret_cast<void*>(RoundUp(reinterpret_cast<uintptr_t>(start), kPageSize));
379 end = reinterpret_cast<void*>(RoundDown(reinterpret_cast<uintptr_t>(end), kPageSize));
380 if (end > start) {
381 size_t length = reinterpret_cast<byte*>(end) - reinterpret_cast<byte*>(start);
382 CHECK_MEMORY_CALL(madvise, (start, length, MADV_DONTNEED), "trim");
Ian Rogers30fab402012-01-23 15:43:46 -0800383 }
384}
385
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700386void AllocSpace::Trim() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700387 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700388 // Trim to release memory at the end of the space.
389 mspace_trim(mspace_, 0);
390 // Visit space looking for page-sized holes to advise the kernel we don't need.
391 mspace_inspect_all(mspace_, MspaceMadviseCallback, NULL);
392}
Ian Rogers30fab402012-01-23 15:43:46 -0800393
394void AllocSpace::Walk(void(*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
395 void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700396 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800397 mspace_inspect_all(mspace_, callback, arg);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700398 callback(NULL, NULL, 0, arg); // Indicate end of a space.
Ian Rogers30fab402012-01-23 15:43:46 -0800399}
400
401size_t AllocSpace::GetFootprintLimit() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700402 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800403 return mspace_footprint_limit(mspace_);
404}
405
406void AllocSpace::SetFootprintLimit(size_t new_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700407 MutexLock mu(Thread::Current(), lock_);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800408 VLOG(heap) << "AllocSpace::SetFootprintLimit " << PrettySize(new_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800409 // Compare against the actual footprint, rather than the Size(), because the heap may not have
410 // grown all the way to the allowed size yet.
Ian Rogers30fab402012-01-23 15:43:46 -0800411 size_t current_space_size = mspace_footprint(mspace_);
412 if (new_size < current_space_size) {
413 // Don't let the space grow any more.
414 new_size = current_space_size;
415 }
416 mspace_set_footprint_limit(mspace_, new_size);
417}
418
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700419size_t ImageSpace::bitmap_index_ = 0;
420
421ImageSpace::ImageSpace(const std::string& name, MemMap* mem_map)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700422 : MemMapSpace(name, mem_map, mem_map->Size(), kGcRetentionPolicyNeverCollect) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700423 const size_t bitmap_index = bitmap_index_++;
424 live_bitmap_.reset(SpaceBitmap::Create(
425 StringPrintf("imagespace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
426 Begin(), Capacity()));
427 DCHECK(live_bitmap_.get() != NULL) << "could not create imagespace live bitmap #" << bitmap_index;
428}
429
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700430ImageSpace* ImageSpace::Create(const std::string& image_file_name) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800431 CHECK(!image_file_name.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800432
433 uint64_t start_time = 0;
434 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
435 start_time = NanoTime();
436 LOG(INFO) << "Space::CreateImageSpace entering" << " image_file_name=" << image_file_name;
437 }
438
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700439 UniquePtr<File> file(OS::OpenFile(image_file_name.c_str(), false));
Elliott Hughes90a33692011-08-30 13:27:07 -0700440 if (file.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800441 LOG(ERROR) << "Failed to open " << image_file_name;
442 return NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700443 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700444 ImageHeader image_header;
445 bool success = file->ReadFully(&image_header, sizeof(image_header));
446 if (!success || !image_header.IsValid()) {
Ian Rogers30fab402012-01-23 15:43:46 -0800447 LOG(ERROR) << "Invalid image header " << image_file_name;
448 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700449 }
Ian Rogers30fab402012-01-23 15:43:46 -0800450 UniquePtr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
Brian Carlstrom89521892011-12-07 22:05:07 -0800451 file->Length(),
452 // TODO: selectively PROT_EXEC stubs
453 PROT_READ | PROT_WRITE | PROT_EXEC,
454 MAP_PRIVATE | MAP_FIXED,
455 file->Fd(),
456 0));
Elliott Hughes90a33692011-08-30 13:27:07 -0700457 if (map.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800458 LOG(ERROR) << "Failed to map " << image_file_name;
459 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700460 }
Ian Rogers30fab402012-01-23 15:43:46 -0800461 CHECK_EQ(image_header.GetImageBegin(), map->Begin());
462 DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700463
Ian Rogers30fab402012-01-23 15:43:46 -0800464 Runtime* runtime = Runtime::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700465 Object* jni_stub_array = image_header.GetImageRoot(ImageHeader::kJniStubArray);
Ian Rogers169c9a72011-11-13 20:13:17 -0800466 runtime->SetJniDlsymLookupStub(down_cast<ByteArray*>(jni_stub_array));
Brian Carlstrom16192862011-09-12 17:50:06 -0700467
Brian Carlstrome24fa612011-09-29 00:53:55 -0700468 Object* ame_stub_array = image_header.GetImageRoot(ImageHeader::kAbstractMethodErrorStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700469 runtime->SetAbstractMethodErrorStubArray(down_cast<ByteArray*>(ame_stub_array));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700470
Ian Rogersfb6adba2012-03-04 21:51:51 -0800471 Object* resolution_stub_array =
472 image_header.GetImageRoot(ImageHeader::kStaticResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700473 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700474 down_cast<ByteArray*>(resolution_stub_array), Runtime::kStaticMethod);
475 resolution_stub_array = image_header.GetImageRoot(ImageHeader::kUnknownMethodResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700476 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700477 down_cast<ByteArray*>(resolution_stub_array), Runtime::kUnknownMethod);
Ian Rogersad25ac52011-10-04 19:13:33 -0700478
Ian Rogers19846512012-02-24 11:42:47 -0800479 Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700480 runtime->SetResolutionMethod(down_cast<AbstractMethod*>(resolution_method));
Ian Rogers19846512012-02-24 11:42:47 -0800481
Ian Rogersff1ed472011-09-20 13:46:24 -0700482 Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700483 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kSaveAll);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700484 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700485 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsOnly);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700486 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700487 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsAndArgs);
Ian Rogersff1ed472011-09-20 13:46:24 -0700488
Ian Rogers30fab402012-01-23 15:43:46 -0800489 ImageSpace* space = new ImageSpace(image_file_name, map.release());
490 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800491 LOG(INFO) << "Space::CreateImageSpace exiting (" << PrettyDuration(NanoTime() - start_time)
492 << ") " << *space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700493 }
Ian Rogers30fab402012-01-23 15:43:46 -0800494 return space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700495}
496
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700497void ImageSpace::RecordImageAllocations(SpaceBitmap* live_bitmap) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800498 uint64_t start_time = 0;
499 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
500 LOG(INFO) << "ImageSpace::RecordImageAllocations entering";
501 start_time = NanoTime();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700502 }
Ian Rogers30fab402012-01-23 15:43:46 -0800503 DCHECK(!Runtime::Current()->IsStarted());
504 CHECK(live_bitmap != NULL);
505 byte* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
506 byte* end = End();
507 while (current < end) {
508 DCHECK_ALIGNED(current, kObjectAlignment);
509 const Object* obj = reinterpret_cast<const Object*>(current);
510 live_bitmap->Set(obj);
511 current += RoundUp(obj->SizeOf(), kObjectAlignment);
512 }
513 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800514 LOG(INFO) << "ImageSpace::RecordImageAllocations exiting ("
515 << PrettyDuration(NanoTime() - start_time) << ")";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700516 }
517}
518
Ian Rogers30fab402012-01-23 15:43:46 -0800519std::ostream& operator<<(std::ostream& os, const Space& space) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700520 space.Dump(os);
Ian Rogers30fab402012-01-23 15:43:46 -0800521 return os;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700522}
523
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700524void AllocSpace::Dump(std::ostream& os) const {
525 os << GetType()
526 << "begin=" << reinterpret_cast<void*>(Begin())
527 << ",end=" << reinterpret_cast<void*>(End())
528 << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity())
529 << ",name=\"" << GetName() << "\"]";
530}
531
532void ImageSpace::Dump(std::ostream& os) const {
533 os << GetType()
534 << "begin=" << reinterpret_cast<void*>(Begin())
535 << ",end=" << reinterpret_cast<void*>(End())
536 << ",size=" << PrettySize(Size())
537 << ",name=\"" << GetName() << "\"]";
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700538}
539
540void LargeObjectSpace::SwapBitmaps() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700541 SpaceSetMap* temp_live_objects = live_objects_.release();
542 live_objects_.reset(mark_objects_.release());
543 mark_objects_.reset(temp_live_objects);
544 // Swap names to get more descriptive diagnostics.
545 std::string temp_name = live_objects_->GetName();
546 live_objects_->SetName(mark_objects_->GetName());
547 mark_objects_->SetName(temp_name);
548}
549
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700550DiscontinuousSpace::DiscontinuousSpace(const std::string& name,
551 GcRetentionPolicy gc_retention_policy)
552 : Space(name, gc_retention_policy) {
553
554}
555
556LargeObjectSpace::LargeObjectSpace(const std::string& name)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700557 : DiscontinuousSpace(name, kGcRetentionPolicyAlwaysCollect),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700558 num_bytes_allocated_(0), num_objects_allocated_(0), total_bytes_allocated_(0),
559 total_objects_allocated_(0) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700560 live_objects_.reset(new SpaceSetMap("large live objects"));
561 mark_objects_.reset(new SpaceSetMap("large marked objects"));
562}
563
564
565void LargeObjectSpace::CopyLiveToMarked() {
566 mark_objects_->CopyFrom(*live_objects_.get());
567}
568
569LargeObjectMapSpace::LargeObjectMapSpace(const std::string& name)
570 : LargeObjectSpace(name),
571 lock_("large object space lock", kAllocSpaceLock)
572{
573
574}
575
576LargeObjectMapSpace* LargeObjectMapSpace::Create(const std::string& name) {
577 return new LargeObjectMapSpace(name);
578}
579
Ian Rogers50b35e22012-10-04 10:09:15 -0700580Object* LargeObjectMapSpace::Alloc(Thread* self, size_t num_bytes) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700581 MemMap* mem_map = MemMap::MapAnonymous("allocation", NULL, num_bytes, PROT_READ | PROT_WRITE);
582 if (mem_map == NULL) {
583 return NULL;
584 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700585 MutexLock mu(self, lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700586 Object* obj = reinterpret_cast<Object*>(mem_map->Begin());
587 large_objects_.push_back(obj);
588 mem_maps_.Put(obj, mem_map);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700589 size_t allocation_size = mem_map->Size();
590 num_bytes_allocated_ += allocation_size;
591 total_bytes_allocated_ += allocation_size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700592 ++num_objects_allocated_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700593 ++total_objects_allocated_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700594 return obj;
595}
596
Ian Rogers50b35e22012-10-04 10:09:15 -0700597void LargeObjectMapSpace::Free(Thread* self, Object* ptr) {
598 MutexLock mu(self, lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700599 MemMaps::iterator found = mem_maps_.find(ptr);
600 CHECK(found != mem_maps_.end()) << "Attempted to free large object which was not live";
601 DCHECK_GE(num_bytes_allocated_, found->second->Size());
602 num_bytes_allocated_ -= found->second->Size();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700603 --num_objects_allocated_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700604 delete found->second;
605 mem_maps_.erase(found);
606}
607
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700608size_t LargeObjectMapSpace::AllocationSize(const Object* obj) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700609 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700610 MemMaps::iterator found = mem_maps_.find(const_cast<Object*>(obj));
611 CHECK(found != mem_maps_.end()) << "Attempted to get size of a large object which is not live";
612 return found->second->Size();
613}
614
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700615void LargeObjectMapSpace::Walk(AllocSpace::WalkCallback callback, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700616 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700617 for (MemMaps::iterator it = mem_maps_.begin(); it != mem_maps_.end(); ++it) {
618 MemMap* mem_map = it->second;
619 callback(mem_map->Begin(), mem_map->End(), mem_map->Size(), arg);
620 callback(NULL, NULL, 0, arg);
621 }
622}
623
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700624bool LargeObjectMapSpace::Contains(const Object* obj) const {
Ian Rogers50b35e22012-10-04 10:09:15 -0700625 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700626 return mem_maps_.find(const_cast<Object*>(obj)) != mem_maps_.end();
627}
628
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700629FreeListSpace* FreeListSpace::Create(const std::string& name, byte* requested_begin, size_t size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700630 CHECK(size % kAlignment == 0);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700631 MemMap* mem_map = MemMap::MapAnonymous(name.c_str(), requested_begin, size,
632 PROT_READ | PROT_WRITE);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700633 CHECK(mem_map != NULL) << "Failed to allocate large object space mem map";
634 return new FreeListSpace(name, mem_map, mem_map->Begin(), mem_map->End());
635}
636
637FreeListSpace::FreeListSpace(const std::string& name, MemMap* mem_map, byte* begin, byte* end)
638 : LargeObjectSpace(name),
639 begin_(begin),
640 end_(end),
641 mem_map_(mem_map),
642 lock_("free list space lock", kAllocSpaceLock) {
643 chunks_.resize(Size() / kAlignment + 1);
644 // Add a dummy chunk so we don't need to handle chunks having no next chunk.
645 chunks_.back().SetSize(kAlignment, false);
646 // Start out with one large free chunk.
647 AddFreeChunk(begin_, end_ - begin_, NULL);
648}
649
650FreeListSpace::~FreeListSpace() {
651
652}
653
654void FreeListSpace::AddFreeChunk(void* address, size_t size, Chunk* previous) {
655 Chunk* chunk = ChunkFromAddr(address);
656 chunk->SetSize(size, true);
657 chunk->SetPrevious(previous);
658 Chunk* next_chunk = GetNextChunk(chunk);
659 next_chunk->SetPrevious(chunk);
660 free_chunks_.insert(chunk);
661}
662
663FreeListSpace::Chunk* FreeListSpace::ChunkFromAddr(void* address) {
664 size_t offset = reinterpret_cast<byte*>(address) - Begin();
665 DCHECK(IsAligned<kAlignment>(offset));
666 DCHECK_LT(offset, Size());
667 return &chunks_[offset / kAlignment];
668}
669
670void* FreeListSpace::AddrFromChunk(Chunk* chunk) {
671 return reinterpret_cast<void*>(Begin() + (chunk - &chunks_.front()) * kAlignment);
672}
673
674void FreeListSpace::RemoveFreeChunk(Chunk* chunk) {
675 // TODO: C++0x
676 // TODO: Improve performance, this might be slow.
677 std::pair<FreeChunks::iterator, FreeChunks::iterator> range = free_chunks_.equal_range(chunk);
678 for (FreeChunks::iterator it = range.first; it != range.second; ++it) {
679 if (*it == chunk) {
680 free_chunks_.erase(it);
681 return;
682 }
683 }
684}
685
686void FreeListSpace::Walk(AllocSpace::WalkCallback callback, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700687 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700688 for (Chunk* chunk = &chunks_.front(); chunk < &chunks_.back(); ) {
689 if (!chunk->IsFree()) {
690 size_t size = chunk->GetSize();
691 void* begin = AddrFromChunk(chunk);
692 void* end = reinterpret_cast<void*>(reinterpret_cast<byte*>(begin) + size);
693 callback(begin, end, size, arg);
694 callback(NULL, NULL, 0, arg);
695 }
696 chunk = GetNextChunk(chunk);
697 }
698}
699
Ian Rogers50b35e22012-10-04 10:09:15 -0700700void FreeListSpace::Free(Thread* self, Object* obj) {
701 MutexLock mu(self, lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700702 CHECK(Contains(obj));
703 // Check adjacent chunks to see if we need to combine.
704 Chunk* chunk = ChunkFromAddr(obj);
705 CHECK(!chunk->IsFree());
706
707 size_t allocation_size = chunk->GetSize();
708 madvise(obj, allocation_size, MADV_DONTNEED);
709 num_objects_allocated_--;
710 num_bytes_allocated_ -= allocation_size;
711 Chunk* prev = chunk->GetPrevious();
712 Chunk* next = GetNextChunk(chunk);
713
714 // Combine any adjacent free chunks
715 size_t extra_size = chunk->GetSize();
716 if (next->IsFree()) {
717 extra_size += next->GetSize();
718 RemoveFreeChunk(next);
719 }
720 if (prev != NULL && prev->IsFree()) {
721 RemoveFreeChunk(prev);
722 AddFreeChunk(AddrFromChunk(prev), prev->GetSize() + extra_size, prev->GetPrevious());
723 } else {
724 AddFreeChunk(AddrFromChunk(chunk), extra_size, prev);
725 }
726}
727
728bool FreeListSpace::Contains(const Object* obj) const {
729 return mem_map_->HasAddress(obj);
730}
731
732FreeListSpace::Chunk* FreeListSpace::GetNextChunk(Chunk* chunk) {
733 return chunk + chunk->GetSize() / kAlignment;
734}
735
736size_t FreeListSpace::AllocationSize(const Object* obj) {
737 Chunk* chunk = ChunkFromAddr(const_cast<Object*>(obj));
738 CHECK(!chunk->IsFree());
739 return chunk->GetSize();
740}
741
Ian Rogers50b35e22012-10-04 10:09:15 -0700742Object* FreeListSpace::Alloc(Thread* self, size_t num_bytes) {
743 MutexLock mu(self, lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700744 num_bytes = RoundUp(num_bytes, kAlignment);
745 Chunk temp;
746 temp.SetSize(num_bytes);
747 // Find the smallest chunk at least num_bytes in size.
748 FreeChunks::iterator found = free_chunks_.lower_bound(&temp);
749 if (found == free_chunks_.end()) {
750 // Out of memory, or too much fragmentation.
751 return NULL;
752 }
753 Chunk* chunk = *found;
754 free_chunks_.erase(found);
755 CHECK(chunk->IsFree());
756 void* addr = AddrFromChunk(chunk);
757 size_t chunk_size = chunk->GetSize();
758 chunk->SetSize(num_bytes);
759 if (chunk_size > num_bytes) {
760 // Split the chunk into two chunks.
761 Chunk* new_chunk = GetNextChunk(chunk);
762 AddFreeChunk(AddrFromChunk(new_chunk), chunk_size - num_bytes, chunk);
763 }
764
765 num_objects_allocated_++;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700766 total_objects_allocated_++;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700767 num_bytes_allocated_ += num_bytes;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700768 total_bytes_allocated_ += num_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700769 return reinterpret_cast<Object*>(addr);
770}
771
Ian Rogers50b35e22012-10-04 10:09:15 -0700772void FreeListSpace::FreeList(Thread* self, size_t num_ptrs, Object** ptrs) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700773 for (size_t i = 0; i < num_ptrs; ++i) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700774 Free(self, ptrs[i]);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700775 }
776}
777
Carl Shapiro69759ea2011-07-21 18:13:35 -0700778} // namespace art