blob: 74e719a84a597764ab6e5f4f0ea9422d4ce57cc0 [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
32#define DEBUG_SPACES 1
Mathieu Chartier2fde5332012-09-14 14:51:54 -070033#else
34#define DEBUG_SPACES 0
Ian Rogers30fab402012-01-23 15:43:46 -080035#endif
36
Mathieu Chartier2fde5332012-09-14 14:51:54 -070037// TODO: Remove define macro
Ian Rogers30fab402012-01-23 15:43:46 -080038#define CHECK_MEMORY_CALL(call, args, what) \
39 do { \
40 int rc = call args; \
41 if (UNLIKELY(rc != 0)) { \
42 errno = rc; \
43 PLOG(FATAL) << # call << " failed for " << what; \
44 } \
45 } while (false)
46
Mathieu Chartier2fde5332012-09-14 14:51:54 -070047Space::Space(const std::string& name, GcRetentionPolicy gc_retention_policy)
48 : name_(name),
49 gc_retention_policy_(gc_retention_policy) {
50
51}
52
53ContinuousSpace::ContinuousSpace(const std::string& name, byte* begin, byte* end,
54 GcRetentionPolicy gc_retention_policy)
55 : Space(name, gc_retention_policy),
56 begin_(begin),
57 end_(end) {
58
59}
60
61MemMapSpace::MemMapSpace(const std::string& name, MemMap* mem_map, size_t initial_size,
62 GcRetentionPolicy gc_retention_policy)
63 : ContinuousSpace(name, mem_map->Begin(), mem_map->Begin() + initial_size, gc_retention_policy),
64 mem_map_(mem_map)
65{
66
67}
68
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070069size_t AllocSpace::bitmap_index_ = 0;
70
Mathieu Chartier2fde5332012-09-14 14:51:54 -070071AllocSpace::AllocSpace(const std::string& name, MemMap* mem_map, void* mspace, byte* begin,
72 byte* end, size_t growth_limit)
73 : MemMapSpace(name, mem_map, end - begin, GCRP_ALWAYS_COLLECT),
74 num_bytes_allocated_(0), num_objects_allocated_(0),
Ian Rogers15bf2d32012-08-28 17:33:04 -070075 lock_("allocation space lock", kAllocSpaceLock), mspace_(mspace),
76 growth_limit_(growth_limit) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070077 CHECK(mspace != NULL);
78
79 size_t bitmap_index = bitmap_index_++;
80
Mathieu Chartier2fde5332012-09-14 14:51:54 -070081 static const uintptr_t kGcCardSize = static_cast<uintptr_t>(GC_CARD_SIZE);
82 CHECK(reinterpret_cast<uintptr_t>(mem_map->Begin()) % kGcCardSize == 0);
83 CHECK(reinterpret_cast<uintptr_t>(mem_map->End()) % kGcCardSize == 0);
Mathieu Chartiercc236d72012-07-20 10:29:05 -070084
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070085 live_bitmap_.reset(SpaceBitmap::Create(
86 StringPrintf("allocspace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
87 Begin(), Capacity()));
88 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace live bitmap #" << bitmap_index;
89
90 mark_bitmap_.reset(SpaceBitmap::Create(
91 StringPrintf("allocspace-%s-mark-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
92 Begin(), Capacity()));
93 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace mark bitmap #" << bitmap_index;
94}
95
Mathieu Chartier2fde5332012-09-14 14:51:54 -070096AllocSpace* AllocSpace::Create(const std::string& name, size_t initial_size, size_t growth_limit,
97 size_t capacity, byte* requested_begin) {
Ian Rogers3bb17a62012-01-27 23:56:44 -080098 // Memory we promise to dlmalloc before it asks for morecore.
99 // Note: making this value large means that large allocations are unlikely to succeed as dlmalloc
100 // will ask for this memory from sys_alloc which will fail as the footprint (this value plus the
101 // size of the large allocation) will be greater than the footprint limit.
102 size_t starting_size = kPageSize;
Ian Rogers30fab402012-01-23 15:43:46 -0800103 uint64_t start_time = 0;
104 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
105 start_time = NanoTime();
106 VLOG(startup) << "Space::CreateAllocSpace entering " << name
Ian Rogers3bb17a62012-01-27 23:56:44 -0800107 << " initial_size=" << PrettySize(initial_size)
108 << " growth_limit=" << PrettySize(growth_limit)
109 << " capacity=" << PrettySize(capacity)
Ian Rogers30fab402012-01-23 15:43:46 -0800110 << " requested_begin=" << reinterpret_cast<void*>(requested_begin);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700111 }
Ian Rogers30fab402012-01-23 15:43:46 -0800112
113 // Sanity check arguments
Ian Rogers3bb17a62012-01-27 23:56:44 -0800114 if (starting_size > initial_size) {
115 initial_size = starting_size;
116 }
Ian Rogers30fab402012-01-23 15:43:46 -0800117 if (initial_size > growth_limit) {
118 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size ("
Ian Rogers3bb17a62012-01-27 23:56:44 -0800119 << PrettySize(initial_size) << ") is larger than its capacity ("
120 << PrettySize(growth_limit) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800121 return NULL;
122 }
123 if (growth_limit > capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800124 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity ("
125 << PrettySize(growth_limit) << ") is larger than the capacity ("
126 << PrettySize(capacity) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800127 return NULL;
128 }
129
130 // Page align growth limit and capacity which will be used to manage mmapped storage
131 growth_limit = RoundUp(growth_limit, kPageSize);
132 capacity = RoundUp(capacity, kPageSize);
133
134 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(name.c_str(), requested_begin,
135 capacity, PROT_READ | PROT_WRITE));
136 if (mem_map.get() == NULL) {
137 LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800138 << PrettySize(capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800139 return NULL;
140 }
141
Ian Rogers3bb17a62012-01-27 23:56:44 -0800142 void* mspace = AllocSpace::CreateMallocSpace(mem_map->Begin(), starting_size, initial_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800143 if (mspace == NULL) {
144 LOG(ERROR) << "Failed to initialize mspace for alloc space (" << name << ")";
145 return NULL;
146 }
147
Ian Rogers3bb17a62012-01-27 23:56:44 -0800148 // Protect memory beyond the initial size.
149 byte* end = mem_map->Begin() + starting_size;
Ian Rogers30fab402012-01-23 15:43:46 -0800150 if (capacity - initial_size > 0) {
151 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name);
152 }
153
154 // Everything is set so record in immutable structure and leave
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700155 MemMap* mem_map_ptr = mem_map.release();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700156 AllocSpace* space = new AllocSpace(name, mem_map_ptr, mspace, mem_map_ptr->Begin(), end,
157 growth_limit);
Ian Rogers30fab402012-01-23 15:43:46 -0800158 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800159 LOG(INFO) << "Space::CreateAllocSpace exiting (" << PrettyDuration(NanoTime() - start_time)
160 << " ) " << *space;
Ian Rogers30fab402012-01-23 15:43:46 -0800161 }
162 return space;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700163}
164
Ian Rogers3bb17a62012-01-27 23:56:44 -0800165void* AllocSpace::CreateMallocSpace(void* begin, size_t morecore_start, size_t initial_size) {
Ian Rogers30fab402012-01-23 15:43:46 -0800166 // clear errno to allow PLOG on error
Carl Shapiro69759ea2011-07-21 18:13:35 -0700167 errno = 0;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800168 // create mspace using our backing storage starting at begin and with a footprint of
169 // morecore_start. Don't use an internal dlmalloc lock (as we already hold heap lock). When
170 // morecore_start bytes of memory is exhaused morecore will be called.
171 void* msp = create_mspace_with_base(begin, morecore_start, false /*locked*/);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700172 if (msp != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800173 // Do not allow morecore requests to succeed beyond the initial size of the heap
Ian Rogers3bb17a62012-01-27 23:56:44 -0800174 mspace_set_footprint_limit(msp, initial_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700175 } else {
Ian Rogers30fab402012-01-23 15:43:46 -0800176 PLOG(ERROR) << "create_mspace_with_base failed";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700177 }
178 return msp;
179}
180
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700181void AllocSpace::SwapBitmaps() {
182 SpaceBitmap* temp_live_bitmap = live_bitmap_.release();
183 live_bitmap_.reset(mark_bitmap_.release());
184 mark_bitmap_.reset(temp_live_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700185 // Swap names to get more descriptive diagnostics.
186 std::string temp_name = live_bitmap_->GetName();
187 live_bitmap_->SetName(mark_bitmap_->GetName());
188 mark_bitmap_->SetName(temp_name);
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700189}
190
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700191Object* AllocSpace::AllocWithoutGrowthLocked(size_t num_bytes) {
Ian Rogers30fab402012-01-23 15:43:46 -0800192 Object* result = reinterpret_cast<Object*>(mspace_calloc(mspace_, 1, num_bytes));
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700193 if (DEBUG_SPACES && result != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800194 CHECK(Contains(result)) << "Allocation (" << reinterpret_cast<void*>(result)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700195 << ") not in bounds of allocation space " << *this;
jeffhaoc1160702011-10-27 15:48:45 -0700196 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700197 num_bytes_allocated_ += AllocationSize(result);
198 ++num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800199 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700200}
201
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700202Object* AllocSpace::AllocWithoutGrowth(size_t num_bytes) {
203 MutexLock mu(lock_);
204 return AllocWithoutGrowthLocked(num_bytes);
205}
206
Ian Rogers30fab402012-01-23 15:43:46 -0800207Object* AllocSpace::AllocWithGrowth(size_t num_bytes) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700208 MutexLock mu(lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800209 // Grow as much as possible within the mspace.
210 size_t max_allowed = Capacity();
211 mspace_set_footprint_limit(mspace_, max_allowed);
212 // Try the allocation.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700213 void* ptr = AllocWithoutGrowthLocked(num_bytes);
Ian Rogers30fab402012-01-23 15:43:46 -0800214 // Shrink back down as small as possible.
215 size_t footprint = mspace_footprint(mspace_);
216 mspace_set_footprint_limit(mspace_, footprint);
217 // Return the new allocation or NULL.
218 Object* result = reinterpret_cast<Object*>(ptr);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700219 CHECK(!DEBUG_SPACES || result == NULL || Contains(result));
Ian Rogers30fab402012-01-23 15:43:46 -0800220 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700221}
222
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700223void AllocSpace::SetGrowthLimit(size_t growth_limit) {
224 growth_limit = RoundUp(growth_limit, kPageSize);
225 growth_limit_ = growth_limit;
226 if (Size() > growth_limit_) {
227 end_ = begin_ + growth_limit;
228 }
229}
230
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700231AllocSpace* AllocSpace::CreateZygoteSpace() {
232 end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize));
233 DCHECK(IsAligned<GC_CARD_SIZE>(begin_));
234 DCHECK(IsAligned<GC_CARD_SIZE>(end_));
235 DCHECK(IsAligned<kPageSize>(begin_));
236 DCHECK(IsAligned<kPageSize>(end_));
237 size_t size = RoundUp(Size(), kPageSize);
238 // Trim the heap so that we minimize the size of the Zygote space.
239 Trim();
240 // Trim our mem-map to free unused pages.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700241 GetMemMap()->UnMapAtEnd(end_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700242 // TODO: Not hardcode these in?
243 const size_t starting_size = kPageSize;
244 const size_t initial_size = 2 * MB;
245 // Remaining size is for the new alloc space.
246 const size_t growth_limit = growth_limit_ - size;
247 const size_t capacity = Capacity() - size;
248 VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_);
249 VLOG(heap) << "End " << reinterpret_cast<const void*>(end_);
250 VLOG(heap) << "Size " << size;
251 VLOG(heap) << "GrowthLimit " << growth_limit_;
252 VLOG(heap) << "Capacity " << Capacity();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700253 SetGrowthLimit(RoundUp(size, kPageSize));
254 SetFootprintLimit(RoundUp(size, kPageSize));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700255 // FIXME: Do we need reference counted pointers here?
256 // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces.
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700257 VLOG(heap) << "Creating new AllocSpace: ";
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700258 VLOG(heap) << "Size " << GetMemMap()->Size();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700259 VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit);
260 VLOG(heap) << "Capacity " << PrettySize(capacity);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700261 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(GetName().c_str(), End(), capacity, PROT_READ | PROT_WRITE));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700262 void* mspace = CreateMallocSpace(end_, starting_size, initial_size);
263 // Protect memory beyond the initial size.
264 byte* end = mem_map->Begin() + starting_size;
265 if (capacity - initial_size > 0) {
266 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name_.c_str());
267 }
268 AllocSpace* alloc_space = new AllocSpace(name_, mem_map.release(), mspace, end_, end, growth_limit);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700269 live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
270 CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
271 mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
272 CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700273 name_ += "-zygote-transformed";
274 VLOG(heap) << "zygote space creation done";
275 return alloc_space;
276}
277
Ian Rogers30fab402012-01-23 15:43:46 -0800278void AllocSpace::Free(Object* ptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700279 MutexLock mu(lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700280 if (DEBUG_SPACES) {
281 CHECK(ptr != NULL);
282 CHECK(Contains(ptr)) << "Free (" << ptr << ") not in bounds of heap " << *this;
283 }
284 num_bytes_allocated_ -= AllocationSize(ptr);
285 --num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800286 mspace_free(mspace_, ptr);
287}
288
289void AllocSpace::FreeList(size_t num_ptrs, Object** ptrs) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700290 MutexLock mu(lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700291 if (DEBUG_SPACES) {
292 CHECK(ptrs != NULL);
293 size_t num_broken_ptrs = 0;
294 for (size_t i = 0; i < num_ptrs; i++) {
295 if (!Contains(ptrs[i])) {
296 num_broken_ptrs++;
297 LOG(ERROR) << "FreeList[" << i << "] (" << ptrs[i] << ") not in bounds of heap " << *this;
298 } else {
299 size_t size = mspace_usable_size(ptrs[i]);
300 memset(ptrs[i], 0xEF, size);
301 }
Ian Rogers30fab402012-01-23 15:43:46 -0800302 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700303 CHECK_EQ(num_broken_ptrs, 0u);
Ian Rogers30fab402012-01-23 15:43:46 -0800304 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700305 for (size_t i = 0; i < num_ptrs; i++) {
306 num_bytes_allocated_ -= AllocationSize(ptrs[i]);
307 }
308 num_objects_allocated_ -= num_ptrs;
Ian Rogers30fab402012-01-23 15:43:46 -0800309 mspace_bulk_free(mspace_, reinterpret_cast<void**>(ptrs), num_ptrs);
310}
311
312// Callback from dlmalloc when it needs to increase the footprint
313extern "C" void* art_heap_morecore(void* mspace, intptr_t increment) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800314 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700315 DCHECK_EQ(heap->GetAllocSpace()->GetMspace(), mspace);
316 return heap->GetAllocSpace()->MoreCore(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800317}
318
319void* AllocSpace::MoreCore(intptr_t increment) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700320 lock_.AssertHeld();
Ian Rogers30fab402012-01-23 15:43:46 -0800321 byte* original_end = end_;
322 if (increment != 0) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800323 VLOG(heap) << "AllocSpace::MoreCore " << PrettySize(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800324 byte* new_end = original_end + increment;
325 if (increment > 0) {
326#if DEBUG_SPACES
327 // Should never be asked to increase the allocation beyond the capacity of the space. Enforced
328 // by mspace_set_footprint_limit.
329 CHECK_LE(new_end, Begin() + Capacity());
330#endif
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700331 CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800332 } else {
333#if DEBUG_SPACES
334 // Should never be asked for negative footprint (ie before begin)
335 CHECK_GT(original_end + increment, Begin());
336#endif
337 // Advise we don't need the pages and protect them
Ian Rogers3bb17a62012-01-27 23:56:44 -0800338 // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be
339 // expensive (note the same isn't true for giving permissions to a page as the protected
340 // page shouldn't be in a TLB). We should investigate performance impact of just
341 // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's
342 // likely just a useful debug feature.
Ian Rogers30fab402012-01-23 15:43:46 -0800343 size_t size = -increment;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700344 CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName());
345 CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800346 }
347 // Update end_
348 end_ = new_end;
349 }
350 return original_end;
351}
352
353size_t AllocSpace::AllocationSize(const Object* obj) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700354 return mspace_usable_size(const_cast<void*>(reinterpret_cast<const void*>(obj))) +
355 kChunkOverhead;
Ian Rogers30fab402012-01-23 15:43:46 -0800356}
357
Brian Carlstromb18e77a2012-08-21 14:20:03 -0700358void MspaceMadviseCallback(void* start, void* end, size_t used_bytes, void* /* arg */) {
359 // Is this chunk in use?
360 if (used_bytes != 0) {
361 return;
362 }
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700363 // Do we have any whole pages to give back?
364 start = reinterpret_cast<void*>(RoundUp(reinterpret_cast<uintptr_t>(start), kPageSize));
365 end = reinterpret_cast<void*>(RoundDown(reinterpret_cast<uintptr_t>(end), kPageSize));
366 if (end > start) {
367 size_t length = reinterpret_cast<byte*>(end) - reinterpret_cast<byte*>(start);
368 CHECK_MEMORY_CALL(madvise, (start, length, MADV_DONTNEED), "trim");
Ian Rogers30fab402012-01-23 15:43:46 -0800369 }
370}
371
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700372void AllocSpace::Trim() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700373 MutexLock mu(lock_);
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700374 // Trim to release memory at the end of the space.
375 mspace_trim(mspace_, 0);
376 // Visit space looking for page-sized holes to advise the kernel we don't need.
377 mspace_inspect_all(mspace_, MspaceMadviseCallback, NULL);
378}
Ian Rogers30fab402012-01-23 15:43:46 -0800379
380void AllocSpace::Walk(void(*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
381 void* arg) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 MutexLock mu(lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800383 mspace_inspect_all(mspace_, callback, arg);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700384 callback(NULL, NULL, 0, arg); // Indicate end of a space.
Ian Rogers30fab402012-01-23 15:43:46 -0800385}
386
387size_t AllocSpace::GetFootprintLimit() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700388 MutexLock mu(lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800389 return mspace_footprint_limit(mspace_);
390}
391
392void AllocSpace::SetFootprintLimit(size_t new_size) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700393 MutexLock mu(lock_);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800394 VLOG(heap) << "AllocSpace::SetFootprintLimit " << PrettySize(new_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800395 // Compare against the actual footprint, rather than the Size(), because the heap may not have
396 // grown all the way to the allowed size yet.
Ian Rogers30fab402012-01-23 15:43:46 -0800397 size_t current_space_size = mspace_footprint(mspace_);
398 if (new_size < current_space_size) {
399 // Don't let the space grow any more.
400 new_size = current_space_size;
401 }
402 mspace_set_footprint_limit(mspace_, new_size);
403}
404
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700405size_t ImageSpace::bitmap_index_ = 0;
406
407ImageSpace::ImageSpace(const std::string& name, MemMap* mem_map)
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700408 : MemMapSpace(name, mem_map, mem_map->Size(), GCRP_NEVER_COLLECT) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700409 const size_t bitmap_index = bitmap_index_++;
410 live_bitmap_.reset(SpaceBitmap::Create(
411 StringPrintf("imagespace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
412 Begin(), Capacity()));
413 DCHECK(live_bitmap_.get() != NULL) << "could not create imagespace live bitmap #" << bitmap_index;
414}
415
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700416ImageSpace* ImageSpace::Create(const std::string& image_file_name) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800417 CHECK(!image_file_name.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800418
419 uint64_t start_time = 0;
420 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
421 start_time = NanoTime();
422 LOG(INFO) << "Space::CreateImageSpace entering" << " image_file_name=" << image_file_name;
423 }
424
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700425 UniquePtr<File> file(OS::OpenFile(image_file_name.c_str(), false));
Elliott Hughes90a33692011-08-30 13:27:07 -0700426 if (file.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800427 LOG(ERROR) << "Failed to open " << image_file_name;
428 return NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700429 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700430 ImageHeader image_header;
431 bool success = file->ReadFully(&image_header, sizeof(image_header));
432 if (!success || !image_header.IsValid()) {
Ian Rogers30fab402012-01-23 15:43:46 -0800433 LOG(ERROR) << "Invalid image header " << image_file_name;
434 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700435 }
Ian Rogers30fab402012-01-23 15:43:46 -0800436 UniquePtr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
Brian Carlstrom89521892011-12-07 22:05:07 -0800437 file->Length(),
438 // TODO: selectively PROT_EXEC stubs
439 PROT_READ | PROT_WRITE | PROT_EXEC,
440 MAP_PRIVATE | MAP_FIXED,
441 file->Fd(),
442 0));
Elliott Hughes90a33692011-08-30 13:27:07 -0700443 if (map.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800444 LOG(ERROR) << "Failed to map " << image_file_name;
445 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700446 }
Ian Rogers30fab402012-01-23 15:43:46 -0800447 CHECK_EQ(image_header.GetImageBegin(), map->Begin());
448 DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700449
Ian Rogers30fab402012-01-23 15:43:46 -0800450 Runtime* runtime = Runtime::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700451 Object* jni_stub_array = image_header.GetImageRoot(ImageHeader::kJniStubArray);
Ian Rogers169c9a72011-11-13 20:13:17 -0800452 runtime->SetJniDlsymLookupStub(down_cast<ByteArray*>(jni_stub_array));
Brian Carlstrom16192862011-09-12 17:50:06 -0700453
Brian Carlstrome24fa612011-09-29 00:53:55 -0700454 Object* ame_stub_array = image_header.GetImageRoot(ImageHeader::kAbstractMethodErrorStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700455 runtime->SetAbstractMethodErrorStubArray(down_cast<ByteArray*>(ame_stub_array));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700456
Ian Rogersfb6adba2012-03-04 21:51:51 -0800457 Object* resolution_stub_array =
458 image_header.GetImageRoot(ImageHeader::kStaticResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700459 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700460 down_cast<ByteArray*>(resolution_stub_array), Runtime::kStaticMethod);
461 resolution_stub_array = image_header.GetImageRoot(ImageHeader::kUnknownMethodResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700462 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700463 down_cast<ByteArray*>(resolution_stub_array), Runtime::kUnknownMethod);
Ian Rogersad25ac52011-10-04 19:13:33 -0700464
Ian Rogers19846512012-02-24 11:42:47 -0800465 Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700466 runtime->SetResolutionMethod(down_cast<AbstractMethod*>(resolution_method));
Ian Rogers19846512012-02-24 11:42:47 -0800467
Ian Rogersff1ed472011-09-20 13:46:24 -0700468 Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700469 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kSaveAll);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700470 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700471 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsOnly);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700472 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700473 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsAndArgs);
Ian Rogersff1ed472011-09-20 13:46:24 -0700474
Ian Rogers30fab402012-01-23 15:43:46 -0800475 ImageSpace* space = new ImageSpace(image_file_name, map.release());
476 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800477 LOG(INFO) << "Space::CreateImageSpace exiting (" << PrettyDuration(NanoTime() - start_time)
478 << ") " << *space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700479 }
Ian Rogers30fab402012-01-23 15:43:46 -0800480 return space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700481}
482
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700483void ImageSpace::RecordImageAllocations(SpaceBitmap* live_bitmap) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800484 uint64_t start_time = 0;
485 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
486 LOG(INFO) << "ImageSpace::RecordImageAllocations entering";
487 start_time = NanoTime();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700488 }
Ian Rogers30fab402012-01-23 15:43:46 -0800489 DCHECK(!Runtime::Current()->IsStarted());
490 CHECK(live_bitmap != NULL);
491 byte* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
492 byte* end = End();
493 while (current < end) {
494 DCHECK_ALIGNED(current, kObjectAlignment);
495 const Object* obj = reinterpret_cast<const Object*>(current);
496 live_bitmap->Set(obj);
497 current += RoundUp(obj->SizeOf(), kObjectAlignment);
498 }
499 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800500 LOG(INFO) << "ImageSpace::RecordImageAllocations exiting ("
501 << PrettyDuration(NanoTime() - start_time) << ")";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700502 }
503}
504
Ian Rogers30fab402012-01-23 15:43:46 -0800505std::ostream& operator<<(std::ostream& os, const Space& space) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700506 space.Dump(os);
Ian Rogers30fab402012-01-23 15:43:46 -0800507 return os;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700508}
509
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700510void AllocSpace::Dump(std::ostream& os) const {
511 os << GetType()
512 << "begin=" << reinterpret_cast<void*>(Begin())
513 << ",end=" << reinterpret_cast<void*>(End())
514 << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity())
515 << ",name=\"" << GetName() << "\"]";
516}
517
518void ImageSpace::Dump(std::ostream& os) const {
519 os << GetType()
520 << "begin=" << reinterpret_cast<void*>(Begin())
521 << ",end=" << reinterpret_cast<void*>(End())
522 << ",size=" << PrettySize(Size())
523 << ",name=\"" << GetName() << "\"]";
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700524}
525
526void LargeObjectSpace::SwapBitmaps() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700527 SpaceSetMap* temp_live_objects = live_objects_.release();
528 live_objects_.reset(mark_objects_.release());
529 mark_objects_.reset(temp_live_objects);
530 // Swap names to get more descriptive diagnostics.
531 std::string temp_name = live_objects_->GetName();
532 live_objects_->SetName(mark_objects_->GetName());
533 mark_objects_->SetName(temp_name);
534}
535
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700536DiscontinuousSpace::DiscontinuousSpace(const std::string& name,
537 GcRetentionPolicy gc_retention_policy)
538 : Space(name, gc_retention_policy) {
539
540}
541
542LargeObjectSpace::LargeObjectSpace(const std::string& name)
543 : DiscontinuousSpace(name, GCRP_ALWAYS_COLLECT),
544 num_bytes_allocated_(0),
545 num_objects_allocated_(0) {
546 live_objects_.reset(new SpaceSetMap("large live objects"));
547 mark_objects_.reset(new SpaceSetMap("large marked objects"));
548}
549
550
551void LargeObjectSpace::CopyLiveToMarked() {
552 mark_objects_->CopyFrom(*live_objects_.get());
553}
554
555LargeObjectMapSpace::LargeObjectMapSpace(const std::string& name)
556 : LargeObjectSpace(name),
557 lock_("large object space lock", kAllocSpaceLock)
558{
559
560}
561
562LargeObjectMapSpace* LargeObjectMapSpace::Create(const std::string& name) {
563 return new LargeObjectMapSpace(name);
564}
565
566Object* LargeObjectMapSpace::Alloc(size_t num_bytes) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700567 MutexLock mu(lock_);
568 MemMap* mem_map = MemMap::MapAnonymous("allocation", NULL, num_bytes, PROT_READ | PROT_WRITE);
569 if (mem_map == NULL) {
570 return NULL;
571 }
572 Object* obj = reinterpret_cast<Object*>(mem_map->Begin());
573 large_objects_.push_back(obj);
574 mem_maps_.Put(obj, mem_map);
575 num_bytes_allocated_ += mem_map->Size();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700576 ++num_objects_allocated_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700577 return obj;
578}
579
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700580void LargeObjectMapSpace::Free(Object* ptr) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700581 MutexLock mu(lock_);
582 MemMaps::iterator found = mem_maps_.find(ptr);
583 CHECK(found != mem_maps_.end()) << "Attempted to free large object which was not live";
584 DCHECK_GE(num_bytes_allocated_, found->second->Size());
585 num_bytes_allocated_ -= found->second->Size();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700586 --num_objects_allocated_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700587 delete found->second;
588 mem_maps_.erase(found);
589}
590
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700591size_t LargeObjectMapSpace::AllocationSize(const Object* obj) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700592 MutexLock mu(lock_);
593 MemMaps::iterator found = mem_maps_.find(const_cast<Object*>(obj));
594 CHECK(found != mem_maps_.end()) << "Attempted to get size of a large object which is not live";
595 return found->second->Size();
596}
597
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700598void LargeObjectMapSpace::Walk(AllocSpace::WalkCallback callback, void* arg) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700599 MutexLock mu(lock_);
600 for (MemMaps::iterator it = mem_maps_.begin(); it != mem_maps_.end(); ++it) {
601 MemMap* mem_map = it->second;
602 callback(mem_map->Begin(), mem_map->End(), mem_map->Size(), arg);
603 callback(NULL, NULL, 0, arg);
604 }
605}
606
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700607bool LargeObjectMapSpace::Contains(const Object* obj) const {
608 MutexLock mu(const_cast<Mutex&>(lock_));
609 return mem_maps_.find(const_cast<Object*>(obj)) != mem_maps_.end();
610}
611
612FreeListSpace* FreeListSpace::Create(const std::string& name, size_t size) {
613 CHECK(size % kAlignment == 0);
614 MemMap* mem_map = MemMap::MapAnonymous(name.c_str(), NULL, size, PROT_READ | PROT_WRITE);
615 CHECK(mem_map != NULL) << "Failed to allocate large object space mem map";
616 return new FreeListSpace(name, mem_map, mem_map->Begin(), mem_map->End());
617}
618
619FreeListSpace::FreeListSpace(const std::string& name, MemMap* mem_map, byte* begin, byte* end)
620 : LargeObjectSpace(name),
621 begin_(begin),
622 end_(end),
623 mem_map_(mem_map),
624 lock_("free list space lock", kAllocSpaceLock) {
625 chunks_.resize(Size() / kAlignment + 1);
626 // Add a dummy chunk so we don't need to handle chunks having no next chunk.
627 chunks_.back().SetSize(kAlignment, false);
628 // Start out with one large free chunk.
629 AddFreeChunk(begin_, end_ - begin_, NULL);
630}
631
632FreeListSpace::~FreeListSpace() {
633
634}
635
636void FreeListSpace::AddFreeChunk(void* address, size_t size, Chunk* previous) {
637 Chunk* chunk = ChunkFromAddr(address);
638 chunk->SetSize(size, true);
639 chunk->SetPrevious(previous);
640 Chunk* next_chunk = GetNextChunk(chunk);
641 next_chunk->SetPrevious(chunk);
642 free_chunks_.insert(chunk);
643}
644
645FreeListSpace::Chunk* FreeListSpace::ChunkFromAddr(void* address) {
646 size_t offset = reinterpret_cast<byte*>(address) - Begin();
647 DCHECK(IsAligned<kAlignment>(offset));
648 DCHECK_LT(offset, Size());
649 return &chunks_[offset / kAlignment];
650}
651
652void* FreeListSpace::AddrFromChunk(Chunk* chunk) {
653 return reinterpret_cast<void*>(Begin() + (chunk - &chunks_.front()) * kAlignment);
654}
655
656void FreeListSpace::RemoveFreeChunk(Chunk* chunk) {
657 // TODO: C++0x
658 // TODO: Improve performance, this might be slow.
659 std::pair<FreeChunks::iterator, FreeChunks::iterator> range = free_chunks_.equal_range(chunk);
660 for (FreeChunks::iterator it = range.first; it != range.second; ++it) {
661 if (*it == chunk) {
662 free_chunks_.erase(it);
663 return;
664 }
665 }
666}
667
668void FreeListSpace::Walk(AllocSpace::WalkCallback callback, void* arg) {
669 MutexLock mu(lock_);
670 for (Chunk* chunk = &chunks_.front(); chunk < &chunks_.back(); ) {
671 if (!chunk->IsFree()) {
672 size_t size = chunk->GetSize();
673 void* begin = AddrFromChunk(chunk);
674 void* end = reinterpret_cast<void*>(reinterpret_cast<byte*>(begin) + size);
675 callback(begin, end, size, arg);
676 callback(NULL, NULL, 0, arg);
677 }
678 chunk = GetNextChunk(chunk);
679 }
680}
681
682void FreeListSpace::Free(Object* obj) {
683 MutexLock mu(lock_);
684 CHECK(Contains(obj));
685 // Check adjacent chunks to see if we need to combine.
686 Chunk* chunk = ChunkFromAddr(obj);
687 CHECK(!chunk->IsFree());
688
689 size_t allocation_size = chunk->GetSize();
690 madvise(obj, allocation_size, MADV_DONTNEED);
691 num_objects_allocated_--;
692 num_bytes_allocated_ -= allocation_size;
693 Chunk* prev = chunk->GetPrevious();
694 Chunk* next = GetNextChunk(chunk);
695
696 // Combine any adjacent free chunks
697 size_t extra_size = chunk->GetSize();
698 if (next->IsFree()) {
699 extra_size += next->GetSize();
700 RemoveFreeChunk(next);
701 }
702 if (prev != NULL && prev->IsFree()) {
703 RemoveFreeChunk(prev);
704 AddFreeChunk(AddrFromChunk(prev), prev->GetSize() + extra_size, prev->GetPrevious());
705 } else {
706 AddFreeChunk(AddrFromChunk(chunk), extra_size, prev);
707 }
708}
709
710bool FreeListSpace::Contains(const Object* obj) const {
711 return mem_map_->HasAddress(obj);
712}
713
714FreeListSpace::Chunk* FreeListSpace::GetNextChunk(Chunk* chunk) {
715 return chunk + chunk->GetSize() / kAlignment;
716}
717
718size_t FreeListSpace::AllocationSize(const Object* obj) {
719 Chunk* chunk = ChunkFromAddr(const_cast<Object*>(obj));
720 CHECK(!chunk->IsFree());
721 return chunk->GetSize();
722}
723
724Object* FreeListSpace::Alloc(size_t num_bytes) {
725 MutexLock mu(lock_);
726 num_bytes = RoundUp(num_bytes, kAlignment);
727 Chunk temp;
728 temp.SetSize(num_bytes);
729 // Find the smallest chunk at least num_bytes in size.
730 FreeChunks::iterator found = free_chunks_.lower_bound(&temp);
731 if (found == free_chunks_.end()) {
732 // Out of memory, or too much fragmentation.
733 return NULL;
734 }
735 Chunk* chunk = *found;
736 free_chunks_.erase(found);
737 CHECK(chunk->IsFree());
738 void* addr = AddrFromChunk(chunk);
739 size_t chunk_size = chunk->GetSize();
740 chunk->SetSize(num_bytes);
741 if (chunk_size > num_bytes) {
742 // Split the chunk into two chunks.
743 Chunk* new_chunk = GetNextChunk(chunk);
744 AddFreeChunk(AddrFromChunk(new_chunk), chunk_size - num_bytes, chunk);
745 }
746
747 num_objects_allocated_++;
748 num_bytes_allocated_ += num_bytes;
749 return reinterpret_cast<Object*>(addr);
750}
751
752void FreeListSpace::FreeList(size_t num_ptrs, Object** ptrs) {
753 for (size_t i = 0; i < num_ptrs; ++i) {
754 Free(ptrs[i]);
755 }
756}
757
Carl Shapiro69759ea2011-07-21 18:13:35 -0700758} // namespace art