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