blob: e618f07e5f655308c8b476f996d36f38a2da4db1 [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 Hughes07ed66b2012-12-12 18:34:25 -080019#include "base/logging.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080020#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080021#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080022#include "card_table.h"
Ian Rogers30fab402012-01-23 15:43:46 -080023#include "dlmalloc.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070024#include "image.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "mirror/array.h"
26#include "mirror/abstract_method.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "mirror/class-inl.h"
28#include "mirror/object-inl.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070029#include "os.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "runtime.h"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070031#include "space_bitmap.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "space_bitmap-inl.h"
33#include "thread.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080034#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "utils.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070036
37namespace art {
38
Mathieu Chartierd22d5482012-11-06 17:14:12 -080039static const bool kPrefetchDuringDlMallocFreeList = true;
40
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070041// Magic padding value that we use to check for buffer overruns.
42static const word kPaddingValue = 0xBAC0BAC0;
Ian Rogers30fab402012-01-23 15:43:46 -080043
Mathieu Chartier2fde5332012-09-14 14:51:54 -070044// TODO: Remove define macro
Ian Rogers30fab402012-01-23 15:43:46 -080045#define CHECK_MEMORY_CALL(call, args, what) \
46 do { \
47 int rc = call args; \
48 if (UNLIKELY(rc != 0)) { \
49 errno = rc; \
50 PLOG(FATAL) << # call << " failed for " << what; \
51 } \
52 } while (false)
53
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070054ImageSpace* Space::AsImageSpace() {
55 DCHECK_EQ(GetType(), kSpaceTypeImageSpace);
56 return down_cast<ImageSpace*>(down_cast<MemMapSpace*>(this));
57}
Mathieu Chartier2fde5332012-09-14 14:51:54 -070058
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070059DlMallocSpace* Space::AsAllocSpace() {
60 DCHECK_EQ(GetType(), kSpaceTypeAllocSpace);
61 return down_cast<DlMallocSpace*>(down_cast<MemMapSpace*>(this));
62}
63
64DlMallocSpace* Space::AsZygoteSpace() {
65 DCHECK_EQ(GetType(), kSpaceTypeZygoteSpace);
66 return down_cast<DlMallocSpace*>(down_cast<MemMapSpace*>(this));
67}
68
69LargeObjectSpace* Space::AsLargeObjectSpace() {
70 DCHECK_EQ(GetType(), kSpaceTypeLargeObjectSpace);
71 return reinterpret_cast<LargeObjectSpace*>(this);
Mathieu Chartier2fde5332012-09-14 14:51:54 -070072}
73
74ContinuousSpace::ContinuousSpace(const std::string& name, byte* begin, byte* end,
75 GcRetentionPolicy gc_retention_policy)
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070076 : name_(name), gc_retention_policy_(gc_retention_policy), begin_(begin), end_(end) {
77
78}
79
80DiscontinuousSpace::DiscontinuousSpace(const std::string& name,
81 GcRetentionPolicy gc_retention_policy)
82 : name_(name), gc_retention_policy_(gc_retention_policy) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -070083
84}
85
86MemMapSpace::MemMapSpace(const std::string& name, MemMap* mem_map, size_t initial_size,
87 GcRetentionPolicy gc_retention_policy)
88 : ContinuousSpace(name, mem_map->Begin(), mem_map->Begin() + initial_size, gc_retention_policy),
89 mem_map_(mem_map)
90{
91
92}
93
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070094size_t DlMallocSpace::bitmap_index_ = 0;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070095
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070096DlMallocSpace::DlMallocSpace(const std::string& name, MemMap* mem_map, void* mspace, byte* begin,
Mathieu Chartier2fde5332012-09-14 14:51:54 -070097 byte* end, size_t growth_limit)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070098 : MemMapSpace(name, mem_map, end - begin, kGcRetentionPolicyAlwaysCollect),
Mathieu Chartier155dfe92012-10-09 14:24:49 -070099 num_bytes_allocated_(0), num_objects_allocated_(0), total_bytes_allocated_(0),
100 total_objects_allocated_(0), lock_("allocation space lock", kAllocSpaceLock), mspace_(mspace),
Ian Rogers15bf2d32012-08-28 17:33:04 -0700101 growth_limit_(growth_limit) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700102 CHECK(mspace != NULL);
103
104 size_t bitmap_index = bitmap_index_++;
105
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700106 static const uintptr_t kGcCardSize = static_cast<uintptr_t>(CardTable::kCardSize);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700107 CHECK(reinterpret_cast<uintptr_t>(mem_map->Begin()) % kGcCardSize == 0);
108 CHECK(reinterpret_cast<uintptr_t>(mem_map->End()) % kGcCardSize == 0);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700109 live_bitmap_.reset(SpaceBitmap::Create(
Ian Rogersa40307e2013-02-22 11:32:44 -0800110 StringPrintf("allocspace %s live-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)),
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700111 Begin(), Capacity()));
112 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace live bitmap #" << bitmap_index;
113
114 mark_bitmap_.reset(SpaceBitmap::Create(
Ian Rogersa40307e2013-02-22 11:32:44 -0800115 StringPrintf("allocspace %s mark-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)),
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700116 Begin(), Capacity()));
117 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace mark bitmap #" << bitmap_index;
118}
119
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700120DlMallocSpace* DlMallocSpace::Create(const std::string& name, size_t initial_size, size_t
121 growth_limit, size_t capacity, byte* requested_begin) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800122 // Memory we promise to dlmalloc before it asks for morecore.
123 // Note: making this value large means that large allocations are unlikely to succeed as dlmalloc
124 // will ask for this memory from sys_alloc which will fail as the footprint (this value plus the
125 // size of the large allocation) will be greater than the footprint limit.
126 size_t starting_size = kPageSize;
Ian Rogers30fab402012-01-23 15:43:46 -0800127 uint64_t start_time = 0;
128 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
129 start_time = NanoTime();
130 VLOG(startup) << "Space::CreateAllocSpace entering " << name
Ian Rogers3bb17a62012-01-27 23:56:44 -0800131 << " initial_size=" << PrettySize(initial_size)
132 << " growth_limit=" << PrettySize(growth_limit)
133 << " capacity=" << PrettySize(capacity)
Ian Rogers30fab402012-01-23 15:43:46 -0800134 << " requested_begin=" << reinterpret_cast<void*>(requested_begin);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700135 }
Ian Rogers30fab402012-01-23 15:43:46 -0800136
137 // Sanity check arguments
Ian Rogers3bb17a62012-01-27 23:56:44 -0800138 if (starting_size > initial_size) {
139 initial_size = starting_size;
140 }
Ian Rogers30fab402012-01-23 15:43:46 -0800141 if (initial_size > growth_limit) {
142 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size ("
Ian Rogers3bb17a62012-01-27 23:56:44 -0800143 << PrettySize(initial_size) << ") is larger than its capacity ("
144 << PrettySize(growth_limit) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800145 return NULL;
146 }
147 if (growth_limit > capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800148 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity ("
149 << PrettySize(growth_limit) << ") is larger than the capacity ("
150 << PrettySize(capacity) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800151 return NULL;
152 }
153
154 // Page align growth limit and capacity which will be used to manage mmapped storage
155 growth_limit = RoundUp(growth_limit, kPageSize);
156 capacity = RoundUp(capacity, kPageSize);
157
158 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(name.c_str(), requested_begin,
159 capacity, PROT_READ | PROT_WRITE));
160 if (mem_map.get() == NULL) {
161 LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800162 << PrettySize(capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800163 return NULL;
164 }
165
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700166 void* mspace = CreateMallocSpace(mem_map->Begin(), starting_size, initial_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800167 if (mspace == NULL) {
168 LOG(ERROR) << "Failed to initialize mspace for alloc space (" << name << ")";
169 return NULL;
170 }
171
Ian Rogers3bb17a62012-01-27 23:56:44 -0800172 // Protect memory beyond the initial size.
173 byte* end = mem_map->Begin() + starting_size;
Ian Rogers30fab402012-01-23 15:43:46 -0800174 if (capacity - initial_size > 0) {
175 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name);
176 }
177
178 // Everything is set so record in immutable structure and leave
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700179 MemMap* mem_map_ptr = mem_map.release();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700180 DlMallocSpace* space = new DlMallocSpace(name, mem_map_ptr, mspace, mem_map_ptr->Begin(), end,
181 growth_limit);
Ian Rogers30fab402012-01-23 15:43:46 -0800182 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800183 LOG(INFO) << "Space::CreateAllocSpace exiting (" << PrettyDuration(NanoTime() - start_time)
184 << " ) " << *space;
Ian Rogers30fab402012-01-23 15:43:46 -0800185 }
186 return space;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700187}
188
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700189void* DlMallocSpace::CreateMallocSpace(void* begin, size_t morecore_start, size_t initial_size) {
Ian Rogers30fab402012-01-23 15:43:46 -0800190 // clear errno to allow PLOG on error
Carl Shapiro69759ea2011-07-21 18:13:35 -0700191 errno = 0;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800192 // create mspace using our backing storage starting at begin and with a footprint of
193 // morecore_start. Don't use an internal dlmalloc lock (as we already hold heap lock). When
194 // morecore_start bytes of memory is exhaused morecore will be called.
195 void* msp = create_mspace_with_base(begin, morecore_start, false /*locked*/);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700196 if (msp != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800197 // Do not allow morecore requests to succeed beyond the initial size of the heap
Ian Rogers3bb17a62012-01-27 23:56:44 -0800198 mspace_set_footprint_limit(msp, initial_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700199 } else {
Ian Rogers30fab402012-01-23 15:43:46 -0800200 PLOG(ERROR) << "create_mspace_with_base failed";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700201 }
202 return msp;
203}
204
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700205void DlMallocSpace::SwapBitmaps() {
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700206 SpaceBitmap* temp_live_bitmap = live_bitmap_.release();
207 live_bitmap_.reset(mark_bitmap_.release());
208 mark_bitmap_.reset(temp_live_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700209 // Swap names to get more descriptive diagnostics.
210 std::string temp_name = live_bitmap_->GetName();
211 live_bitmap_->SetName(mark_bitmap_->GetName());
212 mark_bitmap_->SetName(temp_name);
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700213}
214
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800215mirror::Object* DlMallocSpace::AllocWithoutGrowthLocked(size_t num_bytes) {
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700216 if (kDebugSpaces) {
217 num_bytes += sizeof(word);
218 }
219
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800220 mirror::Object* result = reinterpret_cast<mirror::Object*>(mspace_calloc(mspace_, 1, num_bytes));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700221 if (kDebugSpaces && result != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800222 CHECK(Contains(result)) << "Allocation (" << reinterpret_cast<void*>(result)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700223 << ") not in bounds of allocation space " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700224 // Put a magic pattern before and after the allocation.
225 *reinterpret_cast<word*>(reinterpret_cast<byte*>(result) + AllocationSize(result)
226 - sizeof(word) - kChunkOverhead) = kPaddingValue;
jeffhaoc1160702011-10-27 15:48:45 -0700227 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700228 size_t allocation_size = AllocationSize(result);
229 num_bytes_allocated_ += allocation_size;
230 total_bytes_allocated_ += allocation_size;
231 ++total_objects_allocated_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700232 ++num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800233 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700234}
235
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800236mirror::Object* DlMallocSpace::Alloc(Thread* self, size_t num_bytes) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700237 MutexLock mu(self, lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700238 return AllocWithoutGrowthLocked(num_bytes);
239}
240
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800241mirror::Object* DlMallocSpace::AllocWithGrowth(Thread* self, size_t num_bytes) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700242 MutexLock mu(self, lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800243 // Grow as much as possible within the mspace.
244 size_t max_allowed = Capacity();
245 mspace_set_footprint_limit(mspace_, max_allowed);
246 // Try the allocation.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800247 mirror::Object* result = AllocWithoutGrowthLocked(num_bytes);
Ian Rogers30fab402012-01-23 15:43:46 -0800248 // Shrink back down as small as possible.
249 size_t footprint = mspace_footprint(mspace_);
250 mspace_set_footprint_limit(mspace_, footprint);
251 // Return the new allocation or NULL.
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700252 CHECK(!kDebugSpaces || result == NULL || Contains(result));
Ian Rogers30fab402012-01-23 15:43:46 -0800253 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700254}
255
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700256void DlMallocSpace::SetGrowthLimit(size_t growth_limit) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700257 growth_limit = RoundUp(growth_limit, kPageSize);
258 growth_limit_ = growth_limit;
259 if (Size() > growth_limit_) {
260 end_ = begin_ + growth_limit;
261 }
262}
263
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700264DlMallocSpace* DlMallocSpace::CreateZygoteSpace() {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700265 end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700266 DCHECK(IsAligned<CardTable::kCardSize>(begin_));
267 DCHECK(IsAligned<CardTable::kCardSize>(end_));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700268 DCHECK(IsAligned<kPageSize>(begin_));
269 DCHECK(IsAligned<kPageSize>(end_));
270 size_t size = RoundUp(Size(), kPageSize);
271 // Trim the heap so that we minimize the size of the Zygote space.
272 Trim();
273 // Trim our mem-map to free unused pages.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700274 GetMemMap()->UnMapAtEnd(end_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700275 // TODO: Not hardcode these in?
276 const size_t starting_size = kPageSize;
277 const size_t initial_size = 2 * MB;
278 // Remaining size is for the new alloc space.
279 const size_t growth_limit = growth_limit_ - size;
280 const size_t capacity = Capacity() - size;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700281 VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n"
282 << "End " << reinterpret_cast<const void*>(end_) << "\n"
283 << "Size " << size << "\n"
284 << "GrowthLimit " << growth_limit_ << "\n"
285 << "Capacity " << Capacity();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700286 SetGrowthLimit(RoundUp(size, kPageSize));
287 SetFootprintLimit(RoundUp(size, kPageSize));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700288 // FIXME: Do we need reference counted pointers here?
289 // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces.
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700290 VLOG(heap) << "Creating new AllocSpace: ";
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700291 VLOG(heap) << "Size " << GetMemMap()->Size();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700292 VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit);
293 VLOG(heap) << "Capacity " << PrettySize(capacity);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700294 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(GetName().c_str(), End(), capacity, PROT_READ | PROT_WRITE));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700295 void* mspace = CreateMallocSpace(end_, starting_size, initial_size);
296 // Protect memory beyond the initial size.
297 byte* end = mem_map->Begin() + starting_size;
298 if (capacity - initial_size > 0) {
299 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name_.c_str());
300 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700301 DlMallocSpace* alloc_space =
302 new DlMallocSpace(name_, mem_map.release(), mspace, end_, end, growth_limit);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700303 live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
304 CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
305 mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
306 CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700307 name_ += "-zygote-transformed";
308 VLOG(heap) << "zygote space creation done";
309 return alloc_space;
310}
311
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800312size_t DlMallocSpace::Free(Thread* self, mirror::Object* ptr) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700313 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700314 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700315 CHECK(ptr != NULL);
316 CHECK(Contains(ptr)) << "Free (" << ptr << ") not in bounds of heap " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700317 CHECK_EQ(
318 *reinterpret_cast<word*>(reinterpret_cast<byte*>(ptr) + AllocationSize(ptr) -
319 sizeof(word) - kChunkOverhead), kPaddingValue);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700320 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800321 const size_t bytes_freed = InternalAllocationSize(ptr);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700322 num_bytes_allocated_ -= bytes_freed;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700323 --num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800324 mspace_free(mspace_, ptr);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700325 return bytes_freed;
Ian Rogers30fab402012-01-23 15:43:46 -0800326}
327
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800328size_t DlMallocSpace::FreeList(Thread* self, size_t num_ptrs, mirror::Object** ptrs) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800329 DCHECK(ptrs != NULL);
330
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700331 // Don't need the lock to calculate the size of the freed pointers.
332 size_t bytes_freed = 0;
333 for (size_t i = 0; i < num_ptrs; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800334 mirror::Object* ptr = ptrs[i];
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800335 const size_t look_ahead = 8;
336 if (kPrefetchDuringDlMallocFreeList && i + look_ahead < num_ptrs) {
337 // The head of chunk for the allocation is sizeof(size_t) behind the allocation.
338 __builtin_prefetch(reinterpret_cast<char*>(ptrs[i + look_ahead]) - sizeof(size_t));
339 }
340 bytes_freed += InternalAllocationSize(ptr);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700341 }
342
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700343 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700344 size_t num_broken_ptrs = 0;
345 for (size_t i = 0; i < num_ptrs; i++) {
346 if (!Contains(ptrs[i])) {
347 num_broken_ptrs++;
348 LOG(ERROR) << "FreeList[" << i << "] (" << ptrs[i] << ") not in bounds of heap " << *this;
349 } else {
350 size_t size = mspace_usable_size(ptrs[i]);
351 memset(ptrs[i], 0xEF, size);
352 }
Ian Rogers30fab402012-01-23 15:43:46 -0800353 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700354 CHECK_EQ(num_broken_ptrs, 0u);
Ian Rogers30fab402012-01-23 15:43:46 -0800355 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800356
357 {
358 MutexLock mu(self, lock_);
359 num_bytes_allocated_ -= bytes_freed;
360 num_objects_allocated_ -= num_ptrs;
361 mspace_bulk_free(mspace_, reinterpret_cast<void**>(ptrs), num_ptrs);
362 return bytes_freed;
363 }
Ian Rogers30fab402012-01-23 15:43:46 -0800364}
365
366// Callback from dlmalloc when it needs to increase the footprint
367extern "C" void* art_heap_morecore(void* mspace, intptr_t increment) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800368 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700369 DCHECK_EQ(heap->GetAllocSpace()->GetMspace(), mspace);
370 return heap->GetAllocSpace()->MoreCore(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800371}
372
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700373void* DlMallocSpace::MoreCore(intptr_t increment) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700374 lock_.AssertHeld(Thread::Current());
Ian Rogers30fab402012-01-23 15:43:46 -0800375 byte* original_end = end_;
376 if (increment != 0) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800377 VLOG(heap) << "AllocSpace::MoreCore " << PrettySize(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800378 byte* new_end = original_end + increment;
379 if (increment > 0) {
380#if DEBUG_SPACES
381 // Should never be asked to increase the allocation beyond the capacity of the space. Enforced
382 // by mspace_set_footprint_limit.
383 CHECK_LE(new_end, Begin() + Capacity());
384#endif
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700385 CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800386 } else {
387#if DEBUG_SPACES
388 // Should never be asked for negative footprint (ie before begin)
389 CHECK_GT(original_end + increment, Begin());
390#endif
391 // Advise we don't need the pages and protect them
Ian Rogers3bb17a62012-01-27 23:56:44 -0800392 // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be
393 // expensive (note the same isn't true for giving permissions to a page as the protected
394 // page shouldn't be in a TLB). We should investigate performance impact of just
395 // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's
396 // likely just a useful debug feature.
Ian Rogers30fab402012-01-23 15:43:46 -0800397 size_t size = -increment;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700398 CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName());
399 CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800400 }
401 // Update end_
402 end_ = new_end;
403 }
404 return original_end;
405}
406
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800407// Virtual functions can't get inlined.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800408inline size_t DlMallocSpace::InternalAllocationSize(const mirror::Object* obj) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700409 return mspace_usable_size(const_cast<void*>(reinterpret_cast<const void*>(obj))) +
410 kChunkOverhead;
Ian Rogers30fab402012-01-23 15:43:46 -0800411}
412
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800413size_t DlMallocSpace::AllocationSize(const mirror::Object* obj) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800414 return InternalAllocationSize(obj);
415}
416
Ian Rogers48931882013-01-22 14:35:16 -0800417void MspaceMadviseCallback(void* start, void* end, size_t used_bytes, void* arg) {
Brian Carlstromb18e77a2012-08-21 14:20:03 -0700418 // Is this chunk in use?
419 if (used_bytes != 0) {
420 return;
421 }
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700422 // Do we have any whole pages to give back?
423 start = reinterpret_cast<void*>(RoundUp(reinterpret_cast<uintptr_t>(start), kPageSize));
424 end = reinterpret_cast<void*>(RoundDown(reinterpret_cast<uintptr_t>(end), kPageSize));
425 if (end > start) {
426 size_t length = reinterpret_cast<byte*>(end) - reinterpret_cast<byte*>(start);
427 CHECK_MEMORY_CALL(madvise, (start, length, MADV_DONTNEED), "trim");
Ian Rogers48931882013-01-22 14:35:16 -0800428 size_t* reclaimed = reinterpret_cast<size_t*>(arg);
429 *reclaimed += length;
Ian Rogers30fab402012-01-23 15:43:46 -0800430 }
431}
432
Ian Rogers48931882013-01-22 14:35:16 -0800433size_t DlMallocSpace::Trim() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700434 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700435 // Trim to release memory at the end of the space.
436 mspace_trim(mspace_, 0);
437 // Visit space looking for page-sized holes to advise the kernel we don't need.
Ian Rogers48931882013-01-22 14:35:16 -0800438 size_t reclaimed = 0;
439 mspace_inspect_all(mspace_, MspaceMadviseCallback, &reclaimed);
440 return reclaimed;
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700441}
Ian Rogers30fab402012-01-23 15:43:46 -0800442
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700443void DlMallocSpace::Walk(void(*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
Ian Rogers30fab402012-01-23 15:43:46 -0800444 void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700445 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800446 mspace_inspect_all(mspace_, callback, arg);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700447 callback(NULL, NULL, 0, arg); // Indicate end of a space.
Ian Rogers30fab402012-01-23 15:43:46 -0800448}
449
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700450size_t DlMallocSpace::GetFootprintLimit() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700451 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800452 return mspace_footprint_limit(mspace_);
453}
454
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700455void DlMallocSpace::SetFootprintLimit(size_t new_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700456 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700457 VLOG(heap) << "DLMallocSpace::SetFootprintLimit " << PrettySize(new_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800458 // Compare against the actual footprint, rather than the Size(), because the heap may not have
459 // grown all the way to the allowed size yet.
Ian Rogers30fab402012-01-23 15:43:46 -0800460 size_t current_space_size = mspace_footprint(mspace_);
461 if (new_size < current_space_size) {
462 // Don't let the space grow any more.
463 new_size = current_space_size;
464 }
465 mspace_set_footprint_limit(mspace_, new_size);
466}
467
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700468size_t ImageSpace::bitmap_index_ = 0;
469
470ImageSpace::ImageSpace(const std::string& name, MemMap* mem_map)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700471 : MemMapSpace(name, mem_map, mem_map->Size(), kGcRetentionPolicyNeverCollect) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700472 const size_t bitmap_index = bitmap_index_++;
473 live_bitmap_.reset(SpaceBitmap::Create(
Ian Rogersa40307e2013-02-22 11:32:44 -0800474 StringPrintf("imagespace %s live-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)),
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700475 Begin(), Capacity()));
476 DCHECK(live_bitmap_.get() != NULL) << "could not create imagespace live bitmap #" << bitmap_index;
477}
478
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700479ImageSpace* ImageSpace::Create(const std::string& image_file_name) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800480 CHECK(!image_file_name.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800481
482 uint64_t start_time = 0;
483 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
484 start_time = NanoTime();
485 LOG(INFO) << "Space::CreateImageSpace entering" << " image_file_name=" << image_file_name;
486 }
487
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700488 UniquePtr<File> file(OS::OpenFile(image_file_name.c_str(), false));
Elliott Hughes90a33692011-08-30 13:27:07 -0700489 if (file.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800490 LOG(ERROR) << "Failed to open " << image_file_name;
491 return NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700492 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700493 ImageHeader image_header;
494 bool success = file->ReadFully(&image_header, sizeof(image_header));
495 if (!success || !image_header.IsValid()) {
Ian Rogers30fab402012-01-23 15:43:46 -0800496 LOG(ERROR) << "Invalid image header " << image_file_name;
497 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700498 }
Ian Rogers30fab402012-01-23 15:43:46 -0800499 UniquePtr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
Elliott Hughes76160052012-12-12 16:31:20 -0800500 file->GetLength(),
Brian Carlstrom89521892011-12-07 22:05:07 -0800501 // TODO: selectively PROT_EXEC stubs
502 PROT_READ | PROT_WRITE | PROT_EXEC,
503 MAP_PRIVATE | MAP_FIXED,
504 file->Fd(),
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800505 0,
506 false));
Elliott Hughes90a33692011-08-30 13:27:07 -0700507 if (map.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800508 LOG(ERROR) << "Failed to map " << image_file_name;
509 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700510 }
Ian Rogers30fab402012-01-23 15:43:46 -0800511 CHECK_EQ(image_header.GetImageBegin(), map->Begin());
512 DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700513
Ian Rogers30fab402012-01-23 15:43:46 -0800514 Runtime* runtime = Runtime::Current();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800515 mirror::Object* jni_stub_array = image_header.GetImageRoot(ImageHeader::kJniStubArray);
516 runtime->SetJniDlsymLookupStub(down_cast<mirror::ByteArray*>(jni_stub_array));
Brian Carlstrom16192862011-09-12 17:50:06 -0700517
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800518 mirror::Object* ame_stub_array = image_header.GetImageRoot(ImageHeader::kAbstractMethodErrorStubArray);
519 runtime->SetAbstractMethodErrorStubArray(down_cast<mirror::ByteArray*>(ame_stub_array));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700520
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800521 mirror::Object* resolution_stub_array =
Ian Rogersfb6adba2012-03-04 21:51:51 -0800522 image_header.GetImageRoot(ImageHeader::kStaticResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700523 runtime->SetResolutionStubArray(
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800524 down_cast<mirror::ByteArray*>(resolution_stub_array), Runtime::kStaticMethod);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700525 resolution_stub_array = image_header.GetImageRoot(ImageHeader::kUnknownMethodResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700526 runtime->SetResolutionStubArray(
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800527 down_cast<mirror::ByteArray*>(resolution_stub_array), Runtime::kUnknownMethod);
Ian Rogersad25ac52011-10-04 19:13:33 -0700528
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800529 mirror::Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
530 runtime->SetResolutionMethod(down_cast<mirror::AbstractMethod*>(resolution_method));
Ian Rogers19846512012-02-24 11:42:47 -0800531
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800532 mirror::Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
533 runtime->SetCalleeSaveMethod(down_cast<mirror::AbstractMethod*>(callee_save_method), Runtime::kSaveAll);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700534 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800535 runtime->SetCalleeSaveMethod(down_cast<mirror::AbstractMethod*>(callee_save_method), Runtime::kRefsOnly);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700536 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800537 runtime->SetCalleeSaveMethod(down_cast<mirror::AbstractMethod*>(callee_save_method), Runtime::kRefsAndArgs);
Ian Rogersff1ed472011-09-20 13:46:24 -0700538
Ian Rogers30fab402012-01-23 15:43:46 -0800539 ImageSpace* space = new ImageSpace(image_file_name, map.release());
540 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800541 LOG(INFO) << "Space::CreateImageSpace exiting (" << PrettyDuration(NanoTime() - start_time)
542 << ") " << *space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700543 }
Ian Rogers30fab402012-01-23 15:43:46 -0800544 return space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700545}
546
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700547void ImageSpace::RecordImageAllocations(SpaceBitmap* live_bitmap) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800548 uint64_t start_time = 0;
549 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
550 LOG(INFO) << "ImageSpace::RecordImageAllocations entering";
551 start_time = NanoTime();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700552 }
Ian Rogers30fab402012-01-23 15:43:46 -0800553 DCHECK(!Runtime::Current()->IsStarted());
554 CHECK(live_bitmap != NULL);
555 byte* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
556 byte* end = End();
557 while (current < end) {
558 DCHECK_ALIGNED(current, kObjectAlignment);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800559 const mirror::Object* obj = reinterpret_cast<const mirror::Object*>(current);
Ian Rogers30fab402012-01-23 15:43:46 -0800560 live_bitmap->Set(obj);
561 current += RoundUp(obj->SizeOf(), kObjectAlignment);
562 }
563 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800564 LOG(INFO) << "ImageSpace::RecordImageAllocations exiting ("
565 << PrettyDuration(NanoTime() - start_time) << ")";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700566 }
567}
568
Ian Rogers30fab402012-01-23 15:43:46 -0800569std::ostream& operator<<(std::ostream& os, const Space& space) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700570 space.Dump(os);
Ian Rogers30fab402012-01-23 15:43:46 -0800571 return os;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700572}
573
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700574void DlMallocSpace::Dump(std::ostream& os) const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700575 os << GetType()
576 << "begin=" << reinterpret_cast<void*>(Begin())
577 << ",end=" << reinterpret_cast<void*>(End())
578 << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity())
579 << ",name=\"" << GetName() << "\"]";
580}
581
582void ImageSpace::Dump(std::ostream& os) const {
583 os << GetType()
584 << "begin=" << reinterpret_cast<void*>(Begin())
585 << ",end=" << reinterpret_cast<void*>(End())
586 << ",size=" << PrettySize(Size())
587 << ",name=\"" << GetName() << "\"]";
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700588}
589
Carl Shapiro69759ea2011-07-21 18:13:35 -0700590} // namespace art