blob: 9c8819b21ef05c9a85cc50abab9196acfb2b527b [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "space.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070018
Elliott Hughes90a33692011-08-30 13:27:07 -070019#include "UniquePtr.h"
Ian Rogers30fab402012-01-23 15:43:46 -080020#include "dlmalloc.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070021#include "file.h"
22#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070023#include "logging.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070024#include "os.h"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070025#include "space_bitmap.h"
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070026#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "utils.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070028
29namespace art {
30
Ian Rogers30fab402012-01-23 15:43:46 -080031#ifndef NDEBUG
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070032static const bool kDebugSpaces = true;
Mathieu Chartier2fde5332012-09-14 14:51:54 -070033#else
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070034static const bool kDebugSpaces = false;
Ian Rogers30fab402012-01-23 15:43:46 -080035#endif
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070036// Magic padding value that we use to check for buffer overruns.
37static const word kPaddingValue = 0xBAC0BAC0;
Ian Rogers30fab402012-01-23 15:43:46 -080038
Mathieu Chartier2fde5332012-09-14 14:51:54 -070039// TODO: Remove define macro
Ian Rogers30fab402012-01-23 15:43:46 -080040#define CHECK_MEMORY_CALL(call, args, what) \
41 do { \
42 int rc = call args; \
43 if (UNLIKELY(rc != 0)) { \
44 errno = rc; \
45 PLOG(FATAL) << # call << " failed for " << what; \
46 } \
47 } while (false)
48
Mathieu Chartier2fde5332012-09-14 14:51:54 -070049Space::Space(const std::string& name, GcRetentionPolicy gc_retention_policy)
50 : name_(name),
51 gc_retention_policy_(gc_retention_policy) {
52
53}
54
55ContinuousSpace::ContinuousSpace(const std::string& name, byte* begin, byte* end,
56 GcRetentionPolicy gc_retention_policy)
57 : Space(name, gc_retention_policy),
58 begin_(begin),
59 end_(end) {
60
61}
62
63MemMapSpace::MemMapSpace(const std::string& name, MemMap* mem_map, size_t initial_size,
64 GcRetentionPolicy gc_retention_policy)
65 : ContinuousSpace(name, mem_map->Begin(), mem_map->Begin() + initial_size, gc_retention_policy),
66 mem_map_(mem_map)
67{
68
69}
70
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070071size_t AllocSpace::bitmap_index_ = 0;
72
Mathieu Chartier2fde5332012-09-14 14:51:54 -070073AllocSpace::AllocSpace(const std::string& name, MemMap* mem_map, void* mspace, byte* begin,
74 byte* end, size_t growth_limit)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070075 : MemMapSpace(name, mem_map, end - begin, kGcRetentionPolicyAlwaysCollect),
Mathieu Chartier2fde5332012-09-14 14:51:54 -070076 num_bytes_allocated_(0), num_objects_allocated_(0),
Ian Rogers15bf2d32012-08-28 17:33:04 -070077 lock_("allocation space lock", kAllocSpaceLock), mspace_(mspace),
78 growth_limit_(growth_limit) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070079 CHECK(mspace != NULL);
80
81 size_t bitmap_index = bitmap_index_++;
82
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070083 static const uintptr_t kGcCardSize = static_cast<uintptr_t>(CardTable::kCardSize);
Mathieu Chartier2fde5332012-09-14 14:51:54 -070084 CHECK(reinterpret_cast<uintptr_t>(mem_map->Begin()) % kGcCardSize == 0);
85 CHECK(reinterpret_cast<uintptr_t>(mem_map->End()) % kGcCardSize == 0);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070086 live_bitmap_.reset(SpaceBitmap::Create(
87 StringPrintf("allocspace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
88 Begin(), Capacity()));
89 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace live bitmap #" << bitmap_index;
90
91 mark_bitmap_.reset(SpaceBitmap::Create(
92 StringPrintf("allocspace-%s-mark-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
93 Begin(), Capacity()));
94 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace mark bitmap #" << bitmap_index;
95}
96
Mathieu Chartier2fde5332012-09-14 14:51:54 -070097AllocSpace* AllocSpace::Create(const std::string& name, size_t initial_size, size_t growth_limit,
98 size_t capacity, byte* requested_begin) {
Ian Rogers3bb17a62012-01-27 23:56:44 -080099 // Memory we promise to dlmalloc before it asks for morecore.
100 // Note: making this value large means that large allocations are unlikely to succeed as dlmalloc
101 // will ask for this memory from sys_alloc which will fail as the footprint (this value plus the
102 // size of the large allocation) will be greater than the footprint limit.
103 size_t starting_size = kPageSize;
Ian Rogers30fab402012-01-23 15:43:46 -0800104 uint64_t start_time = 0;
105 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
106 start_time = NanoTime();
107 VLOG(startup) << "Space::CreateAllocSpace entering " << name
Ian Rogers3bb17a62012-01-27 23:56:44 -0800108 << " initial_size=" << PrettySize(initial_size)
109 << " growth_limit=" << PrettySize(growth_limit)
110 << " capacity=" << PrettySize(capacity)
Ian Rogers30fab402012-01-23 15:43:46 -0800111 << " requested_begin=" << reinterpret_cast<void*>(requested_begin);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700112 }
Ian Rogers30fab402012-01-23 15:43:46 -0800113
114 // Sanity check arguments
Ian Rogers3bb17a62012-01-27 23:56:44 -0800115 if (starting_size > initial_size) {
116 initial_size = starting_size;
117 }
Ian Rogers30fab402012-01-23 15:43:46 -0800118 if (initial_size > growth_limit) {
119 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size ("
Ian Rogers3bb17a62012-01-27 23:56:44 -0800120 << PrettySize(initial_size) << ") is larger than its capacity ("
121 << PrettySize(growth_limit) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800122 return NULL;
123 }
124 if (growth_limit > capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800125 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity ("
126 << PrettySize(growth_limit) << ") is larger than the capacity ("
127 << PrettySize(capacity) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800128 return NULL;
129 }
130
131 // Page align growth limit and capacity which will be used to manage mmapped storage
132 growth_limit = RoundUp(growth_limit, kPageSize);
133 capacity = RoundUp(capacity, kPageSize);
134
135 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(name.c_str(), requested_begin,
136 capacity, PROT_READ | PROT_WRITE));
137 if (mem_map.get() == NULL) {
138 LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800139 << PrettySize(capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800140 return NULL;
141 }
142
Ian Rogers3bb17a62012-01-27 23:56:44 -0800143 void* mspace = AllocSpace::CreateMallocSpace(mem_map->Begin(), starting_size, initial_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800144 if (mspace == NULL) {
145 LOG(ERROR) << "Failed to initialize mspace for alloc space (" << name << ")";
146 return NULL;
147 }
148
Ian Rogers3bb17a62012-01-27 23:56:44 -0800149 // Protect memory beyond the initial size.
150 byte* end = mem_map->Begin() + starting_size;
Ian Rogers30fab402012-01-23 15:43:46 -0800151 if (capacity - initial_size > 0) {
152 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name);
153 }
154
155 // Everything is set so record in immutable structure and leave
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700156 MemMap* mem_map_ptr = mem_map.release();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700157 AllocSpace* space = new AllocSpace(name, mem_map_ptr, mspace, mem_map_ptr->Begin(), end,
158 growth_limit);
Ian Rogers30fab402012-01-23 15:43:46 -0800159 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800160 LOG(INFO) << "Space::CreateAllocSpace exiting (" << PrettyDuration(NanoTime() - start_time)
161 << " ) " << *space;
Ian Rogers30fab402012-01-23 15:43:46 -0800162 }
163 return space;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700164}
165
Ian Rogers3bb17a62012-01-27 23:56:44 -0800166void* AllocSpace::CreateMallocSpace(void* begin, size_t morecore_start, size_t initial_size) {
Ian Rogers30fab402012-01-23 15:43:46 -0800167 // clear errno to allow PLOG on error
Carl Shapiro69759ea2011-07-21 18:13:35 -0700168 errno = 0;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800169 // create mspace using our backing storage starting at begin and with a footprint of
170 // morecore_start. Don't use an internal dlmalloc lock (as we already hold heap lock). When
171 // morecore_start bytes of memory is exhaused morecore will be called.
172 void* msp = create_mspace_with_base(begin, morecore_start, false /*locked*/);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700173 if (msp != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800174 // Do not allow morecore requests to succeed beyond the initial size of the heap
Ian Rogers3bb17a62012-01-27 23:56:44 -0800175 mspace_set_footprint_limit(msp, initial_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700176 } else {
Ian Rogers30fab402012-01-23 15:43:46 -0800177 PLOG(ERROR) << "create_mspace_with_base failed";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700178 }
179 return msp;
180}
181
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700182void AllocSpace::SwapBitmaps() {
183 SpaceBitmap* temp_live_bitmap = live_bitmap_.release();
184 live_bitmap_.reset(mark_bitmap_.release());
185 mark_bitmap_.reset(temp_live_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700186 // Swap names to get more descriptive diagnostics.
187 std::string temp_name = live_bitmap_->GetName();
188 live_bitmap_->SetName(mark_bitmap_->GetName());
189 mark_bitmap_->SetName(temp_name);
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700190}
191
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700192Object* AllocSpace::AllocWithoutGrowthLocked(size_t num_bytes) {
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700193 if (kDebugSpaces) {
194 num_bytes += sizeof(word);
195 }
196
Ian Rogers30fab402012-01-23 15:43:46 -0800197 Object* result = reinterpret_cast<Object*>(mspace_calloc(mspace_, 1, num_bytes));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700198 if (kDebugSpaces && result != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800199 CHECK(Contains(result)) << "Allocation (" << reinterpret_cast<void*>(result)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700200 << ") not in bounds of allocation space " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700201 // Put a magic pattern before and after the allocation.
202 *reinterpret_cast<word*>(reinterpret_cast<byte*>(result) + AllocationSize(result)
203 - sizeof(word) - kChunkOverhead) = kPaddingValue;
jeffhaoc1160702011-10-27 15:48:45 -0700204 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700205 num_bytes_allocated_ += AllocationSize(result);
206 ++num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800207 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700208}
209
Ian Rogers50b35e22012-10-04 10:09:15 -0700210Object* AllocSpace::AllocWithoutGrowth(Thread* self, size_t num_bytes) {
211 MutexLock mu(self, lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700212 return AllocWithoutGrowthLocked(num_bytes);
213}
214
Ian Rogers50b35e22012-10-04 10:09:15 -0700215Object* AllocSpace::AllocWithGrowth(Thread* self, size_t num_bytes) {
216 MutexLock mu(self, lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800217 // Grow as much as possible within the mspace.
218 size_t max_allowed = Capacity();
219 mspace_set_footprint_limit(mspace_, max_allowed);
220 // Try the allocation.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700221 void* ptr = AllocWithoutGrowthLocked(num_bytes);
Ian Rogers30fab402012-01-23 15:43:46 -0800222 // Shrink back down as small as possible.
223 size_t footprint = mspace_footprint(mspace_);
224 mspace_set_footprint_limit(mspace_, footprint);
225 // Return the new allocation or NULL.
226 Object* result = reinterpret_cast<Object*>(ptr);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700227 CHECK(!kDebugSpaces || result == NULL || Contains(result));
Ian Rogers30fab402012-01-23 15:43:46 -0800228 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700229}
230
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700231void AllocSpace::SetGrowthLimit(size_t growth_limit) {
232 growth_limit = RoundUp(growth_limit, kPageSize);
233 growth_limit_ = growth_limit;
234 if (Size() > growth_limit_) {
235 end_ = begin_ + growth_limit;
236 }
237}
238
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700239AllocSpace* AllocSpace::CreateZygoteSpace() {
240 end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700241 DCHECK(IsAligned<CardTable::kCardSize>(begin_));
242 DCHECK(IsAligned<CardTable::kCardSize>(end_));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700243 DCHECK(IsAligned<kPageSize>(begin_));
244 DCHECK(IsAligned<kPageSize>(end_));
245 size_t size = RoundUp(Size(), kPageSize);
246 // Trim the heap so that we minimize the size of the Zygote space.
247 Trim();
248 // Trim our mem-map to free unused pages.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700249 GetMemMap()->UnMapAtEnd(end_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700250 // TODO: Not hardcode these in?
251 const size_t starting_size = kPageSize;
252 const size_t initial_size = 2 * MB;
253 // Remaining size is for the new alloc space.
254 const size_t growth_limit = growth_limit_ - size;
255 const size_t capacity = Capacity() - size;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700256 VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n"
257 << "End " << reinterpret_cast<const void*>(end_) << "\n"
258 << "Size " << size << "\n"
259 << "GrowthLimit " << growth_limit_ << "\n"
260 << "Capacity " << Capacity();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700261 SetGrowthLimit(RoundUp(size, kPageSize));
262 SetFootprintLimit(RoundUp(size, kPageSize));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700263 // FIXME: Do we need reference counted pointers here?
264 // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces.
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700265 VLOG(heap) << "Creating new AllocSpace: ";
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700266 VLOG(heap) << "Size " << GetMemMap()->Size();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700267 VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit);
268 VLOG(heap) << "Capacity " << PrettySize(capacity);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700269 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(GetName().c_str(), End(), capacity, PROT_READ | PROT_WRITE));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700270 void* mspace = CreateMallocSpace(end_, starting_size, initial_size);
271 // Protect memory beyond the initial size.
272 byte* end = mem_map->Begin() + starting_size;
273 if (capacity - initial_size > 0) {
274 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name_.c_str());
275 }
276 AllocSpace* alloc_space = new AllocSpace(name_, mem_map.release(), mspace, end_, end, growth_limit);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700277 live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
278 CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
279 mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
280 CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700281 name_ += "-zygote-transformed";
282 VLOG(heap) << "zygote space creation done";
283 return alloc_space;
284}
285
Ian Rogers50b35e22012-10-04 10:09:15 -0700286void AllocSpace::Free(Thread* self, Object* ptr) {
287 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700288 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700289 CHECK(ptr != NULL);
290 CHECK(Contains(ptr)) << "Free (" << ptr << ") not in bounds of heap " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700291 CHECK_EQ(
292 *reinterpret_cast<word*>(reinterpret_cast<byte*>(ptr) + AllocationSize(ptr) -
293 sizeof(word) - kChunkOverhead), kPaddingValue);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700294 }
295 num_bytes_allocated_ -= AllocationSize(ptr);
296 --num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800297 mspace_free(mspace_, ptr);
298}
299
Ian Rogers50b35e22012-10-04 10:09:15 -0700300void AllocSpace::FreeList(Thread* self, size_t num_ptrs, Object** ptrs) {
301 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700302 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700303 CHECK(ptrs != NULL);
304 size_t num_broken_ptrs = 0;
305 for (size_t i = 0; i < num_ptrs; i++) {
306 if (!Contains(ptrs[i])) {
307 num_broken_ptrs++;
308 LOG(ERROR) << "FreeList[" << i << "] (" << ptrs[i] << ") not in bounds of heap " << *this;
309 } else {
310 size_t size = mspace_usable_size(ptrs[i]);
311 memset(ptrs[i], 0xEF, size);
312 }
Ian Rogers30fab402012-01-23 15:43:46 -0800313 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700314 CHECK_EQ(num_broken_ptrs, 0u);
Ian Rogers30fab402012-01-23 15:43:46 -0800315 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700316 for (size_t i = 0; i < num_ptrs; i++) {
317 num_bytes_allocated_ -= AllocationSize(ptrs[i]);
318 }
319 num_objects_allocated_ -= num_ptrs;
Ian Rogers30fab402012-01-23 15:43:46 -0800320 mspace_bulk_free(mspace_, reinterpret_cast<void**>(ptrs), num_ptrs);
321}
322
323// Callback from dlmalloc when it needs to increase the footprint
324extern "C" void* art_heap_morecore(void* mspace, intptr_t increment) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800325 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700326 DCHECK_EQ(heap->GetAllocSpace()->GetMspace(), mspace);
327 return heap->GetAllocSpace()->MoreCore(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800328}
329
330void* AllocSpace::MoreCore(intptr_t increment) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700331 lock_.AssertHeld(Thread::Current());
Ian Rogers30fab402012-01-23 15:43:46 -0800332 byte* original_end = end_;
333 if (increment != 0) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800334 VLOG(heap) << "AllocSpace::MoreCore " << PrettySize(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800335 byte* new_end = original_end + increment;
336 if (increment > 0) {
337#if DEBUG_SPACES
338 // Should never be asked to increase the allocation beyond the capacity of the space. Enforced
339 // by mspace_set_footprint_limit.
340 CHECK_LE(new_end, Begin() + Capacity());
341#endif
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700342 CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800343 } else {
344#if DEBUG_SPACES
345 // Should never be asked for negative footprint (ie before begin)
346 CHECK_GT(original_end + increment, Begin());
347#endif
348 // Advise we don't need the pages and protect them
Ian Rogers3bb17a62012-01-27 23:56:44 -0800349 // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be
350 // expensive (note the same isn't true for giving permissions to a page as the protected
351 // page shouldn't be in a TLB). We should investigate performance impact of just
352 // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's
353 // likely just a useful debug feature.
Ian Rogers30fab402012-01-23 15:43:46 -0800354 size_t size = -increment;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700355 CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName());
356 CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800357 }
358 // Update end_
359 end_ = new_end;
360 }
361 return original_end;
362}
363
364size_t AllocSpace::AllocationSize(const Object* obj) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700365 return mspace_usable_size(const_cast<void*>(reinterpret_cast<const void*>(obj))) +
366 kChunkOverhead;
Ian Rogers30fab402012-01-23 15:43:46 -0800367}
368
Brian Carlstromb18e77a2012-08-21 14:20:03 -0700369void MspaceMadviseCallback(void* start, void* end, size_t used_bytes, void* /* arg */) {
370 // Is this chunk in use?
371 if (used_bytes != 0) {
372 return;
373 }
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700374 // Do we have any whole pages to give back?
375 start = reinterpret_cast<void*>(RoundUp(reinterpret_cast<uintptr_t>(start), kPageSize));
376 end = reinterpret_cast<void*>(RoundDown(reinterpret_cast<uintptr_t>(end), kPageSize));
377 if (end > start) {
378 size_t length = reinterpret_cast<byte*>(end) - reinterpret_cast<byte*>(start);
379 CHECK_MEMORY_CALL(madvise, (start, length, MADV_DONTNEED), "trim");
Ian Rogers30fab402012-01-23 15:43:46 -0800380 }
381}
382
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700383void AllocSpace::Trim() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700384 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700385 // Trim to release memory at the end of the space.
386 mspace_trim(mspace_, 0);
387 // Visit space looking for page-sized holes to advise the kernel we don't need.
388 mspace_inspect_all(mspace_, MspaceMadviseCallback, NULL);
389}
Ian Rogers30fab402012-01-23 15:43:46 -0800390
391void AllocSpace::Walk(void(*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
392 void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700393 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800394 mspace_inspect_all(mspace_, callback, arg);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700395 callback(NULL, NULL, 0, arg); // Indicate end of a space.
Ian Rogers30fab402012-01-23 15:43:46 -0800396}
397
398size_t AllocSpace::GetFootprintLimit() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700399 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800400 return mspace_footprint_limit(mspace_);
401}
402
403void AllocSpace::SetFootprintLimit(size_t new_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700404 MutexLock mu(Thread::Current(), lock_);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800405 VLOG(heap) << "AllocSpace::SetFootprintLimit " << PrettySize(new_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800406 // Compare against the actual footprint, rather than the Size(), because the heap may not have
407 // grown all the way to the allowed size yet.
Ian Rogers30fab402012-01-23 15:43:46 -0800408 size_t current_space_size = mspace_footprint(mspace_);
409 if (new_size < current_space_size) {
410 // Don't let the space grow any more.
411 new_size = current_space_size;
412 }
413 mspace_set_footprint_limit(mspace_, new_size);
414}
415
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700416size_t ImageSpace::bitmap_index_ = 0;
417
418ImageSpace::ImageSpace(const std::string& name, MemMap* mem_map)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700419 : MemMapSpace(name, mem_map, mem_map->Size(), kGcRetentionPolicyNeverCollect) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700420 const size_t bitmap_index = bitmap_index_++;
421 live_bitmap_.reset(SpaceBitmap::Create(
422 StringPrintf("imagespace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
423 Begin(), Capacity()));
424 DCHECK(live_bitmap_.get() != NULL) << "could not create imagespace live bitmap #" << bitmap_index;
425}
426
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700427ImageSpace* ImageSpace::Create(const std::string& image_file_name) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800428 CHECK(!image_file_name.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800429
430 uint64_t start_time = 0;
431 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
432 start_time = NanoTime();
433 LOG(INFO) << "Space::CreateImageSpace entering" << " image_file_name=" << image_file_name;
434 }
435
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700436 UniquePtr<File> file(OS::OpenFile(image_file_name.c_str(), false));
Elliott Hughes90a33692011-08-30 13:27:07 -0700437 if (file.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800438 LOG(ERROR) << "Failed to open " << image_file_name;
439 return NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700440 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700441 ImageHeader image_header;
442 bool success = file->ReadFully(&image_header, sizeof(image_header));
443 if (!success || !image_header.IsValid()) {
Ian Rogers30fab402012-01-23 15:43:46 -0800444 LOG(ERROR) << "Invalid image header " << image_file_name;
445 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700446 }
Ian Rogers30fab402012-01-23 15:43:46 -0800447 UniquePtr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
Brian Carlstrom89521892011-12-07 22:05:07 -0800448 file->Length(),
449 // TODO: selectively PROT_EXEC stubs
450 PROT_READ | PROT_WRITE | PROT_EXEC,
451 MAP_PRIVATE | MAP_FIXED,
452 file->Fd(),
453 0));
Elliott Hughes90a33692011-08-30 13:27:07 -0700454 if (map.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800455 LOG(ERROR) << "Failed to map " << image_file_name;
456 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700457 }
Ian Rogers30fab402012-01-23 15:43:46 -0800458 CHECK_EQ(image_header.GetImageBegin(), map->Begin());
459 DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700460
Ian Rogers30fab402012-01-23 15:43:46 -0800461 Runtime* runtime = Runtime::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700462 Object* jni_stub_array = image_header.GetImageRoot(ImageHeader::kJniStubArray);
Ian Rogers169c9a72011-11-13 20:13:17 -0800463 runtime->SetJniDlsymLookupStub(down_cast<ByteArray*>(jni_stub_array));
Brian Carlstrom16192862011-09-12 17:50:06 -0700464
Brian Carlstrome24fa612011-09-29 00:53:55 -0700465 Object* ame_stub_array = image_header.GetImageRoot(ImageHeader::kAbstractMethodErrorStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700466 runtime->SetAbstractMethodErrorStubArray(down_cast<ByteArray*>(ame_stub_array));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700467
Ian Rogersfb6adba2012-03-04 21:51:51 -0800468 Object* resolution_stub_array =
469 image_header.GetImageRoot(ImageHeader::kStaticResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700470 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700471 down_cast<ByteArray*>(resolution_stub_array), Runtime::kStaticMethod);
472 resolution_stub_array = image_header.GetImageRoot(ImageHeader::kUnknownMethodResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700473 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700474 down_cast<ByteArray*>(resolution_stub_array), Runtime::kUnknownMethod);
Ian Rogersad25ac52011-10-04 19:13:33 -0700475
Ian Rogers19846512012-02-24 11:42:47 -0800476 Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700477 runtime->SetResolutionMethod(down_cast<AbstractMethod*>(resolution_method));
Ian Rogers19846512012-02-24 11:42:47 -0800478
Ian Rogersff1ed472011-09-20 13:46:24 -0700479 Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700480 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kSaveAll);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700481 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700482 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsOnly);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700483 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700484 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsAndArgs);
Ian Rogersff1ed472011-09-20 13:46:24 -0700485
Ian Rogers30fab402012-01-23 15:43:46 -0800486 ImageSpace* space = new ImageSpace(image_file_name, map.release());
487 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800488 LOG(INFO) << "Space::CreateImageSpace exiting (" << PrettyDuration(NanoTime() - start_time)
489 << ") " << *space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700490 }
Ian Rogers30fab402012-01-23 15:43:46 -0800491 return space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700492}
493
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700494void ImageSpace::RecordImageAllocations(SpaceBitmap* live_bitmap) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800495 uint64_t start_time = 0;
496 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
497 LOG(INFO) << "ImageSpace::RecordImageAllocations entering";
498 start_time = NanoTime();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700499 }
Ian Rogers30fab402012-01-23 15:43:46 -0800500 DCHECK(!Runtime::Current()->IsStarted());
501 CHECK(live_bitmap != NULL);
502 byte* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
503 byte* end = End();
504 while (current < end) {
505 DCHECK_ALIGNED(current, kObjectAlignment);
506 const Object* obj = reinterpret_cast<const Object*>(current);
507 live_bitmap->Set(obj);
508 current += RoundUp(obj->SizeOf(), kObjectAlignment);
509 }
510 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800511 LOG(INFO) << "ImageSpace::RecordImageAllocations exiting ("
512 << PrettyDuration(NanoTime() - start_time) << ")";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700513 }
514}
515
Ian Rogers30fab402012-01-23 15:43:46 -0800516std::ostream& operator<<(std::ostream& os, const Space& space) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700517 space.Dump(os);
Ian Rogers30fab402012-01-23 15:43:46 -0800518 return os;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700519}
520
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700521void AllocSpace::Dump(std::ostream& os) const {
522 os << GetType()
523 << "begin=" << reinterpret_cast<void*>(Begin())
524 << ",end=" << reinterpret_cast<void*>(End())
525 << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity())
526 << ",name=\"" << GetName() << "\"]";
527}
528
529void ImageSpace::Dump(std::ostream& os) const {
530 os << GetType()
531 << "begin=" << reinterpret_cast<void*>(Begin())
532 << ",end=" << reinterpret_cast<void*>(End())
533 << ",size=" << PrettySize(Size())
534 << ",name=\"" << GetName() << "\"]";
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700535}
536
537void LargeObjectSpace::SwapBitmaps() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700538 SpaceSetMap* temp_live_objects = live_objects_.release();
539 live_objects_.reset(mark_objects_.release());
540 mark_objects_.reset(temp_live_objects);
541 // Swap names to get more descriptive diagnostics.
542 std::string temp_name = live_objects_->GetName();
543 live_objects_->SetName(mark_objects_->GetName());
544 mark_objects_->SetName(temp_name);
545}
546
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700547DiscontinuousSpace::DiscontinuousSpace(const std::string& name,
548 GcRetentionPolicy gc_retention_policy)
549 : Space(name, gc_retention_policy) {
550
551}
552
553LargeObjectSpace::LargeObjectSpace(const std::string& name)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700554 : DiscontinuousSpace(name, kGcRetentionPolicyAlwaysCollect),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700555 num_bytes_allocated_(0),
556 num_objects_allocated_(0) {
557 live_objects_.reset(new SpaceSetMap("large live objects"));
558 mark_objects_.reset(new SpaceSetMap("large marked objects"));
559}
560
561
562void LargeObjectSpace::CopyLiveToMarked() {
563 mark_objects_->CopyFrom(*live_objects_.get());
564}
565
566LargeObjectMapSpace::LargeObjectMapSpace(const std::string& name)
567 : LargeObjectSpace(name),
568 lock_("large object space lock", kAllocSpaceLock)
569{
570
571}
572
573LargeObjectMapSpace* LargeObjectMapSpace::Create(const std::string& name) {
574 return new LargeObjectMapSpace(name);
575}
576
Ian Rogers50b35e22012-10-04 10:09:15 -0700577Object* LargeObjectMapSpace::Alloc(Thread* self, size_t num_bytes) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700578 MemMap* mem_map = MemMap::MapAnonymous("allocation", NULL, num_bytes, PROT_READ | PROT_WRITE);
579 if (mem_map == NULL) {
580 return NULL;
581 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700582 MutexLock mu(self, lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700583 Object* obj = reinterpret_cast<Object*>(mem_map->Begin());
584 large_objects_.push_back(obj);
585 mem_maps_.Put(obj, mem_map);
586 num_bytes_allocated_ += mem_map->Size();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700587 ++num_objects_allocated_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700588 return obj;
589}
590
Ian Rogers50b35e22012-10-04 10:09:15 -0700591void LargeObjectMapSpace::Free(Thread* self, Object* ptr) {
592 MutexLock mu(self, lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700593 MemMaps::iterator found = mem_maps_.find(ptr);
594 CHECK(found != mem_maps_.end()) << "Attempted to free large object which was not live";
595 DCHECK_GE(num_bytes_allocated_, found->second->Size());
596 num_bytes_allocated_ -= found->second->Size();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700597 --num_objects_allocated_;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700598 delete found->second;
599 mem_maps_.erase(found);
600}
601
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700602size_t LargeObjectMapSpace::AllocationSize(const Object* obj) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700603 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700604 MemMaps::iterator found = mem_maps_.find(const_cast<Object*>(obj));
605 CHECK(found != mem_maps_.end()) << "Attempted to get size of a large object which is not live";
606 return found->second->Size();
607}
608
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700609void LargeObjectMapSpace::Walk(AllocSpace::WalkCallback callback, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700610 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700611 for (MemMaps::iterator it = mem_maps_.begin(); it != mem_maps_.end(); ++it) {
612 MemMap* mem_map = it->second;
613 callback(mem_map->Begin(), mem_map->End(), mem_map->Size(), arg);
614 callback(NULL, NULL, 0, arg);
615 }
616}
617
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700618bool LargeObjectMapSpace::Contains(const Object* obj) const {
Ian Rogers50b35e22012-10-04 10:09:15 -0700619 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700620 return mem_maps_.find(const_cast<Object*>(obj)) != mem_maps_.end();
621}
622
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700623FreeListSpace* FreeListSpace::Create(const std::string& name, byte* requested_begin, size_t size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700624 CHECK(size % kAlignment == 0);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700625 MemMap* mem_map = MemMap::MapAnonymous(name.c_str(), requested_begin, size,
626 PROT_READ | PROT_WRITE);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700627 CHECK(mem_map != NULL) << "Failed to allocate large object space mem map";
628 return new FreeListSpace(name, mem_map, mem_map->Begin(), mem_map->End());
629}
630
631FreeListSpace::FreeListSpace(const std::string& name, MemMap* mem_map, byte* begin, byte* end)
632 : LargeObjectSpace(name),
633 begin_(begin),
634 end_(end),
635 mem_map_(mem_map),
636 lock_("free list space lock", kAllocSpaceLock) {
637 chunks_.resize(Size() / kAlignment + 1);
638 // Add a dummy chunk so we don't need to handle chunks having no next chunk.
639 chunks_.back().SetSize(kAlignment, false);
640 // Start out with one large free chunk.
641 AddFreeChunk(begin_, end_ - begin_, NULL);
642}
643
644FreeListSpace::~FreeListSpace() {
645
646}
647
648void FreeListSpace::AddFreeChunk(void* address, size_t size, Chunk* previous) {
649 Chunk* chunk = ChunkFromAddr(address);
650 chunk->SetSize(size, true);
651 chunk->SetPrevious(previous);
652 Chunk* next_chunk = GetNextChunk(chunk);
653 next_chunk->SetPrevious(chunk);
654 free_chunks_.insert(chunk);
655}
656
657FreeListSpace::Chunk* FreeListSpace::ChunkFromAddr(void* address) {
658 size_t offset = reinterpret_cast<byte*>(address) - Begin();
659 DCHECK(IsAligned<kAlignment>(offset));
660 DCHECK_LT(offset, Size());
661 return &chunks_[offset / kAlignment];
662}
663
664void* FreeListSpace::AddrFromChunk(Chunk* chunk) {
665 return reinterpret_cast<void*>(Begin() + (chunk - &chunks_.front()) * kAlignment);
666}
667
668void FreeListSpace::RemoveFreeChunk(Chunk* chunk) {
669 // TODO: C++0x
670 // TODO: Improve performance, this might be slow.
671 std::pair<FreeChunks::iterator, FreeChunks::iterator> range = free_chunks_.equal_range(chunk);
672 for (FreeChunks::iterator it = range.first; it != range.second; ++it) {
673 if (*it == chunk) {
674 free_chunks_.erase(it);
675 return;
676 }
677 }
678}
679
680void FreeListSpace::Walk(AllocSpace::WalkCallback callback, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700681 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700682 for (Chunk* chunk = &chunks_.front(); chunk < &chunks_.back(); ) {
683 if (!chunk->IsFree()) {
684 size_t size = chunk->GetSize();
685 void* begin = AddrFromChunk(chunk);
686 void* end = reinterpret_cast<void*>(reinterpret_cast<byte*>(begin) + size);
687 callback(begin, end, size, arg);
688 callback(NULL, NULL, 0, arg);
689 }
690 chunk = GetNextChunk(chunk);
691 }
692}
693
Ian Rogers50b35e22012-10-04 10:09:15 -0700694void FreeListSpace::Free(Thread* self, Object* obj) {
695 MutexLock mu(self, lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700696 CHECK(Contains(obj));
697 // Check adjacent chunks to see if we need to combine.
698 Chunk* chunk = ChunkFromAddr(obj);
699 CHECK(!chunk->IsFree());
700
701 size_t allocation_size = chunk->GetSize();
702 madvise(obj, allocation_size, MADV_DONTNEED);
703 num_objects_allocated_--;
704 num_bytes_allocated_ -= allocation_size;
705 Chunk* prev = chunk->GetPrevious();
706 Chunk* next = GetNextChunk(chunk);
707
708 // Combine any adjacent free chunks
709 size_t extra_size = chunk->GetSize();
710 if (next->IsFree()) {
711 extra_size += next->GetSize();
712 RemoveFreeChunk(next);
713 }
714 if (prev != NULL && prev->IsFree()) {
715 RemoveFreeChunk(prev);
716 AddFreeChunk(AddrFromChunk(prev), prev->GetSize() + extra_size, prev->GetPrevious());
717 } else {
718 AddFreeChunk(AddrFromChunk(chunk), extra_size, prev);
719 }
720}
721
722bool FreeListSpace::Contains(const Object* obj) const {
723 return mem_map_->HasAddress(obj);
724}
725
726FreeListSpace::Chunk* FreeListSpace::GetNextChunk(Chunk* chunk) {
727 return chunk + chunk->GetSize() / kAlignment;
728}
729
730size_t FreeListSpace::AllocationSize(const Object* obj) {
731 Chunk* chunk = ChunkFromAddr(const_cast<Object*>(obj));
732 CHECK(!chunk->IsFree());
733 return chunk->GetSize();
734}
735
Ian Rogers50b35e22012-10-04 10:09:15 -0700736Object* FreeListSpace::Alloc(Thread* self, size_t num_bytes) {
737 MutexLock mu(self, lock_);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700738 num_bytes = RoundUp(num_bytes, kAlignment);
739 Chunk temp;
740 temp.SetSize(num_bytes);
741 // Find the smallest chunk at least num_bytes in size.
742 FreeChunks::iterator found = free_chunks_.lower_bound(&temp);
743 if (found == free_chunks_.end()) {
744 // Out of memory, or too much fragmentation.
745 return NULL;
746 }
747 Chunk* chunk = *found;
748 free_chunks_.erase(found);
749 CHECK(chunk->IsFree());
750 void* addr = AddrFromChunk(chunk);
751 size_t chunk_size = chunk->GetSize();
752 chunk->SetSize(num_bytes);
753 if (chunk_size > num_bytes) {
754 // Split the chunk into two chunks.
755 Chunk* new_chunk = GetNextChunk(chunk);
756 AddFreeChunk(AddrFromChunk(new_chunk), chunk_size - num_bytes, chunk);
757 }
758
759 num_objects_allocated_++;
760 num_bytes_allocated_ += num_bytes;
761 return reinterpret_cast<Object*>(addr);
762}
763
Ian Rogers50b35e22012-10-04 10:09:15 -0700764void FreeListSpace::FreeList(Thread* self, size_t num_ptrs, Object** ptrs) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700765 for (size_t i = 0; i < num_ptrs; ++i) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700766 Free(self, ptrs[i]);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700767 }
768}
769
Carl Shapiro69759ea2011-07-21 18:13:35 -0700770} // namespace art