1 /*
   2  * Copyright (c) 1997, 2018, 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 "jfr/jfrEvents.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/gcLocker.hpp"
  38 #include "memory/iterator.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "oops/method.hpp"
  41 #include "oops/objArrayOop.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "runtime/handles.inline.hpp"
  44 #include "runtime/arguments.hpp"
  45 #include "runtime/deoptimization.hpp"
  46 #include "runtime/icache.hpp"
  47 #include "runtime/java.hpp"
  48 #include "runtime/mutexLocker.hpp"
  49 #include "services/memoryService.hpp"
  50 #include "utilities/xmlstream.hpp"
  51 
  52 
  53 // Helper class for printing in CodeCache
  54 
  55 class CodeBlob_sizes {
  56  private:
  57   int count;
  58   int total_size;
  59   int header_size;
  60   int code_size;
  61   int stub_size;
  62   int relocation_size;
  63   int scopes_oop_size;
  64   int scopes_metadata_size;
  65   int scopes_data_size;
  66   int scopes_pcs_size;
  67 
  68  public:
  69   CodeBlob_sizes() {
  70     count            = 0;
  71     total_size       = 0;
  72     header_size      = 0;
  73     code_size        = 0;
  74     stub_size        = 0;
  75     relocation_size  = 0;
  76     scopes_oop_size  = 0;
  77     scopes_metadata_size  = 0;
  78     scopes_data_size = 0;
  79     scopes_pcs_size  = 0;
  80   }
  81 
  82   int total()                                    { return total_size; }
  83   bool is_empty()                                { return count == 0; }
  84 
  85   void print(const char* title) {
  86     tty->print_cr(" #%d %s = %dK (hdr %d%%,  loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])",
  87                   count,
  88                   title,
  89                   (int)(total() / K),
  90                   header_size             * 100 / total_size,
  91                   relocation_size         * 100 / total_size,
  92                   code_size               * 100 / total_size,
  93                   stub_size               * 100 / total_size,
  94                   scopes_oop_size         * 100 / total_size,
  95                   scopes_metadata_size    * 100 / total_size,
  96                   scopes_data_size        * 100 / total_size,
  97                   scopes_pcs_size         * 100 / total_size);
  98   }
  99 
 100   void add(CodeBlob* cb) {
 101     count++;
 102     total_size       += cb->size();
 103     header_size      += cb->header_size();
 104     relocation_size  += cb->relocation_size();
 105     if (cb->is_nmethod()) {
 106       nmethod* nm = cb->as_nmethod_or_null();
 107       code_size        += nm->insts_size();
 108       stub_size        += nm->stub_size();
 109 
 110       scopes_oop_size  += nm->oops_size();
 111       scopes_metadata_size  += nm->metadata_size();
 112       scopes_data_size += nm->scopes_data_size();
 113       scopes_pcs_size  += nm->scopes_pcs_size();
 114     } else {
 115       code_size        += cb->code_size();
 116     }
 117   }
 118 };
 119 
 120 // CodeCache implementation
 121 
 122 CodeHeap * CodeCache::_heap = new CodeHeap();
 123 int CodeCache::_number_of_blobs = 0;
 124 int CodeCache::_number_of_adapters = 0;
 125 int CodeCache::_number_of_nmethods = 0;
 126 int CodeCache::_number_of_nmethods_with_dependencies = 0;
 127 bool CodeCache::_needs_cache_clean = false;
 128 nmethod* CodeCache::_scavenge_root_nmethods = NULL;
 129 
 130 int CodeCache::_codemem_full_count = 0;
 131 
 132 CodeBlob* CodeCache::first() {
 133   assert_locked_or_safepoint(CodeCache_lock);
 134   return (CodeBlob*)_heap->first();
 135 }
 136 
 137 
 138 CodeBlob* CodeCache::next(CodeBlob* cb) {
 139   assert_locked_or_safepoint(CodeCache_lock);
 140   return (CodeBlob*)_heap->next(cb);
 141 }
 142 
 143 
 144 CodeBlob* CodeCache::alive(CodeBlob *cb) {
 145   assert_locked_or_safepoint(CodeCache_lock);
 146   while (cb != NULL && !cb->is_alive()) cb = next(cb);
 147   return cb;
 148 }
 149 
 150 
 151 nmethod* CodeCache::alive_nmethod(CodeBlob* cb) {
 152   assert_locked_or_safepoint(CodeCache_lock);
 153   while (cb != NULL && (!cb->is_alive() || !cb->is_nmethod())) cb = next(cb);
 154   return (nmethod*)cb;
 155 }
 156 
 157 nmethod* CodeCache::first_nmethod() {
 158   assert_locked_or_safepoint(CodeCache_lock);
 159   CodeBlob* cb = first();
 160   while (cb != NULL && !cb->is_nmethod()) {
 161     cb = next(cb);
 162   }
 163   return (nmethod*)cb;
 164 }
 165 
 166 nmethod* CodeCache::next_nmethod (CodeBlob* cb) {
 167   assert_locked_or_safepoint(CodeCache_lock);
 168   cb = next(cb);
 169   while (cb != NULL && !cb->is_nmethod()) {
 170     cb = next(cb);
 171   }
 172   return (nmethod*)cb;
 173 }
 174 
 175 static size_t maxCodeCacheUsed = 0;
 176 
 177 CodeBlob* CodeCache::allocate(int size, bool is_critical) {
 178   // Do not seize the CodeCache lock here--if the caller has not
 179   // already done so, we are going to lose bigtime, since the code
 180   // cache will contain a garbage CodeBlob until the caller can
 181   // run the constructor for the CodeBlob subclass he is busy
 182   // instantiating.
 183   guarantee(size >= 0, "allocation request must be reasonable");
 184   assert_locked_or_safepoint(CodeCache_lock);
 185   CodeBlob* cb = NULL;
 186   _number_of_blobs++;
 187   while (true) {
 188     cb = (CodeBlob*)_heap->allocate(size, is_critical);
 189     if (cb != NULL) break;
 190     if (!_heap->expand_by(CodeCacheExpansionSize)) {
 191       // Expansion failed
 192       if (CodeCache_lock->owned_by_self()) {
 193         MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 194         report_codemem_full();
 195       } else {
 196         report_codemem_full();
 197       }
 198       return NULL;
 199     }
 200     if (PrintCodeCacheExtension) {
 201       ResourceMark rm;
 202       tty->print_cr("code cache extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",
 203                     (intptr_t)_heap->low_boundary(), (intptr_t)_heap->high(),
 204                     (address)_heap->high() - (address)_heap->low_boundary());
 205     }
 206   }
 207   maxCodeCacheUsed = MAX2(maxCodeCacheUsed, ((address)_heap->high_boundary() -
 208                           (address)_heap->low_boundary()) - unallocated_capacity());
 209   verify_if_often();
 210   print_trace("allocation", cb, size);
 211   return cb;
 212 }
 213 
 214 void CodeCache::free(CodeBlob* cb) {
 215   assert_locked_or_safepoint(CodeCache_lock);
 216   verify_if_often();
 217 
 218   print_trace("free", cb);
 219   if (cb->is_nmethod()) {
 220     _number_of_nmethods--;
 221     if (((nmethod *)cb)->has_dependencies()) {
 222       _number_of_nmethods_with_dependencies--;
 223     }
 224   }
 225   if (cb->is_adapter_blob()) {
 226     _number_of_adapters--;
 227   }
 228   _number_of_blobs--;
 229 
 230   _heap->deallocate(cb);
 231 
 232   verify_if_often();
 233   assert(_number_of_blobs >= 0, "sanity check");
 234 }
 235 
 236 
 237 void CodeCache::commit(CodeBlob* cb) {
 238   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 239   assert_locked_or_safepoint(CodeCache_lock);
 240   if (cb->is_nmethod()) {
 241     _number_of_nmethods++;
 242     if (((nmethod *)cb)->has_dependencies()) {
 243       _number_of_nmethods_with_dependencies++;
 244     }
 245   }
 246   if (cb->is_adapter_blob()) {
 247     _number_of_adapters++;
 248   }
 249 
 250   // flush the hardware I-cache
 251   ICache::invalidate_range(cb->content_begin(), cb->content_size());
 252 }
 253 
 254 
 255 void CodeCache::flush() {
 256   assert_locked_or_safepoint(CodeCache_lock);
 257   Unimplemented();
 258 }
 259 
 260 
 261 // Iteration over CodeBlobs
 262 
 263 #define FOR_ALL_BLOBS(var)       for (CodeBlob *var =       first() ; var != NULL; var =       next(var) )
 264 #define FOR_ALL_ALIVE_BLOBS(var) for (CodeBlob *var = alive(first()); var != NULL; var = alive(next(var)))
 265 #define FOR_ALL_ALIVE_NMETHODS(var) for (nmethod *var = alive_nmethod(first()); var != NULL; var = alive_nmethod(next(var)))
 266 
 267 
 268 bool CodeCache::contains(void *p) {
 269   // It should be ok to call contains without holding a lock
 270   return _heap->contains(p);
 271 }
 272 
 273 
 274 // This method is safe to call without holding the CodeCache_lock, as long as a dead codeblob is not
 275 // looked up (i.e., one that has been marked for deletion). It only dependes on the _segmap to contain
 276 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 277 CodeBlob* CodeCache::find_blob(void* start) {
 278   CodeBlob* result = find_blob_unsafe(start);
 279   if (result == NULL) return NULL;
 280   // We could potientially look up non_entrant methods
 281   guarantee(!result->is_zombie() || result->is_locked_by_vm() || is_error_reported(), "unsafe access to zombie method");
 282   return result;
 283 }
 284 
 285 nmethod* CodeCache::find_nmethod(void* start) {
 286   CodeBlob *cb = find_blob(start);
 287   assert(cb == NULL || cb->is_nmethod(), "did not find an nmethod");
 288   return (nmethod*)cb;
 289 }
 290 
 291 
 292 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 293   assert_locked_or_safepoint(CodeCache_lock);
 294   FOR_ALL_BLOBS(p) {
 295     f(p);
 296   }
 297 }
 298 
 299 
 300 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 301   assert_locked_or_safepoint(CodeCache_lock);
 302   FOR_ALL_BLOBS(nm) {
 303     if (nm->is_nmethod()) f((nmethod*)nm);
 304   }
 305 }
 306 
 307 void CodeCache::alive_nmethods_do(void f(nmethod* nm)) {
 308   assert_locked_or_safepoint(CodeCache_lock);
 309   FOR_ALL_ALIVE_NMETHODS(nm) {
 310     f(nm);
 311   }
 312 }
 313 
 314 int CodeCache::alignment_unit() {
 315   return (int)_heap->alignment_unit();
 316 }
 317 
 318 
 319 int CodeCache::alignment_offset() {
 320   return (int)_heap->alignment_offset();
 321 }
 322 
 323 
 324 // Mark nmethods for unloading if they contain otherwise unreachable
 325 // oops.
 326 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
 327   assert_locked_or_safepoint(CodeCache_lock);
 328   FOR_ALL_ALIVE_NMETHODS(nm) {
 329     nm->do_unloading(is_alive, unloading_occurred);
 330   }
 331 }
 332 
 333 void CodeCache::blobs_do(CodeBlobClosure* f) {
 334   assert_locked_or_safepoint(CodeCache_lock);
 335   FOR_ALL_ALIVE_BLOBS(cb) {
 336     f->do_code_blob(cb);
 337 
 338 #ifdef ASSERT
 339     if (cb->is_nmethod())
 340       ((nmethod*)cb)->verify_scavenge_root_oops();
 341 #endif //ASSERT
 342   }
 343 }
 344 
 345 // Walk the list of methods which might contain non-perm oops.
 346 void CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure* f) {
 347   assert_locked_or_safepoint(CodeCache_lock);
 348 
 349   if (UseG1GC) {
 350     return;
 351   }
 352 
 353   const bool fix_relocations = f->fix_relocations();
 354   debug_only(mark_scavenge_root_nmethods());
 355 
 356   nmethod* prev = NULL;
 357   nmethod* cur = scavenge_root_nmethods();
 358   while (cur != NULL) {
 359     debug_only(cur->clear_scavenge_root_marked());
 360     assert(cur->scavenge_root_not_marked(), "");
 361     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 362 
 363     bool is_live = (!cur->is_zombie() && !cur->is_unloaded());
 364 #ifndef PRODUCT
 365     if (TraceScavenge) {
 366       cur->print_on(tty, is_live ? "scavenge root" : "dead scavenge root"); tty->cr();
 367     }
 368 #endif //PRODUCT
 369     if (is_live) {
 370       // Perform cur->oops_do(f), maybe just once per nmethod.
 371       f->do_code_blob(cur);
 372     }
 373     nmethod* const next = cur->scavenge_root_link();
 374     // The scavengable nmethod list must contain all methods with scavengable
 375     // oops. It is safe to include more nmethod on the list, but we do not
 376     // expect any live non-scavengable nmethods on the list.
 377     if (fix_relocations) {
 378       if (!is_live || !cur->detect_scavenge_root_oops()) {
 379         unlink_scavenge_root_nmethod(cur, prev);
 380       } else {
 381         prev = cur;
 382       }
 383     }
 384     cur = next;
 385   }
 386 
 387   // Check for stray marks.
 388   debug_only(verify_perm_nmethods(NULL));
 389 }
 390 
 391 void CodeCache::add_scavenge_root_nmethod(nmethod* nm) {
 392   assert_locked_or_safepoint(CodeCache_lock);
 393 
 394   if (UseG1GC) {
 395     return;
 396   }
 397 
 398   nm->set_on_scavenge_root_list();
 399   nm->set_scavenge_root_link(_scavenge_root_nmethods);
 400   set_scavenge_root_nmethods(nm);
 401   print_trace("add_scavenge_root", nm);
 402 }
 403 
 404 void CodeCache::unlink_scavenge_root_nmethod(nmethod* nm, nmethod* prev) {
 405   assert_locked_or_safepoint(CodeCache_lock);
 406 
 407   assert((prev == NULL && scavenge_root_nmethods() == nm) ||
 408          (prev != NULL && prev->scavenge_root_link() == nm), "precondition");
 409 
 410   assert(!UseG1GC, "G1 does not use the scavenge_root_nmethods list");
 411 
 412   print_trace("unlink_scavenge_root", nm);
 413   if (prev == NULL) {
 414     set_scavenge_root_nmethods(nm->scavenge_root_link());
 415   } else {
 416     prev->set_scavenge_root_link(nm->scavenge_root_link());
 417   }
 418   nm->set_scavenge_root_link(NULL);
 419   nm->clear_on_scavenge_root_list();
 420 }
 421 
 422 void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) {
 423   assert_locked_or_safepoint(CodeCache_lock);
 424 
 425   if (UseG1GC) {
 426     return;
 427   }
 428 
 429   print_trace("drop_scavenge_root", nm);
 430   nmethod* prev = NULL;
 431   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 432     if (cur == nm) {
 433       unlink_scavenge_root_nmethod(cur, prev);
 434       return;
 435     }
 436     prev = cur;
 437   }
 438   assert(false, "should have been on list");
 439 }
 440 
 441 void CodeCache::prune_scavenge_root_nmethods() {
 442   assert_locked_or_safepoint(CodeCache_lock);
 443 
 444   if (UseG1GC) {
 445     return;
 446   }
 447 
 448   debug_only(mark_scavenge_root_nmethods());
 449 
 450   nmethod* last = NULL;
 451   nmethod* cur = scavenge_root_nmethods();
 452   while (cur != NULL) {
 453     nmethod* next = cur->scavenge_root_link();
 454     debug_only(cur->clear_scavenge_root_marked());
 455     assert(cur->scavenge_root_not_marked(), "");
 456     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 457 
 458     if (!cur->is_zombie() && !cur->is_unloaded()
 459         && cur->detect_scavenge_root_oops()) {
 460       // Keep it.  Advance 'last' to prevent deletion.
 461       last = cur;
 462     } else {
 463       // Prune it from the list, so we don't have to look at it any more.
 464       print_trace("prune_scavenge_root", cur);
 465       unlink_scavenge_root_nmethod(cur, last);
 466     }
 467     cur = next;
 468   }
 469 
 470   // Check for stray marks.
 471   debug_only(verify_perm_nmethods(NULL));
 472 }
 473 
 474 #ifndef PRODUCT
 475 void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) {
 476   if (UseG1GC) {
 477     return;
 478   }
 479 
 480   // While we are here, verify the integrity of the list.
 481   mark_scavenge_root_nmethods();
 482   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 483     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 484     cur->clear_scavenge_root_marked();
 485   }
 486   verify_perm_nmethods(f);
 487 }
 488 
 489 // Temporarily mark nmethods that are claimed to be on the non-perm list.
 490 void CodeCache::mark_scavenge_root_nmethods() {
 491   FOR_ALL_ALIVE_BLOBS(cb) {
 492     if (cb->is_nmethod()) {
 493       nmethod *nm = (nmethod*)cb;
 494       assert(nm->scavenge_root_not_marked(), "clean state");
 495       if (nm->on_scavenge_root_list())
 496         nm->set_scavenge_root_marked();
 497     }
 498   }
 499 }
 500 
 501 // If the closure is given, run it on the unlisted nmethods.
 502 // Also make sure that the effects of mark_scavenge_root_nmethods is gone.
 503 void CodeCache::verify_perm_nmethods(CodeBlobClosure* f_or_null) {
 504   FOR_ALL_ALIVE_BLOBS(cb) {
 505     bool call_f = (f_or_null != NULL);
 506     if (cb->is_nmethod()) {
 507       nmethod *nm = (nmethod*)cb;
 508       assert(nm->scavenge_root_not_marked(), "must be already processed");
 509       if (nm->on_scavenge_root_list())
 510         call_f = false;  // don't show this one to the client
 511       nm->verify_scavenge_root_oops();
 512     } else {
 513       call_f = false;   // not an nmethod
 514     }
 515     if (call_f)  f_or_null->do_code_blob(cb);
 516   }
 517 }
 518 #endif //PRODUCT
 519 
 520 void CodeCache::verify_clean_inline_caches() {
 521 #ifdef ASSERT
 522   FOR_ALL_ALIVE_BLOBS(cb) {
 523     if (cb->is_nmethod()) {
 524       nmethod* nm = (nmethod*)cb;
 525       assert(!nm->is_unloaded(), "Tautology");
 526       nm->verify_clean_inline_caches();
 527       nm->verify();
 528     }
 529   }
 530 #endif
 531 }
 532 
 533 void CodeCache::verify_icholder_relocations() {
 534 #ifdef ASSERT
 535   // make sure that we aren't leaking icholders
 536   int count = 0;
 537   FOR_ALL_BLOBS(cb) {
 538     if (cb->is_nmethod()) {
 539       nmethod* nm = (nmethod*)cb;
 540       count += nm->verify_icholder_relocations();
 541     }
 542   }
 543 
 544   assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
 545          CompiledICHolder::live_count(), "must agree");
 546 #endif
 547 }
 548 
 549 void CodeCache::gc_prologue() {
 550 }
 551 
 552 void CodeCache::gc_epilogue() {
 553   assert_locked_or_safepoint(CodeCache_lock);
 554   NOT_DEBUG(if (needs_cache_clean())) {
 555     FOR_ALL_ALIVE_BLOBS(cb) {
 556       if (cb->is_nmethod()) {
 557         nmethod *nm = (nmethod*)cb;
 558         assert(!nm->is_unloaded(), "Tautology");
 559         DEBUG_ONLY(if (needs_cache_clean())) {
 560           nm->cleanup_inline_caches();
 561         }
 562         DEBUG_ONLY(nm->verify());
 563         DEBUG_ONLY(nm->verify_oop_relocations());
 564       }
 565     }
 566   }
 567   set_needs_cache_clean(false);
 568   prune_scavenge_root_nmethods();
 569 
 570   verify_icholder_relocations();
 571 }
 572 
 573 void CodeCache::verify_oops() {
 574   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 575   VerifyOopClosure voc;
 576   FOR_ALL_ALIVE_BLOBS(cb) {
 577     if (cb->is_nmethod()) {
 578       nmethod *nm = (nmethod*)cb;
 579       nm->oops_do(&voc);
 580       nm->verify_oop_relocations();
 581     }
 582   }
 583 }
 584 
 585 
 586 address CodeCache::first_address() {
 587   assert_locked_or_safepoint(CodeCache_lock);
 588   return (address)_heap->low_boundary();
 589 }
 590 
 591 
 592 address CodeCache::last_address() {
 593   assert_locked_or_safepoint(CodeCache_lock);
 594   return (address)_heap->high();
 595 }
 596 
 597 /**
 598  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code cache
 599  * is free, reverse_free_ratio() returns 4.
 600  */
 601 double CodeCache::reverse_free_ratio() {
 602   double unallocated_capacity = (double)(CodeCache::unallocated_capacity() - CodeCacheMinimumFreeSpace);
 603   double max_capacity = (double)CodeCache::max_capacity();
 604   return max_capacity / unallocated_capacity;
 605 }
 606 
 607 void icache_init();
 608 
 609 void CodeCache::initialize() {
 610   assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
 611 #ifdef COMPILER2
 612   assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
 613 #endif
 614   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
 615   // This was originally just a check of the alignment, causing failure, instead, round
 616   // the code cache to the page size.  In particular, Solaris is moving to a larger
 617   // default page size.
 618   CodeCacheExpansionSize = round_to(CodeCacheExpansionSize, os::vm_page_size());
 619   InitialCodeCacheSize = round_to(InitialCodeCacheSize, os::vm_page_size());
 620   ReservedCodeCacheSize = round_to(ReservedCodeCacheSize, os::vm_page_size());
 621   if (!_heap->reserve(ReservedCodeCacheSize, InitialCodeCacheSize, CodeCacheSegmentSize)) {
 622     vm_exit_during_initialization("Could not reserve enough space for code cache");
 623   }
 624 
 625   MemoryService::add_code_heap_memory_pool(_heap);
 626 
 627   // Initialize ICache flush mechanism
 628   // This service is needed for os::register_code_area
 629   icache_init();
 630 
 631   // Give OS a chance to register generated code area.
 632   // This is used on Windows 64 bit platforms to register
 633   // Structured Exception Handlers for our generated code.
 634   os::register_code_area(_heap->low_boundary(), _heap->high_boundary());
 635 }
 636 
 637 
 638 void codeCache_init() {
 639   CodeCache::initialize();
 640 }
 641 
 642 //------------------------------------------------------------------------------------------------
 643 
 644 int CodeCache::number_of_nmethods_with_dependencies() {
 645   return _number_of_nmethods_with_dependencies;
 646 }
 647 
 648 void CodeCache::clear_inline_caches() {
 649   assert_locked_or_safepoint(CodeCache_lock);
 650   FOR_ALL_ALIVE_NMETHODS(nm) {
 651     nm->clear_inline_caches();
 652   }
 653 }
 654 
 655 #ifndef PRODUCT
 656 // used to keep track of how much time is spent in mark_for_deoptimization
 657 static elapsedTimer dependentCheckTime;
 658 static int dependentCheckCount = 0;
 659 #endif // PRODUCT
 660 
 661 
 662 int CodeCache::mark_for_deoptimization(DepChange& changes) {
 663   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 664 
 665 #ifndef PRODUCT
 666   dependentCheckTime.start();
 667   dependentCheckCount++;
 668 #endif // PRODUCT
 669 
 670   int number_of_marked_CodeBlobs = 0;
 671 
 672   // search the hierarchy looking for nmethods which are affected by the loading of this class
 673 
 674   // then search the interfaces this class implements looking for nmethods
 675   // which might be dependent of the fact that an interface only had one
 676   // implementor.
 677 
 678   { No_Safepoint_Verifier nsv;
 679     for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
 680       Klass* d = str.klass();
 681       number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
 682     }
 683   }
 684 
 685   if (VerifyDependencies) {
 686     // Turn off dependency tracing while actually testing deps.
 687     NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );
 688     FOR_ALL_ALIVE_NMETHODS(nm) {
 689       if (!nm->is_marked_for_deoptimization() &&
 690           nm->check_all_dependencies()) {
 691         ResourceMark rm;
 692         tty->print_cr("Should have been marked for deoptimization:");
 693         changes.print();
 694         nm->print();
 695         nm->print_dependencies();
 696       }
 697     }
 698   }
 699 
 700 #ifndef PRODUCT
 701   dependentCheckTime.stop();
 702 #endif // PRODUCT
 703 
 704   return number_of_marked_CodeBlobs;
 705 }
 706 
 707 
 708 #ifdef HOTSWAP
 709 int CodeCache::mark_for_evol_deoptimization(instanceKlassHandle dependee) {
 710   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 711   int number_of_marked_CodeBlobs = 0;
 712 
 713   // Deoptimize all methods of the evolving class itself
 714   Array<Method*>* old_methods = dependee->methods();
 715   for (int i = 0; i < old_methods->length(); i++) {
 716     ResourceMark rm;
 717     Method* old_method = old_methods->at(i);
 718     nmethod *nm = old_method->code();
 719     if (nm != NULL) {
 720       nm->mark_for_deoptimization();
 721       number_of_marked_CodeBlobs++;
 722     }
 723   }
 724 
 725   FOR_ALL_ALIVE_NMETHODS(nm) {
 726     if (nm->is_marked_for_deoptimization()) {
 727       // ...Already marked in the previous pass; don't count it again.
 728     } else if (nm->is_evol_dependent_on(dependee())) {
 729       ResourceMark rm;
 730       nm->mark_for_deoptimization();
 731       number_of_marked_CodeBlobs++;
 732     } else  {
 733       // flush caches in case they refer to a redefined Method*
 734       nm->clear_inline_caches();
 735     }
 736   }
 737 
 738   return number_of_marked_CodeBlobs;
 739 }
 740 #endif // HOTSWAP
 741 
 742 
 743 // Deoptimize all methods
 744 void CodeCache::mark_all_nmethods_for_deoptimization() {
 745   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 746   FOR_ALL_ALIVE_NMETHODS(nm) {
 747     if (!nm->method()->is_method_handle_intrinsic()) {
 748       nm->mark_for_deoptimization();
 749     }
 750   }
 751 }
 752 
 753 
 754 int CodeCache::mark_for_deoptimization(Method* dependee) {
 755   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 756   int number_of_marked_CodeBlobs = 0;
 757 
 758   FOR_ALL_ALIVE_NMETHODS(nm) {
 759     if (nm->is_dependent_on_method(dependee)) {
 760       ResourceMark rm;
 761       nm->mark_for_deoptimization();
 762       number_of_marked_CodeBlobs++;
 763     }
 764   }
 765 
 766   return number_of_marked_CodeBlobs;
 767 }
 768 
 769 void CodeCache::make_marked_nmethods_not_entrant() {
 770   assert_locked_or_safepoint(CodeCache_lock);
 771   FOR_ALL_ALIVE_NMETHODS(nm) {
 772     if (nm->is_marked_for_deoptimization()) {
 773       nm->make_not_entrant();
 774     }
 775   }
 776 }
 777 
 778 void CodeCache::verify() {
 779   _heap->verify();
 780   FOR_ALL_ALIVE_BLOBS(p) {
 781     p->verify();
 782   }
 783 }
 784 
 785 void CodeCache::report_codemem_full() {
 786   _codemem_full_count++;
 787   EventCodeCacheFull event;
 788   if (event.should_commit()) {
 789     event.set_codeBlobType((u1)CodeBlobType::All);
 790     event.set_startAddress((u8)low_bound());
 791     event.set_commitedTopAddress((u8)high());
 792     event.set_reservedTopAddress((u8)high_bound());
 793     event.set_entryCount(nof_blobs());
 794     event.set_methodCount(nof_nmethods());
 795     event.set_adaptorCount(nof_adapters());
 796     event.set_unallocatedCapacity(unallocated_capacity()/K);
 797     event.set_fullCount(_codemem_full_count);
 798     event.commit();
 799   }
 800 }
 801 
 802 //------------------------------------------------------------------------------------------------
 803 // Non-product version
 804 
 805 #ifndef PRODUCT
 806 
 807 void CodeCache::verify_if_often() {
 808   if (VerifyCodeCacheOften) {
 809     _heap->verify();
 810   }
 811 }
 812 
 813 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
 814   if (PrintCodeCache2) {  // Need to add a new flag
 815     ResourceMark rm;
 816     if (size == 0)  size = cb->size();
 817     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
 818   }
 819 }
 820 
 821 void CodeCache::print_internals() {
 822   int nmethodCount = 0;
 823   int runtimeStubCount = 0;
 824   int adapterCount = 0;
 825   int deoptimizationStubCount = 0;
 826   int uncommonTrapStubCount = 0;
 827   int bufferBlobCount = 0;
 828   int total = 0;
 829   int nmethodAlive = 0;
 830   int nmethodNotEntrant = 0;
 831   int nmethodZombie = 0;
 832   int nmethodUnloaded = 0;
 833   int nmethodJava = 0;
 834   int nmethodNative = 0;
 835   int maxCodeSize = 0;
 836   ResourceMark rm;
 837 
 838   CodeBlob *cb;
 839   for (cb = first(); cb != NULL; cb = next(cb)) {
 840     total++;
 841     if (cb->is_nmethod()) {
 842       nmethod* nm = (nmethod*)cb;
 843 
 844       if (Verbose && nm->method() != NULL) {
 845         ResourceMark rm;
 846         char *method_name = nm->method()->name_and_sig_as_C_string();
 847         tty->print("%s", method_name);
 848         if(nm->is_alive()) { tty->print_cr(" alive"); }
 849         if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
 850         if(nm->is_zombie()) { tty->print_cr(" zombie"); }
 851       }
 852 
 853       nmethodCount++;
 854 
 855       if(nm->is_alive()) { nmethodAlive++; }
 856       if(nm->is_not_entrant()) { nmethodNotEntrant++; }
 857       if(nm->is_zombie()) { nmethodZombie++; }
 858       if(nm->is_unloaded()) { nmethodUnloaded++; }
 859       if(nm->is_native_method()) { nmethodNative++; }
 860 
 861       if(nm->method() != NULL && nm->is_java_method()) {
 862         nmethodJava++;
 863         if (nm->insts_size() > maxCodeSize) {
 864           maxCodeSize = nm->insts_size();
 865         }
 866       }
 867     } else if (cb->is_runtime_stub()) {
 868       runtimeStubCount++;
 869     } else if (cb->is_deoptimization_stub()) {
 870       deoptimizationStubCount++;
 871     } else if (cb->is_uncommon_trap_stub()) {
 872       uncommonTrapStubCount++;
 873     } else if (cb->is_adapter_blob()) {
 874       adapterCount++;
 875     } else if (cb->is_buffer_blob()) {
 876       bufferBlobCount++;
 877     }
 878   }
 879 
 880   int bucketSize = 512;
 881   int bucketLimit = maxCodeSize / bucketSize + 1;
 882   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
 883   memset(buckets,0,sizeof(int) * bucketLimit);
 884 
 885   for (cb = first(); cb != NULL; cb = next(cb)) {
 886     if (cb->is_nmethod()) {
 887       nmethod* nm = (nmethod*)cb;
 888       if(nm->is_java_method()) {
 889         buckets[nm->insts_size() / bucketSize]++;
 890       }
 891     }
 892   }
 893   tty->print_cr("Code Cache Entries (total of %d)",total);
 894   tty->print_cr("-------------------------------------------------");
 895   tty->print_cr("nmethods: %d",nmethodCount);
 896   tty->print_cr("\talive: %d",nmethodAlive);
 897   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
 898   tty->print_cr("\tzombie: %d",nmethodZombie);
 899   tty->print_cr("\tunloaded: %d",nmethodUnloaded);
 900   tty->print_cr("\tjava: %d",nmethodJava);
 901   tty->print_cr("\tnative: %d",nmethodNative);
 902   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
 903   tty->print_cr("adapters: %d",adapterCount);
 904   tty->print_cr("buffer blobs: %d",bufferBlobCount);
 905   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
 906   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
 907   tty->print_cr("\nnmethod size distribution (non-zombie java)");
 908   tty->print_cr("-------------------------------------------------");
 909 
 910   for(int i=0; i<bucketLimit; i++) {
 911     if(buckets[i] != 0) {
 912       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
 913       tty->fill_to(40);
 914       tty->print_cr("%d",buckets[i]);
 915     }
 916   }
 917 
 918   FREE_C_HEAP_ARRAY(int, buckets, mtCode);
 919 }
 920 
 921 #endif // !PRODUCT
 922 
 923 void CodeCache::print() {
 924   print_summary(tty);
 925 
 926 #ifndef PRODUCT
 927   if (!Verbose) return;
 928 
 929   CodeBlob_sizes live;
 930   CodeBlob_sizes dead;
 931 
 932   FOR_ALL_BLOBS(p) {
 933     if (!p->is_alive()) {
 934       dead.add(p);
 935     } else {
 936       live.add(p);
 937     }
 938   }
 939 
 940   tty->print_cr("CodeCache:");
 941 
 942   tty->print_cr("nmethod dependency checking time %f, per dependent %f", dependentCheckTime.seconds(),
 943                 dependentCheckTime.seconds() / dependentCheckCount);
 944 
 945   if (!live.is_empty()) {
 946     live.print("live");
 947   }
 948   if (!dead.is_empty()) {
 949     dead.print("dead");
 950   }
 951 
 952 
 953   if (WizardMode) {
 954      // print the oop_map usage
 955     int code_size = 0;
 956     int number_of_blobs = 0;
 957     int number_of_oop_maps = 0;
 958     int map_size = 0;
 959     FOR_ALL_BLOBS(p) {
 960       if (p->is_alive()) {
 961         number_of_blobs++;
 962         code_size += p->code_size();
 963         OopMapSet* set = p->oop_maps();
 964         if (set != NULL) {
 965           number_of_oop_maps += set->size();
 966           map_size           += set->heap_size();
 967         }
 968       }
 969     }
 970     tty->print_cr("OopMaps");
 971     tty->print_cr("  #blobs    = %d", number_of_blobs);
 972     tty->print_cr("  code size = %d", code_size);
 973     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
 974     tty->print_cr("  map size  = %d", map_size);
 975   }
 976 
 977 #endif // !PRODUCT
 978 }
 979 
 980 void CodeCache::print_summary(outputStream* st, bool detailed) {
 981   size_t total = (_heap->high_boundary() - _heap->low_boundary());
 982   st->print_cr("CodeCache: size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
 983                "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
 984                total/K, (total - unallocated_capacity())/K,
 985                maxCodeCacheUsed/K, unallocated_capacity()/K);
 986 
 987   if (detailed) {
 988     st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
 989                  p2i(_heap->low_boundary()),
 990                  p2i(_heap->high()),
 991                  p2i(_heap->high_boundary()));
 992     st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
 993                  " adapters=" UINT32_FORMAT,
 994                  nof_blobs(), nof_nmethods(), nof_adapters());
 995     st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
 996                  "enabled" : Arguments::mode() == Arguments::_int ?
 997                  "disabled (interpreter mode)" :
 998                  "disabled (not enough contiguous free space left)");
 999   }
1000 }
1001 
1002 void CodeCache::log_state(outputStream* st) {
1003   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1004             " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
1005             nof_blobs(), nof_nmethods(), nof_adapters(),
1006             unallocated_capacity());
1007 }
1008