1 /*
   2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2012, 2019, SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   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 "jvm.h"
  28 #include "asm/assembler.inline.hpp"
  29 #include "asm/macroAssembler.inline.hpp"
  30 #include "compiler/disassembler.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "runtime/java.hpp"
  33 #include "runtime/os.hpp"
  34 #include "runtime/stubCodeGenerator.hpp"
  35 #include "utilities/align.hpp"
  36 #include "utilities/defaultStream.hpp"
  37 #include "utilities/globalDefinitions.hpp"
  38 #include "vm_version_ppc.hpp"
  39 
  40 #include <sys/sysinfo.h>
  41 #if defined(_AIX)
  42 #include <libperfstat.h>
  43 #endif
  44 
  45 #if defined(LINUX) && defined(VM_LITTLE_ENDIAN)
  46 #include <sys/auxv.h>
  47 
  48 #ifndef PPC_FEATURE2_HTM_NOSC
  49 #define PPC_FEATURE2_HTM_NOSC (1 << 24)
  50 #endif
  51 #endif
  52 
  53 bool VM_Version::_is_determine_features_test_running = false;
  54 uint64_t VM_Version::_dscr_val = 0;
  55 
  56 #define MSG(flag)   \
  57   if (flag && !FLAG_IS_DEFAULT(flag))                                  \
  58       jio_fprintf(defaultStream::error_stream(),                       \
  59                   "warning: -XX:+" #flag " requires -XX:+UseSIGTRAP\n" \
  60                   "         -XX:+" #flag " will be disabled!\n");
  61 
  62 void VM_Version::initialize() {
  63 
  64   // Test which instructions are supported and measure cache line size.
  65   determine_features();
  66 
  67   // If PowerArchitecturePPC64 hasn't been specified explicitly determine from features.
  68   if (FLAG_IS_DEFAULT(PowerArchitecturePPC64)) {
  69     if (VM_Version::has_darn()) {
  70       FLAG_SET_ERGO(uintx, PowerArchitecturePPC64, 9);
  71     } else if (VM_Version::has_lqarx()) {
  72       FLAG_SET_ERGO(uintx, PowerArchitecturePPC64, 8);
  73     } else if (VM_Version::has_popcntw()) {
  74       FLAG_SET_ERGO(uintx, PowerArchitecturePPC64, 7);
  75     } else if (VM_Version::has_cmpb()) {
  76       FLAG_SET_ERGO(uintx, PowerArchitecturePPC64, 6);
  77     } else if (VM_Version::has_popcntb()) {
  78       FLAG_SET_ERGO(uintx, PowerArchitecturePPC64, 5);
  79     } else {
  80       FLAG_SET_ERGO(uintx, PowerArchitecturePPC64, 0);
  81     }
  82   }
  83 
  84   bool PowerArchitecturePPC64_ok = false;
  85   switch (PowerArchitecturePPC64) {
  86     case 9: if (!VM_Version::has_darn()   ) break;
  87     case 8: if (!VM_Version::has_lqarx()  ) break;
  88     case 7: if (!VM_Version::has_popcntw()) break;
  89     case 6: if (!VM_Version::has_cmpb()   ) break;
  90     case 5: if (!VM_Version::has_popcntb()) break;
  91     case 0: PowerArchitecturePPC64_ok = true; break;
  92     default: break;
  93   }
  94   guarantee(PowerArchitecturePPC64_ok, "PowerArchitecturePPC64 cannot be set to "
  95             UINTX_FORMAT " on this machine", PowerArchitecturePPC64);
  96 
  97   // Power 8: Configure Data Stream Control Register.
  98   if (PowerArchitecturePPC64 >= 8 && has_mfdscr()) {
  99     config_dscr();
 100   }
 101 
 102   if (!UseSIGTRAP) {
 103     MSG(TrapBasedICMissChecks);
 104     MSG(TrapBasedNotEntrantChecks);
 105     MSG(TrapBasedNullChecks);
 106     FLAG_SET_ERGO(bool, TrapBasedNotEntrantChecks, false);
 107     FLAG_SET_ERGO(bool, TrapBasedNullChecks,       false);
 108     FLAG_SET_ERGO(bool, TrapBasedICMissChecks,     false);
 109   }
 110 
 111 #ifdef COMPILER2
 112   if (!UseSIGTRAP) {
 113     MSG(TrapBasedRangeChecks);
 114     FLAG_SET_ERGO(bool, TrapBasedRangeChecks, false);
 115   }
 116 
 117   // On Power6 test for section size.
 118   if (PowerArchitecturePPC64 == 6) {
 119     determine_section_size();
 120   // TODO: PPC port } else {
 121   // TODO: PPC port PdScheduling::power6SectorSize = 0x20;
 122   }
 123 
 124   if (PowerArchitecturePPC64 >= 8) {
 125     if (FLAG_IS_DEFAULT(SuperwordUseVSX)) {
 126       FLAG_SET_ERGO(bool, SuperwordUseVSX, true);
 127     }
 128   } else {
 129     if (SuperwordUseVSX) {
 130       warning("SuperwordUseVSX specified, but needs at least Power8.");
 131       FLAG_SET_DEFAULT(SuperwordUseVSX, false);
 132     }
 133   }
 134   MaxVectorSize = SuperwordUseVSX ? 16 : 8;
 135 
 136   if (PowerArchitecturePPC64 >= 9) {
 137     if (FLAG_IS_DEFAULT(UseCountTrailingZerosInstructionsPPC64)) {
 138       FLAG_SET_ERGO(bool, UseCountTrailingZerosInstructionsPPC64, true);
 139     }
 140     if (FLAG_IS_DEFAULT(UseCharacterCompareIntrinsics)) {
 141       FLAG_SET_ERGO(bool, UseCharacterCompareIntrinsics, true);
 142     }
 143   } else {
 144     if (UseCountTrailingZerosInstructionsPPC64) {
 145       warning("UseCountTrailingZerosInstructionsPPC64 specified, but needs at least Power9.");
 146       FLAG_SET_DEFAULT(UseCountTrailingZerosInstructionsPPC64, false);
 147     }
 148     if (UseCharacterCompareIntrinsics) {
 149       warning("UseCharacterCompareIntrinsics specified, but needs at least Power9.");
 150       FLAG_SET_DEFAULT(UseCharacterCompareIntrinsics, false);
 151     }
 152   }
 153 #endif
 154 
 155   // Create and print feature-string.
 156   char buf[(num_features+1) * 16]; // Max 16 chars per feature.
 157   jio_snprintf(buf, sizeof(buf),
 158                "ppc64%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
 159                (has_fsqrt()   ? " fsqrt"   : ""),
 160                (has_isel()    ? " isel"    : ""),
 161                (has_lxarxeh() ? " lxarxeh" : ""),
 162                (has_cmpb()    ? " cmpb"    : ""),
 163                (has_popcntb() ? " popcntb" : ""),
 164                (has_popcntw() ? " popcntw" : ""),
 165                (has_fcfids()  ? " fcfids"  : ""),
 166                (has_vand()    ? " vand"    : ""),
 167                (has_lqarx()   ? " lqarx"   : ""),
 168                (has_vcipher() ? " aes"     : ""),
 169                (has_vpmsumb() ? " vpmsumb" : ""),
 170                (has_mfdscr()  ? " mfdscr"  : ""),
 171                (has_vsx()     ? " vsx"     : ""),
 172                (has_ldbrx()   ? " ldbrx"   : ""),
 173                (has_stdbrx()  ? " stdbrx"  : ""),
 174                (has_vshasig() ? " sha"     : ""),
 175                (has_tm()      ? " rtm"     : ""),
 176                (has_darn()    ? " darn"    : "")
 177                // Make sure number of %s matches num_features!
 178               );
 179   _features_string = os::strdup(buf);
 180   if (Verbose) {
 181     print_features();
 182   }
 183 
 184   // PPC64 supports 8-byte compare-exchange operations (see Atomic::cmpxchg)
 185   // and 'atomic long memory ops' (see Unsafe_GetLongVolatile).
 186   _supports_cx8 = true;
 187 
 188   // Used by C1.
 189   _supports_atomic_getset4 = true;
 190   _supports_atomic_getadd4 = true;
 191   _supports_atomic_getset8 = true;
 192   _supports_atomic_getadd8 = true;
 193 
 194   UseSSE = 0; // Only on x86 and x64
 195 
 196   intx cache_line_size = L1_data_cache_line_size();
 197 
 198   if (FLAG_IS_DEFAULT(AllocatePrefetchStyle)) AllocatePrefetchStyle = 1;
 199 
 200   if (AllocatePrefetchStyle == 4) {
 201     AllocatePrefetchStepSize = cache_line_size; // Need exact value.
 202     if (FLAG_IS_DEFAULT(AllocatePrefetchLines)) AllocatePrefetchLines = 12; // Use larger blocks by default.
 203     if (AllocatePrefetchDistance < 0) AllocatePrefetchDistance = 2*cache_line_size; // Default is not defined?
 204   } else {
 205     if (cache_line_size > AllocatePrefetchStepSize) AllocatePrefetchStepSize = cache_line_size;
 206     if (FLAG_IS_DEFAULT(AllocatePrefetchLines)) AllocatePrefetchLines = 3; // Optimistic value.
 207     if (AllocatePrefetchDistance < 0) AllocatePrefetchDistance = 3*cache_line_size; // Default is not defined?
 208   }
 209 
 210   assert(AllocatePrefetchLines > 0, "invalid value");
 211   if (AllocatePrefetchLines < 1) { // Set valid value in product VM.
 212     AllocatePrefetchLines = 1; // Conservative value.
 213   }
 214 
 215   if (AllocatePrefetchStyle == 3 && AllocatePrefetchDistance < cache_line_size) {
 216     AllocatePrefetchStyle = 1; // Fall back if inappropriate.
 217   }
 218 
 219   assert(AllocatePrefetchStyle >= 0, "AllocatePrefetchStyle should be positive");
 220 
 221   // If running on Power8 or newer hardware, the implementation uses the available vector instructions.
 222   // In all other cases, the implementation uses only generally available instructions.
 223   if (!UseCRC32Intrinsics) {
 224     if (FLAG_IS_DEFAULT(UseCRC32Intrinsics)) {
 225       FLAG_SET_DEFAULT(UseCRC32Intrinsics, true);
 226     }
 227   }
 228 
 229   // Implementation does not use any of the vector instructions available with Power8.
 230   // Their exploitation is still pending (aka "work in progress").
 231   if (!UseCRC32CIntrinsics) {
 232     if (FLAG_IS_DEFAULT(UseCRC32CIntrinsics)) {
 233       FLAG_SET_DEFAULT(UseCRC32CIntrinsics, true);
 234     }
 235   }
 236 
 237   // TODO: Provide implementation.
 238   if (UseAdler32Intrinsics) {
 239     warning("Adler32Intrinsics not available on this CPU.");
 240     FLAG_SET_DEFAULT(UseAdler32Intrinsics, false);
 241   }
 242 
 243   // The AES intrinsic stubs require AES instruction support.
 244   if (has_vcipher()) {
 245     if (FLAG_IS_DEFAULT(UseAES)) {
 246       UseAES = true;
 247     }
 248   } else if (UseAES) {
 249     if (!FLAG_IS_DEFAULT(UseAES))
 250       warning("AES instructions are not available on this CPU");
 251     FLAG_SET_DEFAULT(UseAES, false);
 252   }
 253 
 254   if (UseAES && has_vcipher()) {
 255     if (FLAG_IS_DEFAULT(UseAESIntrinsics)) {
 256       UseAESIntrinsics = true;
 257     }
 258   } else if (UseAESIntrinsics) {
 259     if (!FLAG_IS_DEFAULT(UseAESIntrinsics))
 260       warning("AES intrinsics are not available on this CPU");
 261     FLAG_SET_DEFAULT(UseAESIntrinsics, false);
 262   }
 263 
 264   if (UseAESCTRIntrinsics) {
 265     warning("AES/CTR intrinsics are not available on this CPU");
 266     FLAG_SET_DEFAULT(UseAESCTRIntrinsics, false);
 267   }
 268 
 269   if (UseGHASHIntrinsics) {
 270     warning("GHASH intrinsics are not available on this CPU");
 271     FLAG_SET_DEFAULT(UseGHASHIntrinsics, false);
 272   }
 273 
 274   if (FLAG_IS_DEFAULT(UseFMA)) {
 275     FLAG_SET_DEFAULT(UseFMA, true);
 276   }
 277 
 278   if (has_vshasig()) {
 279     if (FLAG_IS_DEFAULT(UseSHA)) {
 280       UseSHA = true;
 281     }
 282   } else if (UseSHA) {
 283     if (!FLAG_IS_DEFAULT(UseSHA))
 284       warning("SHA instructions are not available on this CPU");
 285     FLAG_SET_DEFAULT(UseSHA, false);
 286   }
 287 
 288   if (UseSHA1Intrinsics) {
 289     warning("Intrinsics for SHA-1 crypto hash functions not available on this CPU.");
 290     FLAG_SET_DEFAULT(UseSHA1Intrinsics, false);
 291   }
 292 
 293   if (UseSHA && has_vshasig()) {
 294     if (FLAG_IS_DEFAULT(UseSHA256Intrinsics)) {
 295       FLAG_SET_DEFAULT(UseSHA256Intrinsics, true);
 296     }
 297   } else if (UseSHA256Intrinsics) {
 298     warning("Intrinsics for SHA-224 and SHA-256 crypto hash functions not available on this CPU.");
 299     FLAG_SET_DEFAULT(UseSHA256Intrinsics, false);
 300   }
 301 
 302   if (UseSHA && has_vshasig()) {
 303     if (FLAG_IS_DEFAULT(UseSHA512Intrinsics)) {
 304       FLAG_SET_DEFAULT(UseSHA512Intrinsics, true);
 305     }
 306   } else if (UseSHA512Intrinsics) {
 307     warning("Intrinsics for SHA-384 and SHA-512 crypto hash functions not available on this CPU.");
 308     FLAG_SET_DEFAULT(UseSHA512Intrinsics, false);
 309   }
 310 
 311   if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) {
 312     FLAG_SET_DEFAULT(UseSHA, false);
 313   }
 314 
 315   if (FLAG_IS_DEFAULT(UseSquareToLenIntrinsic)) {
 316     UseSquareToLenIntrinsic = true;
 317   }
 318   if (FLAG_IS_DEFAULT(UseMulAddIntrinsic)) {
 319     UseMulAddIntrinsic = true;
 320   }
 321   if (FLAG_IS_DEFAULT(UseMultiplyToLenIntrinsic)) {
 322     UseMultiplyToLenIntrinsic = true;
 323   }
 324   if (FLAG_IS_DEFAULT(UseMontgomeryMultiplyIntrinsic)) {
 325     UseMontgomeryMultiplyIntrinsic = true;
 326   }
 327   if (FLAG_IS_DEFAULT(UseMontgomerySquareIntrinsic)) {
 328     UseMontgomerySquareIntrinsic = true;
 329   }
 330 
 331   if (UseVectorizedMismatchIntrinsic) {
 332     warning("UseVectorizedMismatchIntrinsic specified, but not available on this CPU.");
 333     FLAG_SET_DEFAULT(UseVectorizedMismatchIntrinsic, false);
 334   }
 335 
 336 
 337   // Adjust RTM (Restricted Transactional Memory) flags.
 338   if (UseRTMLocking) {
 339     // If CPU or OS do not support TM:
 340     // Can't continue because UseRTMLocking affects UseBiasedLocking flag
 341     // setting during arguments processing. See use_biased_locking().
 342     // VM_Version_init() is executed after UseBiasedLocking is used
 343     // in Thread::allocate().
 344     if (PowerArchitecturePPC64 < 8) {
 345       vm_exit_during_initialization("RTM instructions are not available on this CPU.");
 346     }
 347 
 348     if (!has_tm()) {
 349       vm_exit_during_initialization("RTM is not supported on this OS version.");
 350     }
 351   }
 352 
 353   if (UseRTMLocking) {
 354 #if INCLUDE_RTM_OPT
 355     if (!FLAG_IS_CMDLINE(UseRTMLocking)) {
 356       // RTM locking should be used only for applications with
 357       // high lock contention. For now we do not use it by default.
 358       vm_exit_during_initialization("UseRTMLocking flag should be only set on command line");
 359     }
 360 #else
 361     // Only C2 does RTM locking optimization.
 362     // Can't continue because UseRTMLocking affects UseBiasedLocking flag
 363     // setting during arguments processing. See use_biased_locking().
 364     vm_exit_during_initialization("RTM locking optimization is not supported in this VM");
 365 #endif
 366   } else { // !UseRTMLocking
 367     if (UseRTMForStackLocks) {
 368       if (!FLAG_IS_DEFAULT(UseRTMForStackLocks)) {
 369         warning("UseRTMForStackLocks flag should be off when UseRTMLocking flag is off");
 370       }
 371       FLAG_SET_DEFAULT(UseRTMForStackLocks, false);
 372     }
 373     if (UseRTMDeopt) {
 374       FLAG_SET_DEFAULT(UseRTMDeopt, false);
 375     }
 376     if (PrintPreciseRTMLockingStatistics) {
 377       FLAG_SET_DEFAULT(PrintPreciseRTMLockingStatistics, false);
 378     }
 379   }
 380 
 381   // This machine allows unaligned memory accesses
 382   if (FLAG_IS_DEFAULT(UseUnalignedAccesses)) {
 383     FLAG_SET_DEFAULT(UseUnalignedAccesses, true);
 384   }
 385 }
 386 
 387 void VM_Version::print_platform_virtualization_info(outputStream* st) {
 388 #if defined(_AIX)
 389   // more info about perfstat API see
 390   // https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/com.ibm.aix.prftools/idprftools_perfstat_glob_partition.htm
 391   int rc = 0;
 392   perfstat_partition_total_t pinfo;
 393   memset(&pinfo, 0, sizeof(perfstat_partition_total_t));
 394   rc = perfstat_partition_total(NULL, &pinfo, sizeof(perfstat_partition_total_t), 1);
 395   if (rc != 1) {
 396     return;
 397   } else {
 398     st->print_cr("Virtualization type   : PowerVM");
 399   }
 400   // CPU information
 401   perfstat_cpu_total_t cpuinfo;
 402   memset(&cpuinfo, 0, sizeof(perfstat_cpu_total_t));
 403   rc = perfstat_cpu_total(NULL, &cpuinfo, sizeof(perfstat_cpu_total_t), 1);
 404   if (rc != 1) {
 405     return;
 406   }
 407 
 408   st->print_cr("Processor description : %s", cpuinfo.description);
 409   st->print_cr("Processor speed       : %llu Hz", cpuinfo.processorHZ);
 410 
 411   st->print_cr("LPAR partition name           : %s", pinfo.name);
 412   st->print_cr("LPAR partition number         : %u", pinfo.lpar_id);
 413   st->print_cr("LPAR partition type           : %s", pinfo.type.b.shared_enabled ? "shared" : "dedicated");
 414   st->print_cr("LPAR mode                     : %s", pinfo.type.b.donate_enabled ? "donating" : pinfo.type.b.capped ? "capped" : "uncapped");
 415   st->print_cr("LPAR partition group ID       : %u", pinfo.group_id);
 416   st->print_cr("LPAR shared pool ID           : %u", pinfo.pool_id);
 417 
 418   st->print_cr("AMS (active memory sharing)   : %s", pinfo.type.b.ams_capable ? "capable" : "not capable");
 419   st->print_cr("AMS (active memory sharing)   : %s", pinfo.type.b.ams_enabled ? "on" : "off");
 420   st->print_cr("AME (active memory expansion) : %s", pinfo.type.b.ame_enabled ? "on" : "off");
 421 
 422   if (pinfo.type.b.ame_enabled) {
 423     st->print_cr("AME true memory in bytes      : %llu", pinfo.true_memory);
 424     st->print_cr("AME expanded memory in bytes  : %llu", pinfo.expanded_memory);
 425   }
 426 
 427   st->print_cr("SMT : %s", pinfo.type.b.smt_capable ? "capable" : "not capable");
 428   st->print_cr("SMT : %s", pinfo.type.b.smt_enabled ? "on" : "off");
 429   int ocpus = pinfo.online_cpus > 0 ?  pinfo.online_cpus : 1;
 430   st->print_cr("LPAR threads              : %d", cpuinfo.ncpus/ocpus);
 431   st->print_cr("LPAR online virtual cpus  : %d", pinfo.online_cpus);
 432   st->print_cr("LPAR logical cpus         : %d", cpuinfo.ncpus);
 433   st->print_cr("LPAR maximum virtual cpus : %u", pinfo.max_cpus);
 434   st->print_cr("LPAR minimum virtual cpus : %u", pinfo.min_cpus);
 435   st->print_cr("LPAR entitled capacity    : %4.2f", (double) (pinfo.entitled_proc_capacity/100.0));
 436   st->print_cr("LPAR online memory        : %llu MB", pinfo.online_memory);
 437   st->print_cr("LPAR maximum memory       : %llu MB", pinfo.max_memory);
 438   st->print_cr("LPAR minimum memory       : %llu MB", pinfo.min_memory);
 439 #else
 440   const char* info_file = "/proc/ppc64/lparcfg";
 441   const char* kw[] = { "system_type=", // qemu indicates PowerKVM
 442                        "partition_entitled_capacity=", // entitled processor capacity percentage
 443                        "partition_max_entitled_capacity=",
 444                        "capacity_weight=", // partition CPU weight
 445                        "partition_active_processors=",
 446                        "partition_potential_processors=",
 447                        "entitled_proc_capacity_available=",
 448                        "capped=", // 0 - uncapped, 1 - vcpus capped at entitled processor capacity percentage
 449                        "shared_processor_mode=", // (non)dedicated partition
 450                        "system_potential_processors=",
 451                        "pool=", // CPU-pool number
 452                        "pool_capacity=",
 453                        "NumLpars=", // on non-KVM machines, NumLpars is not found for full partition mode machines
 454                        NULL };
 455   if (!print_matching_lines_from_file(info_file, st, kw)) {
 456     st->print_cr("  <%s Not Available>", info_file);
 457   }
 458 #endif
 459 }
 460 
 461 bool VM_Version::use_biased_locking() {
 462 #if INCLUDE_RTM_OPT
 463   // RTM locking is most useful when there is high lock contention and
 464   // low data contention. With high lock contention the lock is usually
 465   // inflated and biased locking is not suitable for that case.
 466   // RTM locking code requires that biased locking is off.
 467   // Note: we can't switch off UseBiasedLocking in get_processor_features()
 468   // because it is used by Thread::allocate() which is called before
 469   // VM_Version::initialize().
 470   if (UseRTMLocking && UseBiasedLocking) {
 471     if (FLAG_IS_DEFAULT(UseBiasedLocking)) {
 472       FLAG_SET_DEFAULT(UseBiasedLocking, false);
 473     } else {
 474       warning("Biased locking is not supported with RTM locking; ignoring UseBiasedLocking flag." );
 475       UseBiasedLocking = false;
 476     }
 477   }
 478 #endif
 479   return UseBiasedLocking;
 480 }
 481 
 482 void VM_Version::print_features() {
 483   tty->print_cr("Version: %s L1_data_cache_line_size=%d", features_string(), L1_data_cache_line_size());
 484 }
 485 
 486 #ifdef COMPILER2
 487 // Determine section size on power6: If section size is 8 instructions,
 488 // there should be a difference between the two testloops of ~15 %. If
 489 // no difference is detected the section is assumed to be 32 instructions.
 490 void VM_Version::determine_section_size() {
 491 
 492   int unroll = 80;
 493 
 494   const int code_size = (2* unroll * 32 + 100)*BytesPerInstWord;
 495 
 496   // Allocate space for the code.
 497   ResourceMark rm;
 498   CodeBuffer cb("detect_section_size", code_size, 0);
 499   MacroAssembler* a = new MacroAssembler(&cb);
 500 
 501   uint32_t *code = (uint32_t *)a->pc();
 502   // Emit code.
 503   void (*test1)() = (void(*)())(void *)a->function_entry();
 504 
 505   Label l1;
 506 
 507   a->li(R4, 1);
 508   a->sldi(R4, R4, 28);
 509   a->b(l1);
 510   a->align(CodeEntryAlignment);
 511 
 512   a->bind(l1);
 513 
 514   for (int i = 0; i < unroll; i++) {
 515     // Schleife 1
 516     // ------- sector 0 ------------
 517     // ;; 0
 518     a->nop();                   // 1
 519     a->fpnop0();                // 2
 520     a->fpnop1();                // 3
 521     a->addi(R4,R4, -1); // 4
 522 
 523     // ;;  1
 524     a->nop();                   // 5
 525     a->fmr(F6, F6);             // 6
 526     a->fmr(F7, F7);             // 7
 527     a->endgroup();              // 8
 528     // ------- sector 8 ------------
 529 
 530     // ;;  2
 531     a->nop();                   // 9
 532     a->nop();                   // 10
 533     a->fmr(F8, F8);             // 11
 534     a->fmr(F9, F9);             // 12
 535 
 536     // ;;  3
 537     a->nop();                   // 13
 538     a->fmr(F10, F10);           // 14
 539     a->fmr(F11, F11);           // 15
 540     a->endgroup();              // 16
 541     // -------- sector 16 -------------
 542 
 543     // ;;  4
 544     a->nop();                   // 17
 545     a->nop();                   // 18
 546     a->fmr(F15, F15);           // 19
 547     a->fmr(F16, F16);           // 20
 548 
 549     // ;;  5
 550     a->nop();                   // 21
 551     a->fmr(F17, F17);           // 22
 552     a->fmr(F18, F18);           // 23
 553     a->endgroup();              // 24
 554     // ------- sector 24  ------------
 555 
 556     // ;;  6
 557     a->nop();                   // 25
 558     a->nop();                   // 26
 559     a->fmr(F19, F19);           // 27
 560     a->fmr(F20, F20);           // 28
 561 
 562     // ;;  7
 563     a->nop();                   // 29
 564     a->fmr(F21, F21);           // 30
 565     a->fmr(F22, F22);           // 31
 566     a->brnop0();                // 32
 567 
 568     // ------- sector 32 ------------
 569   }
 570 
 571   // ;; 8
 572   a->cmpdi(CCR0, R4, unroll);   // 33
 573   a->bge(CCR0, l1);             // 34
 574   a->blr();
 575 
 576   // Emit code.
 577   void (*test2)() = (void(*)())(void *)a->function_entry();
 578   // uint32_t *code = (uint32_t *)a->pc();
 579 
 580   Label l2;
 581 
 582   a->li(R4, 1);
 583   a->sldi(R4, R4, 28);
 584   a->b(l2);
 585   a->align(CodeEntryAlignment);
 586 
 587   a->bind(l2);
 588 
 589   for (int i = 0; i < unroll; i++) {
 590     // Schleife 2
 591     // ------- sector 0 ------------
 592     // ;; 0
 593     a->brnop0();                  // 1
 594     a->nop();                     // 2
 595     //a->cmpdi(CCR0, R4, unroll);
 596     a->fpnop0();                  // 3
 597     a->fpnop1();                  // 4
 598     a->addi(R4,R4, -1);           // 5
 599 
 600     // ;; 1
 601 
 602     a->nop();                     // 6
 603     a->fmr(F6, F6);               // 7
 604     a->fmr(F7, F7);               // 8
 605     // ------- sector 8 ---------------
 606 
 607     // ;; 2
 608     a->endgroup();                // 9
 609 
 610     // ;; 3
 611     a->nop();                     // 10
 612     a->nop();                     // 11
 613     a->fmr(F8, F8);               // 12
 614 
 615     // ;; 4
 616     a->fmr(F9, F9);               // 13
 617     a->nop();                     // 14
 618     a->fmr(F10, F10);             // 15
 619 
 620     // ;; 5
 621     a->fmr(F11, F11);             // 16
 622     // -------- sector 16 -------------
 623 
 624     // ;; 6
 625     a->endgroup();                // 17
 626 
 627     // ;; 7
 628     a->nop();                     // 18
 629     a->nop();                     // 19
 630     a->fmr(F15, F15);             // 20
 631 
 632     // ;; 8
 633     a->fmr(F16, F16);             // 21
 634     a->nop();                     // 22
 635     a->fmr(F17, F17);             // 23
 636 
 637     // ;; 9
 638     a->fmr(F18, F18);             // 24
 639     // -------- sector 24 -------------
 640 
 641     // ;; 10
 642     a->endgroup();                // 25
 643 
 644     // ;; 11
 645     a->nop();                     // 26
 646     a->nop();                     // 27
 647     a->fmr(F19, F19);             // 28
 648 
 649     // ;; 12
 650     a->fmr(F20, F20);             // 29
 651     a->nop();                     // 30
 652     a->fmr(F21, F21);             // 31
 653 
 654     // ;; 13
 655     a->fmr(F22, F22);             // 32
 656   }
 657 
 658   // -------- sector 32 -------------
 659   // ;; 14
 660   a->cmpdi(CCR0, R4, unroll); // 33
 661   a->bge(CCR0, l2);           // 34
 662 
 663   a->blr();
 664   uint32_t *code_end = (uint32_t *)a->pc();
 665   a->flush();
 666 
 667   cb.insts()->set_end((u_char*)code_end);
 668 
 669   double loop1_seconds,loop2_seconds, rel_diff;
 670   uint64_t start1, stop1;
 671 
 672   start1 = os::current_thread_cpu_time(false);
 673   (*test1)();
 674   stop1 = os::current_thread_cpu_time(false);
 675   loop1_seconds = (stop1- start1) / (1000 *1000 *1000.0);
 676 
 677 
 678   start1 = os::current_thread_cpu_time(false);
 679   (*test2)();
 680   stop1 = os::current_thread_cpu_time(false);
 681 
 682   loop2_seconds = (stop1 - start1) / (1000 *1000 *1000.0);
 683 
 684   rel_diff = (loop2_seconds - loop1_seconds) / loop1_seconds *100;
 685 
 686   if (PrintAssembly || PrintStubCode) {
 687     ttyLocker ttyl;
 688     tty->print_cr("Decoding section size detection stub at " INTPTR_FORMAT " before execution:", p2i(code));
 689     // Use existing decode function. This enables the [MachCode] format which is needed to DecodeErrorFile.
 690     Disassembler::decode(&cb, (u_char*)code, (u_char*)code_end, tty);
 691     tty->print_cr("Time loop1 :%f", loop1_seconds);
 692     tty->print_cr("Time loop2 :%f", loop2_seconds);
 693     tty->print_cr("(time2 - time1) / time1 = %f %%", rel_diff);
 694 
 695     if (rel_diff > 12.0) {
 696       tty->print_cr("Section Size 8 Instructions");
 697     } else{
 698       tty->print_cr("Section Size 32 Instructions or Power5");
 699     }
 700   }
 701 
 702 #if 0 // TODO: PPC port
 703   // Set sector size (if not set explicitly).
 704   if (FLAG_IS_DEFAULT(Power6SectorSize128PPC64)) {
 705     if (rel_diff > 12.0) {
 706       PdScheduling::power6SectorSize = 0x20;
 707     } else {
 708       PdScheduling::power6SectorSize = 0x80;
 709     }
 710   } else if (Power6SectorSize128PPC64) {
 711     PdScheduling::power6SectorSize = 0x80;
 712   } else {
 713     PdScheduling::power6SectorSize = 0x20;
 714   }
 715 #endif
 716   if (UsePower6SchedulerPPC64) Unimplemented();
 717 }
 718 #endif // COMPILER2
 719 
 720 void VM_Version::determine_features() {
 721 #if defined(ABI_ELFv2)
 722   // 1 InstWord per call for the blr instruction.
 723   const int code_size = (num_features+1+2*1)*BytesPerInstWord;
 724 #else
 725   // 7 InstWords for each call (function descriptor + blr instruction).
 726   const int code_size = (num_features+1+2*7)*BytesPerInstWord;
 727 #endif
 728   int features = 0;
 729 
 730   // create test area
 731   enum { BUFFER_SIZE = 2*4*K }; // Needs to be >=2* max cache line size (cache line size can't exceed min page size).
 732   char test_area[BUFFER_SIZE];
 733   char *mid_of_test_area = &test_area[BUFFER_SIZE>>1];
 734 
 735   // Allocate space for the code.
 736   ResourceMark rm;
 737   CodeBuffer cb("detect_cpu_features", code_size, 0);
 738   MacroAssembler* a = new MacroAssembler(&cb);
 739 
 740   // Must be set to true so we can generate the test code.
 741   _features = VM_Version::all_features_m;
 742 
 743   // Emit code.
 744   void (*test)(address addr, uint64_t offset)=(void(*)(address addr, uint64_t offset))(void *)a->function_entry();
 745   uint32_t *code = (uint32_t *)a->pc();
 746   // Don't use R0 in ldarx.
 747   // Keep R3_ARG1 unmodified, it contains &field (see below).
 748   // Keep R4_ARG2 unmodified, it contains offset = 0 (see below).
 749   a->fsqrt(F3, F4);                            // code[0]  -> fsqrt_m
 750   a->fsqrts(F3, F4);                           // code[1]  -> fsqrts_m
 751   a->isel(R7, R5, R6, 0);                      // code[2]  -> isel_m
 752   a->ldarx_unchecked(R7, R3_ARG1, R4_ARG2, 1); // code[3]  -> lxarx_m
 753   a->cmpb(R7, R5, R6);                         // code[4]  -> cmpb
 754   a->popcntb(R7, R5);                          // code[5]  -> popcntb
 755   a->popcntw(R7, R5);                          // code[6]  -> popcntw
 756   a->fcfids(F3, F4);                           // code[7]  -> fcfids
 757   a->vand(VR0, VR0, VR0);                      // code[8]  -> vand
 758   // arg0 of lqarx must be an even register, (arg1 + arg2) must be a multiple of 16
 759   a->lqarx_unchecked(R6, R3_ARG1, R4_ARG2, 1); // code[9]  -> lqarx_m
 760   a->vcipher(VR0, VR1, VR2);                   // code[10] -> vcipher
 761   a->vpmsumb(VR0, VR1, VR2);                   // code[11] -> vpmsumb
 762   a->mfdscr(R0);                               // code[12] -> mfdscr
 763   a->lxvd2x(VSR0, R3_ARG1);                    // code[13] -> vsx
 764   a->ldbrx(R7, R3_ARG1, R4_ARG2);              // code[14] -> ldbrx
 765   a->stdbrx(R7, R3_ARG1, R4_ARG2);             // code[15] -> stdbrx
 766   a->vshasigmaw(VR0, VR1, 1, 0xF);             // code[16] -> vshasig
 767   // rtm is determined by OS
 768   a->darn(R7);                                 // code[17] -> darn
 769   a->blr();
 770 
 771   // Emit function to set one cache line to zero. Emit function descriptor and get pointer to it.
 772   void (*zero_cacheline_func_ptr)(char*) = (void(*)(char*))(void *)a->function_entry();
 773   a->dcbz(R3_ARG1); // R3_ARG1 = addr
 774   a->blr();
 775 
 776   uint32_t *code_end = (uint32_t *)a->pc();
 777   a->flush();
 778   _features = VM_Version::unknown_m;
 779 
 780   // Print the detection code.
 781   if (PrintAssembly) {
 782     ttyLocker ttyl;
 783     tty->print_cr("Decoding cpu-feature detection stub at " INTPTR_FORMAT " before execution:", p2i(code));
 784     Disassembler::decode((u_char*)code, (u_char*)code_end, tty);
 785   }
 786 
 787   // Measure cache line size.
 788   memset(test_area, 0xFF, BUFFER_SIZE); // Fill test area with 0xFF.
 789   (*zero_cacheline_func_ptr)(mid_of_test_area); // Call function which executes dcbz to the middle.
 790   int count = 0; // count zeroed bytes
 791   for (int i = 0; i < BUFFER_SIZE; i++) if (test_area[i] == 0) count++;
 792   guarantee(is_power_of_2(count), "cache line size needs to be a power of 2");
 793   _L1_data_cache_line_size = count;
 794 
 795   // Execute code. Illegal instructions will be replaced by 0 in the signal handler.
 796   VM_Version::_is_determine_features_test_running = true;
 797   // We must align the first argument to 16 bytes because of the lqarx check.
 798   (*test)(align_up((address)mid_of_test_area, 16), 0);
 799   VM_Version::_is_determine_features_test_running = false;
 800 
 801   // determine which instructions are legal.
 802   int feature_cntr = 0;
 803   if (code[feature_cntr++]) features |= fsqrt_m;
 804   if (code[feature_cntr++]) features |= fsqrts_m;
 805   if (code[feature_cntr++]) features |= isel_m;
 806   if (code[feature_cntr++]) features |= lxarxeh_m;
 807   if (code[feature_cntr++]) features |= cmpb_m;
 808   if (code[feature_cntr++]) features |= popcntb_m;
 809   if (code[feature_cntr++]) features |= popcntw_m;
 810   if (code[feature_cntr++]) features |= fcfids_m;
 811   if (code[feature_cntr++]) features |= vand_m;
 812   if (code[feature_cntr++]) features |= lqarx_m;
 813   if (code[feature_cntr++]) features |= vcipher_m;
 814   if (code[feature_cntr++]) features |= vpmsumb_m;
 815   if (code[feature_cntr++]) features |= mfdscr_m;
 816   if (code[feature_cntr++]) features |= vsx_m;
 817   if (code[feature_cntr++]) features |= ldbrx_m;
 818   if (code[feature_cntr++]) features |= stdbrx_m;
 819   if (code[feature_cntr++]) features |= vshasig_m;
 820   // feature rtm_m is determined by OS
 821   if (code[feature_cntr++]) features |= darn_m;
 822 
 823   // Print the detection code.
 824   if (PrintAssembly) {
 825     ttyLocker ttyl;
 826     tty->print_cr("Decoding cpu-feature detection stub at " INTPTR_FORMAT " after execution:", p2i(code));
 827     Disassembler::decode((u_char*)code, (u_char*)code_end, tty);
 828   }
 829 
 830   _features = features;
 831 
 832 #ifdef AIX
 833   // To enable it on AIX it's necessary POWER8 or above and at least AIX 7.2.
 834   // Actually, this is supported since AIX 7.1.. Unfortunately, this first
 835   // contained bugs, so that it can only be enabled after AIX 7.1.3.30.
 836   // The Java property os.version, which is used in RTM tests to decide
 837   // whether the feature is available, only knows major and minor versions.
 838   // We don't want to change this property, as user code might depend on it.
 839   // So the tests can not check on subversion 3.30, and we only enable RTM
 840   // with AIX 7.2.
 841   if (has_lqarx()) { // POWER8 or above
 842     if (os::Aix::os_version() >= 0x07020000) { // At least AIX 7.2.
 843       _features |= rtm_m;
 844     }
 845   }
 846 #endif
 847 #if defined(LINUX) && defined(VM_LITTLE_ENDIAN)
 848   unsigned long auxv = getauxval(AT_HWCAP2);
 849 
 850   if (auxv & PPC_FEATURE2_HTM_NOSC) {
 851     if (auxv & PPC_FEATURE2_HAS_HTM) {
 852       // TM on POWER8 and POWER9 in compat mode (VM) is supported by the JVM.
 853       // TM on POWER9 DD2.1 NV (baremetal) is not supported by the JVM (TM on
 854       // POWER9 DD2.1 NV has a few issues that need a couple of firmware
 855       // and kernel workarounds, so there is a new mode only supported
 856       // on non-virtualized P9 machines called HTM with no Suspend Mode).
 857       // TM on POWER9 D2.2+ NV is not supported at all by Linux.
 858       _features |= rtm_m;
 859     }
 860   }
 861 #endif
 862 }
 863 
 864 // Power 8: Configure Data Stream Control Register.
 865 void VM_Version::config_dscr() {
 866   // 7 InstWords for each call (function descriptor + blr instruction).
 867   const int code_size = (2+2*7)*BytesPerInstWord;
 868 
 869   // Allocate space for the code.
 870   ResourceMark rm;
 871   CodeBuffer cb("config_dscr", code_size, 0);
 872   MacroAssembler* a = new MacroAssembler(&cb);
 873 
 874   // Emit code.
 875   uint64_t (*get_dscr)() = (uint64_t(*)())(void *)a->function_entry();
 876   uint32_t *code = (uint32_t *)a->pc();
 877   a->mfdscr(R3);
 878   a->blr();
 879 
 880   void (*set_dscr)(long) = (void(*)(long))(void *)a->function_entry();
 881   a->mtdscr(R3);
 882   a->blr();
 883 
 884   uint32_t *code_end = (uint32_t *)a->pc();
 885   a->flush();
 886 
 887   // Print the detection code.
 888   if (PrintAssembly) {
 889     ttyLocker ttyl;
 890     tty->print_cr("Decoding dscr configuration stub at " INTPTR_FORMAT " before execution:", p2i(code));
 891     Disassembler::decode((u_char*)code, (u_char*)code_end, tty);
 892   }
 893 
 894   // Apply the configuration if needed.
 895   _dscr_val = (*get_dscr)();
 896   if (Verbose) {
 897     tty->print_cr("dscr value was 0x%lx" , _dscr_val);
 898   }
 899   bool change_requested = false;
 900   if (DSCR_PPC64 != (uintx)-1) {
 901     _dscr_val = DSCR_PPC64;
 902     change_requested = true;
 903   }
 904   if (DSCR_DPFD_PPC64 <= 7) {
 905     uint64_t mask = 0x7;
 906     if ((_dscr_val & mask) != DSCR_DPFD_PPC64) {
 907       _dscr_val = (_dscr_val & ~mask) | (DSCR_DPFD_PPC64);
 908       change_requested = true;
 909     }
 910   }
 911   if (DSCR_URG_PPC64 <= 7) {
 912     uint64_t mask = 0x7 << 6;
 913     if ((_dscr_val & mask) != DSCR_DPFD_PPC64 << 6) {
 914       _dscr_val = (_dscr_val & ~mask) | (DSCR_URG_PPC64 << 6);
 915       change_requested = true;
 916     }
 917   }
 918   if (change_requested) {
 919     (*set_dscr)(_dscr_val);
 920     if (Verbose) {
 921       tty->print_cr("dscr was set to 0x%lx" , (*get_dscr)());
 922     }
 923   }
 924 }
 925 
 926 static uint64_t saved_features = 0;
 927 
 928 void VM_Version::allow_all() {
 929   saved_features = _features;
 930   _features      = all_features_m;
 931 }
 932 
 933 void VM_Version::revert() {
 934   _features = saved_features;
 935 }