blob: da79109b4fd5c72765145b2c273147cd0d7068ff [file] [log] [blame]
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001/*
2 * Copyright 2014 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 */
16
17#include "jit_code_cache.h"
18
19#include <sstream>
20
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010022#include "entrypoints/runtime_asm_entrypoints.h"
23#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000024#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010025#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080026#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080027#include "oat_file-inl.h"
Nicolas Geoffray62623402015-10-28 19:15:05 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010029#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080030
31namespace art {
32namespace jit {
33
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010034static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
35static constexpr int kProtData = PROT_READ | PROT_WRITE;
36static constexpr int kProtCode = PROT_READ | PROT_EXEC;
37
38#define CHECKED_MPROTECT(memory, size, prot) \
39 do { \
40 int rc = mprotect(memory, size, prot); \
41 if (UNLIKELY(rc != 0)) { \
42 errno = rc; \
43 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
44 } \
45 } while (false) \
46
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000047JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
48 size_t max_capacity,
49 std::string* error_msg) {
50 CHECK_GE(max_capacity, initial_capacity);
51 // We need to have 32 bit offsets from method headers in code cache which point to things
52 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
53 // Ensure we're below 1 GB to be safe.
54 if (max_capacity > 1 * GB) {
55 std::ostringstream oss;
56 oss << "Maxium code cache capacity is limited to 1 GB, "
57 << PrettySize(max_capacity) << " is too big";
58 *error_msg = oss.str();
59 return nullptr;
60 }
61
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080062 std::string error_str;
63 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010064 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000065 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010066 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080067 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000068 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080069 *error_msg = oss.str();
70 return nullptr;
71 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010072
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000073 // Align both capacities to page size, as that's the unit mspaces use.
74 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
75 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
76
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000077 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010078 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000079 size_t data_size = max_capacity / 2;
80 size_t code_size = max_capacity - data_size;
81 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010082 uint8_t* divider = data_map->Begin() + data_size;
83
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010084 MemMap* code_map = data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str);
85 if (code_map == nullptr) {
86 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000087 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010088 *error_msg = oss.str();
89 return nullptr;
90 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010091 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000092 data_size = initial_capacity / 2;
93 code_size = initial_capacity - data_size;
94 DCHECK_EQ(code_size + data_size, initial_capacity);
95 return new JitCodeCache(code_map, data_map, code_size, data_size, max_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080096}
97
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000098JitCodeCache::JitCodeCache(MemMap* code_map,
99 MemMap* data_map,
100 size_t initial_code_capacity,
101 size_t initial_data_capacity,
102 size_t max_capacity)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100103 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100104 lock_cond_("Jit code cache variable", lock_),
105 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100106 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000107 data_map_(data_map),
108 max_capacity_(max_capacity),
109 current_capacity_(initial_code_capacity + initial_data_capacity),
110 code_end_(initial_code_capacity),
111 data_end_(initial_data_capacity),
112 has_done_one_collection_(false) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100113
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000114 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
115 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100116
117 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
118 PLOG(FATAL) << "create_mspace_with_base failed";
119 }
120
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000121 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100122
123 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
124 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100125
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000126 VLOG(jit) << "Created jit code cache: initial data size="
127 << PrettySize(initial_data_capacity)
128 << ", initial code size="
129 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800130}
131
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100132bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100133 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800134}
135
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000136bool JitCodeCache::ContainsMethod(ArtMethod* method) {
137 MutexLock mu(Thread::Current(), lock_);
138 for (auto& it : method_code_map_) {
139 if (it.second == method) {
140 return true;
141 }
142 }
143 return false;
144}
145
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100146class ScopedCodeCacheWrite {
147 public:
148 explicit ScopedCodeCacheWrite(MemMap* code_map) : code_map_(code_map) {
149 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800150 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100151 ~ScopedCodeCacheWrite() {
152 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
153 }
154 private:
155 MemMap* const code_map_;
156
157 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
158};
159
160uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100161 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100162 const uint8_t* mapping_table,
163 const uint8_t* vmap_table,
164 const uint8_t* gc_map,
165 size_t frame_size_in_bytes,
166 size_t core_spill_mask,
167 size_t fp_spill_mask,
168 const uint8_t* code,
169 size_t code_size) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100170 uint8_t* result = CommitCodeInternal(self,
171 method,
172 mapping_table,
173 vmap_table,
174 gc_map,
175 frame_size_in_bytes,
176 core_spill_mask,
177 fp_spill_mask,
178 code,
179 code_size);
180 if (result == nullptr) {
181 // Retry.
182 GarbageCollectCache(self);
183 result = CommitCodeInternal(self,
184 method,
185 mapping_table,
186 vmap_table,
187 gc_map,
188 frame_size_in_bytes,
189 core_spill_mask,
190 fp_spill_mask,
191 code,
192 code_size);
193 }
194 return result;
195}
196
197bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
198 bool in_collection = false;
199 while (collection_in_progress_) {
200 in_collection = true;
201 lock_cond_.Wait(self);
202 }
203 return in_collection;
204}
205
206static uintptr_t FromCodeToAllocation(const void* code) {
207 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
208 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
209}
210
211void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
212 uintptr_t allocation = FromCodeToAllocation(code_ptr);
213 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
214 const uint8_t* data = method_header->GetNativeGcMap();
215 if (data != nullptr) {
216 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
217 }
218 data = method_header->GetMappingTable();
219 if (data != nullptr) {
220 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
221 }
222 // Use the offset directly to prevent sanity check that the method is
223 // compiled with optimizing.
224 // TODO(ngeoffray): Clean up.
225 if (method_header->vmap_table_offset_ != 0) {
226 data = method_header->code_ - method_header->vmap_table_offset_;
227 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
228 }
229 mspace_free(code_mspace_, reinterpret_cast<uint8_t*>(allocation));
230}
231
232void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
233 MutexLock mu(self, lock_);
234 // We do not check if a code cache GC is in progress, as this method comes
235 // with the classlinker_classes_lock_ held, and suspending ourselves could
236 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000237 {
238 ScopedCodeCacheWrite scc(code_map_.get());
239 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
240 if (alloc.ContainsUnsafe(it->second)) {
241 FreeCode(it->first, it->second);
242 it = method_code_map_.erase(it);
243 } else {
244 ++it;
245 }
246 }
247 }
248 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
249 ProfilingInfo* info = *it;
250 if (alloc.ContainsUnsafe(info->GetMethod())) {
251 info->GetMethod()->SetProfilingInfo(nullptr);
252 mspace_free(data_mspace_, reinterpret_cast<uint8_t*>(info));
253 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100254 } else {
255 ++it;
256 }
257 }
258}
259
260uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
261 ArtMethod* method,
262 const uint8_t* mapping_table,
263 const uint8_t* vmap_table,
264 const uint8_t* gc_map,
265 size_t frame_size_in_bytes,
266 size_t core_spill_mask,
267 size_t fp_spill_mask,
268 const uint8_t* code,
269 size_t code_size) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100270 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
271 // Ensure the header ends up at expected instruction alignment.
272 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
273 size_t total_size = header_size + code_size;
274
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100275 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100276 uint8_t* code_ptr = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100277 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000278 ScopedThreadSuspension sts(self, kSuspended);
279 MutexLock mu(self, lock_);
280 WaitForPotentialCollectionToComplete(self);
281 {
282 ScopedCodeCacheWrite scc(code_map_.get());
283 uint8_t* result = reinterpret_cast<uint8_t*>(
284 mspace_memalign(code_mspace_, alignment, total_size));
285 if (result == nullptr) {
286 return nullptr;
287 }
288 code_ptr = result + header_size;
289 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(code_ptr), alignment);
290
291 std::copy(code, code + code_size, code_ptr);
292 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
293 new (method_header) OatQuickMethodHeader(
294 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
295 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
296 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
297 frame_size_in_bytes,
298 core_spill_mask,
299 fp_spill_mask,
300 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100301 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100302
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000303 __builtin___clear_cache(reinterpret_cast<char*>(code_ptr),
304 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100305 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000306 // We need to update the entry point in the runnable state for the instrumentation.
307 {
308 MutexLock mu(self, lock_);
309 method_code_map_.Put(code_ptr, method);
310 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
311 method, method_header->GetEntryPoint());
312 if (collection_in_progress_) {
313 // We need to update the live bitmap if there is a GC to ensure it sees this new
314 // code.
315 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
316 }
317 VLOG(jit)
318 << "JIT added "
319 << PrettyMethod(method) << "@" << method
320 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
321 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
322 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
323 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
324 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100325
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100326 return reinterpret_cast<uint8_t*>(method_header);
327}
328
329size_t JitCodeCache::CodeCacheSize() {
330 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000331 return CodeCacheSizeLocked();
332}
333
334size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100335 size_t bytes_allocated = 0;
336 mspace_inspect_all(code_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
337 return bytes_allocated;
338}
339
340size_t JitCodeCache::DataCacheSize() {
341 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000342 return DataCacheSizeLocked();
343}
344
345size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100346 size_t bytes_allocated = 0;
347 mspace_inspect_all(data_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
348 return bytes_allocated;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800349}
350
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100351size_t JitCodeCache::NumberOfCompiledCode() {
352 MutexLock mu(Thread::Current(), lock_);
353 return method_code_map_.size();
354}
355
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000356void JitCodeCache::ClearData(Thread* self, void* data) {
357 MutexLock mu(self, lock_);
358 mspace_free(data_mspace_, data);
359}
360
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100361uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100362 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100363 uint8_t* result = nullptr;
364
365 {
366 ScopedThreadSuspension sts(self, kSuspended);
367 MutexLock mu(self, lock_);
368 WaitForPotentialCollectionToComplete(self);
369 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
370 }
371
372 if (result == nullptr) {
373 // Retry.
374 GarbageCollectCache(self);
375 ScopedThreadSuspension sts(self, kSuspended);
376 MutexLock mu(self, lock_);
377 WaitForPotentialCollectionToComplete(self);
378 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
379 }
380
381 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100382}
383
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800384uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100385 uint8_t* result = ReserveData(self, end - begin);
386 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800387 return nullptr; // Out of space in the data cache.
388 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100389 std::copy(begin, end, result);
390 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800391}
392
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100393class MarkCodeVisitor FINAL : public StackVisitor {
394 public:
395 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
396 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
397 code_cache_(code_cache_in),
398 bitmap_(code_cache_->GetLiveBitmap()) {}
399
400 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
401 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
402 if (method_header == nullptr) {
403 return true;
404 }
405 const void* code = method_header->GetCode();
406 if (code_cache_->ContainsPc(code)) {
407 // Use the atomic set version, as multiple threads are executing this code.
408 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
409 }
410 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800411 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100412
413 private:
414 JitCodeCache* const code_cache_;
415 CodeCacheBitmap* const bitmap_;
416};
417
418class MarkCodeClosure FINAL : public Closure {
419 public:
420 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
421 : code_cache_(code_cache), barrier_(barrier) {}
422
423 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
424 DCHECK(thread == Thread::Current() || thread->IsSuspended());
425 MarkCodeVisitor visitor(thread, code_cache_);
426 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000427 if (kIsDebugBuild) {
428 // The stack walking code queries the side instrumentation stack if it
429 // sees an instrumentation exit pc, so the JIT code of methods in that stack
430 // must have been seen. We sanity check this below.
431 for (const instrumentation::InstrumentationStackFrame& frame
432 : *thread->GetInstrumentationStack()) {
433 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
434 // its stack frame, it is not the method owning return_pc_. We just pass null to
435 // LookupMethodHeader: the method is only checked against in debug builds.
436 OatQuickMethodHeader* method_header =
437 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
438 if (method_header != nullptr) {
439 const void* code = method_header->GetCode();
440 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
441 }
442 }
443 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700444 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800445 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100446
447 private:
448 JitCodeCache* const code_cache_;
449 Barrier* const barrier_;
450};
451
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000452void JitCodeCache::NotifyCollectionDone(Thread* self) {
453 collection_in_progress_ = false;
454 lock_cond_.Broadcast(self);
455}
456
457void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
458 size_t per_space_footprint = new_footprint / 2;
459 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
460 DCHECK_EQ(per_space_footprint * 2, new_footprint);
461 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
462 {
463 ScopedCodeCacheWrite scc(code_map_.get());
464 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
465 }
466}
467
468bool JitCodeCache::IncreaseCodeCacheCapacity() {
469 if (current_capacity_ == max_capacity_) {
470 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100471 }
472
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000473 // Double the capacity if we're below 1MB, or increase it by 1MB if
474 // we're above.
475 if (current_capacity_ < 1 * MB) {
476 current_capacity_ *= 2;
477 } else {
478 current_capacity_ += 1 * MB;
479 }
480 if (current_capacity_ > max_capacity_) {
481 current_capacity_ = max_capacity_;
482 }
483
484 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
485 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
486 }
487
488 SetFootprintLimit(current_capacity_);
489
490 return true;
491}
492
493void JitCodeCache::GarbageCollectCache(Thread* self) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000494 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100495
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000496 // Wait for an existing collection, or let everyone know we are starting one.
497 {
498 ScopedThreadSuspension sts(self, kSuspended);
499 MutexLock mu(self, lock_);
500 if (WaitForPotentialCollectionToComplete(self)) {
501 return;
502 } else {
503 collection_in_progress_ = true;
504 }
505 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000506
507 // Check if we just need to grow the capacity. If we don't, allocate the bitmap while
508 // we hold the lock.
509 {
510 MutexLock mu(self, lock_);
511 if (has_done_one_collection_ && IncreaseCodeCacheCapacity()) {
512 has_done_one_collection_ = false;
513 NotifyCollectionDone(self);
514 return;
515 } else {
516 live_bitmap_.reset(CodeCacheBitmap::Create(
517 "code-cache-bitmap",
518 reinterpret_cast<uintptr_t>(code_map_->Begin()),
519 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
520 }
521 }
522
523 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
524 LOG(INFO) << "Clearing code cache, code="
525 << PrettySize(CodeCacheSize())
526 << ", data=" << PrettySize(DataCacheSize());
527 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100528 // Walk over all compiled methods and set the entry points of these
529 // methods to interpreter.
530 {
531 MutexLock mu(self, lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100532 for (auto& it : method_code_map_) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000533 instrumentation->UpdateMethodsCode(it.second, GetQuickToInterpreterBridge());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100534 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000535 for (ProfilingInfo* info : profiling_infos_) {
536 info->GetMethod()->SetProfilingInfo(nullptr);
537 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100538 }
539
540 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
541 {
542 Barrier barrier(0);
Nicolas Geoffray62623402015-10-28 19:15:05 +0000543 size_t threads_running_checkpoint = 0;
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000544 MarkCodeClosure closure(this, &barrier);
545 threads_running_checkpoint =
546 Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
547 // Now that we have run our checkpoint, move to a suspended state and wait
548 // for other threads to run the checkpoint.
549 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100550 if (threads_running_checkpoint != 0) {
551 barrier.Increment(self, threads_running_checkpoint);
552 }
553 }
554
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100555 {
556 MutexLock mu(self, lock_);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000557 // Free unused compiled code, and restore the entry point of used compiled code.
558 {
559 ScopedCodeCacheWrite scc(code_map_.get());
560 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
561 const void* code_ptr = it->first;
562 ArtMethod* method = it->second;
563 uintptr_t allocation = FromCodeToAllocation(code_ptr);
564 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
565 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000566 instrumentation->UpdateMethodsCode(method, method_header->GetEntryPoint());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000567 ++it;
568 } else {
569 method->ClearCounter();
570 DCHECK_NE(method->GetEntryPointFromQuickCompiledCode(), method_header->GetEntryPoint());
571 FreeCode(code_ptr, method);
572 it = method_code_map_.erase(it);
573 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100574 }
575 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000576
577 // Free all profiling info.
578 for (ProfilingInfo* info : profiling_infos_) {
579 DCHECK(info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr);
580 mspace_free(data_mspace_, reinterpret_cast<uint8_t*>(info));
581 }
582 profiling_infos_.clear();
583
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000584 live_bitmap_.reset(nullptr);
585 has_done_one_collection_ = true;
586 NotifyCollectionDone(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100587 }
588
589 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
590 LOG(INFO) << "After clearing code cache, code="
591 << PrettySize(CodeCacheSize())
592 << ", data=" << PrettySize(DataCacheSize());
593 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800594}
595
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100596
597OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
598 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
599 if (kRuntimeISA == kArm) {
600 // On Thumb-2, the pc is offset by one.
601 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800602 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100603 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
604 return nullptr;
605 }
606
607 MutexLock mu(Thread::Current(), lock_);
608 if (method_code_map_.empty()) {
609 return nullptr;
610 }
611 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
612 --it;
613
614 const void* code_ptr = it->first;
615 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
616 if (!method_header->Contains(pc)) {
617 return nullptr;
618 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000619 if (kIsDebugBuild && method != nullptr) {
620 DCHECK_EQ(it->second, method)
621 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
622 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100623 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800624}
625
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000626ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
627 ArtMethod* method,
628 const std::vector<uint32_t>& entries,
629 bool retry_allocation) {
630 ProfilingInfo* info = AddProfilingInfoInternal(self, method, entries);
631
632 if (info == nullptr && retry_allocation) {
633 GarbageCollectCache(self);
634 info = AddProfilingInfoInternal(self, method, entries);
635 }
636 return info;
637}
638
639ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self,
640 ArtMethod* method,
641 const std::vector<uint32_t>& entries) {
642 size_t profile_info_size = RoundUp(
643 sizeof(ProfilingInfo) + sizeof(ProfilingInfo::InlineCache) * entries.size(),
644 sizeof(void*));
645 ScopedThreadSuspension sts(self, kSuspended);
646 MutexLock mu(self, lock_);
647 WaitForPotentialCollectionToComplete(self);
648
649 // Check whether some other thread has concurrently created it.
650 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
651 if (info != nullptr) {
652 return info;
653 }
654
655 uint8_t* data = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, profile_info_size));
656 if (data == nullptr) {
657 return nullptr;
658 }
659 info = new (data) ProfilingInfo(method, entries);
660 method->SetProfilingInfo(info);
661 profiling_infos_.push_back(info);
662 return info;
663}
664
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000665// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
666// is already held.
667void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
668 if (code_mspace_ == mspace) {
669 size_t result = code_end_;
670 code_end_ += increment;
671 return reinterpret_cast<void*>(result + code_map_->Begin());
672 } else {
673 DCHECK_EQ(data_mspace_, mspace);
674 size_t result = data_end_;
675 data_end_ += increment;
676 return reinterpret_cast<void*>(result + data_map_->Begin());
677 }
678}
679
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800680} // namespace jit
681} // namespace art