< prev index next >

src/hotspot/share/code/codeHeapState.cpp

Print this page
rev 54099 : 8219586: CodeHeap State Analytics processes dead nmethods
Reviewed-by: thartmann, eosterlund


   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "code/codeHeapState.hpp"
  28 #include "compiler/compileBroker.hpp"

  29 #include "runtime/sweeper.hpp"
  30 
  31 // -------------------------
  32 // |  General Description  |
  33 // -------------------------
  34 // The CodeHeap state analytics are divided in two parts.
  35 // The first part examines the entire CodeHeap and aggregates all
  36 // information that is believed useful/important.
  37 //
  38 // Aggregation condenses the information of a piece of the CodeHeap
  39 // (4096 bytes by default) into an analysis granule. These granules
  40 // contain enough detail to gain initial insight while keeping the
  41 // internal structure sizes in check.
  42 //
  43 // The second part, which consists of several, independent steps,
  44 // prints the previously collected information with emphasis on
  45 // various aspects.
  46 //
  47 // The CodeHeap is a living thing. Therefore, protection against concurrent
  48 // modification (by acquiring the CodeCache_lock) is necessary. It has


 199 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 200     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 201       _outbuf->print("%s", _termString);                      \
 202     }
 203 
 204 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 205     BUFFEREDSTREAM_FLUSH(_termString)
 206 
 207 #define BUFFEREDSTREAM_FLUSH_AUTO(_termString)                \
 208     BUFFEREDSTREAM_FLUSH(_termString)
 209 
 210 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 211     BUFFEREDSTREAM_FLUSH(_termString)
 212 
 213 #define BUFFEREDSTREAM_FLUSH_STAT()
 214 #endif
 215 #define HEX32_FORMAT  "0x%x"  // just a helper format string used below multiple times
 216 
 217 const char  blobTypeChar[] = {' ', 'C', 'N', 'I', 'X', 'Z', 'U', 'R', '?', 'D', 'T', 'E', 'S', 'A', 'M', 'B', 'L' };
 218 const char* blobTypeName[] = {"noType"
 219                              ,     "nMethod (under construction)"
 220                              ,          "nMethod (active)"
 221                              ,               "nMethod (inactive)"
 222                              ,                    "nMethod (deopt)"
 223                              ,                         "nMethod (zombie)"
 224                              ,                              "nMethod (unloaded)"
 225                              ,                                   "runtime stub"
 226                              ,                                        "ricochet stub"
 227                              ,                                             "deopt stub"
 228                              ,                                                  "uncommon trap stub"
 229                              ,                                                       "exception stub"
 230                              ,                                                            "safepoint stub"
 231                              ,                                                                 "adapter blob"
 232                              ,                                                                      "MH adapter blob"
 233                              ,                                                                           "buffer blob"
 234                              ,                                                                                "lastType"
 235                              };
 236 const char* compTypeName[] = { "none", "c1", "c2", "jvmci" };
 237 
 238 // Be prepared for ten different CodeHeap segments. Should be enough for a few years.
 239 const  unsigned int        nSizeDistElements = 31;  // logarithmic range growth, max size: 2**32
 240 const  unsigned int        maxTopSizeBlocks  = 50;
 241 const  unsigned int        tsbStopper        = 2 * maxTopSizeBlocks;
 242 const  unsigned int        maxHeaps          = 10;
 243 static unsigned int        nHeaps            = 0;
 244 static struct CodeHeapStat CodeHeapStatArray[maxHeaps];
 245 
 246 // static struct StatElement *StatArray      = NULL;
 247 static StatElement* StatArray             = NULL;
 248 static int          log2_seg_size         = 0;
 249 static size_t       seg_size              = 0;
 250 static size_t       alloc_granules        = 0;
 251 static size_t       granule_size          = 0;
 252 static bool         segment_granules      = false;
 253 static unsigned int nBlocks_t1            = 0;  // counting "in_use" nmethods only.
 254 static unsigned int nBlocks_t2            = 0;  // counting "in_use" nmethods only.
 255 static unsigned int nBlocks_alive         = 0;  // counting "not_used" and "not_entrant" nmethods only.
 256 static unsigned int nBlocks_dead          = 0;  // counting "zombie" and "unloaded" methods only.
 257 static unsigned int nBlocks_inconstr      = 0;  // counting "inconstruction" nmethods only. This is a transient state.
 258 static unsigned int nBlocks_unloaded      = 0;  // counting "unloaded" nmethods only. This is a transient state.
 259 static unsigned int nBlocks_stub          = 0;
 260 
 261 static struct FreeBlk*          FreeArray = NULL;
 262 static unsigned int      alloc_freeBlocks = 0;
 263 
 264 static struct TopSizeBlk*    TopSizeArray = NULL;
 265 static unsigned int   alloc_topSizeBlocks = 0;
 266 static unsigned int    used_topSizeBlocks = 0;
 267 
 268 static struct SizeDistributionElement*  SizeDistributionArray = NULL;
 269 
 270 // nMethod temperature (hotness) indicators.
 271 static int                     avgTemp    = 0;
 272 static int                     maxTemp    = 0;
 273 static int                     minTemp    = 0;
 274 
 275 static unsigned int  latest_compilation_id   = 0;
 276 static volatile bool initialization_complete = false;
 277 


 308   } else {
 309     nHeaps = 1;
 310     CodeHeapStatArray[0].heapName = heapName;
 311     return 0; // This is the default index if CodeCache is not segmented.
 312   }
 313 }
 314 
 315 void CodeHeapState::get_HeapStatGlobals(outputStream* out, const char* heapName) {
 316   unsigned int ix = findHeapIndex(out, heapName);
 317   if (ix < maxHeaps) {
 318     StatArray             = CodeHeapStatArray[ix].StatArray;
 319     seg_size              = CodeHeapStatArray[ix].segment_size;
 320     log2_seg_size         = seg_size == 0 ? 0 : exact_log2(seg_size);
 321     alloc_granules        = CodeHeapStatArray[ix].alloc_granules;
 322     granule_size          = CodeHeapStatArray[ix].granule_size;
 323     segment_granules      = CodeHeapStatArray[ix].segment_granules;
 324     nBlocks_t1            = CodeHeapStatArray[ix].nBlocks_t1;
 325     nBlocks_t2            = CodeHeapStatArray[ix].nBlocks_t2;
 326     nBlocks_alive         = CodeHeapStatArray[ix].nBlocks_alive;
 327     nBlocks_dead          = CodeHeapStatArray[ix].nBlocks_dead;
 328     nBlocks_inconstr      = CodeHeapStatArray[ix].nBlocks_inconstr;
 329     nBlocks_unloaded      = CodeHeapStatArray[ix].nBlocks_unloaded;
 330     nBlocks_stub          = CodeHeapStatArray[ix].nBlocks_stub;
 331     FreeArray             = CodeHeapStatArray[ix].FreeArray;
 332     alloc_freeBlocks      = CodeHeapStatArray[ix].alloc_freeBlocks;
 333     TopSizeArray          = CodeHeapStatArray[ix].TopSizeArray;
 334     alloc_topSizeBlocks   = CodeHeapStatArray[ix].alloc_topSizeBlocks;
 335     used_topSizeBlocks    = CodeHeapStatArray[ix].used_topSizeBlocks;
 336     SizeDistributionArray = CodeHeapStatArray[ix].SizeDistributionArray;
 337     avgTemp               = CodeHeapStatArray[ix].avgTemp;
 338     maxTemp               = CodeHeapStatArray[ix].maxTemp;
 339     minTemp               = CodeHeapStatArray[ix].minTemp;
 340   } else {
 341     StatArray             = NULL;
 342     seg_size              = 0;
 343     log2_seg_size         = 0;
 344     alloc_granules        = 0;
 345     granule_size          = 0;
 346     segment_granules      = false;
 347     nBlocks_t1            = 0;
 348     nBlocks_t2            = 0;
 349     nBlocks_alive         = 0;
 350     nBlocks_dead          = 0;
 351     nBlocks_inconstr      = 0;
 352     nBlocks_unloaded      = 0;
 353     nBlocks_stub          = 0;
 354     FreeArray             = NULL;
 355     alloc_freeBlocks      = 0;
 356     TopSizeArray          = NULL;
 357     alloc_topSizeBlocks   = 0;
 358     used_topSizeBlocks    = 0;
 359     SizeDistributionArray = NULL;
 360     avgTemp               = 0;
 361     maxTemp               = 0;
 362     minTemp               = 0;
 363   }
 364 }
 365 
 366 void CodeHeapState::set_HeapStatGlobals(outputStream* out, const char* heapName) {
 367   unsigned int ix = findHeapIndex(out, heapName);
 368   if (ix < maxHeaps) {
 369     CodeHeapStatArray[ix].StatArray             = StatArray;
 370     CodeHeapStatArray[ix].segment_size          = seg_size;
 371     CodeHeapStatArray[ix].alloc_granules        = alloc_granules;
 372     CodeHeapStatArray[ix].granule_size          = granule_size;
 373     CodeHeapStatArray[ix].segment_granules      = segment_granules;
 374     CodeHeapStatArray[ix].nBlocks_t1            = nBlocks_t1;
 375     CodeHeapStatArray[ix].nBlocks_t2            = nBlocks_t2;
 376     CodeHeapStatArray[ix].nBlocks_alive         = nBlocks_alive;
 377     CodeHeapStatArray[ix].nBlocks_dead          = nBlocks_dead;
 378     CodeHeapStatArray[ix].nBlocks_inconstr      = nBlocks_inconstr;
 379     CodeHeapStatArray[ix].nBlocks_unloaded      = nBlocks_unloaded;
 380     CodeHeapStatArray[ix].nBlocks_stub          = nBlocks_stub;
 381     CodeHeapStatArray[ix].FreeArray             = FreeArray;
 382     CodeHeapStatArray[ix].alloc_freeBlocks      = alloc_freeBlocks;
 383     CodeHeapStatArray[ix].TopSizeArray          = TopSizeArray;
 384     CodeHeapStatArray[ix].alloc_topSizeBlocks   = alloc_topSizeBlocks;
 385     CodeHeapStatArray[ix].used_topSizeBlocks    = used_topSizeBlocks;
 386     CodeHeapStatArray[ix].SizeDistributionArray = SizeDistributionArray;
 387     CodeHeapStatArray[ix].avgTemp               = avgTemp;
 388     CodeHeapStatArray[ix].maxTemp               = maxTemp;
 389     CodeHeapStatArray[ix].minTemp               = minTemp;
 390   }
 391 }
 392 
 393 //---<  get a new statistics array  >---
 394 void CodeHeapState::prepare_StatArray(outputStream* out, size_t nElem, size_t granularity, const char* heapName) {
 395   if (StatArray == NULL) {
 396     StatArray      = new StatElement[nElem];
 397     //---<  reset some counts  >---
 398     alloc_granules = nElem;


 485 
 486 void CodeHeapState::discard_StatArray(outputStream* out) {
 487   if (StatArray != NULL) {
 488     delete StatArray;
 489     StatArray        = NULL;
 490     alloc_granules   = 0;
 491     granule_size     = 0;
 492   }
 493 }
 494 
 495 void CodeHeapState::discard_FreeArray(outputStream* out) {
 496   if (FreeArray != NULL) {
 497     delete[] FreeArray;
 498     FreeArray        = NULL;
 499     alloc_freeBlocks = 0;
 500   }
 501 }
 502 
 503 void CodeHeapState::discard_TopSizeArray(outputStream* out) {
 504   if (TopSizeArray != NULL) {





 505     delete[] TopSizeArray;
 506     TopSizeArray        = NULL;
 507     alloc_topSizeBlocks = 0;
 508     used_topSizeBlocks  = 0;
 509   }
 510 }
 511 
 512 void CodeHeapState::discard_SizeDistArray(outputStream* out) {
 513   if (SizeDistributionArray != NULL) {
 514     delete[] SizeDistributionArray;
 515     SizeDistributionArray = NULL;
 516   }
 517 }
 518 
 519 // Discard all allocated internal data structures.
 520 // This should be done after an analysis session is completed.
 521 void CodeHeapState::discard(outputStream* out, CodeHeap* heap) {
 522   if (!initialization_complete) {
 523     return;
 524   }


 578     BUFFEREDSTREAM_FLUSH("")
 579   }
 580   get_HeapStatGlobals(out, heapName);
 581 
 582 
 583   // Since we are (and must be) analyzing the CodeHeap contents under the CodeCache_lock,
 584   // all heap information is "constant" and can be safely extracted/calculated before we
 585   // enter the while() loop. Actually, the loop will only be iterated once.
 586   char*  low_bound     = heap->low_boundary();
 587   size_t size          = heap->capacity();
 588   size_t res_size      = heap->max_capacity();
 589   seg_size             = heap->segment_size();
 590   log2_seg_size        = seg_size == 0 ? 0 : exact_log2(seg_size);  // This is a global static value.
 591 
 592   if (seg_size == 0) {
 593     printBox(ast, '-', "Heap not fully initialized yet, segment size is zero for segment ", heapName);
 594     BUFFEREDSTREAM_FLUSH("")
 595     return;
 596   }
 597 
 598   if (!CodeCache_lock->owned_by_self()) {
 599     printBox(ast, '-', "aggregate function called without holding the CodeCache_lock for ", heapName);
 600     BUFFEREDSTREAM_FLUSH("")
 601     return;
 602   }
 603 
 604   // Calculate granularity of analysis (and output).
 605   //   The CodeHeap is managed (allocated) in segments (units) of CodeCacheSegmentSize.
 606   //   The CodeHeap can become fairly large, in particular in productive real-life systems.
 607   //
 608   //   It is often neither feasible nor desirable to aggregate the data with the highest possible
 609   //   level of detail, i.e. inspecting and printing each segment on its own.
 610   //
 611   //   The granularity parameter allows to specify the level of detail available in the analysis.
 612   //   It must be a positive multiple of the segment size and should be selected such that enough
 613   //   detail is provided while, at the same time, the printed output does not explode.
 614   //
 615   //   By manipulating the granularity value, we enforce that at least min_granules units
 616   //   of analysis are available. We also enforce an upper limit of max_granules units to
 617   //   keep the amount of allocated storage in check.
 618   //
 619   //   Finally, we adjust the granularity such that each granule covers at most 64k-1 segments.


 646                 "   Subsequent print functions create their output based on this snapshot.\n"
 647                 "   The CodeHeap is a living thing, and every effort has been made for the\n"
 648                 "   collected data to be consistent. Only the method names and signatures\n"
 649                 "   are retrieved at print time. That may lead to rare cases where the\n"
 650                 "   name of a method is no longer available, e.g. because it was unloaded.\n");
 651   ast->print_cr("   CodeHeap committed size " SIZE_FORMAT "K (" SIZE_FORMAT "M), reserved size " SIZE_FORMAT "K (" SIZE_FORMAT "M), %d%% occupied.",
 652                 size/(size_t)K, size/(size_t)M, res_size/(size_t)K, res_size/(size_t)M, (unsigned int)(100.0*size/res_size));
 653   ast->print_cr("   CodeHeap allocation segment size is " SIZE_FORMAT " bytes. This is the smallest possible granularity.", seg_size);
 654   ast->print_cr("   CodeHeap (committed part) is mapped to " SIZE_FORMAT " granules of size " SIZE_FORMAT " bytes.", granules, granularity);
 655   ast->print_cr("   Each granule takes " SIZE_FORMAT " bytes of C heap, that is " SIZE_FORMAT "K in total for statistics data.", sizeof(StatElement), (sizeof(StatElement)*granules)/(size_t)K);
 656   ast->print_cr("   The number of granules is limited to %dk, requiring a granules size of at least %d bytes for a 1GB heap.", (unsigned int)(max_granules/K), (unsigned int)(G/max_granules));
 657   BUFFEREDSTREAM_FLUSH("\n")
 658 
 659 
 660   while (!done) {
 661     //---<  reset counters with every aggregation  >---
 662     nBlocks_t1       = 0;
 663     nBlocks_t2       = 0;
 664     nBlocks_alive    = 0;
 665     nBlocks_dead     = 0;
 666     nBlocks_inconstr = 0;
 667     nBlocks_unloaded = 0;
 668     nBlocks_stub     = 0;
 669 
 670     nBlocks_free     = 0;
 671     nBlocks_used     = 0;
 672     nBlocks_zomb     = 0;
 673     nBlocks_disconn  = 0;
 674     nBlocks_notentr  = 0;
 675 
 676     //---<  discard old arrays if size does not match  >---
 677     if (granules != alloc_granules) {
 678       discard_StatArray(out);
 679       discard_TopSizeArray(out);
 680     }
 681 
 682     //---<  allocate arrays if they don't yet exist, initialize  >---
 683     prepare_StatArray(out, granules, granularity, heapName);
 684     if (StatArray == NULL) {
 685       set_HeapStatGlobals(out, heapName);
 686       return;
 687     }
 688     prepare_TopSizeArray(out, maxTopSizeBlocks, heapName);
 689     prepare_SizeDistArray(out, nSizeDistElements, heapName);
 690 
 691     latest_compilation_id = CompileBroker::get_compilation_id();
 692     unsigned int highest_compilation_id = 0;
 693     size_t       usedSpace     = 0;
 694     size_t       t1Space       = 0;
 695     size_t       t2Space       = 0;
 696     size_t       aliveSpace    = 0;
 697     size_t       disconnSpace  = 0;
 698     size_t       notentrSpace  = 0;
 699     size_t       deadSpace     = 0;
 700     size_t       inconstrSpace = 0;
 701     size_t       unloadedSpace = 0;
 702     size_t       stubSpace     = 0;
 703     size_t       freeSpace     = 0;
 704     size_t       maxFreeSize   = 0;
 705     HeapBlock*   maxFreeBlock  = NULL;
 706     bool         insane        = false;
 707 
 708     int64_t hotnessAccumulator = 0;
 709     unsigned int n_methods     = 0;
 710     avgTemp       = 0;
 711     minTemp       = (int)(res_size > M ? (res_size/M)*2 : 1);
 712     maxTemp       = -minTemp;
 713 
 714     for (HeapBlock *h = heap->first_block(); h != NULL && !insane; h = heap->next_block(h)) {
 715       unsigned int hb_len     = (unsigned int)h->length();  // despite being size_t, length can never overflow an unsigned int.
 716       size_t       hb_bytelen = ((size_t)hb_len)<<log2_seg_size;
 717       unsigned int ix_beg     = (unsigned int)(((char*)h-low_bound)/granule_size);
 718       unsigned int ix_end     = (unsigned int)(((char*)h-low_bound+(hb_bytelen-1))/granule_size);
 719       unsigned int compile_id = 0;
 720       CompLevel    comp_lvl   = CompLevel_none;


 742       if (ix_beg   >  ix_end) {
 743         insane = true; ast->print_cr("Sanity check: end index (%d) lower than begin index (%d)", ix_end, ix_beg);
 744       }
 745       if (insane) {
 746         BUFFEREDSTREAM_FLUSH("")
 747         continue;
 748       }
 749 
 750       if (h->free()) {
 751         nBlocks_free++;
 752         freeSpace    += hb_bytelen;
 753         if (hb_bytelen > maxFreeSize) {
 754           maxFreeSize   = hb_bytelen;
 755           maxFreeBlock  = h;
 756         }
 757       } else {
 758         update_SizeDistArray(out, hb_len);
 759         nBlocks_used++;
 760         usedSpace    += hb_bytelen;
 761         CodeBlob* cb  = (CodeBlob*)heap->find_start(h);
 762         if (cb != NULL) {
 763           cbType = get_cbType(cb);
 764           if (cb->is_nmethod()) {
 765             compile_id = ((nmethod*)cb)->compile_id();
 766             comp_lvl   = (CompLevel)((nmethod*)cb)->comp_level();
 767             if (((nmethod*)cb)->is_compiled_by_c1()) {














 768               cType = c1;
 769             }
 770             if (((nmethod*)cb)->is_compiled_by_c2()) {
 771               cType = c2;
 772             }
 773             if (((nmethod*)cb)->is_compiled_by_jvmci()) {
 774               cType = jvmci;
 775             }
 776             switch (cbType) {
 777               case nMethod_inuse: { // only for executable methods!!!
 778                 // space for these cbs is accounted for later.
 779                 int temperature = ((nmethod*)cb)->hotness_counter();
 780                 hotnessAccumulator += temperature;
 781                 n_methods++;
 782                 maxTemp = (temperature > maxTemp) ? temperature : maxTemp;
 783                 minTemp = (temperature < minTemp) ? temperature : minTemp;
 784                 break;
 785               }
 786               case nMethod_notused:
 787                 nBlocks_alive++;
 788                 nBlocks_disconn++;
 789                 aliveSpace     += hb_bytelen;
 790                 disconnSpace   += hb_bytelen;
 791                 break;
 792               case nMethod_notentrant:  // equivalent to nMethod_alive
 793                 nBlocks_alive++;
 794                 nBlocks_notentr++;
 795                 aliveSpace     += hb_bytelen;
 796                 notentrSpace   += hb_bytelen;
 797                 break;
 798               case nMethod_unloaded:
 799                 nBlocks_unloaded++;
 800                 unloadedSpace  += hb_bytelen;
 801                 break;
 802               case nMethod_dead:
 803                 nBlocks_dead++;
 804                 deadSpace      += hb_bytelen;
 805                 break;
 806               case nMethod_inconstruction:
 807                 nBlocks_inconstr++;
 808                 inconstrSpace  += hb_bytelen;
 809                 break;
 810               default:
 811                 break;
 812             }
 813           }
 814 
 815           //------------------------------------------
 816           //---<  register block in TopSizeArray  >---
 817           //------------------------------------------
 818           if (alloc_topSizeBlocks > 0) {
 819             if (used_topSizeBlocks == 0) {
 820               TopSizeArray[0].start    = h;

 821               TopSizeArray[0].len      = hb_len;
 822               TopSizeArray[0].index    = tsbStopper;


 823               TopSizeArray[0].compiler = cType;
 824               TopSizeArray[0].level    = comp_lvl;
 825               TopSizeArray[0].type     = cbType;
 826               currMax    = hb_len;
 827               currMin    = hb_len;
 828               currMin_ix = 0;
 829               used_topSizeBlocks++;

 830             // This check roughly cuts 5000 iterations (JVM98, mixed, dbg, termination stats):
 831             } else if ((used_topSizeBlocks < alloc_topSizeBlocks) && (hb_len < currMin)) {
 832               //---<  all blocks in list are larger, but there is room left in array  >---
 833               TopSizeArray[currMin_ix].index = used_topSizeBlocks;
 834               TopSizeArray[used_topSizeBlocks].start    = h;

 835               TopSizeArray[used_topSizeBlocks].len      = hb_len;
 836               TopSizeArray[used_topSizeBlocks].index    = tsbStopper;


 837               TopSizeArray[used_topSizeBlocks].compiler = cType;
 838               TopSizeArray[used_topSizeBlocks].level    = comp_lvl;
 839               TopSizeArray[used_topSizeBlocks].type     = cbType;
 840               currMin    = hb_len;
 841               currMin_ix = used_topSizeBlocks;
 842               used_topSizeBlocks++;

 843             } else {
 844               // This check cuts total_iterations by a factor of 6 (JVM98, mixed, dbg, termination stats):
 845               //   We don't need to search the list if we know beforehand that the current block size is
 846               //   smaller than the currently recorded minimum and there is no free entry left in the list.
 847               if (!((used_topSizeBlocks == alloc_topSizeBlocks) && (hb_len <= currMin))) {
 848                 if (currMax < hb_len) {
 849                   currMax = hb_len;
 850                 }
 851                 unsigned int i;
 852                 unsigned int prev_i  = tsbStopper;
 853                 unsigned int limit_i =  0;
 854                 for (i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
 855                   if (limit_i++ >= alloc_topSizeBlocks) {
 856                     insane = true; break; // emergency exit
 857                   }
 858                   if (i >= used_topSizeBlocks)  {
 859                     insane = true; break; // emergency exit
 860                   }
 861                   total_iterations++;
 862                   if (TopSizeArray[i].len < hb_len) {
 863                     //---<  We want to insert here, element <i> is smaller than the current one  >---
 864                     if (used_topSizeBlocks < alloc_topSizeBlocks) { // still room for a new entry to insert
 865                       // old entry gets moved to the next free element of the array.
 866                       // That's necessary to keep the entry for the largest block at index 0.
 867                       // This move might cause the current minimum to be moved to another place
 868                       if (i == currMin_ix) {
 869                         assert(TopSizeArray[i].len == currMin, "sort error");
 870                         currMin_ix = used_topSizeBlocks;
 871                       }
 872                       memcpy((void*)&TopSizeArray[used_topSizeBlocks], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 873                       TopSizeArray[i].start    = h;

 874                       TopSizeArray[i].len      = hb_len;
 875                       TopSizeArray[i].index    = used_topSizeBlocks;


 876                       TopSizeArray[i].compiler = cType;
 877                       TopSizeArray[i].level    = comp_lvl;
 878                       TopSizeArray[i].type     = cbType;
 879                       used_topSizeBlocks++;

 880                     } else { // no room for new entries, current block replaces entry for smallest block
 881                       //---<  Find last entry (entry for smallest remembered block)  >---






 882                       unsigned int      j  = i;
 883                       unsigned int prev_j  = tsbStopper;
 884                       unsigned int limit_j = 0;
 885                       while (TopSizeArray[j].index != tsbStopper) {
 886                         if (limit_j++ >= alloc_topSizeBlocks) {
 887                           insane = true; break; // emergency exit
 888                         }
 889                         if (j >= used_topSizeBlocks)  {
 890                           insane = true; break; // emergency exit
 891                         }
 892                         total_iterations++;
 893                         prev_j = j;
 894                         j      = TopSizeArray[j].index;
 895                       }
 896                       if (!insane) {



 897                         if (prev_j == tsbStopper) {
 898                           //---<  Above while loop did not iterate, we already are the min entry  >---
 899                           //---<  We have to just replace the smallest entry                      >---
 900                           currMin    = hb_len;
 901                           currMin_ix = j;
 902                           TopSizeArray[j].start    = h;

 903                           TopSizeArray[j].len      = hb_len;
 904                           TopSizeArray[j].index    = tsbStopper; // already set!!


 905                           TopSizeArray[j].compiler = cType;
 906                           TopSizeArray[j].level    = comp_lvl;
 907                           TopSizeArray[j].type     = cbType;
 908                         } else {
 909                           //---<  second-smallest entry is now smallest  >---
 910                           TopSizeArray[prev_j].index = tsbStopper;
 911                           currMin    = TopSizeArray[prev_j].len;
 912                           currMin_ix = prev_j;
 913                           //---<  smallest entry gets overwritten  >---
 914                           memcpy((void*)&TopSizeArray[j], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 915                           TopSizeArray[i].start    = h;

 916                           TopSizeArray[i].len      = hb_len;
 917                           TopSizeArray[i].index    = j;


 918                           TopSizeArray[i].compiler = cType;
 919                           TopSizeArray[i].level    = comp_lvl;
 920                           TopSizeArray[i].type     = cbType;
 921                         }

 922                       } // insane
 923                     }
 924                     break;
 925                   }
 926                   prev_i = i;
 927                 }
 928                 if (insane) {
 929                   // Note: regular analysis could probably continue by resetting "insane" flag.
 930                   out->print_cr("Possible loop in TopSizeBlocks list detected. Analysis aborted.");
 931                   discard_TopSizeArray(out);
 932                 }
 933               }
 934             }
 935           }




 936           //----------------------------------------------
 937           //---<  END register block in TopSizeArray  >---
 938           //----------------------------------------------
 939         } else {
 940           nBlocks_zomb++;
 941         }
 942 
 943         if (ix_beg == ix_end) {
 944           StatArray[ix_beg].type = cbType;
 945           switch (cbType) {
 946             case nMethod_inuse:
 947               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 948               if (comp_lvl < CompLevel_full_optimization) {
 949                 nBlocks_t1++;
 950                 t1Space   += hb_bytelen;
 951                 StatArray[ix_beg].t1_count++;
 952                 StatArray[ix_beg].t1_space += (unsigned short)hb_len;
 953                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 954               } else {
 955                 nBlocks_t2++;
 956                 t2Space   += hb_bytelen;
 957                 StatArray[ix_beg].t2_count++;
 958                 StatArray[ix_beg].t2_space += (unsigned short)hb_len;
 959                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 960               }
 961               StatArray[ix_beg].level     = comp_lvl;
 962               StatArray[ix_beg].compiler  = cType;
 963               break;
 964             case nMethod_inconstruction: // let's count "in construction" nmethods here.
 965             case nMethod_alive:
 966               StatArray[ix_beg].tx_count++;
 967               StatArray[ix_beg].tx_space += (unsigned short)hb_len;
 968               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
 969               StatArray[ix_beg].level     = comp_lvl;
 970               StatArray[ix_beg].compiler  = cType;
 971               break;
 972             case nMethod_dead:
 973             case nMethod_unloaded:
 974               StatArray[ix_beg].dead_count++;
 975               StatArray[ix_beg].dead_space += (unsigned short)hb_len;
 976               break;
 977             default:
 978               // must be a stub, if it's not a dead or alive nMethod
 979               nBlocks_stub++;
 980               stubSpace   += hb_bytelen;
 981               StatArray[ix_beg].stub_count++;
 982               StatArray[ix_beg].stub_space += (unsigned short)hb_len;
 983               break;
 984           }


1001 
1002                 StatArray[ix_end].t1_count++;
1003                 StatArray[ix_end].t1_space += (unsigned short)end_space;
1004                 StatArray[ix_end].t1_age    = StatArray[ix_end].t1_age < compile_id ? compile_id : StatArray[ix_end].t1_age;
1005               } else {
1006                 nBlocks_t2++;
1007                 t2Space   += hb_bytelen;
1008                 StatArray[ix_beg].t2_count++;
1009                 StatArray[ix_beg].t2_space += (unsigned short)beg_space;
1010                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
1011 
1012                 StatArray[ix_end].t2_count++;
1013                 StatArray[ix_end].t2_space += (unsigned short)end_space;
1014                 StatArray[ix_end].t2_age    = StatArray[ix_end].t2_age < compile_id ? compile_id : StatArray[ix_end].t2_age;
1015               }
1016               StatArray[ix_beg].level     = comp_lvl;
1017               StatArray[ix_beg].compiler  = cType;
1018               StatArray[ix_end].level     = comp_lvl;
1019               StatArray[ix_end].compiler  = cType;
1020               break;
1021             case nMethod_inconstruction: // let's count "in construction" nmethods here.
1022             case nMethod_alive:
1023               StatArray[ix_beg].tx_count++;
1024               StatArray[ix_beg].tx_space += (unsigned short)beg_space;
1025               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
1026 
1027               StatArray[ix_end].tx_count++;
1028               StatArray[ix_end].tx_space += (unsigned short)end_space;
1029               StatArray[ix_end].tx_age    = StatArray[ix_end].tx_age < compile_id ? compile_id : StatArray[ix_end].tx_age;
1030 
1031               StatArray[ix_beg].level     = comp_lvl;
1032               StatArray[ix_beg].compiler  = cType;
1033               StatArray[ix_end].level     = comp_lvl;
1034               StatArray[ix_end].compiler  = cType;
1035               break;
1036             case nMethod_dead:
1037             case nMethod_unloaded:
1038               StatArray[ix_beg].dead_count++;
1039               StatArray[ix_beg].dead_space += (unsigned short)beg_space;
1040               StatArray[ix_end].dead_count++;
1041               StatArray[ix_end].dead_space += (unsigned short)end_space;


1049               StatArray[ix_end].stub_count++;
1050               StatArray[ix_end].stub_space += (unsigned short)end_space;
1051               break;
1052           }
1053           for (unsigned int ix = ix_beg+1; ix < ix_end; ix++) {
1054             StatArray[ix].type = cbType;
1055             switch (cbType) {
1056               case nMethod_inuse:
1057                 if (comp_lvl < CompLevel_full_optimization) {
1058                   StatArray[ix].t1_count++;
1059                   StatArray[ix].t1_space += (unsigned short)(granule_size>>log2_seg_size);
1060                   StatArray[ix].t1_age    = StatArray[ix].t1_age < compile_id ? compile_id : StatArray[ix].t1_age;
1061                 } else {
1062                   StatArray[ix].t2_count++;
1063                   StatArray[ix].t2_space += (unsigned short)(granule_size>>log2_seg_size);
1064                   StatArray[ix].t2_age    = StatArray[ix].t2_age < compile_id ? compile_id : StatArray[ix].t2_age;
1065                 }
1066                 StatArray[ix].level     = comp_lvl;
1067                 StatArray[ix].compiler  = cType;
1068                 break;
1069               case nMethod_inconstruction: // let's count "in construction" nmethods here.
1070               case nMethod_alive:
1071                 StatArray[ix].tx_count++;
1072                 StatArray[ix].tx_space += (unsigned short)(granule_size>>log2_seg_size);
1073                 StatArray[ix].tx_age    = StatArray[ix].tx_age < compile_id ? compile_id : StatArray[ix].tx_age;
1074                 StatArray[ix].level     = comp_lvl;
1075                 StatArray[ix].compiler  = cType;
1076                 break;
1077               case nMethod_dead:
1078               case nMethod_unloaded:
1079                 StatArray[ix].dead_count++;
1080                 StatArray[ix].dead_space += (unsigned short)(granule_size>>log2_seg_size);
1081                 break;
1082               default:
1083                 // must be a stub, if it's not a dead or alive nMethod
1084                 StatArray[ix].stub_count++;
1085                 StatArray[ix].stub_space += (unsigned short)(granule_size>>log2_seg_size);
1086                 break;
1087             }
1088           }
1089         }
1090       }
1091     }
1092     done = true;
1093 
1094     if (!insane) {
1095       // There is a risk for this block (because it contains many print statements) to get
1096       // interspersed with print data from other threads. We take this risk intentionally.
1097       // Getting stalled waiting for tty_lock while holding the CodeCache_lock is not desirable.
1098       printBox(ast, '-', "Global CodeHeap statistics for segment ", heapName);
1099       ast->print_cr("freeSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_free     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", freeSpace/(size_t)K,     nBlocks_free,     (100.0*freeSpace)/size,     (100.0*freeSpace)/res_size);
1100       ast->print_cr("usedSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_used     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", usedSpace/(size_t)K,     nBlocks_used,     (100.0*usedSpace)/size,     (100.0*usedSpace)/res_size);
1101       ast->print_cr("  Tier1 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t1       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t1Space/(size_t)K,       nBlocks_t1,       (100.0*t1Space)/size,       (100.0*t1Space)/res_size);
1102       ast->print_cr("  Tier2 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t2       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t2Space/(size_t)K,       nBlocks_t2,       (100.0*t2Space)/size,       (100.0*t2Space)/res_size);
1103       ast->print_cr("  Alive Space    = " SIZE_FORMAT_W(8) "k, nBlocks_alive    = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", aliveSpace/(size_t)K,    nBlocks_alive,    (100.0*aliveSpace)/size,    (100.0*aliveSpace)/res_size);
1104       ast->print_cr("    disconnected = " SIZE_FORMAT_W(8) "k, nBlocks_disconn  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", disconnSpace/(size_t)K,  nBlocks_disconn,  (100.0*disconnSpace)/size,  (100.0*disconnSpace)/res_size);
1105       ast->print_cr("    not entrant  = " SIZE_FORMAT_W(8) "k, nBlocks_notentr  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", notentrSpace/(size_t)K,  nBlocks_notentr,  (100.0*notentrSpace)/size,  (100.0*notentrSpace)/res_size);
1106       ast->print_cr("  inconstrSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_inconstr = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", inconstrSpace/(size_t)K, nBlocks_inconstr, (100.0*inconstrSpace)/size, (100.0*inconstrSpace)/res_size);
1107       ast->print_cr("  unloadedSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_unloaded = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", unloadedSpace/(size_t)K, nBlocks_unloaded, (100.0*unloadedSpace)/size, (100.0*unloadedSpace)/res_size);
1108       ast->print_cr("  deadSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_dead     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", deadSpace/(size_t)K,     nBlocks_dead,     (100.0*deadSpace)/size,     (100.0*deadSpace)/res_size);
1109       ast->print_cr("  stubSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_stub     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", stubSpace/(size_t)K,     nBlocks_stub,     (100.0*stubSpace)/size,     (100.0*stubSpace)/res_size);
1110       ast->print_cr("ZombieBlocks     = %8d. These are HeapBlocks which could not be identified as CodeBlobs.", nBlocks_zomb);
1111       ast->cr();
1112       ast->print_cr("Segment start          = " INTPTR_FORMAT ", used space      = " SIZE_FORMAT_W(8)"k", p2i(low_bound), size/K);
1113       ast->print_cr("Segment end (used)     = " INTPTR_FORMAT ", remaining space = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + size, (res_size - size)/K);
1114       ast->print_cr("Segment end (reserved) = " INTPTR_FORMAT ", reserved space  = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + res_size, res_size/K);
1115       ast->cr();
1116       ast->print_cr("latest allocated compilation id = %d", latest_compilation_id);
1117       ast->print_cr("highest observed compilation id = %d", highest_compilation_id);
1118       ast->print_cr("Building TopSizeList iterations = %ld", total_iterations);
1119       ast->cr();
1120 
1121       int             reset_val = NMethodSweeper::hotness_counter_reset_val();
1122       double reverse_free_ratio = (res_size > size) ? (double)res_size/(double)(res_size-size) : (double)res_size;
1123       printBox(ast, '-', "Method hotness information at time of this analysis", NULL);
1124       ast->print_cr("Highest possible method temperature:          %12d", reset_val);
1125       ast->print_cr("Threshold for method to be considered 'cold': %12.3f", -reset_val + reverse_free_ratio * NmethodSweepActivity);
1126       if (n_methods > 0) {


1264       ast->print_cr("Free block count mismatch could not be resolved.");
1265       ast->print_cr("Try to run \"aggregate\" function to update counters");
1266     }
1267     BUFFEREDSTREAM_FLUSH("")
1268 
1269     //---< discard old array and update global values  >---
1270     discard_FreeArray(out);
1271     set_HeapStatGlobals(out, heapName);
1272     return;
1273   }
1274 
1275   //---<  calculate and fill remaining fields  >---
1276   if (FreeArray != NULL) {
1277     // This loop is intentionally printing directly to "out".
1278     // It should not print anything, anyway.
1279     for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1280       size_t lenSum = 0;
1281       FreeArray[ix].gap = (unsigned int)((address)FreeArray[ix+1].start - ((address)FreeArray[ix].start + FreeArray[ix].len));
1282       for (HeapBlock *h = heap->next_block(FreeArray[ix].start); (h != NULL) && (h != FreeArray[ix+1].start); h = heap->next_block(h)) {
1283         CodeBlob *cb  = (CodeBlob*)(heap->find_start(h));
1284         if ((cb != NULL) && !cb->is_nmethod()) {
1285           FreeArray[ix].stubs_in_gap = true;
1286         }
1287         FreeArray[ix].n_gapBlocks++;
1288         lenSum += h->length()<<log2_seg_size;
1289         if (((address)h < ((address)FreeArray[ix].start+FreeArray[ix].len)) || (h >= FreeArray[ix+1].start)) {
1290           out->print_cr("unsorted occupied CodeHeap block found @ %p, gap interval [%p, %p)", h, (address)FreeArray[ix].start+FreeArray[ix].len, FreeArray[ix+1].start);
1291         }
1292       }
1293       if (lenSum != FreeArray[ix].gap) {
1294         out->print_cr("Length mismatch for gap between FreeBlk[%d] and FreeBlk[%d]. Calculated: %d, accumulated: %d.", ix, ix+1, FreeArray[ix].gap, (unsigned int)lenSum);
1295       }
1296     }
1297   }
1298   set_HeapStatGlobals(out, heapName);
1299 
1300   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   C O M P L E T E   for segment ", heapName);
1301   BUFFEREDSTREAM_FLUSH("\n")
1302 }
1303 
1304 


1316   BUFFEREDSTREAM_DECL(ast, out)
1317 
1318   {
1319     printBox(ast, '=', "U S E D   S P A C E   S T A T I S T I C S   for ", heapName);
1320     ast->print_cr("Note: The Top%d list of the largest used blocks associates method names\n"
1321                   "      and other identifying information with the block size data.\n"
1322                   "\n"
1323                   "      Method names are dynamically retrieved from the code cache at print time.\n"
1324                   "      Due to the living nature of the code cache and because the CodeCache_lock\n"
1325                   "      is not continuously held, the displayed name might be wrong or no name\n"
1326                   "      might be found at all. The likelihood for that to happen increases\n"
1327                   "      over time passed between analysis and print step.\n", used_topSizeBlocks);
1328     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1329   }
1330 
1331   //----------------------------
1332   //--  Print Top Used Blocks --
1333   //----------------------------
1334   {
1335     char*     low_bound = heap->low_boundary();
1336     bool      have_CodeCache_lock = CodeCache_lock->owned_by_self();
1337 
1338     printBox(ast, '-', "Largest Used Blocks in ", heapName);
1339     print_blobType_legend(ast);
1340 
1341     ast->fill_to(51);
1342     ast->print("%4s", "blob");
1343     ast->fill_to(56);
1344     ast->print("%9s", "compiler");
1345     ast->fill_to(66);
1346     ast->print_cr("%6s", "method");
1347     ast->print_cr("%18s %13s %17s %4s %9s  %5s %s",      "Addr(module)      ", "offset", "size", "type", " type lvl", " temp", "Name");
1348     BUFFEREDSTREAM_FLUSH_LOCKED("")
1349 
1350     //---<  print Top Ten Used Blocks  >---
1351     if (used_topSizeBlocks > 0) {
1352       unsigned int printed_topSizeBlocks = 0;
1353       for (unsigned int i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
1354         printed_topSizeBlocks++;
1355         nmethod*           nm = NULL;
1356         const char* blob_name = "unnamed blob or blob name unavailable";

1357         // heap->find_start() is safe. Only works on _segmap.
1358         // Returns NULL or void*. Returned CodeBlob may be uninitialized.
1359         HeapBlock* heapBlock = TopSizeArray[i].start;
1360         CodeBlob*  this_blob = (CodeBlob*)(heap->find_start(heapBlock));
1361         bool    blob_is_safe = blob_access_is_safe(this_blob, NULL);
1362         if (blob_is_safe) {
1363           //---<  access these fields only if we own the CodeCache_lock  >---
1364           if (have_CodeCache_lock) {
1365             blob_name = this_blob->name();
1366             nm        = this_blob->as_nmethod_or_null();
1367           }
1368           //---<  blob address  >---
1369           ast->print(INTPTR_FORMAT, p2i(this_blob));
1370           ast->fill_to(19);
1371           //---<  blob offset from CodeHeap begin  >---
1372           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
1373           ast->fill_to(33);
1374         } else {
1375           //---<  block address  >---
1376           ast->print(INTPTR_FORMAT, p2i(TopSizeArray[i].start));
1377           ast->fill_to(19);
1378           //---<  block offset from CodeHeap begin  >---
1379           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)TopSizeArray[i].start-low_bound));
1380           ast->fill_to(33);
1381         }
1382 
1383         //---<  print size, name, and signature (for nMethods)  >---
1384         // access nmethod and Method fields only if we own the CodeCache_lock.
1385         // This fact is implicitly transported via nm != NULL.
1386         if (CompiledMethod::nmethod_access_is_safe(nm)) {
1387           ResourceMark rm;
1388           Method* method = nm->method();
1389           if (nm->is_in_use()) {
1390             blob_name = method->name_and_sig_as_C_string();
1391           }
1392           if (nm->is_not_entrant()) {
1393             blob_name = method->name_and_sig_as_C_string();
1394           }
1395           //---<  nMethod size in hex  >---
1396           unsigned int total_size = nm->total_size();
1397           ast->print(PTR32_FORMAT, total_size);
1398           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
1399           ast->fill_to(51);
1400           ast->print("  %c", blobTypeChar[TopSizeArray[i].type]);
1401           //---<  compiler information  >---
1402           ast->fill_to(56);
1403           ast->print("%5s %3d", compTypeName[TopSizeArray[i].compiler], TopSizeArray[i].level);
1404           //---<  method temperature  >---
1405           ast->fill_to(67);
1406           ast->print("%5d", nm->hotness_counter());
1407           //---<  name and signature  >---
1408           ast->fill_to(67+6);
1409           if (nm->is_not_installed()) {
1410             ast->print(" not (yet) installed method ");
1411           }
1412           if (nm->is_zombie()) {
1413             ast->print(" zombie method ");
1414           }
1415           ast->print("%s", blob_name);
1416         } else {
1417           //---<  block size in hex  >---
1418           ast->print(PTR32_FORMAT, (unsigned int)(TopSizeArray[i].len<<log2_seg_size));
1419           ast->print("(" SIZE_FORMAT_W(4) "K)", (TopSizeArray[i].len<<log2_seg_size)/K);
1420           //---<  no compiler information  >---
1421           ast->fill_to(56);
1422           //---<  name and signature  >---
1423           ast->fill_to(67+6);
1424           ast->print("%s", blob_name);
1425         }
1426         ast->cr();
1427         BUFFEREDSTREAM_FLUSH_AUTO("")
1428       }
1429       if (used_topSizeBlocks != printed_topSizeBlocks) {
1430         ast->print_cr("used blocks: %d, printed blocks: %d", used_topSizeBlocks, printed_topSizeBlocks);
1431         for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1432           ast->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1433           BUFFEREDSTREAM_FLUSH_AUTO("")
1434         }
1435       }
1436       BUFFEREDSTREAM_FLUSH("\n\n")
1437     }
1438   }
1439 
1440   //-----------------------------
1441   //--  Print Usage Histogram  --
1442   //-----------------------------
1443 
1444   if (SizeDistributionArray != NULL) {


2185 }
2186 
2187 
2188 void CodeHeapState::print_names(outputStream* out, CodeHeap* heap) {
2189   if (!initialization_complete) {
2190     return;
2191   }
2192 
2193   const char* heapName   = get_heapName(heap);
2194   get_HeapStatGlobals(out, heapName);
2195 
2196   if ((StatArray == NULL) || (alloc_granules == 0)) {
2197     return;
2198   }
2199   BUFFEREDSTREAM_DECL(ast, out)
2200 
2201   unsigned int granules_per_line   = 128;
2202   char*        low_bound           = heap->low_boundary();
2203   CodeBlob*    last_blob           = NULL;
2204   bool         name_in_addr_range  = true;
2205   bool         have_CodeCache_lock = CodeCache_lock->owned_by_self();
2206 
2207   //---<  print at least 128K per block (i.e. between headers)  >---
2208   if (granules_per_line*granule_size < 128*K) {
2209     granules_per_line = (unsigned int)((128*K)/granule_size);
2210   }
2211 
2212   printBox(ast, '=', "M E T H O D   N A M E S   for ", heapName);
2213   ast->print_cr("  Method names are dynamically retrieved from the code cache at print time.\n"
2214                 "  Due to the living nature of the code heap and because the CodeCache_lock\n"
2215                 "  is not continuously held, the displayed name might be wrong or no name\n"
2216                 "  might be found at all. The likelihood for that to happen increases\n"
2217                 "  over time passed between aggregtion and print steps.\n");
2218   BUFFEREDSTREAM_FLUSH_LOCKED("")
2219 
2220   for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2221     //---<  print a new blob on a new line  >---
2222     if (ix%granules_per_line == 0) {
2223       if (!name_in_addr_range) {
2224         ast->print_cr("No methods, blobs, or stubs found in this address range");
2225       }
2226       name_in_addr_range = false;
2227 
2228       size_t end_ix = (ix+granules_per_line <= alloc_granules) ? ix+granules_per_line : alloc_granules;
2229       ast->cr();
2230       ast->print_cr("--------------------------------------------------------------------");
2231       ast->print_cr("Address range [" INTPTR_FORMAT "," INTPTR_FORMAT "), " SIZE_FORMAT "k", p2i(low_bound+ix*granule_size), p2i(low_bound + end_ix*granule_size), (end_ix - ix)*granule_size/(size_t)K);
2232       ast->print_cr("--------------------------------------------------------------------");
2233       BUFFEREDSTREAM_FLUSH_AUTO("")
2234     }
2235     // Only check granule if it contains at least one blob.
2236     unsigned int nBlobs  = StatArray[ix].t1_count   + StatArray[ix].t2_count + StatArray[ix].tx_count +
2237                            StatArray[ix].stub_count + StatArray[ix].dead_count;
2238     if (nBlobs > 0 ) {
2239     for (unsigned int is = 0; is < granule_size; is+=(unsigned int)seg_size) {
2240       // heap->find_start() is safe. Only works on _segmap.
2241       // Returns NULL or void*. Returned CodeBlob may be uninitialized.
2242       char*     this_seg  = low_bound + ix*granule_size + is;
2243       CodeBlob* this_blob = (CodeBlob*)(heap->find_start(this_seg));
2244       bool   blob_is_safe = blob_access_is_safe(this_blob, NULL);
2245       // blob could have been flushed, freed, and merged.
2246       // this_blob < last_blob is an indicator for that.
2247       if (blob_is_safe && (this_blob > last_blob)) {
2248         last_blob          = this_blob;
2249 
2250         //---<  get type and name  >---
2251         blobType       cbType = noType;
2252         if (segment_granules) {
2253           cbType = (blobType)StatArray[ix].type;
2254         } else {
2255           //---<  access these fields only if we own the CodeCache_lock  >---
2256           if (have_CodeCache_lock) {
2257             cbType = get_cbType(this_blob);
2258           }
2259         }
2260 
2261         //---<  access these fields only if we own the CodeCache_lock  >---
2262         const char* blob_name = "<unavailable>";
2263         nmethod*           nm = NULL;
2264         if (have_CodeCache_lock) {
2265           blob_name = this_blob->name();
2266           nm        = this_blob->as_nmethod_or_null();
2267           // this_blob->name() could return NULL if no name was given to CTOR. Inlined, maybe invisible on stack
2268           if ((blob_name == NULL) || !os::is_readable_pointer(blob_name)) {
2269             blob_name = "<unavailable>";
2270           }
2271         }
2272 
2273         //---<  print table header for new print range  >---
2274         if (!name_in_addr_range) {
2275           name_in_addr_range = true;
2276           ast->fill_to(51);
2277           ast->print("%9s", "compiler");
2278           ast->fill_to(61);
2279           ast->print_cr("%6s", "method");
2280           ast->print_cr("%18s %13s %17s %9s  %5s %18s  %s", "Addr(module)      ", "offset", "size", " type lvl", " temp", "blobType          ", "Name");
2281           BUFFEREDSTREAM_FLUSH_AUTO("")
2282         }
2283 
2284         //---<  print line prefix (address and offset from CodeHeap start)  >---
2285         ast->print(INTPTR_FORMAT, p2i(this_blob));
2286         ast->fill_to(19);
2287         ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
2288         ast->fill_to(33);
2289 
2290         // access nmethod and Method fields only if we own the CodeCache_lock.
2291         // This fact is implicitly transported via nm != NULL.
2292         if (CompiledMethod::nmethod_access_is_safe(nm)) {
2293           Method* method = nm->method();
2294           ResourceMark rm;
2295           //---<  collect all data to locals as quickly as possible  >---
2296           unsigned int total_size = nm->total_size();
2297           int          hotness    = nm->hotness_counter();
2298           bool         get_name   = (cbType == nMethod_inuse) || (cbType == nMethod_notused);
2299           //---<  nMethod size in hex  >---
2300           ast->print(PTR32_FORMAT, total_size);
2301           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
2302           //---<  compiler information  >---
2303           ast->fill_to(51);
2304           ast->print("%5s %3d", compTypeName[StatArray[ix].compiler], StatArray[ix].level);
2305           //---<  method temperature  >---
2306           ast->fill_to(62);
2307           ast->print("%5d", hotness);
2308           //---<  name and signature  >---
2309           ast->fill_to(62+6);
2310           ast->print("%s", blobTypeName[cbType]);
2311           ast->fill_to(82+6);
2312           if (cbType == nMethod_dead) {


2478       ast->print("|");
2479     }
2480     ast->cr();
2481 
2482     // can't use BUFFEREDSTREAM_FLUSH_IF("", 512) here.
2483     // can't use this expression. bufferedStream::capacity() does not exist.
2484     // if ((ast->capacity() - ast->size()) < 512) {
2485     // Assume instead that default bufferedStream capacity (4K) was used.
2486     if (ast->size() > 3*K) {
2487       ttyLocker ttyl;
2488       out->print("%s", ast->as_string());
2489       ast->reset();
2490     }
2491 
2492     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2493     ast->fill_to(19);
2494     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2495   }
2496 }
2497 


2498 CodeHeapState::blobType CodeHeapState::get_cbType(CodeBlob* cb) {
2499   if ((cb != NULL) && os::is_readable_pointer(cb)) {
2500     if (cb->is_runtime_stub())                return runtimeStub;
2501     if (cb->is_deoptimization_stub())         return deoptimizationStub;
2502     if (cb->is_uncommon_trap_stub())          return uncommonTrapStub;
2503     if (cb->is_exception_stub())              return exceptionStub;
2504     if (cb->is_safepoint_stub())              return safepointStub;
2505     if (cb->is_adapter_blob())                return adapterBlob;
2506     if (cb->is_method_handles_adapter_blob()) return mh_adapterBlob;
2507     if (cb->is_buffer_blob())                 return bufferBlob;
2508 
2509     //---<  access these fields only if we own the CodeCache_lock  >---
2510     // Should be ensured by caller. aggregate() amd print_names() do that.
2511     if (CodeCache_lock->owned_by_self()) {
2512       nmethod*  nm = cb->as_nmethod_or_null();
2513       if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
2514         if (nm->is_not_installed()) return nMethod_inconstruction;
2515         if (nm->is_zombie())        return nMethod_dead;
2516         if (nm->is_unloaded())      return nMethod_unloaded;
2517         if (nm->is_in_use())        return nMethod_inuse;
2518         if (nm->is_alive() && !(nm->is_not_entrant()))   return nMethod_notused;
2519         if (nm->is_alive())         return nMethod_alive;
2520         return nMethod_dead;
2521       }
2522     }
2523   }
2524   return noType;
2525 }
2526 
2527 bool CodeHeapState::blob_access_is_safe(CodeBlob* this_blob, CodeBlob* prev_blob) {

2528   return (this_blob != NULL) && // a blob must have been found, obviously
2529          ((this_blob == prev_blob) || (prev_blob == NULL)) &&  // when re-checking, the same blob must have been found
2530          (this_blob->header_size() >= 0) &&
2531          (this_blob->relocation_size() >= 0) &&
2532          ((address)this_blob + this_blob->header_size() == (address)(this_blob->relocation_begin())) &&
2533          ((address)this_blob + CodeBlob::align_code_offset(this_blob->header_size() + this_blob->relocation_size()) == (address)(this_blob->content_begin())) &&
2534          os::is_readable_pointer((address)(this_blob->relocation_begin())) &&
2535          os::is_readable_pointer(this_blob->content_begin());









2536 }


   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "code/codeHeapState.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "runtime/safepoint.hpp"
  30 #include "runtime/sweeper.hpp"
  31 
  32 // -------------------------
  33 // |  General Description  |
  34 // -------------------------
  35 // The CodeHeap state analytics are divided in two parts.
  36 // The first part examines the entire CodeHeap and aggregates all
  37 // information that is believed useful/important.
  38 //
  39 // Aggregation condenses the information of a piece of the CodeHeap
  40 // (4096 bytes by default) into an analysis granule. These granules
  41 // contain enough detail to gain initial insight while keeping the
  42 // internal structure sizes in check.
  43 //
  44 // The second part, which consists of several, independent steps,
  45 // prints the previously collected information with emphasis on
  46 // various aspects.
  47 //
  48 // The CodeHeap is a living thing. Therefore, protection against concurrent
  49 // modification (by acquiring the CodeCache_lock) is necessary. It has


 200 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 201     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 202       _outbuf->print("%s", _termString);                      \
 203     }
 204 
 205 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 206     BUFFEREDSTREAM_FLUSH(_termString)
 207 
 208 #define BUFFEREDSTREAM_FLUSH_AUTO(_termString)                \
 209     BUFFEREDSTREAM_FLUSH(_termString)
 210 
 211 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 212     BUFFEREDSTREAM_FLUSH(_termString)
 213 
 214 #define BUFFEREDSTREAM_FLUSH_STAT()
 215 #endif
 216 #define HEX32_FORMAT  "0x%x"  // just a helper format string used below multiple times
 217 
 218 const char  blobTypeChar[] = {' ', 'C', 'N', 'I', 'X', 'Z', 'U', 'R', '?', 'D', 'T', 'E', 'S', 'A', 'M', 'B', 'L' };
 219 const char* blobTypeName[] = {"noType"
 220                              ,     "nMethod (under construction), cannot be observed"
 221                              ,          "nMethod (active)"
 222                              ,               "nMethod (inactive)"
 223                              ,                    "nMethod (deopt)"
 224                              ,                         "nMethod (zombie)"
 225                              ,                              "nMethod (unloaded)"
 226                              ,                                   "runtime stub"
 227                              ,                                        "ricochet stub"
 228                              ,                                             "deopt stub"
 229                              ,                                                  "uncommon trap stub"
 230                              ,                                                       "exception stub"
 231                              ,                                                            "safepoint stub"
 232                              ,                                                                 "adapter blob"
 233                              ,                                                                      "MH adapter blob"
 234                              ,                                                                           "buffer blob"
 235                              ,                                                                                "lastType"
 236                              };
 237 const char* compTypeName[] = { "none", "c1", "c2", "jvmci" };
 238 
 239 // Be prepared for ten different CodeHeap segments. Should be enough for a few years.
 240 const  unsigned int        nSizeDistElements = 31;  // logarithmic range growth, max size: 2**32
 241 const  unsigned int        maxTopSizeBlocks  = 100;
 242 const  unsigned int        tsbStopper        = 2 * maxTopSizeBlocks;
 243 const  unsigned int        maxHeaps          = 10;
 244 static unsigned int        nHeaps            = 0;
 245 static struct CodeHeapStat CodeHeapStatArray[maxHeaps];
 246 
 247 // static struct StatElement *StatArray      = NULL;
 248 static StatElement* StatArray             = NULL;
 249 static int          log2_seg_size         = 0;
 250 static size_t       seg_size              = 0;
 251 static size_t       alloc_granules        = 0;
 252 static size_t       granule_size          = 0;
 253 static bool         segment_granules      = false;
 254 static unsigned int nBlocks_t1            = 0;  // counting "in_use" nmethods only.
 255 static unsigned int nBlocks_t2            = 0;  // counting "in_use" nmethods only.
 256 static unsigned int nBlocks_alive         = 0;  // counting "not_used" and "not_entrant" nmethods only.
 257 static unsigned int nBlocks_dead          = 0;  // counting "zombie" and "unloaded" methods only.

 258 static unsigned int nBlocks_unloaded      = 0;  // counting "unloaded" nmethods only. This is a transient state.
 259 static unsigned int nBlocks_stub          = 0;
 260 
 261 static struct FreeBlk*          FreeArray = NULL;
 262 static unsigned int      alloc_freeBlocks = 0;
 263 
 264 static struct TopSizeBlk*    TopSizeArray = NULL;
 265 static unsigned int   alloc_topSizeBlocks = 0;
 266 static unsigned int    used_topSizeBlocks = 0;
 267 
 268 static struct SizeDistributionElement*  SizeDistributionArray = NULL;
 269 
 270 // nMethod temperature (hotness) indicators.
 271 static int                     avgTemp    = 0;
 272 static int                     maxTemp    = 0;
 273 static int                     minTemp    = 0;
 274 
 275 static unsigned int  latest_compilation_id   = 0;
 276 static volatile bool initialization_complete = false;
 277 


 308   } else {
 309     nHeaps = 1;
 310     CodeHeapStatArray[0].heapName = heapName;
 311     return 0; // This is the default index if CodeCache is not segmented.
 312   }
 313 }
 314 
 315 void CodeHeapState::get_HeapStatGlobals(outputStream* out, const char* heapName) {
 316   unsigned int ix = findHeapIndex(out, heapName);
 317   if (ix < maxHeaps) {
 318     StatArray             = CodeHeapStatArray[ix].StatArray;
 319     seg_size              = CodeHeapStatArray[ix].segment_size;
 320     log2_seg_size         = seg_size == 0 ? 0 : exact_log2(seg_size);
 321     alloc_granules        = CodeHeapStatArray[ix].alloc_granules;
 322     granule_size          = CodeHeapStatArray[ix].granule_size;
 323     segment_granules      = CodeHeapStatArray[ix].segment_granules;
 324     nBlocks_t1            = CodeHeapStatArray[ix].nBlocks_t1;
 325     nBlocks_t2            = CodeHeapStatArray[ix].nBlocks_t2;
 326     nBlocks_alive         = CodeHeapStatArray[ix].nBlocks_alive;
 327     nBlocks_dead          = CodeHeapStatArray[ix].nBlocks_dead;

 328     nBlocks_unloaded      = CodeHeapStatArray[ix].nBlocks_unloaded;
 329     nBlocks_stub          = CodeHeapStatArray[ix].nBlocks_stub;
 330     FreeArray             = CodeHeapStatArray[ix].FreeArray;
 331     alloc_freeBlocks      = CodeHeapStatArray[ix].alloc_freeBlocks;
 332     TopSizeArray          = CodeHeapStatArray[ix].TopSizeArray;
 333     alloc_topSizeBlocks   = CodeHeapStatArray[ix].alloc_topSizeBlocks;
 334     used_topSizeBlocks    = CodeHeapStatArray[ix].used_topSizeBlocks;
 335     SizeDistributionArray = CodeHeapStatArray[ix].SizeDistributionArray;
 336     avgTemp               = CodeHeapStatArray[ix].avgTemp;
 337     maxTemp               = CodeHeapStatArray[ix].maxTemp;
 338     minTemp               = CodeHeapStatArray[ix].minTemp;
 339   } else {
 340     StatArray             = NULL;
 341     seg_size              = 0;
 342     log2_seg_size         = 0;
 343     alloc_granules        = 0;
 344     granule_size          = 0;
 345     segment_granules      = false;
 346     nBlocks_t1            = 0;
 347     nBlocks_t2            = 0;
 348     nBlocks_alive         = 0;
 349     nBlocks_dead          = 0;

 350     nBlocks_unloaded      = 0;
 351     nBlocks_stub          = 0;
 352     FreeArray             = NULL;
 353     alloc_freeBlocks      = 0;
 354     TopSizeArray          = NULL;
 355     alloc_topSizeBlocks   = 0;
 356     used_topSizeBlocks    = 0;
 357     SizeDistributionArray = NULL;
 358     avgTemp               = 0;
 359     maxTemp               = 0;
 360     minTemp               = 0;
 361   }
 362 }
 363 
 364 void CodeHeapState::set_HeapStatGlobals(outputStream* out, const char* heapName) {
 365   unsigned int ix = findHeapIndex(out, heapName);
 366   if (ix < maxHeaps) {
 367     CodeHeapStatArray[ix].StatArray             = StatArray;
 368     CodeHeapStatArray[ix].segment_size          = seg_size;
 369     CodeHeapStatArray[ix].alloc_granules        = alloc_granules;
 370     CodeHeapStatArray[ix].granule_size          = granule_size;
 371     CodeHeapStatArray[ix].segment_granules      = segment_granules;
 372     CodeHeapStatArray[ix].nBlocks_t1            = nBlocks_t1;
 373     CodeHeapStatArray[ix].nBlocks_t2            = nBlocks_t2;
 374     CodeHeapStatArray[ix].nBlocks_alive         = nBlocks_alive;
 375     CodeHeapStatArray[ix].nBlocks_dead          = nBlocks_dead;

 376     CodeHeapStatArray[ix].nBlocks_unloaded      = nBlocks_unloaded;
 377     CodeHeapStatArray[ix].nBlocks_stub          = nBlocks_stub;
 378     CodeHeapStatArray[ix].FreeArray             = FreeArray;
 379     CodeHeapStatArray[ix].alloc_freeBlocks      = alloc_freeBlocks;
 380     CodeHeapStatArray[ix].TopSizeArray          = TopSizeArray;
 381     CodeHeapStatArray[ix].alloc_topSizeBlocks   = alloc_topSizeBlocks;
 382     CodeHeapStatArray[ix].used_topSizeBlocks    = used_topSizeBlocks;
 383     CodeHeapStatArray[ix].SizeDistributionArray = SizeDistributionArray;
 384     CodeHeapStatArray[ix].avgTemp               = avgTemp;
 385     CodeHeapStatArray[ix].maxTemp               = maxTemp;
 386     CodeHeapStatArray[ix].minTemp               = minTemp;
 387   }
 388 }
 389 
 390 //---<  get a new statistics array  >---
 391 void CodeHeapState::prepare_StatArray(outputStream* out, size_t nElem, size_t granularity, const char* heapName) {
 392   if (StatArray == NULL) {
 393     StatArray      = new StatElement[nElem];
 394     //---<  reset some counts  >---
 395     alloc_granules = nElem;


 482 
 483 void CodeHeapState::discard_StatArray(outputStream* out) {
 484   if (StatArray != NULL) {
 485     delete StatArray;
 486     StatArray        = NULL;
 487     alloc_granules   = 0;
 488     granule_size     = 0;
 489   }
 490 }
 491 
 492 void CodeHeapState::discard_FreeArray(outputStream* out) {
 493   if (FreeArray != NULL) {
 494     delete[] FreeArray;
 495     FreeArray        = NULL;
 496     alloc_freeBlocks = 0;
 497   }
 498 }
 499 
 500 void CodeHeapState::discard_TopSizeArray(outputStream* out) {
 501   if (TopSizeArray != NULL) {
 502     for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
 503       if (TopSizeArray[i].blob_name != NULL) {
 504         os::free((void*)TopSizeArray[i].blob_name);
 505       }
 506     }
 507     delete[] TopSizeArray;
 508     TopSizeArray        = NULL;
 509     alloc_topSizeBlocks = 0;
 510     used_topSizeBlocks  = 0;
 511   }
 512 }
 513 
 514 void CodeHeapState::discard_SizeDistArray(outputStream* out) {
 515   if (SizeDistributionArray != NULL) {
 516     delete[] SizeDistributionArray;
 517     SizeDistributionArray = NULL;
 518   }
 519 }
 520 
 521 // Discard all allocated internal data structures.
 522 // This should be done after an analysis session is completed.
 523 void CodeHeapState::discard(outputStream* out, CodeHeap* heap) {
 524   if (!initialization_complete) {
 525     return;
 526   }


 580     BUFFEREDSTREAM_FLUSH("")
 581   }
 582   get_HeapStatGlobals(out, heapName);
 583 
 584 
 585   // Since we are (and must be) analyzing the CodeHeap contents under the CodeCache_lock,
 586   // all heap information is "constant" and can be safely extracted/calculated before we
 587   // enter the while() loop. Actually, the loop will only be iterated once.
 588   char*  low_bound     = heap->low_boundary();
 589   size_t size          = heap->capacity();
 590   size_t res_size      = heap->max_capacity();
 591   seg_size             = heap->segment_size();
 592   log2_seg_size        = seg_size == 0 ? 0 : exact_log2(seg_size);  // This is a global static value.
 593 
 594   if (seg_size == 0) {
 595     printBox(ast, '-', "Heap not fully initialized yet, segment size is zero for segment ", heapName);
 596     BUFFEREDSTREAM_FLUSH("")
 597     return;
 598   }
 599 
 600   if (!holding_required_locks()) {
 601     printBox(ast, '-', "Must be at safepoint or hold Compile_lock and CodeCache_lock when calling aggregate function for ", heapName);
 602     BUFFEREDSTREAM_FLUSH("")
 603     return;
 604   }
 605 
 606   // Calculate granularity of analysis (and output).
 607   //   The CodeHeap is managed (allocated) in segments (units) of CodeCacheSegmentSize.
 608   //   The CodeHeap can become fairly large, in particular in productive real-life systems.
 609   //
 610   //   It is often neither feasible nor desirable to aggregate the data with the highest possible
 611   //   level of detail, i.e. inspecting and printing each segment on its own.
 612   //
 613   //   The granularity parameter allows to specify the level of detail available in the analysis.
 614   //   It must be a positive multiple of the segment size and should be selected such that enough
 615   //   detail is provided while, at the same time, the printed output does not explode.
 616   //
 617   //   By manipulating the granularity value, we enforce that at least min_granules units
 618   //   of analysis are available. We also enforce an upper limit of max_granules units to
 619   //   keep the amount of allocated storage in check.
 620   //
 621   //   Finally, we adjust the granularity such that each granule covers at most 64k-1 segments.


 648                 "   Subsequent print functions create their output based on this snapshot.\n"
 649                 "   The CodeHeap is a living thing, and every effort has been made for the\n"
 650                 "   collected data to be consistent. Only the method names and signatures\n"
 651                 "   are retrieved at print time. That may lead to rare cases where the\n"
 652                 "   name of a method is no longer available, e.g. because it was unloaded.\n");
 653   ast->print_cr("   CodeHeap committed size " SIZE_FORMAT "K (" SIZE_FORMAT "M), reserved size " SIZE_FORMAT "K (" SIZE_FORMAT "M), %d%% occupied.",
 654                 size/(size_t)K, size/(size_t)M, res_size/(size_t)K, res_size/(size_t)M, (unsigned int)(100.0*size/res_size));
 655   ast->print_cr("   CodeHeap allocation segment size is " SIZE_FORMAT " bytes. This is the smallest possible granularity.", seg_size);
 656   ast->print_cr("   CodeHeap (committed part) is mapped to " SIZE_FORMAT " granules of size " SIZE_FORMAT " bytes.", granules, granularity);
 657   ast->print_cr("   Each granule takes " SIZE_FORMAT " bytes of C heap, that is " SIZE_FORMAT "K in total for statistics data.", sizeof(StatElement), (sizeof(StatElement)*granules)/(size_t)K);
 658   ast->print_cr("   The number of granules is limited to %dk, requiring a granules size of at least %d bytes for a 1GB heap.", (unsigned int)(max_granules/K), (unsigned int)(G/max_granules));
 659   BUFFEREDSTREAM_FLUSH("\n")
 660 
 661 
 662   while (!done) {
 663     //---<  reset counters with every aggregation  >---
 664     nBlocks_t1       = 0;
 665     nBlocks_t2       = 0;
 666     nBlocks_alive    = 0;
 667     nBlocks_dead     = 0;

 668     nBlocks_unloaded = 0;
 669     nBlocks_stub     = 0;
 670 
 671     nBlocks_free     = 0;
 672     nBlocks_used     = 0;
 673     nBlocks_zomb     = 0;
 674     nBlocks_disconn  = 0;
 675     nBlocks_notentr  = 0;
 676 
 677     //---<  discard old arrays if size does not match  >---
 678     if (granules != alloc_granules) {
 679       discard_StatArray(out);
 680       discard_TopSizeArray(out);
 681     }
 682 
 683     //---<  allocate arrays if they don't yet exist, initialize  >---
 684     prepare_StatArray(out, granules, granularity, heapName);
 685     if (StatArray == NULL) {
 686       set_HeapStatGlobals(out, heapName);
 687       return;
 688     }
 689     prepare_TopSizeArray(out, maxTopSizeBlocks, heapName);
 690     prepare_SizeDistArray(out, nSizeDistElements, heapName);
 691 
 692     latest_compilation_id = CompileBroker::get_compilation_id();
 693     unsigned int highest_compilation_id = 0;
 694     size_t       usedSpace     = 0;
 695     size_t       t1Space       = 0;
 696     size_t       t2Space       = 0;
 697     size_t       aliveSpace    = 0;
 698     size_t       disconnSpace  = 0;
 699     size_t       notentrSpace  = 0;
 700     size_t       deadSpace     = 0;

 701     size_t       unloadedSpace = 0;
 702     size_t       stubSpace     = 0;
 703     size_t       freeSpace     = 0;
 704     size_t       maxFreeSize   = 0;
 705     HeapBlock*   maxFreeBlock  = NULL;
 706     bool         insane        = false;
 707 
 708     int64_t hotnessAccumulator = 0;
 709     unsigned int n_methods     = 0;
 710     avgTemp       = 0;
 711     minTemp       = (int)(res_size > M ? (res_size/M)*2 : 1);
 712     maxTemp       = -minTemp;
 713 
 714     for (HeapBlock *h = heap->first_block(); h != NULL && !insane; h = heap->next_block(h)) {
 715       unsigned int hb_len     = (unsigned int)h->length();  // despite being size_t, length can never overflow an unsigned int.
 716       size_t       hb_bytelen = ((size_t)hb_len)<<log2_seg_size;
 717       unsigned int ix_beg     = (unsigned int)(((char*)h-low_bound)/granule_size);
 718       unsigned int ix_end     = (unsigned int)(((char*)h-low_bound+(hb_bytelen-1))/granule_size);
 719       unsigned int compile_id = 0;
 720       CompLevel    comp_lvl   = CompLevel_none;


 742       if (ix_beg   >  ix_end) {
 743         insane = true; ast->print_cr("Sanity check: end index (%d) lower than begin index (%d)", ix_end, ix_beg);
 744       }
 745       if (insane) {
 746         BUFFEREDSTREAM_FLUSH("")
 747         continue;
 748       }
 749 
 750       if (h->free()) {
 751         nBlocks_free++;
 752         freeSpace    += hb_bytelen;
 753         if (hb_bytelen > maxFreeSize) {
 754           maxFreeSize   = hb_bytelen;
 755           maxFreeBlock  = h;
 756         }
 757       } else {
 758         update_SizeDistArray(out, hb_len);
 759         nBlocks_used++;
 760         usedSpace    += hb_bytelen;
 761         CodeBlob* cb  = (CodeBlob*)heap->find_start(h);
 762         cbType = get_cbType(cb);  // Will check for cb == NULL and other safety things.
 763         if (cbType != noType) {
 764           const char* blob_name  = os::strdup(cb->name());
 765           unsigned int nm_size   = 0;
 766           int temperature        = 0;
 767           nmethod*  nm = cb->as_nmethod_or_null();
 768           if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
 769             ResourceMark rm;
 770             Method* method = nm->method();
 771             if (nm->is_in_use()) {
 772               blob_name = os::strdup(method->name_and_sig_as_C_string());
 773             }
 774             if (nm->is_not_entrant()) {
 775               blob_name = os::strdup(method->name_and_sig_as_C_string());
 776             }
 777 
 778             nm_size    = nm->total_size();
 779             compile_id = nm->compile_id();
 780             comp_lvl   = (CompLevel)(nm->comp_level());
 781             if (nm->is_compiled_by_c1()) {
 782               cType = c1;
 783             }
 784             if (nm->is_compiled_by_c2()) {
 785               cType = c2;
 786             }
 787             if (nm->is_compiled_by_jvmci()) {
 788               cType = jvmci;
 789             }
 790             switch (cbType) {
 791               case nMethod_inuse: { // only for executable methods!!!
 792                 // space for these cbs is accounted for later.
 793                 temperature = nm->hotness_counter();
 794                 hotnessAccumulator += temperature;
 795                 n_methods++;
 796                 maxTemp = (temperature > maxTemp) ? temperature : maxTemp;
 797                 minTemp = (temperature < minTemp) ? temperature : minTemp;
 798                 break;
 799               }
 800               case nMethod_notused:
 801                 nBlocks_alive++;
 802                 nBlocks_disconn++;
 803                 aliveSpace     += hb_bytelen;
 804                 disconnSpace   += hb_bytelen;
 805                 break;
 806               case nMethod_notentrant:  // equivalent to nMethod_alive
 807                 nBlocks_alive++;
 808                 nBlocks_notentr++;
 809                 aliveSpace     += hb_bytelen;
 810                 notentrSpace   += hb_bytelen;
 811                 break;
 812               case nMethod_unloaded:
 813                 nBlocks_unloaded++;
 814                 unloadedSpace  += hb_bytelen;
 815                 break;
 816               case nMethod_dead:
 817                 nBlocks_dead++;
 818                 deadSpace      += hb_bytelen;
 819                 break;




 820               default:
 821                 break;
 822             }
 823           }
 824 
 825           //------------------------------------------
 826           //---<  register block in TopSizeArray  >---
 827           //------------------------------------------
 828           if (alloc_topSizeBlocks > 0) {
 829             if (used_topSizeBlocks == 0) {
 830               TopSizeArray[0].start       = h;
 831               TopSizeArray[0].blob_name   = blob_name;
 832               TopSizeArray[0].len         = hb_len;
 833               TopSizeArray[0].index       = tsbStopper;
 834               TopSizeArray[0].nm_size     = nm_size;
 835               TopSizeArray[0].temperature = temperature;
 836               TopSizeArray[0].compiler    = cType;
 837               TopSizeArray[0].level       = comp_lvl;
 838               TopSizeArray[0].type        = cbType;
 839               currMax    = hb_len;
 840               currMin    = hb_len;
 841               currMin_ix = 0;
 842               used_topSizeBlocks++;
 843               blob_name  = NULL; // indicate blob_name was consumed
 844             // This check roughly cuts 5000 iterations (JVM98, mixed, dbg, termination stats):
 845             } else if ((used_topSizeBlocks < alloc_topSizeBlocks) && (hb_len < currMin)) {
 846               //---<  all blocks in list are larger, but there is room left in array  >---
 847               TopSizeArray[currMin_ix].index = used_topSizeBlocks;
 848               TopSizeArray[used_topSizeBlocks].start       = h;
 849               TopSizeArray[used_topSizeBlocks].blob_name   = blob_name;
 850               TopSizeArray[used_topSizeBlocks].len         = hb_len;
 851               TopSizeArray[used_topSizeBlocks].index       = tsbStopper;
 852               TopSizeArray[used_topSizeBlocks].nm_size     = nm_size;
 853               TopSizeArray[used_topSizeBlocks].temperature = temperature;
 854               TopSizeArray[used_topSizeBlocks].compiler    = cType;
 855               TopSizeArray[used_topSizeBlocks].level       = comp_lvl;
 856               TopSizeArray[used_topSizeBlocks].type        = cbType;
 857               currMin    = hb_len;
 858               currMin_ix = used_topSizeBlocks;
 859               used_topSizeBlocks++;
 860               blob_name  = NULL; // indicate blob_name was consumed
 861             } else {
 862               // This check cuts total_iterations by a factor of 6 (JVM98, mixed, dbg, termination stats):
 863               //   We don't need to search the list if we know beforehand that the current block size is
 864               //   smaller than the currently recorded minimum and there is no free entry left in the list.
 865               if (!((used_topSizeBlocks == alloc_topSizeBlocks) && (hb_len <= currMin))) {
 866                 if (currMax < hb_len) {
 867                   currMax = hb_len;
 868                 }
 869                 unsigned int i;
 870                 unsigned int prev_i  = tsbStopper;
 871                 unsigned int limit_i =  0;
 872                 for (i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
 873                   if (limit_i++ >= alloc_topSizeBlocks) {
 874                     insane = true; break; // emergency exit
 875                   }
 876                   if (i >= used_topSizeBlocks)  {
 877                     insane = true; break; // emergency exit
 878                   }
 879                   total_iterations++;
 880                   if (TopSizeArray[i].len < hb_len) {
 881                     //---<  We want to insert here, element <i> is smaller than the current one  >---
 882                     if (used_topSizeBlocks < alloc_topSizeBlocks) { // still room for a new entry to insert
 883                       // old entry gets moved to the next free element of the array.
 884                       // That's necessary to keep the entry for the largest block at index 0.
 885                       // This move might cause the current minimum to be moved to another place
 886                       if (i == currMin_ix) {
 887                         assert(TopSizeArray[i].len == currMin, "sort error");
 888                         currMin_ix = used_topSizeBlocks;
 889                       }
 890                       memcpy((void*)&TopSizeArray[used_topSizeBlocks], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 891                       TopSizeArray[i].start       = h;
 892                       TopSizeArray[i].blob_name   = blob_name;
 893                       TopSizeArray[i].len         = hb_len;
 894                       TopSizeArray[i].index       = used_topSizeBlocks;
 895                       TopSizeArray[i].nm_size     = nm_size;
 896                       TopSizeArray[i].temperature = temperature;
 897                       TopSizeArray[i].compiler    = cType;
 898                       TopSizeArray[i].level       = comp_lvl;
 899                       TopSizeArray[i].type        = cbType;
 900                       used_topSizeBlocks++;
 901                       blob_name  = NULL; // indicate blob_name was consumed
 902                     } else { // no room for new entries, current block replaces entry for smallest block
 903                       //---<  Find last entry (entry for smallest remembered block)  >---
 904                       // We either want to insert right before the smallest entry, which is when <i>
 905                       // indexes the smallest entry. We then just overwrite the smallest entry.
 906                       // What's more likely:
 907                       // We want to insert somewhere in the list. The smallest entry (@<j>) then falls off the cliff.
 908                       // The element at the insert point <i> takes it's slot. The second-smallest entry now becomes smallest.
 909                       // Data of the current block is filled in at index <i>.
 910                       unsigned int      j  = i;
 911                       unsigned int prev_j  = tsbStopper;
 912                       unsigned int limit_j = 0;
 913                       while (TopSizeArray[j].index != tsbStopper) {
 914                         if (limit_j++ >= alloc_topSizeBlocks) {
 915                           insane = true; break; // emergency exit
 916                         }
 917                         if (j >= used_topSizeBlocks)  {
 918                           insane = true; break; // emergency exit
 919                         }
 920                         total_iterations++;
 921                         prev_j = j;
 922                         j      = TopSizeArray[j].index;
 923                       }
 924                       if (!insane) {
 925                         if (TopSizeArray[j].blob_name != NULL) {
 926                           os::free((void*)TopSizeArray[j].blob_name);
 927                         }
 928                         if (prev_j == tsbStopper) {
 929                           //---<  Above while loop did not iterate, we already are the min entry  >---
 930                           //---<  We have to just replace the smallest entry                      >---
 931                           currMin    = hb_len;
 932                           currMin_ix = j;
 933                           TopSizeArray[j].start       = h;
 934                           TopSizeArray[j].blob_name   = blob_name;
 935                           TopSizeArray[j].len         = hb_len;
 936                           TopSizeArray[j].index       = tsbStopper; // already set!!
 937                           TopSizeArray[i].nm_size     = nm_size;
 938                           TopSizeArray[i].temperature = temperature;
 939                           TopSizeArray[j].compiler    = cType;
 940                           TopSizeArray[j].level       = comp_lvl;
 941                           TopSizeArray[j].type        = cbType;
 942                         } else {
 943                           //---<  second-smallest entry is now smallest  >---
 944                           TopSizeArray[prev_j].index = tsbStopper;
 945                           currMin    = TopSizeArray[prev_j].len;
 946                           currMin_ix = prev_j;
 947                           //---<  previously smallest entry gets overwritten  >---
 948                           memcpy((void*)&TopSizeArray[j], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 949                           TopSizeArray[i].start       = h;
 950                           TopSizeArray[i].blob_name   = blob_name;
 951                           TopSizeArray[i].len         = hb_len;
 952                           TopSizeArray[i].index       = j;
 953                           TopSizeArray[i].nm_size     = nm_size;
 954                           TopSizeArray[i].temperature = temperature;
 955                           TopSizeArray[i].compiler    = cType;
 956                           TopSizeArray[i].level       = comp_lvl;
 957                           TopSizeArray[i].type        = cbType;
 958                         }
 959                         blob_name  = NULL; // indicate blob_name was consumed
 960                       } // insane
 961                     }
 962                     break;
 963                   }
 964                   prev_i = i;
 965                 }
 966                 if (insane) {
 967                   // Note: regular analysis could probably continue by resetting "insane" flag.
 968                   out->print_cr("Possible loop in TopSizeBlocks list detected. Analysis aborted.");
 969                   discard_TopSizeArray(out);
 970                 }
 971               }
 972             }
 973           }
 974           if (blob_name != NULL) {
 975             os::free((void*)blob_name);
 976             blob_name = NULL;
 977           }
 978           //----------------------------------------------
 979           //---<  END register block in TopSizeArray  >---
 980           //----------------------------------------------
 981         } else {
 982           nBlocks_zomb++;
 983         }
 984 
 985         if (ix_beg == ix_end) {
 986           StatArray[ix_beg].type = cbType;
 987           switch (cbType) {
 988             case nMethod_inuse:
 989               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 990               if (comp_lvl < CompLevel_full_optimization) {
 991                 nBlocks_t1++;
 992                 t1Space   += hb_bytelen;
 993                 StatArray[ix_beg].t1_count++;
 994                 StatArray[ix_beg].t1_space += (unsigned short)hb_len;
 995                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 996               } else {
 997                 nBlocks_t2++;
 998                 t2Space   += hb_bytelen;
 999                 StatArray[ix_beg].t2_count++;
1000                 StatArray[ix_beg].t2_space += (unsigned short)hb_len;
1001                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
1002               }
1003               StatArray[ix_beg].level     = comp_lvl;
1004               StatArray[ix_beg].compiler  = cType;
1005               break;

1006             case nMethod_alive:
1007               StatArray[ix_beg].tx_count++;
1008               StatArray[ix_beg].tx_space += (unsigned short)hb_len;
1009               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
1010               StatArray[ix_beg].level     = comp_lvl;
1011               StatArray[ix_beg].compiler  = cType;
1012               break;
1013             case nMethod_dead:
1014             case nMethod_unloaded:
1015               StatArray[ix_beg].dead_count++;
1016               StatArray[ix_beg].dead_space += (unsigned short)hb_len;
1017               break;
1018             default:
1019               // must be a stub, if it's not a dead or alive nMethod
1020               nBlocks_stub++;
1021               stubSpace   += hb_bytelen;
1022               StatArray[ix_beg].stub_count++;
1023               StatArray[ix_beg].stub_space += (unsigned short)hb_len;
1024               break;
1025           }


1042 
1043                 StatArray[ix_end].t1_count++;
1044                 StatArray[ix_end].t1_space += (unsigned short)end_space;
1045                 StatArray[ix_end].t1_age    = StatArray[ix_end].t1_age < compile_id ? compile_id : StatArray[ix_end].t1_age;
1046               } else {
1047                 nBlocks_t2++;
1048                 t2Space   += hb_bytelen;
1049                 StatArray[ix_beg].t2_count++;
1050                 StatArray[ix_beg].t2_space += (unsigned short)beg_space;
1051                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
1052 
1053                 StatArray[ix_end].t2_count++;
1054                 StatArray[ix_end].t2_space += (unsigned short)end_space;
1055                 StatArray[ix_end].t2_age    = StatArray[ix_end].t2_age < compile_id ? compile_id : StatArray[ix_end].t2_age;
1056               }
1057               StatArray[ix_beg].level     = comp_lvl;
1058               StatArray[ix_beg].compiler  = cType;
1059               StatArray[ix_end].level     = comp_lvl;
1060               StatArray[ix_end].compiler  = cType;
1061               break;

1062             case nMethod_alive:
1063               StatArray[ix_beg].tx_count++;
1064               StatArray[ix_beg].tx_space += (unsigned short)beg_space;
1065               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
1066 
1067               StatArray[ix_end].tx_count++;
1068               StatArray[ix_end].tx_space += (unsigned short)end_space;
1069               StatArray[ix_end].tx_age    = StatArray[ix_end].tx_age < compile_id ? compile_id : StatArray[ix_end].tx_age;
1070 
1071               StatArray[ix_beg].level     = comp_lvl;
1072               StatArray[ix_beg].compiler  = cType;
1073               StatArray[ix_end].level     = comp_lvl;
1074               StatArray[ix_end].compiler  = cType;
1075               break;
1076             case nMethod_dead:
1077             case nMethod_unloaded:
1078               StatArray[ix_beg].dead_count++;
1079               StatArray[ix_beg].dead_space += (unsigned short)beg_space;
1080               StatArray[ix_end].dead_count++;
1081               StatArray[ix_end].dead_space += (unsigned short)end_space;


1089               StatArray[ix_end].stub_count++;
1090               StatArray[ix_end].stub_space += (unsigned short)end_space;
1091               break;
1092           }
1093           for (unsigned int ix = ix_beg+1; ix < ix_end; ix++) {
1094             StatArray[ix].type = cbType;
1095             switch (cbType) {
1096               case nMethod_inuse:
1097                 if (comp_lvl < CompLevel_full_optimization) {
1098                   StatArray[ix].t1_count++;
1099                   StatArray[ix].t1_space += (unsigned short)(granule_size>>log2_seg_size);
1100                   StatArray[ix].t1_age    = StatArray[ix].t1_age < compile_id ? compile_id : StatArray[ix].t1_age;
1101                 } else {
1102                   StatArray[ix].t2_count++;
1103                   StatArray[ix].t2_space += (unsigned short)(granule_size>>log2_seg_size);
1104                   StatArray[ix].t2_age    = StatArray[ix].t2_age < compile_id ? compile_id : StatArray[ix].t2_age;
1105                 }
1106                 StatArray[ix].level     = comp_lvl;
1107                 StatArray[ix].compiler  = cType;
1108                 break;

1109               case nMethod_alive:
1110                 StatArray[ix].tx_count++;
1111                 StatArray[ix].tx_space += (unsigned short)(granule_size>>log2_seg_size);
1112                 StatArray[ix].tx_age    = StatArray[ix].tx_age < compile_id ? compile_id : StatArray[ix].tx_age;
1113                 StatArray[ix].level     = comp_lvl;
1114                 StatArray[ix].compiler  = cType;
1115                 break;
1116               case nMethod_dead:
1117               case nMethod_unloaded:
1118                 StatArray[ix].dead_count++;
1119                 StatArray[ix].dead_space += (unsigned short)(granule_size>>log2_seg_size);
1120                 break;
1121               default:
1122                 // must be a stub, if it's not a dead or alive nMethod
1123                 StatArray[ix].stub_count++;
1124                 StatArray[ix].stub_space += (unsigned short)(granule_size>>log2_seg_size);
1125                 break;
1126             }
1127           }
1128         }
1129       }
1130     }
1131     done = true;
1132 
1133     if (!insane) {
1134       // There is a risk for this block (because it contains many print statements) to get
1135       // interspersed with print data from other threads. We take this risk intentionally.
1136       // Getting stalled waiting for tty_lock while holding the CodeCache_lock is not desirable.
1137       printBox(ast, '-', "Global CodeHeap statistics for segment ", heapName);
1138       ast->print_cr("freeSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_free     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", freeSpace/(size_t)K,     nBlocks_free,     (100.0*freeSpace)/size,     (100.0*freeSpace)/res_size);
1139       ast->print_cr("usedSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_used     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", usedSpace/(size_t)K,     nBlocks_used,     (100.0*usedSpace)/size,     (100.0*usedSpace)/res_size);
1140       ast->print_cr("  Tier1 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t1       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t1Space/(size_t)K,       nBlocks_t1,       (100.0*t1Space)/size,       (100.0*t1Space)/res_size);
1141       ast->print_cr("  Tier2 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t2       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t2Space/(size_t)K,       nBlocks_t2,       (100.0*t2Space)/size,       (100.0*t2Space)/res_size);
1142       ast->print_cr("  Alive Space    = " SIZE_FORMAT_W(8) "k, nBlocks_alive    = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", aliveSpace/(size_t)K,    nBlocks_alive,    (100.0*aliveSpace)/size,    (100.0*aliveSpace)/res_size);
1143       ast->print_cr("    disconnected = " SIZE_FORMAT_W(8) "k, nBlocks_disconn  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", disconnSpace/(size_t)K,  nBlocks_disconn,  (100.0*disconnSpace)/size,  (100.0*disconnSpace)/res_size);
1144       ast->print_cr("    not entrant  = " SIZE_FORMAT_W(8) "k, nBlocks_notentr  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", notentrSpace/(size_t)K,  nBlocks_notentr,  (100.0*notentrSpace)/size,  (100.0*notentrSpace)/res_size);

1145       ast->print_cr("  unloadedSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_unloaded = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", unloadedSpace/(size_t)K, nBlocks_unloaded, (100.0*unloadedSpace)/size, (100.0*unloadedSpace)/res_size);
1146       ast->print_cr("  deadSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_dead     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", deadSpace/(size_t)K,     nBlocks_dead,     (100.0*deadSpace)/size,     (100.0*deadSpace)/res_size);
1147       ast->print_cr("  stubSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_stub     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", stubSpace/(size_t)K,     nBlocks_stub,     (100.0*stubSpace)/size,     (100.0*stubSpace)/res_size);
1148       ast->print_cr("ZombieBlocks     = %8d. These are HeapBlocks which could not be identified as CodeBlobs.", nBlocks_zomb);
1149       ast->cr();
1150       ast->print_cr("Segment start          = " INTPTR_FORMAT ", used space      = " SIZE_FORMAT_W(8)"k", p2i(low_bound), size/K);
1151       ast->print_cr("Segment end (used)     = " INTPTR_FORMAT ", remaining space = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + size, (res_size - size)/K);
1152       ast->print_cr("Segment end (reserved) = " INTPTR_FORMAT ", reserved space  = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + res_size, res_size/K);
1153       ast->cr();
1154       ast->print_cr("latest allocated compilation id = %d", latest_compilation_id);
1155       ast->print_cr("highest observed compilation id = %d", highest_compilation_id);
1156       ast->print_cr("Building TopSizeList iterations = %ld", total_iterations);
1157       ast->cr();
1158 
1159       int             reset_val = NMethodSweeper::hotness_counter_reset_val();
1160       double reverse_free_ratio = (res_size > size) ? (double)res_size/(double)(res_size-size) : (double)res_size;
1161       printBox(ast, '-', "Method hotness information at time of this analysis", NULL);
1162       ast->print_cr("Highest possible method temperature:          %12d", reset_val);
1163       ast->print_cr("Threshold for method to be considered 'cold': %12.3f", -reset_val + reverse_free_ratio * NmethodSweepActivity);
1164       if (n_methods > 0) {


1302       ast->print_cr("Free block count mismatch could not be resolved.");
1303       ast->print_cr("Try to run \"aggregate\" function to update counters");
1304     }
1305     BUFFEREDSTREAM_FLUSH("")
1306 
1307     //---< discard old array and update global values  >---
1308     discard_FreeArray(out);
1309     set_HeapStatGlobals(out, heapName);
1310     return;
1311   }
1312 
1313   //---<  calculate and fill remaining fields  >---
1314   if (FreeArray != NULL) {
1315     // This loop is intentionally printing directly to "out".
1316     // It should not print anything, anyway.
1317     for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1318       size_t lenSum = 0;
1319       FreeArray[ix].gap = (unsigned int)((address)FreeArray[ix+1].start - ((address)FreeArray[ix].start + FreeArray[ix].len));
1320       for (HeapBlock *h = heap->next_block(FreeArray[ix].start); (h != NULL) && (h != FreeArray[ix+1].start); h = heap->next_block(h)) {
1321         CodeBlob *cb  = (CodeBlob*)(heap->find_start(h));
1322         if ((cb != NULL) && !cb->is_nmethod()) { // checks equivalent to those in get_cbType()
1323           FreeArray[ix].stubs_in_gap = true;
1324         }
1325         FreeArray[ix].n_gapBlocks++;
1326         lenSum += h->length()<<log2_seg_size;
1327         if (((address)h < ((address)FreeArray[ix].start+FreeArray[ix].len)) || (h >= FreeArray[ix+1].start)) {
1328           out->print_cr("unsorted occupied CodeHeap block found @ %p, gap interval [%p, %p)", h, (address)FreeArray[ix].start+FreeArray[ix].len, FreeArray[ix+1].start);
1329         }
1330       }
1331       if (lenSum != FreeArray[ix].gap) {
1332         out->print_cr("Length mismatch for gap between FreeBlk[%d] and FreeBlk[%d]. Calculated: %d, accumulated: %d.", ix, ix+1, FreeArray[ix].gap, (unsigned int)lenSum);
1333       }
1334     }
1335   }
1336   set_HeapStatGlobals(out, heapName);
1337 
1338   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   C O M P L E T E   for segment ", heapName);
1339   BUFFEREDSTREAM_FLUSH("\n")
1340 }
1341 
1342 


1354   BUFFEREDSTREAM_DECL(ast, out)
1355 
1356   {
1357     printBox(ast, '=', "U S E D   S P A C E   S T A T I S T I C S   for ", heapName);
1358     ast->print_cr("Note: The Top%d list of the largest used blocks associates method names\n"
1359                   "      and other identifying information with the block size data.\n"
1360                   "\n"
1361                   "      Method names are dynamically retrieved from the code cache at print time.\n"
1362                   "      Due to the living nature of the code cache and because the CodeCache_lock\n"
1363                   "      is not continuously held, the displayed name might be wrong or no name\n"
1364                   "      might be found at all. The likelihood for that to happen increases\n"
1365                   "      over time passed between analysis and print step.\n", used_topSizeBlocks);
1366     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1367   }
1368 
1369   //----------------------------
1370   //--  Print Top Used Blocks --
1371   //----------------------------
1372   {
1373     char*     low_bound  = heap->low_boundary();

1374 
1375     printBox(ast, '-', "Largest Used Blocks in ", heapName);
1376     print_blobType_legend(ast);
1377 
1378     ast->fill_to(51);
1379     ast->print("%4s", "blob");
1380     ast->fill_to(56);
1381     ast->print("%9s", "compiler");
1382     ast->fill_to(66);
1383     ast->print_cr("%6s", "method");
1384     ast->print_cr("%18s %13s %17s %4s %9s  %5s %s",      "Addr(module)      ", "offset", "size", "type", " type lvl", " temp", "Name");
1385     BUFFEREDSTREAM_FLUSH_LOCKED("")
1386 
1387     //---<  print Top Ten Used Blocks  >---
1388     if (used_topSizeBlocks > 0) {
1389       unsigned int printed_topSizeBlocks = 0;
1390       for (unsigned int i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
1391         printed_topSizeBlocks++;
1392         if (TopSizeArray[i].blob_name == NULL) {
1393           TopSizeArray[i].blob_name = os::strdup("unnamed blob or blob name unavailable");
1394         }
1395         // heap->find_start() is safe. Only works on _segmap.
1396         // Returns NULL or void*. Returned CodeBlob may be uninitialized.
1397         HeapBlock* heapBlock = TopSizeArray[i].start;
1398         CodeBlob*  this_blob = (CodeBlob*)(heap->find_start(heapBlock));
1399         if (this_blob != NULL) {

1400           //---<  access these fields only if we own the CodeCache_lock  >---




1401           //---<  blob address  >---
1402           ast->print(INTPTR_FORMAT, p2i(this_blob));
1403           ast->fill_to(19);
1404           //---<  blob offset from CodeHeap begin  >---
1405           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
1406           ast->fill_to(33);
1407         } else {
1408           //---<  block address  >---
1409           ast->print(INTPTR_FORMAT, p2i(TopSizeArray[i].start));
1410           ast->fill_to(19);
1411           //---<  block offset from CodeHeap begin  >---
1412           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)TopSizeArray[i].start-low_bound));
1413           ast->fill_to(33);
1414         }
1415 
1416         //---<  print size, name, and signature (for nMethods)  >---
1417         bool is_nmethod = TopSizeArray[i].nm_size > 0;
1418         if (is_nmethod) {









1419           //---<  nMethod size in hex  >---
1420           ast->print(PTR32_FORMAT, TopSizeArray[i].nm_size);
1421           ast->print("(" SIZE_FORMAT_W(4) "K)", TopSizeArray[i].nm_size/K);

1422           ast->fill_to(51);
1423           ast->print("  %c", blobTypeChar[TopSizeArray[i].type]);
1424           //---<  compiler information  >---
1425           ast->fill_to(56);
1426           ast->print("%5s %3d", compTypeName[TopSizeArray[i].compiler], TopSizeArray[i].level);
1427           //---<  method temperature  >---
1428           ast->fill_to(67);
1429           ast->print("%5d", TopSizeArray[i].temperature);
1430           //---<  name and signature  >---
1431           ast->fill_to(67+6);
1432           if (TopSizeArray[i].type == nMethod_dead) {



1433             ast->print(" zombie method ");
1434           }
1435           ast->print("%s", TopSizeArray[i].blob_name);
1436         } else {
1437           //---<  block size in hex  >---
1438           ast->print(PTR32_FORMAT, (unsigned int)(TopSizeArray[i].len<<log2_seg_size));
1439           ast->print("(" SIZE_FORMAT_W(4) "K)", (TopSizeArray[i].len<<log2_seg_size)/K);
1440           //---<  no compiler information  >---
1441           ast->fill_to(56);
1442           //---<  name and signature  >---
1443           ast->fill_to(67+6);
1444           ast->print("%s", TopSizeArray[i].blob_name);
1445         }
1446         ast->cr();
1447         BUFFEREDSTREAM_FLUSH_AUTO("")
1448       }
1449       if (used_topSizeBlocks != printed_topSizeBlocks) {
1450         ast->print_cr("used blocks: %d, printed blocks: %d", used_topSizeBlocks, printed_topSizeBlocks);
1451         for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1452           ast->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1453           BUFFEREDSTREAM_FLUSH_AUTO("")
1454         }
1455       }
1456       BUFFEREDSTREAM_FLUSH("\n\n")
1457     }
1458   }
1459 
1460   //-----------------------------
1461   //--  Print Usage Histogram  --
1462   //-----------------------------
1463 
1464   if (SizeDistributionArray != NULL) {


2205 }
2206 
2207 
2208 void CodeHeapState::print_names(outputStream* out, CodeHeap* heap) {
2209   if (!initialization_complete) {
2210     return;
2211   }
2212 
2213   const char* heapName   = get_heapName(heap);
2214   get_HeapStatGlobals(out, heapName);
2215 
2216   if ((StatArray == NULL) || (alloc_granules == 0)) {
2217     return;
2218   }
2219   BUFFEREDSTREAM_DECL(ast, out)
2220 
2221   unsigned int granules_per_line   = 128;
2222   char*        low_bound           = heap->low_boundary();
2223   CodeBlob*    last_blob           = NULL;
2224   bool         name_in_addr_range  = true;
2225   bool         have_locks          = holding_required_locks();
2226 
2227   //---<  print at least 128K per block (i.e. between headers)  >---
2228   if (granules_per_line*granule_size < 128*K) {
2229     granules_per_line = (unsigned int)((128*K)/granule_size);
2230   }
2231 
2232   printBox(ast, '=', "M E T H O D   N A M E S   for ", heapName);
2233   ast->print_cr("  Method names are dynamically retrieved from the code cache at print time.\n"
2234                 "  Due to the living nature of the code heap and because the CodeCache_lock\n"
2235                 "  is not continuously held, the displayed name might be wrong or no name\n"
2236                 "  might be found at all. The likelihood for that to happen increases\n"
2237                 "  over time passed between aggregation and print steps.\n");
2238   BUFFEREDSTREAM_FLUSH_LOCKED("")
2239 
2240   for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2241     //---<  print a new blob on a new line  >---
2242     if (ix%granules_per_line == 0) {
2243       if (!name_in_addr_range) {
2244         ast->print_cr("No methods, blobs, or stubs found in this address range");
2245       }
2246       name_in_addr_range = false;
2247 
2248       size_t end_ix = (ix+granules_per_line <= alloc_granules) ? ix+granules_per_line : alloc_granules;
2249       ast->cr();
2250       ast->print_cr("--------------------------------------------------------------------");
2251       ast->print_cr("Address range [" INTPTR_FORMAT "," INTPTR_FORMAT "), " SIZE_FORMAT "k", p2i(low_bound+ix*granule_size), p2i(low_bound + end_ix*granule_size), (end_ix - ix)*granule_size/(size_t)K);
2252       ast->print_cr("--------------------------------------------------------------------");
2253       BUFFEREDSTREAM_FLUSH_AUTO("")
2254     }
2255     // Only check granule if it contains at least one blob.
2256     unsigned int nBlobs  = StatArray[ix].t1_count   + StatArray[ix].t2_count + StatArray[ix].tx_count +
2257                            StatArray[ix].stub_count + StatArray[ix].dead_count;
2258     if (nBlobs > 0 ) {
2259     for (unsigned int is = 0; is < granule_size; is+=(unsigned int)seg_size) {
2260       // heap->find_start() is safe. Only works on _segmap.
2261       // Returns NULL or void*. Returned CodeBlob may be uninitialized.
2262       char*     this_seg  = low_bound + ix*granule_size + is;
2263       CodeBlob* this_blob = (CodeBlob*)(heap->find_start(this_seg));
2264       bool   blob_is_safe = blob_access_is_safe(this_blob);
2265       // blob could have been flushed, freed, and merged.
2266       // this_blob < last_blob is an indicator for that.
2267       if (blob_is_safe && (this_blob > last_blob)) {
2268         last_blob          = this_blob;
2269 
2270         //---<  get type and name  >---
2271         blobType       cbType = noType;
2272         if (segment_granules) {
2273           cbType = (blobType)StatArray[ix].type;
2274         } else {
2275           //---<  access these fields only if we own the CodeCache_lock  >---
2276           if (have_locks) {
2277             cbType = get_cbType(this_blob);
2278           }
2279         }
2280 
2281         //---<  access these fields only if we own the CodeCache_lock  >---
2282         const char* blob_name = "<unavailable>";
2283         nmethod*           nm = NULL;
2284         if (have_locks) {
2285           blob_name = this_blob->name();
2286           nm        = this_blob->as_nmethod_or_null();
2287           // this_blob->name() could return NULL if no name was given to CTOR. Inlined, maybe invisible on stack
2288           if (blob_name == NULL) {
2289             blob_name = "<unavailable>";
2290           }
2291         }
2292 
2293         //---<  print table header for new print range  >---
2294         if (!name_in_addr_range) {
2295           name_in_addr_range = true;
2296           ast->fill_to(51);
2297           ast->print("%9s", "compiler");
2298           ast->fill_to(61);
2299           ast->print_cr("%6s", "method");
2300           ast->print_cr("%18s %13s %17s %9s  %5s %18s  %s", "Addr(module)      ", "offset", "size", " type lvl", " temp", "blobType          ", "Name");
2301           BUFFEREDSTREAM_FLUSH_AUTO("")
2302         }
2303 
2304         //---<  print line prefix (address and offset from CodeHeap start)  >---
2305         ast->print(INTPTR_FORMAT, p2i(this_blob));
2306         ast->fill_to(19);
2307         ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
2308         ast->fill_to(33);
2309 
2310         // access nmethod and Method fields only if we own the CodeCache_lock.
2311         // This fact is implicitly transported via nm != NULL.
2312         if (nmethod_access_is_safe(nm)) {
2313           Method* method = nm->method();
2314           ResourceMark rm;
2315           //---<  collect all data to locals as quickly as possible  >---
2316           unsigned int total_size = nm->total_size();
2317           int          hotness    = nm->hotness_counter();
2318           bool         get_name   = (cbType == nMethod_inuse) || (cbType == nMethod_notused);
2319           //---<  nMethod size in hex  >---
2320           ast->print(PTR32_FORMAT, total_size);
2321           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
2322           //---<  compiler information  >---
2323           ast->fill_to(51);
2324           ast->print("%5s %3d", compTypeName[StatArray[ix].compiler], StatArray[ix].level);
2325           //---<  method temperature  >---
2326           ast->fill_to(62);
2327           ast->print("%5d", hotness);
2328           //---<  name and signature  >---
2329           ast->fill_to(62+6);
2330           ast->print("%s", blobTypeName[cbType]);
2331           ast->fill_to(82+6);
2332           if (cbType == nMethod_dead) {


2498       ast->print("|");
2499     }
2500     ast->cr();
2501 
2502     // can't use BUFFEREDSTREAM_FLUSH_IF("", 512) here.
2503     // can't use this expression. bufferedStream::capacity() does not exist.
2504     // if ((ast->capacity() - ast->size()) < 512) {
2505     // Assume instead that default bufferedStream capacity (4K) was used.
2506     if (ast->size() > 3*K) {
2507       ttyLocker ttyl;
2508       out->print("%s", ast->as_string());
2509       ast->reset();
2510     }
2511 
2512     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2513     ast->fill_to(19);
2514     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2515   }
2516 }
2517 
2518 // Find out which blob type we have at hand.
2519 // Return "noType" if anything abnormal is detected.
2520 CodeHeapState::blobType CodeHeapState::get_cbType(CodeBlob* cb) {
2521   if (cb != NULL) {
2522     if (cb->is_runtime_stub())                return runtimeStub;
2523     if (cb->is_deoptimization_stub())         return deoptimizationStub;
2524     if (cb->is_uncommon_trap_stub())          return uncommonTrapStub;
2525     if (cb->is_exception_stub())              return exceptionStub;
2526     if (cb->is_safepoint_stub())              return safepointStub;
2527     if (cb->is_adapter_blob())                return adapterBlob;
2528     if (cb->is_method_handles_adapter_blob()) return mh_adapterBlob;
2529     if (cb->is_buffer_blob())                 return bufferBlob;
2530 
2531     //---<  access these fields only if we own CodeCache_lock and Compile_lock  >---
2532     // Should be ensured by caller. aggregate() and print_names() do that.
2533     if (holding_required_locks()) {
2534       nmethod*  nm = cb->as_nmethod_or_null();
2535       if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.

2536         if (nm->is_zombie())        return nMethod_dead;
2537         if (nm->is_unloaded())      return nMethod_unloaded;
2538         if (nm->is_in_use())        return nMethod_inuse;
2539         if (nm->is_alive() && !(nm->is_not_entrant()))   return nMethod_notused;
2540         if (nm->is_alive())         return nMethod_alive;
2541         return nMethod_dead;
2542       }
2543     }
2544   }
2545   return noType;
2546 }
2547 
2548 // make sure the blob at hand is not garbage.
2549 bool CodeHeapState::blob_access_is_safe(CodeBlob* this_blob) {
2550   return (this_blob != NULL) && // a blob must have been found, obviously

2551          (this_blob->header_size() >= 0) &&
2552          (this_blob->relocation_size() >= 0) &&
2553          ((address)this_blob + this_blob->header_size() == (address)(this_blob->relocation_begin())) &&
2554          ((address)this_blob + CodeBlob::align_code_offset(this_blob->header_size() + this_blob->relocation_size()) == (address)(this_blob->content_begin()));
2555 }
2556 
2557 // make sure the nmethod at hand (and the linked method) is not garbage.
2558 bool CodeHeapState::nmethod_access_is_safe(nmethod* nm) {
2559   Method* method = (nm == NULL) ? NULL : nm->method(); // nm->method() was found to be uninitialized, i.e. != NULL, but invalid.
2560   return (nm != NULL) && (method != NULL) && nm->is_alive() && (method->signature() != NULL);
2561 }
2562 
2563 bool CodeHeapState::holding_required_locks() {
2564   return SafepointSynchronize::is_at_safepoint() ||
2565         (CodeCache_lock->owned_by_self() && Compile_lock->owned_by_self());
2566 }
< prev index next >