blob: 8595dd00ec503d5648440383d720b662619793d2 [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
Mathieu Chartierd22d5482012-11-06 17:14:12 -080031static const bool kPrefetchDuringDlMallocFreeList = true;
32
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070033// Magic padding value that we use to check for buffer overruns.
34static const word kPaddingValue = 0xBAC0BAC0;
Ian Rogers30fab402012-01-23 15:43:46 -080035
Mathieu Chartier2fde5332012-09-14 14:51:54 -070036// TODO: Remove define macro
Ian Rogers30fab402012-01-23 15:43:46 -080037#define CHECK_MEMORY_CALL(call, args, what) \
38 do { \
39 int rc = call args; \
40 if (UNLIKELY(rc != 0)) { \
41 errno = rc; \
42 PLOG(FATAL) << # call << " failed for " << what; \
43 } \
44 } while (false)
45
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070046ImageSpace* Space::AsImageSpace() {
47 DCHECK_EQ(GetType(), kSpaceTypeImageSpace);
48 return down_cast<ImageSpace*>(down_cast<MemMapSpace*>(this));
49}
Mathieu Chartier2fde5332012-09-14 14:51:54 -070050
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070051DlMallocSpace* Space::AsAllocSpace() {
52 DCHECK_EQ(GetType(), kSpaceTypeAllocSpace);
53 return down_cast<DlMallocSpace*>(down_cast<MemMapSpace*>(this));
54}
55
56DlMallocSpace* Space::AsZygoteSpace() {
57 DCHECK_EQ(GetType(), kSpaceTypeZygoteSpace);
58 return down_cast<DlMallocSpace*>(down_cast<MemMapSpace*>(this));
59}
60
61LargeObjectSpace* Space::AsLargeObjectSpace() {
62 DCHECK_EQ(GetType(), kSpaceTypeLargeObjectSpace);
63 return reinterpret_cast<LargeObjectSpace*>(this);
Mathieu Chartier2fde5332012-09-14 14:51:54 -070064}
65
66ContinuousSpace::ContinuousSpace(const std::string& name, byte* begin, byte* end,
67 GcRetentionPolicy gc_retention_policy)
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070068 : name_(name), gc_retention_policy_(gc_retention_policy), begin_(begin), end_(end) {
69
70}
71
72DiscontinuousSpace::DiscontinuousSpace(const std::string& name,
73 GcRetentionPolicy gc_retention_policy)
74 : name_(name), gc_retention_policy_(gc_retention_policy) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -070075
76}
77
78MemMapSpace::MemMapSpace(const std::string& name, MemMap* mem_map, size_t initial_size,
79 GcRetentionPolicy gc_retention_policy)
80 : ContinuousSpace(name, mem_map->Begin(), mem_map->Begin() + initial_size, gc_retention_policy),
81 mem_map_(mem_map)
82{
83
84}
85
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070086size_t DlMallocSpace::bitmap_index_ = 0;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070087
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070088DlMallocSpace::DlMallocSpace(const std::string& name, MemMap* mem_map, void* mspace, byte* begin,
Mathieu Chartier2fde5332012-09-14 14:51:54 -070089 byte* end, size_t growth_limit)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070090 : MemMapSpace(name, mem_map, end - begin, kGcRetentionPolicyAlwaysCollect),
Mathieu Chartier155dfe92012-10-09 14:24:49 -070091 num_bytes_allocated_(0), num_objects_allocated_(0), total_bytes_allocated_(0),
92 total_objects_allocated_(0), lock_("allocation space lock", kAllocSpaceLock), mspace_(mspace),
Ian Rogers15bf2d32012-08-28 17:33:04 -070093 growth_limit_(growth_limit) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070094 CHECK(mspace != NULL);
95
96 size_t bitmap_index = bitmap_index_++;
97
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070098 static const uintptr_t kGcCardSize = static_cast<uintptr_t>(CardTable::kCardSize);
Mathieu Chartier2fde5332012-09-14 14:51:54 -070099 CHECK(reinterpret_cast<uintptr_t>(mem_map->Begin()) % kGcCardSize == 0);
100 CHECK(reinterpret_cast<uintptr_t>(mem_map->End()) % kGcCardSize == 0);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700101 live_bitmap_.reset(SpaceBitmap::Create(
102 StringPrintf("allocspace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
103 Begin(), Capacity()));
104 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace live bitmap #" << bitmap_index;
105
106 mark_bitmap_.reset(SpaceBitmap::Create(
107 StringPrintf("allocspace-%s-mark-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
108 Begin(), Capacity()));
109 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace mark bitmap #" << bitmap_index;
110}
111
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700112DlMallocSpace* DlMallocSpace::Create(const std::string& name, size_t initial_size, size_t
113 growth_limit, size_t capacity, byte* requested_begin) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800114 // Memory we promise to dlmalloc before it asks for morecore.
115 // Note: making this value large means that large allocations are unlikely to succeed as dlmalloc
116 // will ask for this memory from sys_alloc which will fail as the footprint (this value plus the
117 // size of the large allocation) will be greater than the footprint limit.
118 size_t starting_size = kPageSize;
Ian Rogers30fab402012-01-23 15:43:46 -0800119 uint64_t start_time = 0;
120 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
121 start_time = NanoTime();
122 VLOG(startup) << "Space::CreateAllocSpace entering " << name
Ian Rogers3bb17a62012-01-27 23:56:44 -0800123 << " initial_size=" << PrettySize(initial_size)
124 << " growth_limit=" << PrettySize(growth_limit)
125 << " capacity=" << PrettySize(capacity)
Ian Rogers30fab402012-01-23 15:43:46 -0800126 << " requested_begin=" << reinterpret_cast<void*>(requested_begin);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700127 }
Ian Rogers30fab402012-01-23 15:43:46 -0800128
129 // Sanity check arguments
Ian Rogers3bb17a62012-01-27 23:56:44 -0800130 if (starting_size > initial_size) {
131 initial_size = starting_size;
132 }
Ian Rogers30fab402012-01-23 15:43:46 -0800133 if (initial_size > growth_limit) {
134 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size ("
Ian Rogers3bb17a62012-01-27 23:56:44 -0800135 << PrettySize(initial_size) << ") is larger than its capacity ("
136 << PrettySize(growth_limit) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800137 return NULL;
138 }
139 if (growth_limit > capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800140 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity ("
141 << PrettySize(growth_limit) << ") is larger than the capacity ("
142 << PrettySize(capacity) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800143 return NULL;
144 }
145
146 // Page align growth limit and capacity which will be used to manage mmapped storage
147 growth_limit = RoundUp(growth_limit, kPageSize);
148 capacity = RoundUp(capacity, kPageSize);
149
150 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(name.c_str(), requested_begin,
151 capacity, PROT_READ | PROT_WRITE));
152 if (mem_map.get() == NULL) {
153 LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800154 << PrettySize(capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800155 return NULL;
156 }
157
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700158 void* mspace = CreateMallocSpace(mem_map->Begin(), starting_size, initial_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800159 if (mspace == NULL) {
160 LOG(ERROR) << "Failed to initialize mspace for alloc space (" << name << ")";
161 return NULL;
162 }
163
Ian Rogers3bb17a62012-01-27 23:56:44 -0800164 // Protect memory beyond the initial size.
165 byte* end = mem_map->Begin() + starting_size;
Ian Rogers30fab402012-01-23 15:43:46 -0800166 if (capacity - initial_size > 0) {
167 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name);
168 }
169
170 // Everything is set so record in immutable structure and leave
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700171 MemMap* mem_map_ptr = mem_map.release();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700172 DlMallocSpace* space = new DlMallocSpace(name, mem_map_ptr, mspace, mem_map_ptr->Begin(), end,
173 growth_limit);
Ian Rogers30fab402012-01-23 15:43:46 -0800174 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800175 LOG(INFO) << "Space::CreateAllocSpace exiting (" << PrettyDuration(NanoTime() - start_time)
176 << " ) " << *space;
Ian Rogers30fab402012-01-23 15:43:46 -0800177 }
178 return space;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700179}
180
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700181void* DlMallocSpace::CreateMallocSpace(void* begin, size_t morecore_start, size_t initial_size) {
Ian Rogers30fab402012-01-23 15:43:46 -0800182 // clear errno to allow PLOG on error
Carl Shapiro69759ea2011-07-21 18:13:35 -0700183 errno = 0;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800184 // create mspace using our backing storage starting at begin and with a footprint of
185 // morecore_start. Don't use an internal dlmalloc lock (as we already hold heap lock). When
186 // morecore_start bytes of memory is exhaused morecore will be called.
187 void* msp = create_mspace_with_base(begin, morecore_start, false /*locked*/);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700188 if (msp != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800189 // Do not allow morecore requests to succeed beyond the initial size of the heap
Ian Rogers3bb17a62012-01-27 23:56:44 -0800190 mspace_set_footprint_limit(msp, initial_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700191 } else {
Ian Rogers30fab402012-01-23 15:43:46 -0800192 PLOG(ERROR) << "create_mspace_with_base failed";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700193 }
194 return msp;
195}
196
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700197void DlMallocSpace::SwapBitmaps() {
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700198 SpaceBitmap* temp_live_bitmap = live_bitmap_.release();
199 live_bitmap_.reset(mark_bitmap_.release());
200 mark_bitmap_.reset(temp_live_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700201 // Swap names to get more descriptive diagnostics.
202 std::string temp_name = live_bitmap_->GetName();
203 live_bitmap_->SetName(mark_bitmap_->GetName());
204 mark_bitmap_->SetName(temp_name);
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700205}
206
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700207Object* DlMallocSpace::AllocWithoutGrowthLocked(size_t num_bytes) {
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700208 if (kDebugSpaces) {
209 num_bytes += sizeof(word);
210 }
211
Ian Rogers30fab402012-01-23 15:43:46 -0800212 Object* result = reinterpret_cast<Object*>(mspace_calloc(mspace_, 1, num_bytes));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700213 if (kDebugSpaces && result != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800214 CHECK(Contains(result)) << "Allocation (" << reinterpret_cast<void*>(result)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700215 << ") not in bounds of allocation space " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700216 // Put a magic pattern before and after the allocation.
217 *reinterpret_cast<word*>(reinterpret_cast<byte*>(result) + AllocationSize(result)
218 - sizeof(word) - kChunkOverhead) = kPaddingValue;
jeffhaoc1160702011-10-27 15:48:45 -0700219 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700220 size_t allocation_size = AllocationSize(result);
221 num_bytes_allocated_ += allocation_size;
222 total_bytes_allocated_ += allocation_size;
223 ++total_objects_allocated_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700224 ++num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800225 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700226}
227
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700228Object* DlMallocSpace::Alloc(Thread* self, size_t num_bytes) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700229 MutexLock mu(self, lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 return AllocWithoutGrowthLocked(num_bytes);
231}
232
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700233Object* DlMallocSpace::AllocWithGrowth(Thread* self, size_t num_bytes) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700234 MutexLock mu(self, lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800235 // Grow as much as possible within the mspace.
236 size_t max_allowed = Capacity();
237 mspace_set_footprint_limit(mspace_, max_allowed);
238 // Try the allocation.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700239 Object* result = AllocWithoutGrowthLocked(num_bytes);
Ian Rogers30fab402012-01-23 15:43:46 -0800240 // Shrink back down as small as possible.
241 size_t footprint = mspace_footprint(mspace_);
242 mspace_set_footprint_limit(mspace_, footprint);
243 // Return the new allocation or NULL.
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700244 CHECK(!kDebugSpaces || result == NULL || Contains(result));
Ian Rogers30fab402012-01-23 15:43:46 -0800245 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700246}
247
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700248void DlMallocSpace::SetGrowthLimit(size_t growth_limit) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700249 growth_limit = RoundUp(growth_limit, kPageSize);
250 growth_limit_ = growth_limit;
251 if (Size() > growth_limit_) {
252 end_ = begin_ + growth_limit;
253 }
254}
255
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700256DlMallocSpace* DlMallocSpace::CreateZygoteSpace() {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700257 end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700258 DCHECK(IsAligned<CardTable::kCardSize>(begin_));
259 DCHECK(IsAligned<CardTable::kCardSize>(end_));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700260 DCHECK(IsAligned<kPageSize>(begin_));
261 DCHECK(IsAligned<kPageSize>(end_));
262 size_t size = RoundUp(Size(), kPageSize);
263 // Trim the heap so that we minimize the size of the Zygote space.
264 Trim();
265 // Trim our mem-map to free unused pages.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700266 GetMemMap()->UnMapAtEnd(end_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700267 // TODO: Not hardcode these in?
268 const size_t starting_size = kPageSize;
269 const size_t initial_size = 2 * MB;
270 // Remaining size is for the new alloc space.
271 const size_t growth_limit = growth_limit_ - size;
272 const size_t capacity = Capacity() - size;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700273 VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n"
274 << "End " << reinterpret_cast<const void*>(end_) << "\n"
275 << "Size " << size << "\n"
276 << "GrowthLimit " << growth_limit_ << "\n"
277 << "Capacity " << Capacity();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700278 SetGrowthLimit(RoundUp(size, kPageSize));
279 SetFootprintLimit(RoundUp(size, kPageSize));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700280 // FIXME: Do we need reference counted pointers here?
281 // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces.
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700282 VLOG(heap) << "Creating new AllocSpace: ";
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700283 VLOG(heap) << "Size " << GetMemMap()->Size();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700284 VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit);
285 VLOG(heap) << "Capacity " << PrettySize(capacity);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700286 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(GetName().c_str(), End(), capacity, PROT_READ | PROT_WRITE));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700287 void* mspace = CreateMallocSpace(end_, starting_size, initial_size);
288 // Protect memory beyond the initial size.
289 byte* end = mem_map->Begin() + starting_size;
290 if (capacity - initial_size > 0) {
291 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name_.c_str());
292 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700293 DlMallocSpace* alloc_space =
294 new DlMallocSpace(name_, mem_map.release(), mspace, end_, end, growth_limit);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700295 live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
296 CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
297 mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
298 CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700299 name_ += "-zygote-transformed";
300 VLOG(heap) << "zygote space creation done";
301 return alloc_space;
302}
303
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700304size_t DlMallocSpace::Free(Thread* self, Object* ptr) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700305 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700306 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700307 CHECK(ptr != NULL);
308 CHECK(Contains(ptr)) << "Free (" << ptr << ") not in bounds of heap " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700309 CHECK_EQ(
310 *reinterpret_cast<word*>(reinterpret_cast<byte*>(ptr) + AllocationSize(ptr) -
311 sizeof(word) - kChunkOverhead), kPaddingValue);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700312 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800313 const size_t bytes_freed = InternalAllocationSize(ptr);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700314 num_bytes_allocated_ -= bytes_freed;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700315 --num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800316 mspace_free(mspace_, ptr);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700317 return bytes_freed;
Ian Rogers30fab402012-01-23 15:43:46 -0800318}
319
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700320size_t DlMallocSpace::FreeList(Thread* self, size_t num_ptrs, Object** ptrs) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800321 DCHECK(ptrs != NULL);
322
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700323 // Don't need the lock to calculate the size of the freed pointers.
324 size_t bytes_freed = 0;
325 for (size_t i = 0; i < num_ptrs; i++) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800326 Object* ptr = ptrs[i];
327 const size_t look_ahead = 8;
328 if (kPrefetchDuringDlMallocFreeList && i + look_ahead < num_ptrs) {
329 // The head of chunk for the allocation is sizeof(size_t) behind the allocation.
330 __builtin_prefetch(reinterpret_cast<char*>(ptrs[i + look_ahead]) - sizeof(size_t));
331 }
332 bytes_freed += InternalAllocationSize(ptr);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700333 }
334
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700335 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700336 size_t num_broken_ptrs = 0;
337 for (size_t i = 0; i < num_ptrs; i++) {
338 if (!Contains(ptrs[i])) {
339 num_broken_ptrs++;
340 LOG(ERROR) << "FreeList[" << i << "] (" << ptrs[i] << ") not in bounds of heap " << *this;
341 } else {
342 size_t size = mspace_usable_size(ptrs[i]);
343 memset(ptrs[i], 0xEF, size);
344 }
Ian Rogers30fab402012-01-23 15:43:46 -0800345 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700346 CHECK_EQ(num_broken_ptrs, 0u);
Ian Rogers30fab402012-01-23 15:43:46 -0800347 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800348
349 {
350 MutexLock mu(self, lock_);
351 num_bytes_allocated_ -= bytes_freed;
352 num_objects_allocated_ -= num_ptrs;
353 mspace_bulk_free(mspace_, reinterpret_cast<void**>(ptrs), num_ptrs);
354 return bytes_freed;
355 }
Ian Rogers30fab402012-01-23 15:43:46 -0800356}
357
358// Callback from dlmalloc when it needs to increase the footprint
359extern "C" void* art_heap_morecore(void* mspace, intptr_t increment) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800360 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700361 DCHECK_EQ(heap->GetAllocSpace()->GetMspace(), mspace);
362 return heap->GetAllocSpace()->MoreCore(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800363}
364
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700365void* DlMallocSpace::MoreCore(intptr_t increment) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700366 lock_.AssertHeld(Thread::Current());
Ian Rogers30fab402012-01-23 15:43:46 -0800367 byte* original_end = end_;
368 if (increment != 0) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800369 VLOG(heap) << "AllocSpace::MoreCore " << PrettySize(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800370 byte* new_end = original_end + increment;
371 if (increment > 0) {
372#if DEBUG_SPACES
373 // Should never be asked to increase the allocation beyond the capacity of the space. Enforced
374 // by mspace_set_footprint_limit.
375 CHECK_LE(new_end, Begin() + Capacity());
376#endif
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700377 CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800378 } else {
379#if DEBUG_SPACES
380 // Should never be asked for negative footprint (ie before begin)
381 CHECK_GT(original_end + increment, Begin());
382#endif
383 // Advise we don't need the pages and protect them
Ian Rogers3bb17a62012-01-27 23:56:44 -0800384 // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be
385 // expensive (note the same isn't true for giving permissions to a page as the protected
386 // page shouldn't be in a TLB). We should investigate performance impact of just
387 // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's
388 // likely just a useful debug feature.
Ian Rogers30fab402012-01-23 15:43:46 -0800389 size_t size = -increment;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700390 CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName());
391 CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800392 }
393 // Update end_
394 end_ = new_end;
395 }
396 return original_end;
397}
398
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800399// Virtual functions can't get inlined.
400inline size_t DlMallocSpace::InternalAllocationSize(const Object* obj) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700401 return mspace_usable_size(const_cast<void*>(reinterpret_cast<const void*>(obj))) +
402 kChunkOverhead;
Ian Rogers30fab402012-01-23 15:43:46 -0800403}
404
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800405size_t DlMallocSpace::AllocationSize(const Object* obj) {
406 return InternalAllocationSize(obj);
407}
408
Brian Carlstromb18e77a2012-08-21 14:20:03 -0700409void MspaceMadviseCallback(void* start, void* end, size_t used_bytes, void* /* arg */) {
410 // Is this chunk in use?
411 if (used_bytes != 0) {
412 return;
413 }
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700414 // Do we have any whole pages to give back?
415 start = reinterpret_cast<void*>(RoundUp(reinterpret_cast<uintptr_t>(start), kPageSize));
416 end = reinterpret_cast<void*>(RoundDown(reinterpret_cast<uintptr_t>(end), kPageSize));
417 if (end > start) {
418 size_t length = reinterpret_cast<byte*>(end) - reinterpret_cast<byte*>(start);
419 CHECK_MEMORY_CALL(madvise, (start, length, MADV_DONTNEED), "trim");
Ian Rogers30fab402012-01-23 15:43:46 -0800420 }
421}
422
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700423void DlMallocSpace::Trim() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700424 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700425 // Trim to release memory at the end of the space.
426 mspace_trim(mspace_, 0);
427 // Visit space looking for page-sized holes to advise the kernel we don't need.
428 mspace_inspect_all(mspace_, MspaceMadviseCallback, NULL);
429}
Ian Rogers30fab402012-01-23 15:43:46 -0800430
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700431void DlMallocSpace::Walk(void(*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
Ian Rogers30fab402012-01-23 15:43:46 -0800432 void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700433 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800434 mspace_inspect_all(mspace_, callback, arg);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700435 callback(NULL, NULL, 0, arg); // Indicate end of a space.
Ian Rogers30fab402012-01-23 15:43:46 -0800436}
437
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700438size_t DlMallocSpace::GetFootprintLimit() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700439 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800440 return mspace_footprint_limit(mspace_);
441}
442
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700443void DlMallocSpace::SetFootprintLimit(size_t new_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700444 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700445 VLOG(heap) << "DLMallocSpace::SetFootprintLimit " << PrettySize(new_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800446 // Compare against the actual footprint, rather than the Size(), because the heap may not have
447 // grown all the way to the allowed size yet.
Ian Rogers30fab402012-01-23 15:43:46 -0800448 size_t current_space_size = mspace_footprint(mspace_);
449 if (new_size < current_space_size) {
450 // Don't let the space grow any more.
451 new_size = current_space_size;
452 }
453 mspace_set_footprint_limit(mspace_, new_size);
454}
455
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700456size_t ImageSpace::bitmap_index_ = 0;
457
458ImageSpace::ImageSpace(const std::string& name, MemMap* mem_map)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700459 : MemMapSpace(name, mem_map, mem_map->Size(), kGcRetentionPolicyNeverCollect) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700460 const size_t bitmap_index = bitmap_index_++;
461 live_bitmap_.reset(SpaceBitmap::Create(
462 StringPrintf("imagespace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
463 Begin(), Capacity()));
464 DCHECK(live_bitmap_.get() != NULL) << "could not create imagespace live bitmap #" << bitmap_index;
465}
466
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700467ImageSpace* ImageSpace::Create(const std::string& image_file_name) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800468 CHECK(!image_file_name.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800469
470 uint64_t start_time = 0;
471 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
472 start_time = NanoTime();
473 LOG(INFO) << "Space::CreateImageSpace entering" << " image_file_name=" << image_file_name;
474 }
475
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700476 UniquePtr<File> file(OS::OpenFile(image_file_name.c_str(), false));
Elliott Hughes90a33692011-08-30 13:27:07 -0700477 if (file.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800478 LOG(ERROR) << "Failed to open " << image_file_name;
479 return NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700480 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700481 ImageHeader image_header;
482 bool success = file->ReadFully(&image_header, sizeof(image_header));
483 if (!success || !image_header.IsValid()) {
Ian Rogers30fab402012-01-23 15:43:46 -0800484 LOG(ERROR) << "Invalid image header " << image_file_name;
485 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700486 }
Ian Rogers30fab402012-01-23 15:43:46 -0800487 UniquePtr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
Brian Carlstrom89521892011-12-07 22:05:07 -0800488 file->Length(),
489 // TODO: selectively PROT_EXEC stubs
490 PROT_READ | PROT_WRITE | PROT_EXEC,
491 MAP_PRIVATE | MAP_FIXED,
492 file->Fd(),
493 0));
Elliott Hughes90a33692011-08-30 13:27:07 -0700494 if (map.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800495 LOG(ERROR) << "Failed to map " << image_file_name;
496 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700497 }
Ian Rogers30fab402012-01-23 15:43:46 -0800498 CHECK_EQ(image_header.GetImageBegin(), map->Begin());
499 DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700500
Ian Rogers30fab402012-01-23 15:43:46 -0800501 Runtime* runtime = Runtime::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700502 Object* jni_stub_array = image_header.GetImageRoot(ImageHeader::kJniStubArray);
Ian Rogers169c9a72011-11-13 20:13:17 -0800503 runtime->SetJniDlsymLookupStub(down_cast<ByteArray*>(jni_stub_array));
Brian Carlstrom16192862011-09-12 17:50:06 -0700504
Brian Carlstrome24fa612011-09-29 00:53:55 -0700505 Object* ame_stub_array = image_header.GetImageRoot(ImageHeader::kAbstractMethodErrorStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700506 runtime->SetAbstractMethodErrorStubArray(down_cast<ByteArray*>(ame_stub_array));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700507
Ian Rogersfb6adba2012-03-04 21:51:51 -0800508 Object* resolution_stub_array =
509 image_header.GetImageRoot(ImageHeader::kStaticResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700510 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700511 down_cast<ByteArray*>(resolution_stub_array), Runtime::kStaticMethod);
512 resolution_stub_array = image_header.GetImageRoot(ImageHeader::kUnknownMethodResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700513 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700514 down_cast<ByteArray*>(resolution_stub_array), Runtime::kUnknownMethod);
Ian Rogersad25ac52011-10-04 19:13:33 -0700515
Ian Rogers19846512012-02-24 11:42:47 -0800516 Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700517 runtime->SetResolutionMethod(down_cast<AbstractMethod*>(resolution_method));
Ian Rogers19846512012-02-24 11:42:47 -0800518
Ian Rogersff1ed472011-09-20 13:46:24 -0700519 Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700520 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kSaveAll);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700521 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700522 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsOnly);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700523 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700524 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsAndArgs);
Ian Rogersff1ed472011-09-20 13:46:24 -0700525
Ian Rogers30fab402012-01-23 15:43:46 -0800526 ImageSpace* space = new ImageSpace(image_file_name, map.release());
527 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800528 LOG(INFO) << "Space::CreateImageSpace exiting (" << PrettyDuration(NanoTime() - start_time)
529 << ") " << *space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700530 }
Ian Rogers30fab402012-01-23 15:43:46 -0800531 return space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700532}
533
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700534void ImageSpace::RecordImageAllocations(SpaceBitmap* live_bitmap) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800535 uint64_t start_time = 0;
536 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
537 LOG(INFO) << "ImageSpace::RecordImageAllocations entering";
538 start_time = NanoTime();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700539 }
Ian Rogers30fab402012-01-23 15:43:46 -0800540 DCHECK(!Runtime::Current()->IsStarted());
541 CHECK(live_bitmap != NULL);
542 byte* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
543 byte* end = End();
544 while (current < end) {
545 DCHECK_ALIGNED(current, kObjectAlignment);
546 const Object* obj = reinterpret_cast<const Object*>(current);
547 live_bitmap->Set(obj);
548 current += RoundUp(obj->SizeOf(), kObjectAlignment);
549 }
550 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800551 LOG(INFO) << "ImageSpace::RecordImageAllocations exiting ("
552 << PrettyDuration(NanoTime() - start_time) << ")";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700553 }
554}
555
Ian Rogers30fab402012-01-23 15:43:46 -0800556std::ostream& operator<<(std::ostream& os, const Space& space) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700557 space.Dump(os);
Ian Rogers30fab402012-01-23 15:43:46 -0800558 return os;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700559}
560
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700561void DlMallocSpace::Dump(std::ostream& os) const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700562 os << GetType()
563 << "begin=" << reinterpret_cast<void*>(Begin())
564 << ",end=" << reinterpret_cast<void*>(End())
565 << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity())
566 << ",name=\"" << GetName() << "\"]";
567}
568
569void ImageSpace::Dump(std::ostream& os) const {
570 os << GetType()
571 << "begin=" << reinterpret_cast<void*>(Begin())
572 << ",end=" << reinterpret_cast<void*>(End())
573 << ",size=" << PrettySize(Size())
574 << ",name=\"" << GetName() << "\"]";
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700575}
576
Carl Shapiro69759ea2011-07-21 18:13:35 -0700577} // namespace art