1 /* 2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "code/codeBlob.hpp" 27 #include "code/codeCache.hpp" 28 #include "code/compiledIC.hpp" 29 #include "code/dependencies.hpp" 30 #include "code/icBuffer.hpp" 31 #include "code/nmethod.hpp" 32 #include "code/pcDesc.hpp" 33 #include "compiler/compileBroker.hpp" 34 #include "gc_implementation/shared/markSweep.hpp" 35 #include "memory/allocation.inline.hpp" 36 #include "memory/gcLocker.hpp" 37 #include "memory/iterator.hpp" 38 #include "memory/resourceArea.hpp" 39 #include "oops/method.hpp" 40 #include "oops/objArrayOop.hpp" 41 #include "oops/oop.inline.hpp" 42 #include "runtime/handles.inline.hpp" 43 #include "runtime/arguments.hpp" 44 #include "runtime/icache.hpp" 45 #include "runtime/java.hpp" 46 #include "runtime/mutexLocker.hpp" 47 #include "services/memoryService.hpp" 48 #include "trace/tracing.hpp" 49 #include "utilities/xmlstream.hpp" 50 51 52 // Helper class for printing in CodeCache 53 class CodeBlob_sizes { 54 private: 55 int count; 56 int total_size; 57 int header_size; 58 int code_size; 59 int stub_size; 60 int relocation_size; 61 int scopes_oop_size; 62 int scopes_metadata_size; 63 int scopes_data_size; 64 int scopes_pcs_size; 65 66 public: 67 CodeBlob_sizes() { 68 count = 0; 69 total_size = 0; 70 header_size = 0; 71 code_size = 0; 72 stub_size = 0; 73 relocation_size = 0; 74 scopes_oop_size = 0; 75 scopes_metadata_size = 0; 76 scopes_data_size = 0; 77 scopes_pcs_size = 0; 78 } 79 80 int total() { return total_size; } 81 bool is_empty() { return count == 0; } 82 83 void print(const char* title) { 84 tty->print_cr(" #%d %s = %dK (hdr %d%%, loc %d%%, code %d%%, stub %d%%, [oops %d%%, data %d%%, pcs %d%%])", 85 count, 86 title, 87 total() / K, 88 header_size * 100 / total_size, 89 relocation_size * 100 / total_size, 90 code_size * 100 / total_size, 91 stub_size * 100 / total_size, 92 scopes_oop_size * 100 / total_size, 93 scopes_metadata_size * 100 / total_size, 94 scopes_data_size * 100 / total_size, 95 scopes_pcs_size * 100 / total_size); 96 } 97 98 void add(CodeBlob* cb) { 99 count++; 100 total_size += cb->size(); 101 header_size += cb->header_size(); 102 relocation_size += cb->relocation_size(); 103 if (cb->is_nmethod()) { 104 nmethod* nm = cb->as_nmethod_or_null(); 105 code_size += nm->insts_size(); 106 stub_size += nm->stub_size(); 107 108 scopes_oop_size += nm->oops_size(); 109 scopes_metadata_size += nm->metadata_size(); 110 scopes_data_size += nm->scopes_data_size(); 111 scopes_pcs_size += nm->scopes_pcs_size(); 112 } else { 113 code_size += cb->code_size(); 114 } 115 } 116 }; 117 118 119 // Iterates of all heap indexes (index) 120 #define FOR_ALL_HEAPS(index) for (int index = 0; index < _heaps->length(); ++index) 121 // Iterates over all CodeBlobs (cb) of the given heap index (heap_index) 122 #define FOR_ALL_BLOBS(cb, heap_index) for (CodeBlob* cb = (CodeBlob*)_heaps->at(heap_index)->first(); cb != NULL; cb = (CodeBlob*)_heaps->at(heap_index)->next(cb)) 123 // Iterates over all CodeBlobTypes (bt) corresponding to nmethods compiled at different tiers 124 #define FOR_ALL_METHOD_TYPES(bt) for (CodeBlobType bt = btMethodNoProfile; (int)bt <= (int)btMethodProfile; bt = (CodeBlobType) ((int)bt + 1)) 125 // Iterates over all nmethods (nm) of the given CodeBlobType (bt) 126 #define FOR_ALL_NMETHODS(nm, bt) for (nmethod* nm = (nmethod*)first_blob(bt); nm != NULL; nm = (nmethod*)next_blob(nm, bt)) 127 // Iterates over all alive nmethods (nm) of the given CodeBlobType (bt) 128 #define FOR_ALL_ALIVE_NMETHODS(nm, bt) for (nmethod* nm = (nmethod*)first_alive_blob(bt); nm != NULL; nm = (nmethod*)next_alive_blob(nm, bt)) 129 130 // Addresses of the code heaps (referenced by vmStructs) 131 CodeHeap* CodeCache::_heap_non_profiled = NULL; 132 CodeHeap* CodeCache::_heap_profiled = NULL; 133 CodeHeap* CodeCache::_heap_non_method = NULL; 134 135 address CodeCache::_low_bound = 0; 136 address CodeCache::_high_bound = 0; 137 int CodeCache::_number_of_blobs = 0; 138 int CodeCache::_number_of_adapters = 0; 139 int CodeCache::_number_of_nmethods = 0; 140 int CodeCache::_number_of_nmethods_with_dependencies = 0; 141 bool CodeCache::_needs_cache_clean = false; 142 nmethod* CodeCache::_scavenge_root_nmethods = NULL; 143 int CodeCache::_codemem_full_count = 0; 144 145 // Initialize array of CodeHeaps 146 GrowableArray<CodeHeap*>* CodeCache::_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (3, true); 147 148 void CodeCache::initialize_heaps() { 149 // Per default (with TieredCompilation) we use 2/3 of the ReservedCodeCacheSize 150 // for non-profiled methods and 1/3 for profiled methods. If we no not need one 151 // of the heaps, we use all space for the remaining heap. 152 if (FLAG_IS_DEFAULT(NonProfiledCodeHeapSize) && heap_available(btNonMethod)) { 153 FLAG_SET_DEFAULT(NonProfiledCodeHeapSize, ReservedCodeCacheSize * (heap_available(btMethodProfile) ? (double)2/3 : 1)); 154 } else if (!heap_available(btMethodNoProfile)) { 155 FLAG_SET_DEFAULT(NonProfiledCodeHeapSize, 0); 156 } 157 if (FLAG_IS_DEFAULT(ProfiledCodeHeapSize) && heap_available(btMethodProfile)) { 158 FLAG_SET_DEFAULT(ProfiledCodeHeapSize, ReservedCodeCacheSize * (heap_available(btMethodNoProfile) ? (double)1/3 : 1)); 159 } else if (!heap_available(btMethodProfile)) { 160 FLAG_SET_DEFAULT(ProfiledCodeHeapSize, 0); 161 } 162 // Check sizes 163 assert(ProfiledCodeHeapSize + NonProfiledCodeHeapSize <= ReservedCodeCacheSize, "CodeHeap size check"); 164 165 // Compute reserved sizes of CodeHeaps 166 // We need at most 8mb for the non method heap 167 size_t non_method_size = ReservedCodeSpace::allocation_align_size_up(MIN2(ReservedCodeCacheSize, 8*M)); 168 size_t no_profile_size = ReservedCodeSpace::allocation_align_size_up(NonProfiledCodeHeapSize); 169 size_t profile_size = ProfiledCodeHeapSize; 170 if (profile_size > non_method_size) { 171 profile_size = ProfiledCodeHeapSize - non_method_size; 172 } 173 profile_size = ReservedCodeSpace::allocation_align_size_up(profile_size); 174 175 // Compute initial sizes of CodeHeaps 176 size_t init_non_method_size = MIN2(InitialCodeCacheSize, non_method_size); 177 size_t init_no_profile_size = MIN2(InitialCodeCacheSize, no_profile_size); 178 size_t init_profile_size = MIN2(InitialCodeCacheSize, profile_size); 179 180 // Reserve one continuous chunk of memory for CodeHeaps and split it into 181 // parts for the individual heaps. The memory layout looks like this: 182 // ------ high ------- 183 // Non-methods 184 // T2 and T3 methods 185 // T1 and T4 methods 186 // ------ low -------- 187 ReservedCodeSpace rs = reserve_heap_memory(no_profile_size + profile_size + non_method_size); 188 ReservedSpace no_profile_space = rs.first_part(no_profile_size); 189 ReservedSpace rest = rs.last_part(no_profile_size); 190 ReservedSpace profile_space = rest.first_part(profile_size); 191 ReservedSpace non_method_space = rest.last_part(profile_size); 192 193 // T1 and T4 methods (+ native) 194 add_heap(no_profile_space, "T1 and T4 methods", init_no_profile_size, btMethodNoProfile); 195 // T2 and T3 methods 196 add_heap(profile_space, "T2 and T3 methods", init_profile_size, btMethodProfile); 197 // Non-methods 198 add_heap(non_method_space, "Non-methods", init_non_method_size, btNonMethod); 199 200 // Save addresses of code heap (referenced by vmStructs) 201 _heap_non_profiled = get_code_heap(btMethodNoProfile); 202 _heap_profiled = get_code_heap(btMethodProfile); 203 _heap_non_method = get_code_heap(btNonMethod); 204 } 205 206 ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) { 207 // Determine alignment 208 const size_t page_size = os::can_execute_large_page_memory() ? 209 os::page_size_for_region(InitialCodeCacheSize, size, 8) : 210 os::vm_page_size(); 211 const size_t granularity = os::vm_allocation_granularity(); 212 const size_t r_align = MAX2(page_size, granularity); 213 const size_t r_size = align_size_up(size, r_align); 214 const size_t rs_align = page_size == (size_t) os::vm_page_size() ? 0 : 215 MAX2(page_size, granularity); 216 217 ReservedCodeSpace rs(r_size, rs_align, rs_align > 0); 218 219 // Initialize bounds 220 _low_bound = (address)rs.base(); 221 _high_bound = _low_bound + rs.size(); 222 guarantee(low_bound() < high_bound(), "Bound check"); 223 224 return rs; 225 } 226 227 bool CodeCache::heap_available(CodeBlobType bt) { 228 if (TieredCompilation || bt == btNonMethod) { 229 // Use all heaps for TieredCompilation 230 return true; 231 } else { 232 #ifdef COMPILER2 233 // We only need the heap for C2 234 return (bt == btMethodNoProfile); 235 #else 236 // We need both heaps 237 return true; 238 #endif 239 } 240 } 241 242 void CodeCache::add_heap(ReservedSpace rs, const char* name, size_t size_initial, CodeBlobType bt) { 243 // Check if heap is needed 244 if (!heap_available(bt)) { 245 return; 246 } 247 248 // Create CodeHeap 249 CodeHeap* heap = new CodeHeap(name, bt); 250 _heaps->append(heap); 251 252 // Reserve Space 253 size_initial = round_to(size_initial, os::vm_page_size()); 254 255 if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) { 256 vm_exit_during_initialization("Could not reserve enough space for code cache"); 257 } 258 259 // Register the CodeHeap 260 MemoryService::add_code_heap_memory_pool(heap, name); 261 } 262 263 CodeHeap* CodeCache::get_code_heap(CodeBlobType bt) { 264 FOR_ALL_HEAPS(i) { 265 if (_heaps->at(i)->accepts(bt)) { 266 return _heaps->at(i); 267 } 268 } 269 return NULL; 270 } 271 272 CodeBlob* CodeCache::first_blob(CodeBlobType bt) { 273 assert_locked_or_safepoint(CodeCache_lock); 274 CodeHeap* heap = get_code_heap(bt); 275 if (heap != NULL) { 276 return (CodeBlob*)heap->first(); 277 } else { 278 return NULL; 279 } 280 } 281 282 CodeBlob* CodeCache::first_alive_blob(CodeBlobType bt) { 283 assert_locked_or_safepoint(CodeCache_lock); 284 CodeBlob* cb = first_blob(bt); 285 while (cb != NULL && !cb->is_alive()) { 286 cb = next_blob(cb, bt); 287 } 288 return cb; 289 } 290 291 CodeBlob* CodeCache::next_blob(CodeBlob* cb, CodeBlobType bt) { 292 assert_locked_or_safepoint(CodeCache_lock); 293 CodeHeap* heap = get_code_heap(bt); 294 if (heap != NULL) { 295 return (CodeBlob*)heap->next(cb); 296 } else { 297 return NULL; 298 } 299 } 300 301 CodeBlob* CodeCache::next_alive_blob(CodeBlob* cb, CodeBlobType bt) { 302 assert_locked_or_safepoint(CodeCache_lock); 303 cb = next_blob(cb, bt); 304 while (cb != NULL && !cb->is_alive()) { 305 cb = next_blob(cb, bt); 306 } 307 return cb; 308 } 309 310 CodeBlob* CodeCache::allocate(int size, CodeBlobType bt, bool is_critical) { 311 // Do not seize the CodeCache lock here--if the caller has not 312 // already done so, we are going to lose bigtime, since the code 313 // cache will contain a garbage CodeBlob until the caller can 314 // run the constructor for the CodeBlob subclass he is busy 315 // instantiating. 316 guarantee(size >= 0, "allocation request must be reasonable"); 317 assert_locked_or_safepoint(CodeCache_lock); 318 CodeBlob* cb = NULL; 319 _number_of_blobs++; 320 321 // Get code heap for the given CodeBlobType 322 CodeHeap * heap = get_code_heap(bt); 323 assert (heap != NULL, "Heap exists"); 324 325 while (true) { 326 cb = (CodeBlob*)heap->allocate(size, is_critical); 327 if (cb != NULL) break; 328 if (!heap->expand_by(CodeCacheExpansionSize)) { 329 // Expansion failed 330 return NULL; 331 } 332 if (PrintCodeCacheExtension) { 333 ResourceMark rm; 334 tty->print_cr("CodeHeap '%s' extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (%d bytes)", 335 heap->getName(), (intptr_t)heap->low_boundary(), (intptr_t)heap->high(), 336 (address)heap->high() - (address)heap->low_boundary()); 337 } 338 } 339 340 verify_if_often(); 341 print_trace("allocation", cb, size); 342 343 return cb; 344 } 345 346 void CodeCache::free(CodeBlob* cb, CodeBlobType bt) { 347 assert_locked_or_safepoint(CodeCache_lock); 348 verify_if_often(); 349 350 print_trace("free", cb); 351 if (cb->is_nmethod()) { 352 _number_of_nmethods--; 353 if (((nmethod *)cb)->has_dependencies()) { 354 _number_of_nmethods_with_dependencies--; 355 } 356 } 357 if (cb->is_adapter_blob()) { 358 _number_of_adapters--; 359 } 360 _number_of_blobs--; 361 362 // Get heap for given CodeBlobType and deallocate 363 get_code_heap(bt)->deallocate(cb); 364 365 verify_if_often(); 366 assert(_number_of_blobs >= 0, "sanity check"); 367 } 368 369 void CodeCache::commit(CodeBlob* cb) { 370 // this is called by nmethod::nmethod, which must already own CodeCache_lock 371 assert_locked_or_safepoint(CodeCache_lock); 372 if (cb->is_nmethod()) { 373 _number_of_nmethods++; 374 if (((nmethod *)cb)->has_dependencies()) { 375 _number_of_nmethods_with_dependencies++; 376 } 377 } 378 if (cb->is_adapter_blob()) { 379 _number_of_adapters++; 380 } 381 382 // flush the hardware I-cache 383 ICache::invalidate_range(cb->content_begin(), cb->content_size()); 384 } 385 386 bool CodeCache::contains(void *p) { 387 // It should be ok to call contains without holding a lock 388 FOR_ALL_HEAPS(i) { 389 CodeHeap* heap = (CodeHeap*) _heaps->at(i); 390 if (heap->contains(p)) { 391 return true; 392 } 393 } 394 return false; 395 } 396 397 // This method is safe to call without holding the CodeCache_lock, as long as a dead CodeBlob is not 398 // looked up (i.e., one that has been marked for deletion). It only depends on the _segmap to contain 399 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled. 400 CodeBlob* CodeCache::find_blob(void* start) { 401 CodeBlob* result = find_blob_unsafe(start); 402 // We could potentially look up non_entrant methods 403 guarantee(result == NULL || !result->is_zombie() || result->is_locked_by_vm() || is_error_reported(), "unsafe access to zombie method"); 404 return result; 405 } 406 407 // Lookup that does not fail if you lookup a zombie method (if you call this, be sure to know 408 // what you are doing) 409 CodeBlob* CodeCache::find_blob_unsafe(void* start) { 410 // NMT can walk the stack before code cache is created 411 if (_heaps->first() == NULL) return NULL; 412 413 FOR_ALL_HEAPS(i) { 414 CodeBlob* result = (CodeBlob*)_heaps->at(i)->find_start(start); 415 if (result != NULL && result->blob_contains((address)start)) { 416 return result; 417 } 418 } 419 return NULL; 420 } 421 422 nmethod* CodeCache::find_nmethod(void* start) { 423 CodeBlob* cb = find_blob(start); 424 assert(cb->is_nmethod(), "did not find an nmethod"); 425 return (nmethod*)cb; 426 } 427 428 bool CodeCache::contains_nmethod(nmethod* nm) { 429 FOR_ALL_METHOD_TYPES(bt) { 430 if (get_code_heap(bt)->contains(nm)) { 431 return true; 432 } 433 } 434 return false; 435 } 436 437 void CodeCache::blobs_do(void f(CodeBlob* nm)) { 438 assert_locked_or_safepoint(CodeCache_lock); 439 FOR_ALL_HEAPS(i) { 440 FOR_ALL_BLOBS(cb, i) { 441 f(cb); 442 } 443 } 444 } 445 446 void CodeCache::nmethods_do(void f(nmethod* nm)) { 447 assert_locked_or_safepoint(CodeCache_lock); 448 FOR_ALL_METHOD_TYPES(bt) { 449 FOR_ALL_NMETHODS(nm, bt) { 450 f(nm); 451 } 452 } 453 } 454 455 void CodeCache::alive_nmethods_do(void f(nmethod* nm)) { 456 assert_locked_or_safepoint(CodeCache_lock); 457 FOR_ALL_METHOD_TYPES(bt) { 458 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 459 f(nm); 460 } 461 } 462 } 463 464 int CodeCache::alignment_unit() { 465 return (int)_heaps->first()->alignment_unit(); 466 } 467 468 int CodeCache::alignment_offset() { 469 return (int)_heaps->first()->alignment_offset(); 470 } 471 472 // Mark nmethods for unloading if they contain otherwise unreachable oops. 473 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) { 474 assert_locked_or_safepoint(CodeCache_lock); 475 FOR_ALL_METHOD_TYPES(bt) { 476 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 477 nm->do_unloading(is_alive, unloading_occurred); 478 } 479 } 480 } 481 482 void CodeCache::blobs_do(CodeBlobClosure* f) { 483 assert_locked_or_safepoint(CodeCache_lock); 484 FOR_ALL_HEAPS(i) { 485 FOR_ALL_BLOBS(cb, i) { 486 if (cb->is_alive()) { 487 f->do_code_blob(cb); 488 489 #ifdef ASSERT 490 if (cb->is_nmethod()) 491 ((nmethod*)cb)->verify_scavenge_root_oops(); 492 #endif //ASSERT 493 } 494 } 495 } 496 } 497 498 // Walk the list of methods which might contain non-perm oops. 499 void CodeCache::scavenge_root_nmethods_do(CodeBlobClosure* f) { 500 assert_locked_or_safepoint(CodeCache_lock); 501 debug_only(mark_scavenge_root_nmethods()); 502 503 for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) { 504 debug_only(cur->clear_scavenge_root_marked()); 505 assert(cur->scavenge_root_not_marked(), ""); 506 assert(cur->on_scavenge_root_list(), "else shouldn't be on this list"); 507 508 bool is_live = (!cur->is_zombie() && !cur->is_unloaded()); 509 #ifndef PRODUCT 510 if (TraceScavenge) { 511 cur->print_on(tty, is_live ? "scavenge root" : "dead scavenge root"); tty->cr(); 512 } 513 #endif //PRODUCT 514 if (is_live) { 515 // Perform cur->oops_do(f), maybe just once per nmethod. 516 f->do_code_blob(cur); 517 } 518 } 519 520 // Check for stray marks. 521 debug_only(verify_perm_nmethods(NULL)); 522 } 523 524 void CodeCache::add_scavenge_root_nmethod(nmethod* nm) { 525 assert_locked_or_safepoint(CodeCache_lock); 526 nm->set_on_scavenge_root_list(); 527 nm->set_scavenge_root_link(_scavenge_root_nmethods); 528 set_scavenge_root_nmethods(nm); 529 print_trace("add_scavenge_root", nm); 530 } 531 532 void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) { 533 assert_locked_or_safepoint(CodeCache_lock); 534 print_trace("drop_scavenge_root", nm); 535 nmethod* last = NULL; 536 nmethod* cur = scavenge_root_nmethods(); 537 while (cur != NULL) { 538 nmethod* next = cur->scavenge_root_link(); 539 if (cur == nm) { 540 if (last != NULL) 541 last->set_scavenge_root_link(next); 542 else set_scavenge_root_nmethods(next); 543 nm->set_scavenge_root_link(NULL); 544 nm->clear_on_scavenge_root_list(); 545 return; 546 } 547 last = cur; 548 cur = next; 549 } 550 assert(false, "should have been on list"); 551 } 552 553 void CodeCache::prune_scavenge_root_nmethods() { 554 assert_locked_or_safepoint(CodeCache_lock); 555 debug_only(mark_scavenge_root_nmethods()); 556 557 nmethod* last = NULL; 558 nmethod* cur = scavenge_root_nmethods(); 559 while (cur != NULL) { 560 nmethod* next = cur->scavenge_root_link(); 561 debug_only(cur->clear_scavenge_root_marked()); 562 assert(cur->scavenge_root_not_marked(), ""); 563 assert(cur->on_scavenge_root_list(), "else shouldn't be on this list"); 564 565 if (!cur->is_zombie() && !cur->is_unloaded() 566 && cur->detect_scavenge_root_oops()) { 567 // Keep it. Advance 'last' to prevent deletion. 568 last = cur; 569 } else { 570 // Prune it from the list, so we don't have to look at it any more. 571 print_trace("prune_scavenge_root", cur); 572 cur->set_scavenge_root_link(NULL); 573 cur->clear_on_scavenge_root_list(); 574 if (last != NULL) 575 last->set_scavenge_root_link(next); 576 else set_scavenge_root_nmethods(next); 577 } 578 cur = next; 579 } 580 581 // Check for stray marks. 582 debug_only(verify_perm_nmethods(NULL)); 583 } 584 585 #ifndef PRODUCT 586 void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) { 587 // While we are here, verify the integrity of the list. 588 mark_scavenge_root_nmethods(); 589 for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) { 590 assert(cur->on_scavenge_root_list(), "else shouldn't be on this list"); 591 cur->clear_scavenge_root_marked(); 592 } 593 verify_perm_nmethods(f); 594 } 595 596 // Temporarily mark nmethods that are claimed to be on the non-perm list. 597 void CodeCache::mark_scavenge_root_nmethods() { 598 FOR_ALL_METHOD_TYPES(bt) { 599 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 600 assert(nm->scavenge_root_not_marked(), "clean state"); 601 if (nm->on_scavenge_root_list()) 602 nm->set_scavenge_root_marked(); 603 } 604 } 605 } 606 607 // If the closure is given, run it on the unlisted nmethods. 608 // Also make sure that the effects of mark_scavenge_root_nmethods is gone. 609 void CodeCache::verify_perm_nmethods(CodeBlobClosure* f_or_null) { 610 FOR_ALL_METHOD_TYPES(bt) { 611 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 612 bool call_f = (f_or_null != NULL); 613 assert(nm->scavenge_root_not_marked(), "must be already processed"); 614 if (nm->on_scavenge_root_list()) 615 call_f = false; // don't show this one to the client 616 nm->verify_scavenge_root_oops(); 617 if (call_f) f_or_null->do_code_blob(nm); 618 } 619 } 620 } 621 #endif //PRODUCT 622 623 void CodeCache::gc_prologue() { 624 assert(!nmethod::oops_do_marking_is_active(), "oops_do_marking_epilogue must be called"); 625 } 626 627 void CodeCache::gc_epilogue() { 628 assert_locked_or_safepoint(CodeCache_lock); 629 FOR_ALL_METHOD_TYPES(bt) { 630 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 631 assert(!nm->is_unloaded(), "Tautology"); 632 if (needs_cache_clean()) { 633 nm->cleanup_inline_caches(); 634 } 635 DEBUG_ONLY(nm->verify()); 636 nm->fix_oop_relocations(); 637 } 638 } 639 set_needs_cache_clean(false); 640 prune_scavenge_root_nmethods(); 641 assert(!nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called"); 642 643 #ifdef ASSERT 644 // make sure that we aren't leaking icholders 645 int count = 0; 646 FOR_ALL_METHOD_TYPES(bt) { 647 FOR_ALL_NMETHODS(nm, bt) { 648 RelocIterator iter(nm); 649 while(iter.next()) { 650 if (iter.type() == relocInfo::virtual_call_type) { 651 if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) { 652 CompiledIC *ic = CompiledIC_at(iter.reloc()); 653 if (TraceCompiledIC) { 654 tty->print("noticed icholder " INTPTR_FORMAT " ", ic->cached_icholder()); 655 ic->print(); 656 } 657 assert(ic->cached_icholder() != NULL, "must be non-NULL"); 658 count++; 659 } 660 } 661 } 662 } 663 } 664 665 assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() == 666 CompiledICHolder::live_count(), "must agree"); 667 #endif 668 } 669 670 void CodeCache::verify_oops() { 671 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 672 VerifyOopClosure voc; 673 FOR_ALL_METHOD_TYPES(bt) { 674 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 675 nm->oops_do(&voc); 676 nm->verify_oop_relocations(); 677 } 678 } 679 } 680 681 size_t CodeCache::capacity() { 682 size_t cap = 0; 683 FOR_ALL_HEAPS(i) { 684 cap += _heaps->at(i)->capacity(); 685 } 686 return cap; 687 } 688 689 size_t CodeCache::unallocated_capacity() { 690 size_t unallocated_cap = 0; 691 FOR_ALL_HEAPS(i) { 692 unallocated_cap += _heaps->at(i)->unallocated_capacity(); 693 } 694 return unallocated_cap; 695 } 696 697 size_t CodeCache::max_capacity() { 698 size_t max_cap = 0; 699 FOR_ALL_HEAPS(i) { 700 max_cap += _heaps->at(i)->max_capacity(); 701 } 702 return max_cap; 703 } 704 705 /** 706 * Returns the reverse free ratio. E.g., if 25% (1/4) of the code cache 707 * is free, reverse_free_ratio() returns 4. 708 */ 709 double CodeCache::reverse_free_ratio(CodeBlobType bt) { 710 CodeHeap* heap = get_code_heap(bt); 711 if (heap == NULL) { 712 return 0; 713 } 714 double unallocated_capacity = (double)(heap->unallocated_capacity() - CodeCacheMinimumFreeSpace); 715 double max_capacity = (double)heap->max_capacity(); 716 return max_capacity / unallocated_capacity; 717 } 718 719 void icache_init(); 720 721 void CodeCache::initialize() { 722 assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points"); 723 #ifdef COMPILER2 724 assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment, "CodeCacheSegmentSize must be large enough to align inner loops"); 725 #endif 726 assert(CodeCacheSegmentSize >= sizeof(jdouble), "CodeCacheSegmentSize must be large enough to align constants"); 727 // This was originally just a check of the alignment, causing failure, instead, round 728 // the code cache to the page size. In particular, Solaris is moving to a larger 729 // default page size. 730 CodeCacheExpansionSize = round_to(CodeCacheExpansionSize, os::vm_page_size()); 731 732 // Reserve space and create heaps 733 initialize_heaps(); 734 735 // Initialize ICache flush mechanism 736 // This service is needed for os::register_code_area 737 icache_init(); 738 739 // Give OS a chance to register generated code area. 740 // This is used on Windows 64 bit platforms to register 741 // Structured Exception Handlers for our generated code. 742 os::register_code_area((char*)low_bound(), (char*)high_bound()); 743 } 744 745 void codeCache_init() { 746 CodeCache::initialize(); 747 } 748 749 //------------------------------------------------------------------------------------------------ 750 751 int CodeCache::number_of_nmethods_with_dependencies() { 752 return _number_of_nmethods_with_dependencies; 753 } 754 755 void CodeCache::clear_inline_caches() { 756 assert_locked_or_safepoint(CodeCache_lock); 757 FOR_ALL_METHOD_TYPES(bt) { 758 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 759 nm->clear_inline_caches(); 760 } 761 } 762 } 763 764 #ifndef PRODUCT 765 // used to keep track of how much time is spent in mark_for_deoptimization 766 static elapsedTimer dependentCheckTime; 767 static int dependentCheckCount = 0; 768 #endif // PRODUCT 769 770 771 int CodeCache::mark_for_deoptimization(DepChange& changes) { 772 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 773 774 #ifndef PRODUCT 775 dependentCheckTime.start(); 776 dependentCheckCount++; 777 #endif // PRODUCT 778 779 int number_of_marked_CodeBlobs = 0; 780 781 // search the hierarchy looking for nmethods which are affected by the loading of this class 782 783 // then search the interfaces this class implements looking for nmethods 784 // which might be dependent of the fact that an interface only had one 785 // implementor. 786 787 { No_Safepoint_Verifier nsv; 788 for (DepChange::ContextStream str(changes, nsv); str.next(); ) { 789 Klass* d = str.klass(); 790 number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes); 791 } 792 } 793 794 if (VerifyDependencies) { 795 // Turn off dependency tracing while actually testing deps. 796 NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) ); 797 FOR_ALL_METHOD_TYPES(bt) { 798 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 799 if (!nm->is_marked_for_deoptimization() && 800 nm->check_all_dependencies()) { 801 ResourceMark rm; 802 tty->print_cr("Should have been marked for deoptimization:"); 803 changes.print(); 804 nm->print(); 805 nm->print_dependencies(); 806 } 807 } 808 } 809 } 810 811 #ifndef PRODUCT 812 dependentCheckTime.stop(); 813 #endif // PRODUCT 814 815 return number_of_marked_CodeBlobs; 816 } 817 818 819 #ifdef HOTSWAP 820 int CodeCache::mark_for_evol_deoptimization(instanceKlassHandle dependee) { 821 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 822 int number_of_marked_CodeBlobs = 0; 823 824 // Deoptimize all methods of the evolving class itself 825 Array<Method*>* old_methods = dependee->methods(); 826 for (int i = 0; i < old_methods->length(); i++) { 827 ResourceMark rm; 828 Method* old_method = old_methods->at(i); 829 nmethod *nm = old_method->code(); 830 if (nm != NULL) { 831 nm->mark_for_deoptimization(); 832 number_of_marked_CodeBlobs++; 833 } 834 } 835 836 FOR_ALL_METHOD_TYPES(bt) { 837 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 838 if (nm->is_marked_for_deoptimization()) { 839 // ...Already marked in the previous pass; don't count it again. 840 } else if (nm->is_evol_dependent_on(dependee())) { 841 ResourceMark rm; 842 nm->mark_for_deoptimization(); 843 number_of_marked_CodeBlobs++; 844 } else { 845 // flush caches in case they refer to a redefined Method* 846 nm->clear_inline_caches(); 847 } 848 } 849 } 850 851 return number_of_marked_CodeBlobs; 852 } 853 #endif // HOTSWAP 854 855 856 // Deoptimize all methods 857 void CodeCache::mark_all_nmethods_for_deoptimization() { 858 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 859 FOR_ALL_METHOD_TYPES(bt) { 860 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 861 nm->mark_for_deoptimization(); 862 } 863 } 864 } 865 866 int CodeCache::mark_for_deoptimization(Method* dependee) { 867 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 868 int number_of_marked_CodeBlobs = 0; 869 870 FOR_ALL_METHOD_TYPES(bt) { 871 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 872 if (nm->is_dependent_on_method(dependee)) { 873 ResourceMark rm; 874 nm->mark_for_deoptimization(); 875 number_of_marked_CodeBlobs++; 876 } 877 } 878 } 879 880 return number_of_marked_CodeBlobs; 881 } 882 883 void CodeCache::make_marked_nmethods_zombies() { 884 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint"); 885 FOR_ALL_METHOD_TYPES(bt) { 886 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 887 if (nm->is_marked_for_deoptimization()) { 888 889 // If the nmethod has already been made non-entrant and it can be converted 890 // then zombie it now. Otherwise make it non-entrant and it will eventually 891 // be zombied when it is no longer seen on the stack. Note that the nmethod 892 // might be "entrant" and not on the stack and so could be zombied immediately 893 // but we can't tell because we don't track it on stack until it becomes 894 // non-entrant. 895 896 if (nm->is_not_entrant() && nm->can_not_entrant_be_converted()) { 897 nm->make_zombie(); 898 } else { 899 nm->make_not_entrant(); 900 } 901 } 902 } 903 } 904 } 905 906 void CodeCache::make_marked_nmethods_not_entrant() { 907 assert_locked_or_safepoint(CodeCache_lock); 908 FOR_ALL_METHOD_TYPES(bt) { 909 FOR_ALL_ALIVE_NMETHODS(nm, bt) { 910 if (nm->is_marked_for_deoptimization()) { 911 nm->make_not_entrant(); 912 } 913 } 914 } 915 } 916 917 void CodeCache::verify() { 918 assert_locked_or_safepoint(CodeCache_lock); 919 FOR_ALL_HEAPS(i) { 920 _heaps->at(i)->verify(); 921 FOR_ALL_BLOBS(cb, i) { 922 if (cb->is_alive()) { 923 cb->verify(); 924 } 925 } 926 } 927 } 928 929 void CodeCache::report_codemem_full(CodeBlobType bt) { 930 // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event 931 CodeHeap* heap = get_code_heap(bt); 932 933 if (!heap->was_full()) { 934 // Not yet reported for this heap, report 935 heap->report_full(); 936 warning("CodeHeap for %s is full. Compilation for these methods has been delayed.", CodeCache::get_heap_name(bt)); 937 warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize="); 938 939 ResourceMark rm; 940 stringStream s; 941 // Dump CodeCache summary into a buffer before locking the tty 942 { 943 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 944 print_summary(&s, true); 945 } 946 ttyLocker ttyl; 947 tty->print(s.as_string()); 948 } 949 950 _codemem_full_count++; 951 EventCodeCacheFull event; 952 if (event.should_commit()) { 953 event.set_codeBlobType(bt); 954 event.set_startAddress((u8)heap->low_boundary()); 955 event.set_commitedTopAddress((u8)heap->high()); 956 event.set_reservedTopAddress((u8)heap->high_boundary()); 957 event.set_entryCount(nof_blobs()); 958 event.set_methodCount(nof_nmethods()); 959 event.set_adaptorCount(nof_adapters()); 960 event.set_unallocatedCapacity(heap->unallocated_capacity()/K); 961 event.set_fullCount(_codemem_full_count); 962 event.commit(); 963 } 964 } 965 966 //------------------------------------------------------------------------------------------------ 967 // Non-product version 968 969 #ifndef PRODUCT 970 971 void CodeCache::verify_if_often() { 972 if (VerifyCodeCacheOften) { 973 FOR_ALL_HEAPS(i) { 974 _heaps->at(i)->verify(); 975 } 976 } 977 } 978 979 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) { 980 if (PrintCodeCache2) { // Need to add a new flag 981 ResourceMark rm; 982 if (size == 0) size = cb->size(); 983 tty->print_cr("CodeCache %s: addr: " INTPTR_FORMAT ", size: 0x%x", event, cb, size); 984 } 985 } 986 987 void CodeCache::print_internals() { 988 int nmethodCount = 0; 989 int runtimeStubCount = 0; 990 int adapterCount = 0; 991 int deoptimizationStubCount = 0; 992 int uncommonTrapStubCount = 0; 993 int bufferBlobCount = 0; 994 int total = 0; 995 int nmethodAlive = 0; 996 int nmethodNotEntrant = 0; 997 int nmethodZombie = 0; 998 int nmethodUnloaded = 0; 999 int nmethodJava = 0; 1000 int nmethodNative = 0; 1001 int maxCodeSize = 0; 1002 ResourceMark rm; 1003 1004 int i = 0; 1005 FOR_ALL_HEAPS(i) { 1006 if (Verbose) { 1007 tty->print_cr("## Heap '%s' ##", _heaps->at(i)->getName()); 1008 } 1009 FOR_ALL_BLOBS(cb, i) { 1010 total++; 1011 if (cb->is_nmethod()) { 1012 nmethod* nm = (nmethod*)cb; 1013 1014 if (Verbose && nm->method() != NULL) { 1015 ResourceMark rm; 1016 char *method_name = nm->method()->name_and_sig_as_C_string(); 1017 tty->print("%s %d", method_name, nm->comp_level()); 1018 if(nm->is_alive()) { tty->print_cr(" alive"); } 1019 if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); } 1020 if(nm->is_zombie()) { tty->print_cr(" zombie"); } 1021 } 1022 1023 nmethodCount++; 1024 1025 if(nm->is_alive()) { nmethodAlive++; } 1026 if(nm->is_not_entrant()) { nmethodNotEntrant++; } 1027 if(nm->is_zombie()) { nmethodZombie++; } 1028 if(nm->is_unloaded()) { nmethodUnloaded++; } 1029 if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; } 1030 1031 if(nm->method() != NULL && nm->is_java_method()) { 1032 nmethodJava++; 1033 if (nm->insts_size() > maxCodeSize) { 1034 maxCodeSize = nm->insts_size(); 1035 } 1036 } 1037 } else if (cb->is_runtime_stub()) { 1038 runtimeStubCount++; 1039 } else if (cb->is_deoptimization_stub()) { 1040 deoptimizationStubCount++; 1041 } else if (cb->is_uncommon_trap_stub()) { 1042 uncommonTrapStubCount++; 1043 } else if (cb->is_adapter_blob()) { 1044 adapterCount++; 1045 } else if (cb->is_buffer_blob()) { 1046 bufferBlobCount++; 1047 } 1048 } 1049 } 1050 1051 int bucketSize = 512; 1052 int bucketLimit = maxCodeSize / bucketSize + 1; 1053 int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode); 1054 memset(buckets,0,sizeof(int) * bucketLimit); 1055 1056 FOR_ALL_METHOD_TYPES(bt) { 1057 FOR_ALL_NMETHODS(nm, bt) { 1058 if(nm->method() != NULL && nm->is_java_method()) { 1059 buckets[nm->insts_size() / bucketSize]++; 1060 } 1061 } 1062 } 1063 tty->print_cr("Code Cache Entries (total of %d)",total); 1064 tty->print_cr("-------------------------------------------------"); 1065 tty->print_cr("nmethods: %d",nmethodCount); 1066 tty->print_cr("\talive: %d",nmethodAlive); 1067 tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant); 1068 tty->print_cr("\tzombie: %d",nmethodZombie); 1069 tty->print_cr("\tunloaded: %d",nmethodUnloaded); 1070 tty->print_cr("\tjava: %d",nmethodJava); 1071 tty->print_cr("\tnative: %d",nmethodNative); 1072 tty->print_cr("runtime_stubs: %d",runtimeStubCount); 1073 tty->print_cr("adapters: %d",adapterCount); 1074 tty->print_cr("buffer blobs: %d",bufferBlobCount); 1075 tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount); 1076 tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount); 1077 tty->print_cr("\nnmethod size distribution (non-zombie java)"); 1078 tty->print_cr("-------------------------------------------------"); 1079 1080 for(int i = 0; i < bucketLimit; ++i) { 1081 if(buckets[i] != 0) { 1082 tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize); 1083 tty->fill_to(40); 1084 tty->print_cr("%d",buckets[i]); 1085 } 1086 } 1087 1088 FREE_C_HEAP_ARRAY(int, buckets, mtCode); 1089 } 1090 1091 #endif // !PRODUCT 1092 1093 void CodeCache::print() { 1094 print_summary(tty); 1095 1096 #ifndef PRODUCT 1097 if (!Verbose) return; 1098 1099 CodeBlob_sizes live; 1100 CodeBlob_sizes dead; 1101 1102 FOR_ALL_HEAPS(i) { 1103 FOR_ALL_BLOBS(cb, i) { 1104 if (!cb->is_alive()) { 1105 dead.add(cb); 1106 } else { 1107 live.add(cb); 1108 } 1109 } 1110 } 1111 1112 tty->print_cr("CodeCache:"); 1113 1114 tty->print_cr("nmethod dependency checking time %f", dependentCheckTime.seconds(), 1115 dependentCheckTime.seconds() / dependentCheckCount); 1116 1117 if (!live.is_empty()) { 1118 live.print("live"); 1119 } 1120 if (!dead.is_empty()) { 1121 dead.print("dead"); 1122 } 1123 1124 if (WizardMode) { 1125 // print the oop_map usage 1126 int code_size = 0; 1127 int number_of_blobs = 0; 1128 int number_of_oop_maps = 0; 1129 int map_size = 0; 1130 FOR_ALL_HEAPS(i) { 1131 FOR_ALL_BLOBS(cb, i) { 1132 if (cb->is_alive()) { 1133 number_of_blobs++; 1134 code_size += cb->code_size(); 1135 OopMapSet* set = cb->oop_maps(); 1136 if (set != NULL) { 1137 number_of_oop_maps += set->size(); 1138 map_size += set->heap_size(); 1139 } 1140 } 1141 } 1142 } 1143 tty->print_cr("OopMaps"); 1144 tty->print_cr(" #blobs = %d", number_of_blobs); 1145 tty->print_cr(" code size = %d", code_size); 1146 tty->print_cr(" #oop_maps = %d", number_of_oop_maps); 1147 tty->print_cr(" map size = %d", map_size); 1148 } 1149 1150 #endif // !PRODUCT 1151 } 1152 1153 void CodeCache::print_summary(outputStream* st, bool detailed) { 1154 st->print_cr("CodeCache Summary:"); 1155 FOR_ALL_HEAPS(i) { 1156 CodeHeap* heap = _heaps->at(i); 1157 size_t total = (heap->high_boundary() - heap->low_boundary()); 1158 st->print_cr("Heap '%s': size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT 1159 "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb", 1160 _heaps->at(i)->getName(), total/K, (total - heap->unallocated_capacity())/K, 1161 heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K); 1162 1163 if (detailed) { 1164 st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]", 1165 heap->low_boundary(), 1166 heap->high(), 1167 heap->high_boundary()); 1168 1169 } 1170 } 1171 1172 if (detailed) { 1173 log_state(st); 1174 st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ? 1175 "enabled" : Arguments::mode() == Arguments::_int ? 1176 "disabled (interpreter mode)" : 1177 "disabled (not enough contiguous free space left)"); 1178 } 1179 } 1180 1181 void CodeCache::log_state(outputStream* st) { 1182 st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'" 1183 " adapters='" UINT32_FORMAT "'", 1184 nof_blobs(), nof_nmethods(), nof_adapters()); 1185 } 1186