blob: 2d575bdb31cf11aa1fc98b59fae84090d9c354eb [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"
David Srbecky5cc349f2015-12-18 15:04:48 +000024#include "debugger_interface.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010025#include "entrypoints/runtime_asm_entrypoints.h"
26#include "gc/accounting/bitmap-inl.h"
Nicolas Geoffray26705e22015-10-28 12:50:11 +000027#include "jit/profiling_info.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010028#include "linear_alloc.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080029#include "mem_map.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080030#include "oat_file-inl.h"
Nicolas Geoffray62623402015-10-28 19:15:05 +000031#include "scoped_thread_state_change.h"
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +010032#include "thread_list.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080033
34namespace art {
35namespace jit {
36
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010037static constexpr int kProtAll = PROT_READ | PROT_WRITE | PROT_EXEC;
38static constexpr int kProtData = PROT_READ | PROT_WRITE;
39static constexpr int kProtCode = PROT_READ | PROT_EXEC;
40
41#define CHECKED_MPROTECT(memory, size, prot) \
42 do { \
43 int rc = mprotect(memory, size, prot); \
44 if (UNLIKELY(rc != 0)) { \
45 errno = rc; \
46 PLOG(FATAL) << "Failed to mprotect jit code cache"; \
47 } \
48 } while (false) \
49
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000050JitCodeCache* JitCodeCache::Create(size_t initial_capacity,
51 size_t max_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000052 bool generate_debug_info,
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000053 std::string* error_msg) {
54 CHECK_GE(max_capacity, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000055
56 // Generating debug information is mostly for using the 'perf' tool, which does
57 // not work with ashmem.
58 bool use_ashmem = !generate_debug_info;
59 // With 'perf', we want a 1-1 mapping between an address and a method.
60 bool garbage_collect_code = !generate_debug_info;
61
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000062 // We need to have 32 bit offsets from method headers in code cache which point to things
63 // in the data cache. If the maps are more than 4G apart, having multiple maps wouldn't work.
64 // Ensure we're below 1 GB to be safe.
65 if (max_capacity > 1 * GB) {
66 std::ostringstream oss;
67 oss << "Maxium code cache capacity is limited to 1 GB, "
68 << PrettySize(max_capacity) << " is too big";
69 *error_msg = oss.str();
70 return nullptr;
71 }
72
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080073 std::string error_str;
74 // Map name specific for android_os_Debug.cpp accounting.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010075 MemMap* data_map = MemMap::MapAnonymous(
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000076 "data-code-cache", nullptr, max_capacity, kProtAll, false, false, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010077 if (data_map == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080078 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000079 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080080 *error_msg = oss.str();
81 return nullptr;
82 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010083
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000084 // Align both capacities to page size, as that's the unit mspaces use.
85 initial_capacity = RoundDown(initial_capacity, 2 * kPageSize);
86 max_capacity = RoundDown(max_capacity, 2 * kPageSize);
87
Nicolas Geoffray4e915fb2015-10-28 17:39:47 +000088 // Data cache is 1 / 2 of the map.
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010089 // TODO: Make this variable?
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000090 size_t data_size = max_capacity / 2;
91 size_t code_size = max_capacity - data_size;
92 DCHECK_EQ(code_size + data_size, max_capacity);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010093 uint8_t* divider = data_map->Begin() + data_size;
94
Nicolas Geoffraya25dce92016-01-12 16:41:10 +000095 MemMap* code_map =
96 data_map->RemapAtEnd(divider, "jit-code-cache", kProtAll, &error_str, use_ashmem);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +010097 if (code_map == nullptr) {
98 std::ostringstream oss;
Nicolas Geoffray0a3be162015-11-18 11:15:22 +000099 oss << "Failed to create read write execute cache: " << error_str << " size=" << max_capacity;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100100 *error_msg = oss.str();
101 return nullptr;
102 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100103 DCHECK_EQ(code_map->Begin(), divider);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000104 data_size = initial_capacity / 2;
105 code_size = initial_capacity - data_size;
106 DCHECK_EQ(code_size + data_size, initial_capacity);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000107 return new JitCodeCache(
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000108 code_map, data_map, code_size, data_size, max_capacity, garbage_collect_code);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800109}
110
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000111JitCodeCache::JitCodeCache(MemMap* code_map,
112 MemMap* data_map,
113 size_t initial_code_capacity,
114 size_t initial_data_capacity,
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000115 size_t max_capacity,
116 bool garbage_collect_code)
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100117 : lock_("Jit code cache", kJitCodeCacheLock),
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100118 lock_cond_("Jit code cache variable", lock_),
119 collection_in_progress_(false),
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100120 code_map_(code_map),
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000121 data_map_(data_map),
122 max_capacity_(max_capacity),
123 current_capacity_(initial_code_capacity + initial_data_capacity),
124 code_end_(initial_code_capacity),
125 data_end_(initial_data_capacity),
Calin Juravle31f2c152015-10-23 17:56:15 +0100126 has_done_one_collection_(false),
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000127 last_update_time_ns_(0),
128 garbage_collect_code_(garbage_collect_code) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100129
Nicolas Geoffrayc3fec4c2016-01-14 16:16:35 +0000130 DCHECK_GE(max_capacity, initial_code_capacity + initial_data_capacity);
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000131 code_mspace_ = create_mspace_with_base(code_map_->Begin(), code_end_, false /*locked*/);
132 data_mspace_ = create_mspace_with_base(data_map_->Begin(), data_end_, false /*locked*/);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100133
134 if (code_mspace_ == nullptr || data_mspace_ == nullptr) {
135 PLOG(FATAL) << "create_mspace_with_base failed";
136 }
137
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000138 SetFootprintLimit(current_capacity_);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100139
140 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
141 CHECKED_MPROTECT(data_map_->Begin(), data_map_->Size(), kProtData);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100142
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000143 VLOG(jit) << "Created jit code cache: initial data size="
144 << PrettySize(initial_data_capacity)
145 << ", initial code size="
146 << PrettySize(initial_code_capacity);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800147}
148
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100149bool JitCodeCache::ContainsPc(const void* ptr) const {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100150 return code_map_->Begin() <= ptr && ptr < code_map_->End();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800151}
152
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000153bool JitCodeCache::ContainsMethod(ArtMethod* method) {
154 MutexLock mu(Thread::Current(), lock_);
155 for (auto& it : method_code_map_) {
156 if (it.second == method) {
157 return true;
158 }
159 }
160 return false;
161}
162
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100163class ScopedCodeCacheWrite {
164 public:
165 explicit ScopedCodeCacheWrite(MemMap* code_map) : code_map_(code_map) {
166 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtAll);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800167 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100168 ~ScopedCodeCacheWrite() {
169 CHECKED_MPROTECT(code_map_->Begin(), code_map_->Size(), kProtCode);
170 }
171 private:
172 MemMap* const code_map_;
173
174 DISALLOW_COPY_AND_ASSIGN(ScopedCodeCacheWrite);
175};
176
177uint8_t* JitCodeCache::CommitCode(Thread* self,
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100178 ArtMethod* method,
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100179 const uint8_t* mapping_table,
180 const uint8_t* vmap_table,
181 const uint8_t* gc_map,
182 size_t frame_size_in_bytes,
183 size_t core_spill_mask,
184 size_t fp_spill_mask,
185 const uint8_t* code,
186 size_t code_size) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100187 uint8_t* result = CommitCodeInternal(self,
188 method,
189 mapping_table,
190 vmap_table,
191 gc_map,
192 frame_size_in_bytes,
193 core_spill_mask,
194 fp_spill_mask,
195 code,
196 code_size);
197 if (result == nullptr) {
198 // Retry.
199 GarbageCollectCache(self);
200 result = CommitCodeInternal(self,
201 method,
202 mapping_table,
203 vmap_table,
204 gc_map,
205 frame_size_in_bytes,
206 core_spill_mask,
207 fp_spill_mask,
208 code,
209 code_size);
210 }
211 return result;
212}
213
214bool JitCodeCache::WaitForPotentialCollectionToComplete(Thread* self) {
215 bool in_collection = false;
216 while (collection_in_progress_) {
217 in_collection = true;
218 lock_cond_.Wait(self);
219 }
220 return in_collection;
221}
222
223static uintptr_t FromCodeToAllocation(const void* code) {
224 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
225 return reinterpret_cast<uintptr_t>(code) - RoundUp(sizeof(OatQuickMethodHeader), alignment);
226}
227
228void JitCodeCache::FreeCode(const void* code_ptr, ArtMethod* method ATTRIBUTE_UNUSED) {
229 uintptr_t allocation = FromCodeToAllocation(code_ptr);
230 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
231 const uint8_t* data = method_header->GetNativeGcMap();
David Srbecky5cc349f2015-12-18 15:04:48 +0000232 // Notify native debugger that we are about to remove the code.
233 // It does nothing if we are not using native debugger.
234 DeleteJITCodeEntryForAddress(reinterpret_cast<uintptr_t>(code_ptr));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100235 if (data != nullptr) {
236 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
237 }
238 data = method_header->GetMappingTable();
239 if (data != nullptr) {
240 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
241 }
242 // Use the offset directly to prevent sanity check that the method is
243 // compiled with optimizing.
244 // TODO(ngeoffray): Clean up.
245 if (method_header->vmap_table_offset_ != 0) {
246 data = method_header->code_ - method_header->vmap_table_offset_;
247 mspace_free(data_mspace_, const_cast<uint8_t*>(data));
248 }
249 mspace_free(code_mspace_, reinterpret_cast<uint8_t*>(allocation));
250}
251
252void JitCodeCache::RemoveMethodsIn(Thread* self, const LinearAlloc& alloc) {
253 MutexLock mu(self, lock_);
254 // We do not check if a code cache GC is in progress, as this method comes
255 // with the classlinker_classes_lock_ held, and suspending ourselves could
256 // lead to a deadlock.
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000257 {
258 ScopedCodeCacheWrite scc(code_map_.get());
259 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
260 if (alloc.ContainsUnsafe(it->second)) {
261 FreeCode(it->first, it->second);
262 it = method_code_map_.erase(it);
263 } else {
264 ++it;
265 }
266 }
267 }
268 for (auto it = profiling_infos_.begin(); it != profiling_infos_.end();) {
269 ProfilingInfo* info = *it;
270 if (alloc.ContainsUnsafe(info->GetMethod())) {
271 info->GetMethod()->SetProfilingInfo(nullptr);
272 mspace_free(data_mspace_, reinterpret_cast<uint8_t*>(info));
273 it = profiling_infos_.erase(it);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100274 } else {
275 ++it;
276 }
277 }
278}
279
280uint8_t* JitCodeCache::CommitCodeInternal(Thread* self,
281 ArtMethod* method,
282 const uint8_t* mapping_table,
283 const uint8_t* vmap_table,
284 const uint8_t* gc_map,
285 size_t frame_size_in_bytes,
286 size_t core_spill_mask,
287 size_t fp_spill_mask,
288 const uint8_t* code,
289 size_t code_size) {
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100290 size_t alignment = GetInstructionSetAlignment(kRuntimeISA);
291 // Ensure the header ends up at expected instruction alignment.
292 size_t header_size = RoundUp(sizeof(OatQuickMethodHeader), alignment);
293 size_t total_size = header_size + code_size;
294
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100295 OatQuickMethodHeader* method_header = nullptr;
Nicolas Geoffray1e7de6c2015-10-21 12:07:31 +0100296 uint8_t* code_ptr = nullptr;
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100297 {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000298 ScopedThreadSuspension sts(self, kSuspended);
299 MutexLock mu(self, lock_);
300 WaitForPotentialCollectionToComplete(self);
301 {
302 ScopedCodeCacheWrite scc(code_map_.get());
303 uint8_t* result = reinterpret_cast<uint8_t*>(
304 mspace_memalign(code_mspace_, alignment, total_size));
305 if (result == nullptr) {
306 return nullptr;
307 }
308 code_ptr = result + header_size;
309 DCHECK_ALIGNED_PARAM(reinterpret_cast<uintptr_t>(code_ptr), alignment);
310
311 std::copy(code, code + code_size, code_ptr);
312 method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
313 new (method_header) OatQuickMethodHeader(
314 (mapping_table == nullptr) ? 0 : code_ptr - mapping_table,
315 (vmap_table == nullptr) ? 0 : code_ptr - vmap_table,
316 (gc_map == nullptr) ? 0 : code_ptr - gc_map,
317 frame_size_in_bytes,
318 core_spill_mask,
319 fp_spill_mask,
320 code_size);
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100321 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100322
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000323 __builtin___clear_cache(reinterpret_cast<char*>(code_ptr),
324 reinterpret_cast<char*>(code_ptr + code_size));
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100325 }
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000326 // We need to update the entry point in the runnable state for the instrumentation.
327 {
328 MutexLock mu(self, lock_);
329 method_code_map_.Put(code_ptr, method);
330 Runtime::Current()->GetInstrumentation()->UpdateMethodsCode(
331 method, method_header->GetEntryPoint());
332 if (collection_in_progress_) {
333 // We need to update the live bitmap if there is a GC to ensure it sees this new
334 // code.
335 GetLiveBitmap()->AtomicTestAndSet(FromCodeToAllocation(code_ptr));
336 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000337 last_update_time_ns_.StoreRelease(NanoTime());
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000338 VLOG(jit)
339 << "JIT added "
340 << PrettyMethod(method) << "@" << method
341 << " ccache_size=" << PrettySize(CodeCacheSizeLocked()) << ": "
342 << " dcache_size=" << PrettySize(DataCacheSizeLocked()) << ": "
343 << reinterpret_cast<const void*>(method_header->GetEntryPoint()) << ","
344 << reinterpret_cast<const void*>(method_header->GetEntryPoint() + method_header->code_size_);
345 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100346
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100347 return reinterpret_cast<uint8_t*>(method_header);
348}
349
350size_t JitCodeCache::CodeCacheSize() {
351 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000352 return CodeCacheSizeLocked();
353}
354
355size_t JitCodeCache::CodeCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100356 size_t bytes_allocated = 0;
357 mspace_inspect_all(code_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
358 return bytes_allocated;
359}
360
361size_t JitCodeCache::DataCacheSize() {
362 MutexLock mu(Thread::Current(), lock_);
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000363 return DataCacheSizeLocked();
364}
365
366size_t JitCodeCache::DataCacheSizeLocked() {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100367 size_t bytes_allocated = 0;
368 mspace_inspect_all(data_mspace_, DlmallocBytesAllocatedCallback, &bytes_allocated);
369 return bytes_allocated;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800370}
371
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100372size_t JitCodeCache::NumberOfCompiledCode() {
373 MutexLock mu(Thread::Current(), lock_);
374 return method_code_map_.size();
375}
376
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000377void JitCodeCache::ClearData(Thread* self, void* data) {
378 MutexLock mu(self, lock_);
379 mspace_free(data_mspace_, data);
380}
381
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100382uint8_t* JitCodeCache::ReserveData(Thread* self, size_t size) {
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100383 size = RoundUp(size, sizeof(void*));
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100384 uint8_t* result = nullptr;
385
386 {
387 ScopedThreadSuspension sts(self, kSuspended);
388 MutexLock mu(self, lock_);
389 WaitForPotentialCollectionToComplete(self);
390 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
391 }
392
393 if (result == nullptr) {
394 // Retry.
395 GarbageCollectCache(self);
396 ScopedThreadSuspension sts(self, kSuspended);
397 MutexLock mu(self, lock_);
398 WaitForPotentialCollectionToComplete(self);
399 result = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, size));
400 }
401
402 return result;
Nicolas Geoffray5550ca82015-08-21 18:38:30 +0100403}
404
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800405uint8_t* JitCodeCache::AddDataArray(Thread* self, const uint8_t* begin, const uint8_t* end) {
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100406 uint8_t* result = ReserveData(self, end - begin);
407 if (result == nullptr) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800408 return nullptr; // Out of space in the data cache.
409 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +0100410 std::copy(begin, end, result);
411 return result;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800412}
413
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100414class MarkCodeVisitor FINAL : public StackVisitor {
415 public:
416 MarkCodeVisitor(Thread* thread_in, JitCodeCache* code_cache_in)
417 : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
418 code_cache_(code_cache_in),
419 bitmap_(code_cache_->GetLiveBitmap()) {}
420
421 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
422 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
423 if (method_header == nullptr) {
424 return true;
425 }
426 const void* code = method_header->GetCode();
427 if (code_cache_->ContainsPc(code)) {
428 // Use the atomic set version, as multiple threads are executing this code.
429 bitmap_->AtomicTestAndSet(FromCodeToAllocation(code));
430 }
431 return true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800432 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100433
434 private:
435 JitCodeCache* const code_cache_;
436 CodeCacheBitmap* const bitmap_;
437};
438
439class MarkCodeClosure FINAL : public Closure {
440 public:
441 MarkCodeClosure(JitCodeCache* code_cache, Barrier* barrier)
442 : code_cache_(code_cache), barrier_(barrier) {}
443
444 void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
445 DCHECK(thread == Thread::Current() || thread->IsSuspended());
446 MarkCodeVisitor visitor(thread, code_cache_);
447 visitor.WalkStack();
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000448 if (kIsDebugBuild) {
449 // The stack walking code queries the side instrumentation stack if it
450 // sees an instrumentation exit pc, so the JIT code of methods in that stack
451 // must have been seen. We sanity check this below.
452 for (const instrumentation::InstrumentationStackFrame& frame
453 : *thread->GetInstrumentationStack()) {
454 // The 'method_' in InstrumentationStackFrame is the one that has return_pc_ in
455 // its stack frame, it is not the method owning return_pc_. We just pass null to
456 // LookupMethodHeader: the method is only checked against in debug builds.
457 OatQuickMethodHeader* method_header =
458 code_cache_->LookupMethodHeader(frame.return_pc_, nullptr);
459 if (method_header != nullptr) {
460 const void* code = method_header->GetCode();
461 CHECK(code_cache_->GetLiveBitmap()->Test(FromCodeToAllocation(code)));
462 }
463 }
464 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700465 barrier_->Pass(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800466 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100467
468 private:
469 JitCodeCache* const code_cache_;
470 Barrier* const barrier_;
471};
472
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000473void JitCodeCache::NotifyCollectionDone(Thread* self) {
474 collection_in_progress_ = false;
475 lock_cond_.Broadcast(self);
476}
477
478void JitCodeCache::SetFootprintLimit(size_t new_footprint) {
479 size_t per_space_footprint = new_footprint / 2;
480 DCHECK(IsAlignedParam(per_space_footprint, kPageSize));
481 DCHECK_EQ(per_space_footprint * 2, new_footprint);
482 mspace_set_footprint_limit(data_mspace_, per_space_footprint);
483 {
484 ScopedCodeCacheWrite scc(code_map_.get());
485 mspace_set_footprint_limit(code_mspace_, per_space_footprint);
486 }
487}
488
489bool JitCodeCache::IncreaseCodeCacheCapacity() {
490 if (current_capacity_ == max_capacity_) {
491 return false;
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100492 }
493
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000494 // Double the capacity if we're below 1MB, or increase it by 1MB if
495 // we're above.
496 if (current_capacity_ < 1 * MB) {
497 current_capacity_ *= 2;
498 } else {
499 current_capacity_ += 1 * MB;
500 }
501 if (current_capacity_ > max_capacity_) {
502 current_capacity_ = max_capacity_;
503 }
504
505 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
506 LOG(INFO) << "Increasing code cache capacity to " << PrettySize(current_capacity_);
507 }
508
509 SetFootprintLimit(current_capacity_);
510
511 return true;
512}
513
514void JitCodeCache::GarbageCollectCache(Thread* self) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000515 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100516
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000517 // Wait for an existing collection, or let everyone know we are starting one.
518 {
519 ScopedThreadSuspension sts(self, kSuspended);
520 MutexLock mu(self, lock_);
521 if (WaitForPotentialCollectionToComplete(self)) {
522 return;
523 } else {
524 collection_in_progress_ = true;
525 }
526 }
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000527
528 // Check if we just need to grow the capacity. If we don't, allocate the bitmap while
529 // we hold the lock.
530 {
531 MutexLock mu(self, lock_);
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000532 if (!garbage_collect_code_) {
533 IncreaseCodeCacheCapacity();
534 NotifyCollectionDone(self);
535 return;
536 } else if (has_done_one_collection_ && IncreaseCodeCacheCapacity()) {
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000537 has_done_one_collection_ = false;
538 NotifyCollectionDone(self);
539 return;
540 } else {
541 live_bitmap_.reset(CodeCacheBitmap::Create(
542 "code-cache-bitmap",
543 reinterpret_cast<uintptr_t>(code_map_->Begin()),
544 reinterpret_cast<uintptr_t>(code_map_->Begin() + current_capacity_ / 2)));
545 }
546 }
547
548 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
549 LOG(INFO) << "Clearing code cache, code="
550 << PrettySize(CodeCacheSize())
551 << ", data=" << PrettySize(DataCacheSize());
552 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100553 // Walk over all compiled methods and set the entry points of these
554 // methods to interpreter.
555 {
556 MutexLock mu(self, lock_);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100557 for (auto& it : method_code_map_) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000558 instrumentation->UpdateMethodsCode(it.second, GetQuickToInterpreterBridge());
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100559 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000560 for (ProfilingInfo* info : profiling_infos_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100561 if (!info->IsMethodBeingCompiled()) {
562 info->GetMethod()->SetProfilingInfo(nullptr);
563 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000564 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100565 }
566
567 // Run a checkpoint on all threads to mark the JIT compiled code they are running.
568 {
569 Barrier barrier(0);
Nicolas Geoffray62623402015-10-28 19:15:05 +0000570 size_t threads_running_checkpoint = 0;
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000571 MarkCodeClosure closure(this, &barrier);
572 threads_running_checkpoint =
573 Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
574 // Now that we have run our checkpoint, move to a suspended state and wait
575 // for other threads to run the checkpoint.
576 ScopedThreadSuspension sts(self, kSuspended);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100577 if (threads_running_checkpoint != 0) {
578 barrier.Increment(self, threads_running_checkpoint);
579 }
580 }
581
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100582 {
583 MutexLock mu(self, lock_);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000584 // Free unused compiled code, and restore the entry point of used compiled code.
585 {
586 ScopedCodeCacheWrite scc(code_map_.get());
587 for (auto it = method_code_map_.begin(); it != method_code_map_.end();) {
588 const void* code_ptr = it->first;
589 ArtMethod* method = it->second;
590 uintptr_t allocation = FromCodeToAllocation(code_ptr);
591 const OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
592 if (GetLiveBitmap()->Test(allocation)) {
Nicolas Geoffraya5891e82015-11-06 14:18:27 +0000593 instrumentation->UpdateMethodsCode(method, method_header->GetEntryPoint());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000594 ++it;
595 } else {
596 method->ClearCounter();
597 DCHECK_NE(method->GetEntryPointFromQuickCompiledCode(), method_header->GetEntryPoint());
598 FreeCode(code_ptr, method);
599 it = method_code_map_.erase(it);
600 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100601 }
602 }
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000603
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100604 void* data_mspace = data_mspace_;
605 // Free all profiling infos of methods that were not being compiled.
606 auto profiling_kept_end = std::remove_if(profiling_infos_.begin(), profiling_infos_.end(),
607 [data_mspace] (ProfilingInfo* info) {
608 if (info->GetMethod()->GetProfilingInfo(sizeof(void*)) == nullptr) {
609 mspace_free(data_mspace, reinterpret_cast<uint8_t*>(info));
610 return true;
611 }
612 return false;
613 });
614 profiling_infos_.erase(profiling_kept_end, profiling_infos_.end());
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000615
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000616 live_bitmap_.reset(nullptr);
617 has_done_one_collection_ = true;
618 NotifyCollectionDone(self);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100619 }
620
621 if (!kIsDebugBuild || VLOG_IS_ON(jit)) {
622 LOG(INFO) << "After clearing code cache, code="
623 << PrettySize(CodeCacheSize())
624 << ", data=" << PrettySize(DataCacheSize());
625 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800626}
627
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100628
629OatQuickMethodHeader* JitCodeCache::LookupMethodHeader(uintptr_t pc, ArtMethod* method) {
630 static_assert(kRuntimeISA != kThumb2, "kThumb2 cannot be a runtime ISA");
631 if (kRuntimeISA == kArm) {
632 // On Thumb-2, the pc is offset by one.
633 --pc;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800634 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100635 if (!ContainsPc(reinterpret_cast<const void*>(pc))) {
636 return nullptr;
637 }
638
639 MutexLock mu(Thread::Current(), lock_);
640 if (method_code_map_.empty()) {
641 return nullptr;
642 }
643 auto it = method_code_map_.lower_bound(reinterpret_cast<const void*>(pc));
644 --it;
645
646 const void* code_ptr = it->first;
647 OatQuickMethodHeader* method_header = OatQuickMethodHeader::FromCodePointer(code_ptr);
648 if (!method_header->Contains(pc)) {
649 return nullptr;
650 }
Nicolas Geoffray5a23d2e2015-11-03 18:58:57 +0000651 if (kIsDebugBuild && method != nullptr) {
652 DCHECK_EQ(it->second, method)
653 << PrettyMethod(method) << " " << PrettyMethod(it->second) << " " << std::hex << pc;
654 }
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +0100655 return method_header;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800656}
657
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000658ProfilingInfo* JitCodeCache::AddProfilingInfo(Thread* self,
659 ArtMethod* method,
660 const std::vector<uint32_t>& entries,
661 bool retry_allocation) {
662 ProfilingInfo* info = AddProfilingInfoInternal(self, method, entries);
663
664 if (info == nullptr && retry_allocation) {
665 GarbageCollectCache(self);
666 info = AddProfilingInfoInternal(self, method, entries);
667 }
668 return info;
669}
670
671ProfilingInfo* JitCodeCache::AddProfilingInfoInternal(Thread* self,
672 ArtMethod* method,
673 const std::vector<uint32_t>& entries) {
674 size_t profile_info_size = RoundUp(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100675 sizeof(ProfilingInfo) + sizeof(InlineCache) * entries.size(),
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000676 sizeof(void*));
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000677 MutexLock mu(self, lock_);
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000678
679 // Check whether some other thread has concurrently created it.
680 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
681 if (info != nullptr) {
682 return info;
683 }
684
685 uint8_t* data = reinterpret_cast<uint8_t*>(mspace_malloc(data_mspace_, profile_info_size));
686 if (data == nullptr) {
687 return nullptr;
688 }
689 info = new (data) ProfilingInfo(method, entries);
Nicolas Geoffray07f35642016-01-04 16:06:51 +0000690
691 // Make sure other threads see the data in the profiling info object before the
692 // store in the ArtMethod's ProfilingInfo pointer.
693 QuasiAtomic::ThreadFenceRelease();
694
Nicolas Geoffray26705e22015-10-28 12:50:11 +0000695 method->SetProfilingInfo(info);
696 profiling_infos_.push_back(info);
697 return info;
698}
699
Nicolas Geoffray0a3be162015-11-18 11:15:22 +0000700// NO_THREAD_SAFETY_ANALYSIS as this is called from mspace code, at which point the lock
701// is already held.
702void* JitCodeCache::MoreCore(const void* mspace, intptr_t increment) NO_THREAD_SAFETY_ANALYSIS {
703 if (code_mspace_ == mspace) {
704 size_t result = code_end_;
705 code_end_ += increment;
706 return reinterpret_cast<void*>(result + code_map_->Begin());
707 } else {
708 DCHECK_EQ(data_mspace_, mspace);
709 size_t result = data_end_;
710 data_end_ += increment;
711 return reinterpret_cast<void*>(result + data_map_->Begin());
712 }
713}
714
Calin Juravle66f55232015-12-08 15:09:10 +0000715void JitCodeCache::GetCompiledArtMethods(const std::set<const std::string>& dex_base_locations,
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000716 std::vector<ArtMethod*>& methods) {
Calin Juravle31f2c152015-10-23 17:56:15 +0100717 MutexLock mu(Thread::Current(), lock_);
718 for (auto it : method_code_map_) {
Calin Juravle66f55232015-12-08 15:09:10 +0000719 if (ContainsElement(dex_base_locations, it.second->GetDexFile()->GetBaseLocation())) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000720 methods.push_back(it.second);
Calin Juravle31f2c152015-10-23 17:56:15 +0100721 }
722 }
723}
724
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000725uint64_t JitCodeCache::GetLastUpdateTimeNs() const {
726 return last_update_time_ns_.LoadAcquire();
Calin Juravle31f2c152015-10-23 17:56:15 +0100727}
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100728
729bool JitCodeCache::NotifyCompilationOf(ArtMethod* method, Thread* self) {
730 if (ContainsPc(method->GetEntryPointFromQuickCompiledCode())) {
731 return false;
732 }
733 MutexLock mu(self, lock_);
734 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
735 if (info == nullptr || info->IsMethodBeingCompiled()) {
736 return false;
737 }
738 info->SetIsMethodBeingCompiled(true);
739 return true;
740}
741
742void JitCodeCache::DoneCompiling(ArtMethod* method, Thread* self ATTRIBUTE_UNUSED) {
743 ProfilingInfo* info = method->GetProfilingInfo(sizeof(void*));
744 DCHECK(info->IsMethodBeingCompiled());
745 info->SetIsMethodBeingCompiled(false);
746}
747
Nicolas Geoffraya25dce92016-01-12 16:41:10 +0000748size_t JitCodeCache::GetMemorySizeOfCodePointer(const void* ptr) {
749 MutexLock mu(Thread::Current(), lock_);
750 return mspace_usable_size(reinterpret_cast<const void*>(FromCodeToAllocation(ptr)));
751}
752
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800753} // namespace jit
754} // namespace art