blob: 05a153ddc7eddb8766a51522dbf4aa6eb2ed8023 [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"
Calin Juravle66f55232015-12-08 15:09:10 +000022#include "base/stl_util.h"
Calin Juravle31f2c152015-10-23 17:56:15 +010023#include "base/time_utils.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010024#include "entrypoints/runtime_asm_entrypoints.h"
25#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000026#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010027#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080028#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080029#include "oat_file-inl.h"
Nicolas Geoffray62623402015-10-28 19:15:05 +000030#include "scoped_thread_state_change.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010031#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080032
33namespace art {
34namespace jit {
35
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010036static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
37static constexpr int kProtData = PROT_READ | PROT_WRITE;
38static constexpr int kProtCode = PROT_READ | PROT_EXEC;
39
40#define CHECKED_MPROTECT(memory, size, prot) \
41 do { \
42 int rc = mprotect(memory, size, prot); \
43 if (UNLIKELY(rc != 0)) { \
44 errno = rc; \
45 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
46 } \
47 } while (false) \
48
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000049JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
50 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000051 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000052 std::string* error_msg) {
53 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000054
55 // Generating debug information is mostly for using the 'perf' tool, which does
56 // not work with ashmem.
57 bool use_ashmem = !generate_debug_info;
58 // With 'perf', we want a 1-1 mapping between an address and a method.
59 bool garbage_collect_code = !generate_debug_info;
60
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000061 // We need to have 32 bit offsets from method headers in code cache which point to things
62 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
63 // Ensure we're below 1 GB to be safe.
64 if (max_capacity > 1 * GB) {
65 std::ostringstream oss;
66 oss << "Maxium code cache capacity is limited to 1 GB, "
67 << PrettySize(max_capacity) << " is too big";
68 *error_msg = oss.str();
69 return nullptr;
70 }
71
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080072 std::string error_str;
73 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010074 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000075 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010076 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080077 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000078 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080079 *error_msg = oss.str();
80 return nullptr;
81 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010082
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000083 // Align both capacities to page size, as that's the unit mspaces use.
84 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
85 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
86
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000087 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010088 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000089 size_t data_size = max_capacity / 2;
90 size_t code_size = max_capacity - data_size;
91 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010092 uint8_t* divider = data_map->Begin() + data_size;
93
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000094 MemMap* code_map =
95 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010096 if (code_map == nullptr) {
97 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000098 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010099 *error_msg = oss.str();
100 return nullptr;
101 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100102 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000103 data_size = initial_capacity / 2;
104 code_size = initial_capacity - data_size;
105 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000106 return new JitCodeCache(
107 code_map, data_map, code_size, data_size, garbage_collect_code, max_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800108}
109
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000110JitCodeCache::JitCodeCache(MemMap* code_map,
111 MemMap* data_map,
112 size_t initial_code_capacity,
113 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000114 size_t max_capacity,
115 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100116 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100117 lock_cond_("Jit code cache variable", lock_),
118 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100119 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000120 data_map_(data_map),
121 max_capacity_(max_capacity),
122 current_capacity_(initial_code_capacity + initial_data_capacity),
123 code_end_(initial_code_capacity),
124 data_end_(initial_data_capacity),
Calin Juravle31f2c152015-10-23 17:56:15 +0100125 has_done_one_collection_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000126 last_update_time_ns_(0),
127 garbage_collect_code_(garbage_collect_code) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100128
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000129 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
130 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100131
132 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
133 PLOG(FATAL) << "create_mspace_with_base failed";
134 }
135
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000136 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100137
138 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
139 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100140
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000141 VLOG(jit) << "Created jit code cache: initial data size="
142 << PrettySize(initial_data_capacity)
143 << ", initial code size="
144 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800145}
146
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100147bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100148 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800149}
150
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000151bool JitCodeCache::ContainsMethod(ArtMethod* method) {
152 MutexLock mu(Thread::Current(), lock_);
153 for (auto& it : method_code_map_) {
154 if (it.second == method) {
155 return true;
156 }
157 }
158 return false;
159}
160
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100161class ScopedCodeCacheWrite {
162 public:
163 explicit ScopedCodeCacheWrite(MemMap* code_map) : code_map_(code_map) {
164 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800165 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100166 ~ScopedCodeCacheWrite() {
167 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
168 }
169 private:
170 MemMap* const code_map_;
171
172 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
173};
174
175uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100176 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100177 const uint8_t* mapping_table,
178 const uint8_t* vmap_table,
179 const uint8_t* gc_map,
180 size_t frame_size_in_bytes,
181 size_t core_spill_mask,
182 size_t fp_spill_mask,
183 const uint8_t* code,
184 size_t code_size) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100185 uint8_t* result = CommitCodeInternal(self,
186 method,
187 mapping_table,
188 vmap_table,
189 gc_map,
190 frame_size_in_bytes,
191 core_spill_mask,
192 fp_spill_mask,
193 code,
194 code_size);
195 if (result == nullptr) {
196 // Retry.
197 GarbageCollectCache(self);
198 result = CommitCodeInternal(self,
199 method,
200 mapping_table,
201 vmap_table,
202 gc_map,
203 frame_size_in_bytes,
204 core_spill_mask,
205 fp_spill_mask,
206 code,
207 code_size);
208 }
209 return result;
210}
211
212bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
213 bool in_collection = false;
214 while (collection_in_progress_) {
215 in_collection = true;
216 lock_cond_.Wait(self);
217 }
218 return in_collection;
219}
220
221static uintptr_t FromCodeToAllocation(const void* code) {
222 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
223 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
224}
225
226void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
227 uintptr_t allocation = FromCodeToAllocation(code_ptr);
228 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
229 const uint8_t* data = method_header->GetNativeGcMap();
230 if (data != nullptr) {
231 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
232 }
233 data = method_header->GetMappingTable();
234 if (data != nullptr) {
235 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
236 }
237 // Use the offset directly to prevent sanity check that the method is
238 // compiled with optimizing.
239 // TODO(ngeoffray): Clean up.
240 if (method_header->vmap_table_offset_ != 0) {
241 data = method_header->code_ - method_header->vmap_table_offset_;
242 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
243 }
244 mspace_free(code_mspace_, reinterpret_cast<uint8_t*>(allocation));
245}
246
247void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
248 MutexLock mu(self, lock_);
249 // We do not check if a code cache GC is in progress, as this method comes
250 // with the classlinker_classes_lock_ held, and suspending ourselves could
251 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000252 {
253 ScopedCodeCacheWrite scc(code_map_.get());
254 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
255 if (alloc.ContainsUnsafe(it->second)) {
256 FreeCode(it->first, it->second);
257 it = method_code_map_.erase(it);
258 } else {
259 ++it;
260 }
261 }
262 }
263 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
264 ProfilingInfo* info = *it;
265 if (alloc.ContainsUnsafe(info->GetMethod())) {
266 info->GetMethod()->SetProfilingInfo(nullptr);
267 mspace_free(data_mspace_, reinterpret_cast<uint8_t*>(info));
268 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100269 } else {
270 ++it;
271 }
272 }
273}
274
275uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
276 ArtMethod* method,
277 const uint8_t* mapping_table,
278 const uint8_t* vmap_table,
279 const uint8_t* gc_map,
280 size_t frame_size_in_bytes,
281 size_t core_spill_mask,
282 size_t fp_spill_mask,
283 const uint8_t* code,
284 size_t code_size) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100285 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
286 // Ensure the header ends up at expected instruction alignment.
287 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
288 size_t total_size = header_size + code_size;
289
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100290 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100291 uint8_t* code_ptr = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100292 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000293 ScopedThreadSuspension sts(self, kSuspended);
294 MutexLock mu(self, lock_);
295 WaitForPotentialCollectionToComplete(self);
296 {
297 ScopedCodeCacheWrite scc(code_map_.get());
298 uint8_t* result = reinterpret_cast<uint8_t*>(
299 mspace_memalign(code_mspace_, alignment, total_size));
300 if (result == nullptr) {
301 return nullptr;
302 }
303 code_ptr = result + header_size;
304 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(code_ptr), alignment);
305
306 std::copy(code, code + code_size, code_ptr);
307 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
308 new (method_header) OatQuickMethodHeader(
309 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
310 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
311 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
312 frame_size_in_bytes,
313 core_spill_mask,
314 fp_spill_mask,
315 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100316 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100317
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000318 __builtin___clear_cache(reinterpret_cast<char*>(code_ptr),
319 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100320 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000321 // We need to update the entry point in the runnable state for the instrumentation.
322 {
323 MutexLock mu(self, lock_);
324 method_code_map_.Put(code_ptr, method);
325 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
326 method, method_header->GetEntryPoint());
327 if (collection_in_progress_) {
328 // We need to update the live bitmap if there is a GC to ensure it sees this new
329 // code.
330 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
331 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000332 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000333 VLOG(jit)
334 << "JIT added "
335 << PrettyMethod(method) << "@" << method
336 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
337 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
338 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
339 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
340 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100341
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100342 return reinterpret_cast<uint8_t*>(method_header);
343}
344
345size_t JitCodeCache::CodeCacheSize() {
346 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000347 return CodeCacheSizeLocked();
348}
349
350size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100351 size_t bytes_allocated = 0;
352 mspace_inspect_all(code_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
353 return bytes_allocated;
354}
355
356size_t JitCodeCache::DataCacheSize() {
357 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000358 return DataCacheSizeLocked();
359}
360
361size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100362 size_t bytes_allocated = 0;
363 mspace_inspect_all(data_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
364 return bytes_allocated;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800365}
366
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100367size_t JitCodeCache::NumberOfCompiledCode() {
368 MutexLock mu(Thread::Current(), lock_);
369 return method_code_map_.size();
370}
371
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000372void JitCodeCache::ClearData(Thread* self, void* data) {
373 MutexLock mu(self, lock_);
374 mspace_free(data_mspace_, data);
375}
376
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100377uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100378 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100379 uint8_t* result = nullptr;
380
381 {
382 ScopedThreadSuspension sts(self, kSuspended);
383 MutexLock mu(self, lock_);
384 WaitForPotentialCollectionToComplete(self);
385 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
386 }
387
388 if (result == nullptr) {
389 // Retry.
390 GarbageCollectCache(self);
391 ScopedThreadSuspension sts(self, kSuspended);
392 MutexLock mu(self, lock_);
393 WaitForPotentialCollectionToComplete(self);
394 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
395 }
396
397 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100398}
399
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800400uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100401 uint8_t* result = ReserveData(self, end - begin);
402 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800403 return nullptr; // Out of space in the data cache.
404 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100405 std::copy(begin, end, result);
406 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800407}
408
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100409class MarkCodeVisitor FINAL : public StackVisitor {
410 public:
411 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
412 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
413 code_cache_(code_cache_in),
414 bitmap_(code_cache_->GetLiveBitmap()) {}
415
416 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
417 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
418 if (method_header == nullptr) {
419 return true;
420 }
421 const void* code = method_header->GetCode();
422 if (code_cache_->ContainsPc(code)) {
423 // Use the atomic set version, as multiple threads are executing this code.
424 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
425 }
426 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800427 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100428
429 private:
430 JitCodeCache* const code_cache_;
431 CodeCacheBitmap* const bitmap_;
432};
433
434class MarkCodeClosure FINAL : public Closure {
435 public:
436 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
437 : code_cache_(code_cache), barrier_(barrier) {}
438
439 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
440 DCHECK(thread == Thread::Current() || thread->IsSuspended());
441 MarkCodeVisitor visitor(thread, code_cache_);
442 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000443 if (kIsDebugBuild) {
444 // The stack walking code queries the side instrumentation stack if it
445 // sees an instrumentation exit pc, so the JIT code of methods in that stack
446 // must have been seen. We sanity check this below.
447 for (const instrumentation::InstrumentationStackFrame& frame
448 : *thread->GetInstrumentationStack()) {
449 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
450 // its stack frame, it is not the method owning return_pc_. We just pass null to
451 // LookupMethodHeader: the method is only checked against in debug builds.
452 OatQuickMethodHeader* method_header =
453 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
454 if (method_header != nullptr) {
455 const void* code = method_header->GetCode();
456 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
457 }
458 }
459 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700460 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800461 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100462
463 private:
464 JitCodeCache* const code_cache_;
465 Barrier* const barrier_;
466};
467
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000468void JitCodeCache::NotifyCollectionDone(Thread* self) {
469 collection_in_progress_ = false;
470 lock_cond_.Broadcast(self);
471}
472
473void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
474 size_t per_space_footprint = new_footprint / 2;
475 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
476 DCHECK_EQ(per_space_footprint * 2, new_footprint);
477 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
478 {
479 ScopedCodeCacheWrite scc(code_map_.get());
480 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
481 }
482}
483
484bool JitCodeCache::IncreaseCodeCacheCapacity() {
485 if (current_capacity_ == max_capacity_) {
486 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100487 }
488
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000489 // Double the capacity if we're below 1MB, or increase it by 1MB if
490 // we're above.
491 if (current_capacity_ < 1 * MB) {
492 current_capacity_ *= 2;
493 } else {
494 current_capacity_ += 1 * MB;
495 }
496 if (current_capacity_ > max_capacity_) {
497 current_capacity_ = max_capacity_;
498 }
499
500 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
501 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
502 }
503
504 SetFootprintLimit(current_capacity_);
505
506 return true;
507}
508
509void JitCodeCache::GarbageCollectCache(Thread* self) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000510 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100511
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000512 // Wait for an existing collection, or let everyone know we are starting one.
513 {
514 ScopedThreadSuspension sts(self, kSuspended);
515 MutexLock mu(self, lock_);
516 if (WaitForPotentialCollectionToComplete(self)) {
517 return;
518 } else {
519 collection_in_progress_ = true;
520 }
521 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000522
523 // Check if we just need to grow the capacity. If we don't, allocate the bitmap while
524 // we hold the lock.
525 {
526 MutexLock mu(self, lock_);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000527 if (!garbage_collect_code_) {
528 IncreaseCodeCacheCapacity();
529 NotifyCollectionDone(self);
530 return;
531 } else if (has_done_one_collection_ && IncreaseCodeCacheCapacity()) {
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000532 has_done_one_collection_ = false;
533 NotifyCollectionDone(self);
534 return;
535 } else {
536 live_bitmap_.reset(CodeCacheBitmap::Create(
537 "code-cache-bitmap",
538 reinterpret_cast<uintptr_t>(code_map_->Begin()),
539 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
540 }
541 }
542
543 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
544 LOG(INFO) << "Clearing code cache, code="
545 << PrettySize(CodeCacheSize())
546 << ", data=" << PrettySize(DataCacheSize());
547 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100548 // Walk over all compiled methods and set the entry points of these
549 // methods to interpreter.
550 {
551 MutexLock mu(self, lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100552 for (auto& it : method_code_map_) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000553 instrumentation->UpdateMethodsCode(it.second, GetQuickToInterpreterBridge());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100554 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000555 for (ProfilingInfo* info : profiling_infos_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100556 if (!info->IsMethodBeingCompiled()) {
557 info->GetMethod()->SetProfilingInfo(nullptr);
558 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000559 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100560 }
561
562 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
563 {
564 Barrier barrier(0);
Nicolas Geoffray62623402015-10-28 19:15:05 +0000565 size_t threads_running_checkpoint = 0;
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000566 MarkCodeClosure closure(this, &barrier);
567 threads_running_checkpoint =
568 Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
569 // Now that we have run our checkpoint, move to a suspended state and wait
570 // for other threads to run the checkpoint.
571 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100572 if (threads_running_checkpoint != 0) {
573 barrier.Increment(self, threads_running_checkpoint);
574 }
575 }
576
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100577 {
578 MutexLock mu(self, lock_);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000579 // Free unused compiled code, and restore the entry point of used compiled code.
580 {
581 ScopedCodeCacheWrite scc(code_map_.get());
582 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
583 const void* code_ptr = it->first;
584 ArtMethod* method = it->second;
585 uintptr_t allocation = FromCodeToAllocation(code_ptr);
586 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
587 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000588 instrumentation->UpdateMethodsCode(method, method_header->GetEntryPoint());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000589 ++it;
590 } else {
591 method->ClearCounter();
592 DCHECK_NE(method->GetEntryPointFromQuickCompiledCode(), method_header->GetEntryPoint());
593 FreeCode(code_ptr, method);
594 it = method_code_map_.erase(it);
595 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100596 }
597 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000598
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100599 void* data_mspace = data_mspace_;
600 // Free all profiling infos of methods that were not being compiled.
601 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
602 [data_mspace] (ProfilingInfo* info) {
603 if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
604 mspace_free(data_mspace, reinterpret_cast<uint8_t*>(info));
605 return true;
606 }
607 return false;
608 });
609 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000610
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000611 live_bitmap_.reset(nullptr);
612 has_done_one_collection_ = true;
613 NotifyCollectionDone(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100614 }
615
616 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
617 LOG(INFO) << "After clearing code cache, code="
618 << PrettySize(CodeCacheSize())
619 << ", data=" << PrettySize(DataCacheSize());
620 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800621}
622
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100623
624OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
625 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
626 if (kRuntimeISA == kArm) {
627 // On Thumb-2, the pc is offset by one.
628 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800629 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100630 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
631 return nullptr;
632 }
633
634 MutexLock mu(Thread::Current(), lock_);
635 if (method_code_map_.empty()) {
636 return nullptr;
637 }
638 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
639 --it;
640
641 const void* code_ptr = it->first;
642 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
643 if (!method_header->Contains(pc)) {
644 return nullptr;
645 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000646 if (kIsDebugBuild && method != nullptr) {
647 DCHECK_EQ(it->second, method)
648 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
649 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100650 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800651}
652
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000653ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
654 ArtMethod* method,
655 const std::vector<uint32_t>& entries,
656 bool retry_allocation) {
657 ProfilingInfo* info = AddProfilingInfoInternal(self, method, entries);
658
659 if (info == nullptr && retry_allocation) {
660 GarbageCollectCache(self);
661 info = AddProfilingInfoInternal(self, method, entries);
662 }
663 return info;
664}
665
666ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self,
667 ArtMethod* method,
668 const std::vector<uint32_t>& entries) {
669 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100670 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000671 sizeof(void*));
672 ScopedThreadSuspension sts(self, kSuspended);
673 MutexLock mu(self, lock_);
674 WaitForPotentialCollectionToComplete(self);
675
676 // Check whether some other thread has concurrently created it.
677 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
678 if (info != nullptr) {
679 return info;
680 }
681
682 uint8_t* data = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, profile_info_size));
683 if (data == nullptr) {
684 return nullptr;
685 }
686 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000687
688 // Make sure other threads see the data in the profiling info object before the
689 // store in the ArtMethod's ProfilingInfo pointer.
690 QuasiAtomic::ThreadFenceRelease();
691
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000692 method->SetProfilingInfo(info);
693 profiling_infos_.push_back(info);
694 return info;
695}
696
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000697// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
698// is already held.
699void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
700 if (code_mspace_ == mspace) {
701 size_t result = code_end_;
702 code_end_ += increment;
703 return reinterpret_cast<void*>(result + code_map_->Begin());
704 } else {
705 DCHECK_EQ(data_mspace_, mspace);
706 size_t result = data_end_;
707 data_end_ += increment;
708 return reinterpret_cast<void*>(result + data_map_->Begin());
709 }
710}
711
Calin Juravle66f55232015-12-08 15:09:10 +0000712void JitCodeCache::GetCompiledArtMethods(const std::set<const std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000713 std::vector<ArtMethod*>& methods) {
Calin Juravle31f2c152015-10-23 17:56:15 +0100714 MutexLock mu(Thread::Current(), lock_);
715 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000716 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000717 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100718 }
719 }
720}
721
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000722uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
723 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100724}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100725
726bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self) {
727 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
728 return false;
729 }
730 MutexLock mu(self, lock_);
731 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
732 if (info == nullptr || info->IsMethodBeingCompiled()) {
733 return false;
734 }
735 info->SetIsMethodBeingCompiled(true);
736 return true;
737}
738
739void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
740 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
741 DCHECK(info->IsMethodBeingCompiled());
742 info->SetIsMethodBeingCompiled(false);
743}
744
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000745size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
746 MutexLock mu(Thread::Current(), lock_);
747 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
748}
749
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800750} // namespace jit
751} // namespace art