1 /*
   2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // no precompiled headers
  26 #include "jvm.h"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "code/icBuffer.hpp"
  29 #include "code/vtableStubs.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "compiler/disassembler.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "jvmtifiles/jvmti.h"
  34 #include "logging/log.hpp"
  35 #include "logging/logStream.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "os_linux.inline.hpp"
  39 #include "os_posix.inline.hpp"
  40 #include "os_share_linux.hpp"
  41 #include "osContainer_linux.hpp"
  42 #include "prims/jniFastGetField.hpp"
  43 #include "prims/jvm_misc.hpp"
  44 #include "runtime/arguments.hpp"
  45 #include "runtime/atomic.hpp"
  46 #include "runtime/globals.hpp"
  47 #include "runtime/globals_extension.hpp"
  48 #include "runtime/interfaceSupport.inline.hpp"
  49 #include "runtime/init.hpp"
  50 #include "runtime/java.hpp"
  51 #include "runtime/javaCalls.hpp"
  52 #include "runtime/mutexLocker.hpp"
  53 #include "runtime/objectMonitor.hpp"
  54 #include "runtime/osThread.hpp"
  55 #include "runtime/perfMemory.hpp"
  56 #include "runtime/sharedRuntime.hpp"
  57 #include "runtime/statSampler.hpp"
  58 #include "runtime/stubRoutines.hpp"
  59 #include "runtime/thread.inline.hpp"
  60 #include "runtime/threadCritical.hpp"
  61 #include "runtime/threadSMR.hpp"
  62 #include "runtime/timer.hpp"
  63 #include "runtime/vm_version.hpp"
  64 #include "signals_posix.hpp"
  65 #include "semaphore_posix.hpp"
  66 #include "services/memTracker.hpp"
  67 #include "services/runtimeService.hpp"
  68 #include "utilities/align.hpp"
  69 #include "utilities/decoder.hpp"
  70 #include "utilities/defaultStream.hpp"
  71 #include "utilities/events.hpp"
  72 #include "utilities/elfFile.hpp"
  73 #include "utilities/growableArray.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 #include "utilities/vmError.hpp"
  77 
  78 // put OS-includes here
  79 # include <sys/types.h>
  80 # include <sys/mman.h>
  81 # include <sys/stat.h>
  82 # include <sys/select.h>
  83 # include <pthread.h>
  84 # include <signal.h>
  85 # include <endian.h>
  86 # include <errno.h>
  87 # include <dlfcn.h>
  88 # include <stdio.h>
  89 # include <unistd.h>
  90 # include <sys/resource.h>
  91 # include <pthread.h>
  92 # include <sys/stat.h>
  93 # include <sys/time.h>
  94 # include <sys/times.h>
  95 # include <sys/utsname.h>
  96 # include <sys/socket.h>
  97 # include <pwd.h>
  98 # include <poll.h>
  99 # include <fcntl.h>
 100 # include <string.h>
 101 # include <syscall.h>
 102 # include <sys/sysinfo.h>
 103 # include <sys/ipc.h>
 104 # include <sys/shm.h>
 105 # include <link.h>
 106 # include <stdint.h>
 107 # include <inttypes.h>
 108 # include <sys/ioctl.h>
 109 # include <linux/elf-em.h>
 110 #ifdef __GLIBC__
 111 # include <malloc.h>
 112 #endif
 113 
 114 #ifndef _GNU_SOURCE
 115   #define _GNU_SOURCE
 116   #include <sched.h>
 117   #undef _GNU_SOURCE
 118 #else
 119   #include <sched.h>
 120 #endif
 121 
 122 // if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling
 123 // getrusage() is prepared to handle the associated failure.
 124 #ifndef RUSAGE_THREAD
 125   #define RUSAGE_THREAD   (1)               /* only the calling thread */
 126 #endif
 127 
 128 #define MAX_PATH    (2 * K)
 129 
 130 #define MAX_SECS 100000000
 131 
 132 // for timer info max values which include all bits
 133 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF)
 134 
 135 #ifdef MUSL_LIBC
 136 // dlvsym is not a part of POSIX
 137 // and musl libc doesn't implement it.
 138 static void *dlvsym(void *handle,
 139                     const char *symbol,
 140                     const char *version) {
 141    // load the latest version of symbol
 142    return dlsym(handle, symbol);
 143 }
 144 #endif
 145 
 146 enum CoredumpFilterBit {
 147   FILE_BACKED_PVT_BIT = 1 << 2,
 148   FILE_BACKED_SHARED_BIT = 1 << 3,
 149   LARGEPAGES_BIT = 1 << 6,
 150   DAX_SHARED_BIT = 1 << 8
 151 };
 152 
 153 ////////////////////////////////////////////////////////////////////////////////
 154 // global variables
 155 julong os::Linux::_physical_memory = 0;
 156 
 157 address   os::Linux::_initial_thread_stack_bottom = NULL;
 158 uintptr_t os::Linux::_initial_thread_stack_size   = 0;
 159 
 160 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL;
 161 int (*os::Linux::_pthread_setname_np)(pthread_t, const char*) = NULL;
 162 pthread_t os::Linux::_main_thread;
 163 int os::Linux::_page_size = -1;
 164 bool os::Linux::_supports_fast_thread_cpu_time = false;
 165 const char * os::Linux::_libc_version = NULL;
 166 const char * os::Linux::_libpthread_version = NULL;
 167 size_t os::Linux::_default_large_page_size = 0;
 168 
 169 #ifdef __GLIBC__
 170 os::Linux::mallinfo_func_t os::Linux::_mallinfo = NULL;
 171 os::Linux::mallinfo2_func_t os::Linux::_mallinfo2 = NULL;
 172 #endif // __GLIBC__
 173 
 174 static int clock_tics_per_sec = 100;
 175 
 176 // If the VM might have been created on the primordial thread, we need to resolve the
 177 // primordial thread stack bounds and check if the current thread might be the
 178 // primordial thread in places. If we know that the primordial thread is never used,
 179 // such as when the VM was created by one of the standard java launchers, we can
 180 // avoid this
 181 static bool suppress_primordial_thread_resolution = false;
 182 
 183 // utility functions
 184 
 185 julong os::available_memory() {
 186   return Linux::available_memory();
 187 }
 188 
 189 julong os::Linux::available_memory() {
 190   // values in struct sysinfo are "unsigned long"
 191   struct sysinfo si;
 192   julong avail_mem;
 193 
 194   if (OSContainer::is_containerized()) {
 195     jlong mem_limit, mem_usage;
 196     if ((mem_limit = OSContainer::memory_limit_in_bytes()) < 1) {
 197       log_debug(os, container)("container memory limit %s: " JLONG_FORMAT ", using host value",
 198                              mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);
 199     }
 200     if (mem_limit > 0 && (mem_usage = OSContainer::memory_usage_in_bytes()) < 1) {
 201       log_debug(os, container)("container memory usage failed: " JLONG_FORMAT ", using host value", mem_usage);
 202     }
 203     if (mem_limit > 0 && mem_usage > 0 ) {
 204       avail_mem = mem_limit > mem_usage ? (julong)mem_limit - (julong)mem_usage : 0;
 205       log_trace(os)("available container memory: " JULONG_FORMAT, avail_mem);
 206       return avail_mem;
 207     }
 208   }
 209 
 210   sysinfo(&si);
 211   avail_mem = (julong)si.freeram * si.mem_unit;
 212   log_trace(os)("available memory: " JULONG_FORMAT, avail_mem);
 213   return avail_mem;
 214 }
 215 
 216 julong os::physical_memory() {
 217   jlong phys_mem = 0;
 218   if (OSContainer::is_containerized()) {
 219     jlong mem_limit;
 220     if ((mem_limit = OSContainer::memory_limit_in_bytes()) > 0) {
 221       log_trace(os)("total container memory: " JLONG_FORMAT, mem_limit);
 222       return mem_limit;
 223     }
 224     log_debug(os, container)("container memory limit %s: " JLONG_FORMAT ", using host value",
 225                             mem_limit == OSCONTAINER_ERROR ? "failed" : "unlimited", mem_limit);
 226   }
 227 
 228   phys_mem = Linux::physical_memory();
 229   log_trace(os)("total system memory: " JLONG_FORMAT, phys_mem);
 230   return phys_mem;
 231 }
 232 
 233 static uint64_t initial_total_ticks = 0;
 234 static uint64_t initial_steal_ticks = 0;
 235 static bool     has_initial_tick_info = false;
 236 
 237 static void next_line(FILE *f) {
 238   int c;
 239   do {
 240     c = fgetc(f);
 241   } while (c != '\n' && c != EOF);
 242 }
 243 
 244 bool os::Linux::get_tick_information(CPUPerfTicks* pticks, int which_logical_cpu) {
 245   FILE*         fh;
 246   uint64_t      userTicks, niceTicks, systemTicks, idleTicks;
 247   // since at least kernel 2.6 : iowait: time waiting for I/O to complete
 248   // irq: time  servicing interrupts; softirq: time servicing softirqs
 249   uint64_t      iowTicks = 0, irqTicks = 0, sirqTicks= 0;
 250   // steal (since kernel 2.6.11): time spent in other OS when running in a virtualized environment
 251   uint64_t      stealTicks = 0;
 252   // guest (since kernel 2.6.24): time spent running a virtual CPU for guest OS under the
 253   // control of the Linux kernel
 254   uint64_t      guestNiceTicks = 0;
 255   int           logical_cpu = -1;
 256   const int     required_tickinfo_count = (which_logical_cpu == -1) ? 4 : 5;
 257   int           n;
 258 
 259   memset(pticks, 0, sizeof(CPUPerfTicks));
 260 
 261   if ((fh = fopen("/proc/stat", "r")) == NULL) {
 262     return false;
 263   }
 264 
 265   if (which_logical_cpu == -1) {
 266     n = fscanf(fh, "cpu " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 267             UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 268             UINT64_FORMAT " " UINT64_FORMAT " ",
 269             &userTicks, &niceTicks, &systemTicks, &idleTicks,
 270             &iowTicks, &irqTicks, &sirqTicks,
 271             &stealTicks, &guestNiceTicks);
 272   } else {
 273     // Move to next line
 274     next_line(fh);
 275 
 276     // find the line for requested cpu faster to just iterate linefeeds?
 277     for (int i = 0; i < which_logical_cpu; i++) {
 278       next_line(fh);
 279     }
 280 
 281     n = fscanf(fh, "cpu%u " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 282                UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "
 283                UINT64_FORMAT " " UINT64_FORMAT " ",
 284                &logical_cpu, &userTicks, &niceTicks,
 285                &systemTicks, &idleTicks, &iowTicks, &irqTicks, &sirqTicks,
 286                &stealTicks, &guestNiceTicks);
 287   }
 288 
 289   fclose(fh);
 290   if (n < required_tickinfo_count || logical_cpu != which_logical_cpu) {
 291     return false;
 292   }
 293   pticks->used       = userTicks + niceTicks;
 294   pticks->usedKernel = systemTicks + irqTicks + sirqTicks;
 295   pticks->total      = userTicks + niceTicks + systemTicks + idleTicks +
 296                        iowTicks + irqTicks + sirqTicks + stealTicks + guestNiceTicks;
 297 
 298   if (n > required_tickinfo_count + 3) {
 299     pticks->steal = stealTicks;
 300     pticks->has_steal_ticks = true;
 301   } else {
 302     pticks->steal = 0;
 303     pticks->has_steal_ticks = false;
 304   }
 305 
 306   return true;
 307 }
 308 
 309 #ifndef SYS_gettid
 310 // i386: 224, ia64: 1105, amd64: 186, sparc: 143
 311   #ifdef __ia64__
 312     #define SYS_gettid 1105
 313   #else
 314     #ifdef __i386__
 315       #define SYS_gettid 224
 316     #else
 317       #ifdef __amd64__
 318         #define SYS_gettid 186
 319       #else
 320         #ifdef __sparc__
 321           #define SYS_gettid 143
 322         #else
 323           #error define gettid for the arch
 324         #endif
 325       #endif
 326     #endif
 327   #endif
 328 #endif
 329 
 330 
 331 // pid_t gettid()
 332 //
 333 // Returns the kernel thread id of the currently running thread. Kernel
 334 // thread id is used to access /proc.
 335 pid_t os::Linux::gettid() {
 336   int rslt = syscall(SYS_gettid);
 337   assert(rslt != -1, "must be."); // old linuxthreads implementation?
 338   return (pid_t)rslt;
 339 }
 340 
 341 // Most versions of linux have a bug where the number of processors are
 342 // determined by looking at the /proc file system.  In a chroot environment,
 343 // the system call returns 1.
 344 static bool unsafe_chroot_detected = false;
 345 static const char *unstable_chroot_error = "/proc file system not found.\n"
 346                      "Java may be unstable running multithreaded in a chroot "
 347                      "environment on Linux when /proc filesystem is not mounted.";
 348 
 349 void os::Linux::initialize_system_info() {
 350   set_processor_count(sysconf(_SC_NPROCESSORS_CONF));
 351   if (processor_count() == 1) {
 352     pid_t pid = os::Linux::gettid();
 353     char fname[32];
 354     jio_snprintf(fname, sizeof(fname), "/proc/%d", pid);
 355     FILE *fp = fopen(fname, "r");
 356     if (fp == NULL) {
 357       unsafe_chroot_detected = true;
 358     } else {
 359       fclose(fp);
 360     }
 361   }
 362   _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE);
 363   assert(processor_count() > 0, "linux error");
 364 }
 365 
 366 void os::init_system_properties_values() {
 367   // The next steps are taken in the product version:
 368   //
 369   // Obtain the JAVA_HOME value from the location of libjvm.so.
 370   // This library should be located at:
 371   // <JAVA_HOME>/lib/{client|server}/libjvm.so.
 372   //
 373   // If "/jre/lib/" appears at the right place in the path, then we
 374   // assume libjvm.so is installed in a JDK and we use this path.
 375   //
 376   // Otherwise exit with message: "Could not create the Java virtual machine."
 377   //
 378   // The following extra steps are taken in the debugging version:
 379   //
 380   // If "/jre/lib/" does NOT appear at the right place in the path
 381   // instead of exit check for $JAVA_HOME environment variable.
 382   //
 383   // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>,
 384   // then we append a fake suffix "hotspot/libjvm.so" to this path so
 385   // it looks like libjvm.so is installed there
 386   // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so.
 387   //
 388   // Otherwise exit.
 389   //
 390   // Important note: if the location of libjvm.so changes this
 391   // code needs to be changed accordingly.
 392 
 393   // See ld(1):
 394   //      The linker uses the following search paths to locate required
 395   //      shared libraries:
 396   //        1: ...
 397   //        ...
 398   //        7: The default directories, normally /lib and /usr/lib.
 399 #ifndef OVERRIDE_LIBPATH
 400   #if defined(_LP64)
 401     #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib"
 402   #else
 403     #define DEFAULT_LIBPATH "/lib:/usr/lib"
 404   #endif
 405 #else
 406   #define DEFAULT_LIBPATH OVERRIDE_LIBPATH
 407 #endif
 408 
 409 // Base path of extensions installed on the system.
 410 #define SYS_EXT_DIR     "/usr/java/packages"
 411 #define EXTENSIONS_DIR  "/lib/ext"
 412 
 413   // Buffer that fits several sprintfs.
 414   // Note that the space for the colon and the trailing null are provided
 415   // by the nulls included by the sizeof operator.
 416   const size_t bufsize =
 417     MAX2((size_t)MAXPATHLEN,  // For dll_dir & friends.
 418          (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir
 419   char *buf = NEW_C_HEAP_ARRAY(char, bufsize, mtInternal);
 420 
 421   // sysclasspath, java_home, dll_dir
 422   {
 423     char *pslash;
 424     os::jvm_path(buf, bufsize);
 425 
 426     // Found the full path to libjvm.so.
 427     // Now cut the path to <java_home>/jre if we can.
 428     pslash = strrchr(buf, '/');
 429     if (pslash != NULL) {
 430       *pslash = '\0';            // Get rid of /libjvm.so.
 431     }
 432     pslash = strrchr(buf, '/');
 433     if (pslash != NULL) {
 434       *pslash = '\0';            // Get rid of /{client|server|hotspot}.
 435     }
 436     Arguments::set_dll_dir(buf);
 437 
 438     if (pslash != NULL) {
 439       pslash = strrchr(buf, '/');
 440       if (pslash != NULL) {
 441         *pslash = '\0';        // Get rid of /lib.
 442       }
 443     }
 444     Arguments::set_java_home(buf);
 445     if (!set_boot_path('/', ':')) {
 446       vm_exit_during_initialization("Failed setting boot class path.", NULL);
 447     }
 448   }
 449 
 450   // Where to look for native libraries.
 451   //
 452   // Note: Due to a legacy implementation, most of the library path
 453   // is set in the launcher. This was to accomodate linking restrictions
 454   // on legacy Linux implementations (which are no longer supported).
 455   // Eventually, all the library path setting will be done here.
 456   //
 457   // However, to prevent the proliferation of improperly built native
 458   // libraries, the new path component /usr/java/packages is added here.
 459   // Eventually, all the library path setting will be done here.
 460   {
 461     // Get the user setting of LD_LIBRARY_PATH, and prepended it. It
 462     // should always exist (until the legacy problem cited above is
 463     // addressed).
 464     const char *v = ::getenv("LD_LIBRARY_PATH");
 465     const char *v_colon = ":";
 466     if (v == NULL) { v = ""; v_colon = ""; }
 467     // That's +1 for the colon and +1 for the trailing '\0'.
 468     char *ld_library_path = NEW_C_HEAP_ARRAY(char,
 469                                              strlen(v) + 1 +
 470                                              sizeof(SYS_EXT_DIR) + sizeof("/lib/") + sizeof(DEFAULT_LIBPATH) + 1,
 471                                              mtInternal);
 472     sprintf(ld_library_path, "%s%s" SYS_EXT_DIR "/lib:" DEFAULT_LIBPATH, v, v_colon);
 473     Arguments::set_library_path(ld_library_path);
 474     FREE_C_HEAP_ARRAY(char, ld_library_path);
 475   }
 476 
 477   // Extensions directories.
 478   sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home());
 479   Arguments::set_ext_dirs(buf);
 480 
 481   FREE_C_HEAP_ARRAY(char, buf);
 482 
 483 #undef DEFAULT_LIBPATH
 484 #undef SYS_EXT_DIR
 485 #undef EXTENSIONS_DIR
 486 }
 487 
 488 ////////////////////////////////////////////////////////////////////////////////
 489 // breakpoint support
 490 
 491 void os::breakpoint() {
 492   BREAKPOINT;
 493 }
 494 
 495 extern "C" void breakpoint() {
 496   // use debugger to set breakpoint here
 497 }
 498 
 499 //////////////////////////////////////////////////////////////////////////////
 500 // detecting pthread library
 501 
 502 void os::Linux::libpthread_init() {
 503   // Save glibc and pthread version strings.
 504 #if !defined(_CS_GNU_LIBC_VERSION) || \
 505     !defined(_CS_GNU_LIBPTHREAD_VERSION)
 506   #error "glibc too old (< 2.3.2)"
 507 #endif
 508 
 509 #ifdef MUSL_LIBC
 510   // confstr() from musl libc returns EINVAL for
 511   // _CS_GNU_LIBC_VERSION and _CS_GNU_LIBPTHREAD_VERSION
 512   os::Linux::set_libc_version("musl - unknown");
 513   os::Linux::set_libpthread_version("musl - unknown");
 514 #else
 515   size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0);
 516   assert(n > 0, "cannot retrieve glibc version");
 517   char *str = (char *)malloc(n, mtInternal);
 518   confstr(_CS_GNU_LIBC_VERSION, str, n);
 519   os::Linux::set_libc_version(str);
 520 
 521   n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0);
 522   assert(n > 0, "cannot retrieve pthread version");
 523   str = (char *)malloc(n, mtInternal);
 524   confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n);
 525   os::Linux::set_libpthread_version(str);
 526 #endif
 527 }
 528 
 529 /////////////////////////////////////////////////////////////////////////////
 530 // thread stack expansion
 531 
 532 // os::Linux::manually_expand_stack() takes care of expanding the thread
 533 // stack. Note that this is normally not needed: pthread stacks allocate
 534 // thread stack using mmap() without MAP_NORESERVE, so the stack is already
 535 // committed. Therefore it is not necessary to expand the stack manually.
 536 //
 537 // Manually expanding the stack was historically needed on LinuxThreads
 538 // thread stacks, which were allocated with mmap(MAP_GROWSDOWN). Nowadays
 539 // it is kept to deal with very rare corner cases:
 540 //
 541 // For one, user may run the VM on an own implementation of threads
 542 // whose stacks are - like the old LinuxThreads - implemented using
 543 // mmap(MAP_GROWSDOWN).
 544 //
 545 // Also, this coding may be needed if the VM is running on the primordial
 546 // thread. Normally we avoid running on the primordial thread; however,
 547 // user may still invoke the VM on the primordial thread.
 548 //
 549 // The following historical comment describes the details about running
 550 // on a thread stack allocated with mmap(MAP_GROWSDOWN):
 551 
 552 
 553 // Force Linux kernel to expand current thread stack. If "bottom" is close
 554 // to the stack guard, caller should block all signals.
 555 //
 556 // MAP_GROWSDOWN:
 557 //   A special mmap() flag that is used to implement thread stacks. It tells
 558 //   kernel that the memory region should extend downwards when needed. This
 559 //   allows early versions of LinuxThreads to only mmap the first few pages
 560 //   when creating a new thread. Linux kernel will automatically expand thread
 561 //   stack as needed (on page faults).
 562 //
 563 //   However, because the memory region of a MAP_GROWSDOWN stack can grow on
 564 //   demand, if a page fault happens outside an already mapped MAP_GROWSDOWN
 565 //   region, it's hard to tell if the fault is due to a legitimate stack
 566 //   access or because of reading/writing non-exist memory (e.g. buffer
 567 //   overrun). As a rule, if the fault happens below current stack pointer,
 568 //   Linux kernel does not expand stack, instead a SIGSEGV is sent to the
 569 //   application (see Linux kernel fault.c).
 570 //
 571 //   This Linux feature can cause SIGSEGV when VM bangs thread stack for
 572 //   stack overflow detection.
 573 //
 574 //   Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do
 575 //   not use MAP_GROWSDOWN.
 576 //
 577 // To get around the problem and allow stack banging on Linux, we need to
 578 // manually expand thread stack after receiving the SIGSEGV.
 579 //
 580 // There are two ways to expand thread stack to address "bottom", we used
 581 // both of them in JVM before 1.5:
 582 //   1. adjust stack pointer first so that it is below "bottom", and then
 583 //      touch "bottom"
 584 //   2. mmap() the page in question
 585 //
 586 // Now alternate signal stack is gone, it's harder to use 2. For instance,
 587 // if current sp is already near the lower end of page 101, and we need to
 588 // call mmap() to map page 100, it is possible that part of the mmap() frame
 589 // will be placed in page 100. When page 100 is mapped, it is zero-filled.
 590 // That will destroy the mmap() frame and cause VM to crash.
 591 //
 592 // The following code works by adjusting sp first, then accessing the "bottom"
 593 // page to force a page fault. Linux kernel will then automatically expand the
 594 // stack mapping.
 595 //
 596 // _expand_stack_to() assumes its frame size is less than page size, which
 597 // should always be true if the function is not inlined.
 598 
 599 static void NOINLINE _expand_stack_to(address bottom) {
 600   address sp;
 601   size_t size;
 602   volatile char *p;
 603 
 604   // Adjust bottom to point to the largest address within the same page, it
 605   // gives us a one-page buffer if alloca() allocates slightly more memory.
 606   bottom = (address)align_down((uintptr_t)bottom, os::Linux::page_size());
 607   bottom += os::Linux::page_size() - 1;
 608 
 609   // sp might be slightly above current stack pointer; if that's the case, we
 610   // will alloca() a little more space than necessary, which is OK. Don't use
 611   // os::current_stack_pointer(), as its result can be slightly below current
 612   // stack pointer, causing us to not alloca enough to reach "bottom".
 613   sp = (address)&sp;
 614 
 615   if (sp > bottom) {
 616     size = sp - bottom;
 617     p = (volatile char *)alloca(size);
 618     assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?");
 619     p[0] = '\0';
 620   }
 621 }
 622 
 623 void os::Linux::expand_stack_to(address bottom) {
 624   _expand_stack_to(bottom);
 625 }
 626 
 627 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) {
 628   assert(t!=NULL, "just checking");
 629   assert(t->osthread()->expanding_stack(), "expand should be set");
 630 
 631   if (t->is_in_usable_stack(addr)) {
 632     sigset_t mask_all, old_sigset;
 633     sigfillset(&mask_all);
 634     pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset);
 635     _expand_stack_to(addr);
 636     pthread_sigmask(SIG_SETMASK, &old_sigset, NULL);
 637     return true;
 638   }
 639   return false;
 640 }
 641 
 642 //////////////////////////////////////////////////////////////////////////////
 643 // create new thread
 644 
 645 // Thread start routine for all newly created threads
 646 static void *thread_native_entry(Thread *thread) {
 647 
 648   thread->record_stack_base_and_size();
 649 
 650 #ifndef __GLIBC__
 651   // Try to randomize the cache line index of hot stack frames.
 652   // This helps when threads of the same stack traces evict each other's
 653   // cache lines. The threads can be either from the same JVM instance, or
 654   // from different JVM instances. The benefit is especially true for
 655   // processors with hyperthreading technology.
 656   // This code is not needed anymore in glibc because it has MULTI_PAGE_ALIASING
 657   // and we did not see any degradation in performance without `alloca()`.
 658   static int counter = 0;
 659   int pid = os::current_process_id();
 660   int random = ((pid ^ counter++) & 7) * 128;
 661   void *stackmem = alloca(random != 0 ? random : 1); // ensure we allocate > 0
 662   // Ensure the alloca result is used in a way that prevents the compiler from eliding it.
 663   *(char *)stackmem = 1;
 664 #endif
 665 
 666   thread->initialize_thread_current();
 667 
 668   OSThread* osthread = thread->osthread();
 669   Monitor* sync = osthread->startThread_lock();
 670 
 671   osthread->set_thread_id(os::current_thread_id());
 672 
 673   if (UseNUMA) {
 674     int lgrp_id = os::numa_get_group_id();
 675     if (lgrp_id != -1) {
 676       thread->set_lgrp_id(lgrp_id);
 677     }
 678   }
 679   // initialize signal mask for this thread
 680   PosixSignals::hotspot_sigmask(thread);
 681 
 682   // initialize floating point control register
 683   os::Linux::init_thread_fpu_state();
 684 
 685   // handshaking with parent thread
 686   {
 687     MutexLocker ml(sync, Mutex::_no_safepoint_check_flag);
 688 
 689     // notify parent thread
 690     osthread->set_state(INITIALIZED);
 691     sync->notify_all();
 692 
 693     // wait until os::start_thread()
 694     while (osthread->get_state() == INITIALIZED) {
 695       sync->wait_without_safepoint_check();
 696     }
 697   }
 698 
 699   log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 700     os::current_thread_id(), (uintx) pthread_self());
 701 
 702   assert(osthread->pthread_id() != 0, "pthread_id was not set as expected");
 703 
 704   // call one more level start routine
 705   thread->call_run();
 706 
 707   // Note: at this point the thread object may already have deleted itself.
 708   // Prevent dereferencing it from here on out.
 709   thread = NULL;
 710 
 711   log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 712     os::current_thread_id(), (uintx) pthread_self());
 713 
 714   return 0;
 715 }
 716 
 717 // On Linux, glibc places static TLS blocks (for __thread variables) on
 718 // the thread stack. This decreases the stack size actually available
 719 // to threads.
 720 //
 721 // For large static TLS sizes, this may cause threads to malfunction due
 722 // to insufficient stack space. This is a well-known issue in glibc:
 723 // http://sourceware.org/bugzilla/show_bug.cgi?id=11787.
 724 //
 725 // As a workaround, we call a private but assumed-stable glibc function,
 726 // __pthread_get_minstack() to obtain the minstack size and derive the
 727 // static TLS size from it. We then increase the user requested stack
 728 // size by this TLS size.
 729 //
 730 // Due to compatibility concerns, this size adjustment is opt-in and
 731 // controlled via AdjustStackSizeForTLS.
 732 typedef size_t (*GetMinStack)(const pthread_attr_t *attr);
 733 
 734 GetMinStack _get_minstack_func = NULL;
 735 
 736 static void get_minstack_init() {
 737   _get_minstack_func =
 738         (GetMinStack)dlsym(RTLD_DEFAULT, "__pthread_get_minstack");
 739   log_info(os, thread)("Lookup of __pthread_get_minstack %s",
 740                        _get_minstack_func == NULL ? "failed" : "succeeded");
 741 }
 742 
 743 // Returns the size of the static TLS area glibc puts on thread stacks.
 744 // The value is cached on first use, which occurs when the first thread
 745 // is created during VM initialization.
 746 static size_t get_static_tls_area_size(const pthread_attr_t *attr) {
 747   size_t tls_size = 0;
 748   if (_get_minstack_func != NULL) {
 749     // Obtain the pthread minstack size by calling __pthread_get_minstack.
 750     size_t minstack_size = _get_minstack_func(attr);
 751 
 752     // Remove non-TLS area size included in minstack size returned
 753     // by __pthread_get_minstack() to get the static TLS size.
 754     // In glibc before 2.27, minstack size includes guard_size.
 755     // In glibc 2.27 and later, guard_size is automatically added
 756     // to the stack size by pthread_create and is no longer included
 757     // in minstack size. In both cases, the guard_size is taken into
 758     // account, so there is no need to adjust the result for that.
 759     //
 760     // Although __pthread_get_minstack() is a private glibc function,
 761     // it is expected to have a stable behavior across future glibc
 762     // versions while glibc still allocates the static TLS blocks off
 763     // the stack. Following is glibc 2.28 __pthread_get_minstack():
 764     //
 765     // size_t
 766     // __pthread_get_minstack (const pthread_attr_t *attr)
 767     // {
 768     //   return GLRO(dl_pagesize) + __static_tls_size + PTHREAD_STACK_MIN;
 769     // }
 770     //
 771     //
 772     // The following 'minstack_size > os::vm_page_size() + PTHREAD_STACK_MIN'
 773     // if check is done for precaution.
 774     if (minstack_size > (size_t)os::vm_page_size() + PTHREAD_STACK_MIN) {
 775       tls_size = minstack_size - os::vm_page_size() - PTHREAD_STACK_MIN;
 776     }
 777   }
 778 
 779   log_info(os, thread)("Stack size adjustment for TLS is " SIZE_FORMAT,
 780                        tls_size);
 781   return tls_size;
 782 }
 783 
 784 bool os::create_thread(Thread* thread, ThreadType thr_type,
 785                        size_t req_stack_size) {
 786   assert(thread->osthread() == NULL, "caller responsible");
 787 
 788   // Allocate the OSThread object
 789   OSThread* osthread = new OSThread(NULL, NULL);
 790   if (osthread == NULL) {
 791     return false;
 792   }
 793 
 794   // set the correct thread state
 795   osthread->set_thread_type(thr_type);
 796 
 797   // Initial state is ALLOCATED but not INITIALIZED
 798   osthread->set_state(ALLOCATED);
 799 
 800   thread->set_osthread(osthread);
 801 
 802   // init thread attributes
 803   pthread_attr_t attr;
 804   pthread_attr_init(&attr);
 805   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 806 
 807   // Calculate stack size if it's not specified by caller.
 808   size_t stack_size = os::Posix::get_initial_stack_size(thr_type, req_stack_size);
 809   // In glibc versions prior to 2.7 the guard size mechanism
 810   // is not implemented properly. The posix standard requires adding
 811   // the size of the guard pages to the stack size, instead Linux
 812   // takes the space out of 'stacksize'. Thus we adapt the requested
 813   // stack_size by the size of the guard pages to mimick proper
 814   // behaviour. However, be careful not to end up with a size
 815   // of zero due to overflow. Don't add the guard page in that case.
 816   size_t guard_size = os::Linux::default_guard_size(thr_type);
 817   // Configure glibc guard page. Must happen before calling
 818   // get_static_tls_area_size(), which uses the guard_size.
 819   pthread_attr_setguardsize(&attr, guard_size);
 820 
 821   size_t stack_adjust_size = 0;
 822   if (AdjustStackSizeForTLS) {
 823     // Adjust the stack_size for on-stack TLS - see get_static_tls_area_size().
 824     stack_adjust_size += get_static_tls_area_size(&attr);
 825   } else {
 826     stack_adjust_size += guard_size;
 827   }
 828 
 829   stack_adjust_size = align_up(stack_adjust_size, os::vm_page_size());
 830   if (stack_size <= SIZE_MAX - stack_adjust_size) {
 831     stack_size += stack_adjust_size;
 832   }
 833   assert(is_aligned(stack_size, os::vm_page_size()), "stack_size not aligned");
 834 
 835   int status = pthread_attr_setstacksize(&attr, stack_size);
 836   if (status != 0) {
 837     // pthread_attr_setstacksize() function can fail
 838     // if the stack size exceeds a system-imposed limit.
 839     assert_status(status == EINVAL, status, "pthread_attr_setstacksize");
 840     log_warning(os, thread)("The %sthread stack size specified is invalid: " SIZE_FORMAT "k",
 841                             (thr_type == compiler_thread) ? "compiler " : ((thr_type == java_thread) ? "" : "VM "),
 842                             stack_size / K);
 843     thread->set_osthread(NULL);
 844     delete osthread;
 845     return false;
 846   }
 847 
 848   ThreadState state;
 849 
 850   {
 851     ResourceMark rm;
 852     pthread_t tid;
 853     int ret = 0;
 854     int limit = 3;
 855     do {
 856       ret = pthread_create(&tid, &attr, (void* (*)(void*)) thread_native_entry, thread);
 857     } while (ret == EAGAIN && limit-- > 0);
 858 
 859     char buf[64];
 860     if (ret == 0) {
 861       log_info(os, thread)("Thread \"%s\" started (pthread id: " UINTX_FORMAT ", attributes: %s). ",
 862                            thread->name(), (uintx) tid, os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 863     } else {
 864       log_warning(os, thread)("Failed to start thread \"%s\" - pthread_create failed (%s) for attributes: %s.",
 865                               thread->name(), os::errno_name(ret), os::Posix::describe_pthread_attr(buf, sizeof(buf), &attr));
 866       // Log some OS information which might explain why creating the thread failed.
 867       log_info(os, thread)("Number of threads approx. running in the VM: %d", Threads::number_of_threads());
 868       LogStream st(Log(os, thread)::info());
 869       os::Posix::print_rlimit_info(&st);
 870       os::print_memory_info(&st);
 871       os::Linux::print_proc_sys_info(&st);
 872       os::Linux::print_container_info(&st);
 873     }
 874 
 875     pthread_attr_destroy(&attr);
 876 
 877     if (ret != 0) {
 878       // Need to clean up stuff we've allocated so far
 879       thread->set_osthread(NULL);
 880       delete osthread;
 881       return false;
 882     }
 883 
 884     // Store pthread info into the OSThread
 885     osthread->set_pthread_id(tid);
 886 
 887     // Wait until child thread is either initialized or aborted
 888     {
 889       Monitor* sync_with_child = osthread->startThread_lock();
 890       MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 891       while ((state = osthread->get_state()) == ALLOCATED) {
 892         sync_with_child->wait_without_safepoint_check();
 893       }
 894     }
 895   }
 896 
 897   // The thread is returned suspended (in state INITIALIZED),
 898   // and is started higher up in the call chain
 899   assert(state == INITIALIZED, "race condition");
 900   return true;
 901 }
 902 
 903 /////////////////////////////////////////////////////////////////////////////
 904 // attach existing thread
 905 
 906 // bootstrap the main thread
 907 bool os::create_main_thread(JavaThread* thread) {
 908   assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread");
 909   return create_attached_thread(thread);
 910 }
 911 
 912 bool os::create_attached_thread(JavaThread* thread) {
 913 #ifdef ASSERT
 914   thread->verify_not_published();
 915 #endif
 916 
 917   // Allocate the OSThread object
 918   OSThread* osthread = new OSThread(NULL, NULL);
 919 
 920   if (osthread == NULL) {
 921     return false;
 922   }
 923 
 924   // Store pthread info into the OSThread
 925   osthread->set_thread_id(os::Linux::gettid());
 926   osthread->set_pthread_id(::pthread_self());
 927 
 928   // initialize floating point control register
 929   os::Linux::init_thread_fpu_state();
 930 
 931   // Initial thread state is RUNNABLE
 932   osthread->set_state(RUNNABLE);
 933 
 934   thread->set_osthread(osthread);
 935 
 936   if (UseNUMA) {
 937     int lgrp_id = os::numa_get_group_id();
 938     if (lgrp_id != -1) {
 939       thread->set_lgrp_id(lgrp_id);
 940     }
 941   }
 942 
 943   if (os::is_primordial_thread()) {
 944     // If current thread is primordial thread, its stack is mapped on demand,
 945     // see notes about MAP_GROWSDOWN. Here we try to force kernel to map
 946     // the entire stack region to avoid SEGV in stack banging.
 947     // It is also useful to get around the heap-stack-gap problem on SuSE
 948     // kernel (see 4821821 for details). We first expand stack to the top
 949     // of yellow zone, then enable stack yellow zone (order is significant,
 950     // enabling yellow zone first will crash JVM on SuSE Linux), so there
 951     // is no gap between the last two virtual memory regions.
 952 
 953     StackOverflow* overflow_state = thread->stack_overflow_state();
 954     address addr = overflow_state->stack_reserved_zone_base();
 955     assert(addr != NULL, "initialization problem?");
 956     assert(overflow_state->stack_available(addr) > 0, "stack guard should not be enabled");
 957 
 958     osthread->set_expanding_stack();
 959     os::Linux::manually_expand_stack(thread, addr);
 960     osthread->clear_expanding_stack();
 961   }
 962 
 963   // initialize signal mask for this thread
 964   // and save the caller's signal mask
 965   PosixSignals::hotspot_sigmask(thread);
 966 
 967   log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ", pthread id: " UINTX_FORMAT ").",
 968     os::current_thread_id(), (uintx) pthread_self());
 969 
 970   return true;
 971 }
 972 
 973 void os::pd_start_thread(Thread* thread) {
 974   OSThread * osthread = thread->osthread();
 975   assert(osthread->get_state() != INITIALIZED, "just checking");
 976   Monitor* sync_with_child = osthread->startThread_lock();
 977   MutexLocker ml(sync_with_child, Mutex::_no_safepoint_check_flag);
 978   sync_with_child->notify();
 979 }
 980 
 981 // Free Linux resources related to the OSThread
 982 void os::free_thread(OSThread* osthread) {
 983   assert(osthread != NULL, "osthread not set");
 984 
 985   // We are told to free resources of the argument thread,
 986   // but we can only really operate on the current thread.
 987   assert(Thread::current()->osthread() == osthread,
 988          "os::free_thread but not current thread");
 989 
 990 #ifdef ASSERT
 991   sigset_t current;
 992   sigemptyset(&current);
 993   pthread_sigmask(SIG_SETMASK, NULL, &current);
 994   assert(!sigismember(&current, PosixSignals::SR_signum), "SR signal should not be blocked!");
 995 #endif
 996 
 997   // Restore caller's signal mask
 998   sigset_t sigmask = osthread->caller_sigmask();
 999   pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
1000 
1001   delete osthread;
1002 }
1003 
1004 //////////////////////////////////////////////////////////////////////////////
1005 // primordial thread
1006 
1007 // Check if current thread is the primordial thread, similar to Solaris thr_main.
1008 bool os::is_primordial_thread(void) {
1009   if (suppress_primordial_thread_resolution) {
1010     return false;
1011   }
1012   char dummy;
1013   // If called before init complete, thread stack bottom will be null.
1014   // Can be called if fatal error occurs before initialization.
1015   if (os::Linux::initial_thread_stack_bottom() == NULL) return false;
1016   assert(os::Linux::initial_thread_stack_bottom() != NULL &&
1017          os::Linux::initial_thread_stack_size()   != 0,
1018          "os::init did not locate primordial thread's stack region");
1019   if ((address)&dummy >= os::Linux::initial_thread_stack_bottom() &&
1020       (address)&dummy < os::Linux::initial_thread_stack_bottom() +
1021                         os::Linux::initial_thread_stack_size()) {
1022     return true;
1023   } else {
1024     return false;
1025   }
1026 }
1027 
1028 // Find the virtual memory area that contains addr
1029 static bool find_vma(address addr, address* vma_low, address* vma_high) {
1030   FILE *fp = fopen("/proc/self/maps", "r");
1031   if (fp) {
1032     address low, high;
1033     while (!feof(fp)) {
1034       if (fscanf(fp, "%p-%p", &low, &high) == 2) {
1035         if (low <= addr && addr < high) {
1036           if (vma_low)  *vma_low  = low;
1037           if (vma_high) *vma_high = high;
1038           fclose(fp);
1039           return true;
1040         }
1041       }
1042       for (;;) {
1043         int ch = fgetc(fp);
1044         if (ch == EOF || ch == (int)'\n') break;
1045       }
1046     }
1047     fclose(fp);
1048   }
1049   return false;
1050 }
1051 
1052 // Locate primordial thread stack. This special handling of primordial thread stack
1053 // is needed because pthread_getattr_np() on most (all?) Linux distros returns
1054 // bogus value for the primordial process thread. While the launcher has created
1055 // the VM in a new thread since JDK 6, we still have to allow for the use of the
1056 // JNI invocation API from a primordial thread.
1057 void os::Linux::capture_initial_stack(size_t max_size) {
1058 
1059   // max_size is either 0 (which means accept OS default for thread stacks) or
1060   // a user-specified value known to be at least the minimum needed. If we
1061   // are actually on the primordial thread we can make it appear that we have a
1062   // smaller max_size stack by inserting the guard pages at that location. But we
1063   // cannot do anything to emulate a larger stack than what has been provided by
1064   // the OS or threading library. In fact if we try to use a stack greater than
1065   // what is set by rlimit then we will crash the hosting process.
1066 
1067   // Maximum stack size is the easy part, get it from RLIMIT_STACK.
1068   // If this is "unlimited" then it will be a huge value.
1069   struct rlimit rlim;
1070   getrlimit(RLIMIT_STACK, &rlim);
1071   size_t stack_size = rlim.rlim_cur;
1072 
1073   // 6308388: a bug in ld.so will relocate its own .data section to the
1074   //   lower end of primordial stack; reduce ulimit -s value a little bit
1075   //   so we won't install guard page on ld.so's data section.
1076   //   But ensure we don't underflow the stack size - allow 1 page spare
1077   if (stack_size >= (size_t)(3 * page_size())) {
1078     stack_size -= 2 * page_size();
1079   }
1080 
1081   // Try to figure out where the stack base (top) is. This is harder.
1082   //
1083   // When an application is started, glibc saves the initial stack pointer in
1084   // a global variable "__libc_stack_end", which is then used by system
1085   // libraries. __libc_stack_end should be pretty close to stack top. The
1086   // variable is available since the very early days. However, because it is
1087   // a private interface, it could disappear in the future.
1088   //
1089   // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar
1090   // to __libc_stack_end, it is very close to stack top, but isn't the real
1091   // stack top. Note that /proc may not exist if VM is running as a chroot
1092   // program, so reading /proc/<pid>/stat could fail. Also the contents of
1093   // /proc/<pid>/stat could change in the future (though unlikely).
1094   //
1095   // We try __libc_stack_end first. If that doesn't work, look for
1096   // /proc/<pid>/stat. If neither of them works, we use current stack pointer
1097   // as a hint, which should work well in most cases.
1098 
1099   uintptr_t stack_start;
1100 
1101   // try __libc_stack_end first
1102   uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end");
1103   if (p && *p) {
1104     stack_start = *p;
1105   } else {
1106     // see if we can get the start_stack field from /proc/self/stat
1107     FILE *fp;
1108     int pid;
1109     char state;
1110     int ppid;
1111     int pgrp;
1112     int session;
1113     int nr;
1114     int tpgrp;
1115     unsigned long flags;
1116     unsigned long minflt;
1117     unsigned long cminflt;
1118     unsigned long majflt;
1119     unsigned long cmajflt;
1120     unsigned long utime;
1121     unsigned long stime;
1122     long cutime;
1123     long cstime;
1124     long prio;
1125     long nice;
1126     long junk;
1127     long it_real;
1128     uintptr_t start;
1129     uintptr_t vsize;
1130     intptr_t rss;
1131     uintptr_t rsslim;
1132     uintptr_t scodes;
1133     uintptr_t ecode;
1134     int i;
1135 
1136     // Figure what the primordial thread stack base is. Code is inspired
1137     // by email from Hans Boehm. /proc/self/stat begins with current pid,
1138     // followed by command name surrounded by parentheses, state, etc.
1139     char stat[2048];
1140     int statlen;
1141 
1142     fp = fopen("/proc/self/stat", "r");
1143     if (fp) {
1144       statlen = fread(stat, 1, 2047, fp);
1145       stat[statlen] = '\0';
1146       fclose(fp);
1147 
1148       // Skip pid and the command string. Note that we could be dealing with
1149       // weird command names, e.g. user could decide to rename java launcher
1150       // to "java 1.4.2 :)", then the stat file would look like
1151       //                1234 (java 1.4.2 :)) R ... ...
1152       // We don't really need to know the command string, just find the last
1153       // occurrence of ")" and then start parsing from there. See bug 4726580.
1154       char * s = strrchr(stat, ')');
1155 
1156       i = 0;
1157       if (s) {
1158         // Skip blank chars
1159         do { s++; } while (s && isspace(*s));
1160 
1161 #define _UFM UINTX_FORMAT
1162 #define _DFM INTX_FORMAT
1163 
1164         //                                     1   1   1   1   1   1   1   1   1   1   2   2    2    2    2    2    2    2    2
1165         //              3  4  5  6  7  8   9   0   1   2   3   4   5   6   7   8   9   0   1    2    3    4    5    6    7    8
1166         i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " _UFM _UFM _DFM _UFM _UFM _UFM _UFM,
1167                    &state,          // 3  %c
1168                    &ppid,           // 4  %d
1169                    &pgrp,           // 5  %d
1170                    &session,        // 6  %d
1171                    &nr,             // 7  %d
1172                    &tpgrp,          // 8  %d
1173                    &flags,          // 9  %lu
1174                    &minflt,         // 10 %lu
1175                    &cminflt,        // 11 %lu
1176                    &majflt,         // 12 %lu
1177                    &cmajflt,        // 13 %lu
1178                    &utime,          // 14 %lu
1179                    &stime,          // 15 %lu
1180                    &cutime,         // 16 %ld
1181                    &cstime,         // 17 %ld
1182                    &prio,           // 18 %ld
1183                    &nice,           // 19 %ld
1184                    &junk,           // 20 %ld
1185                    &it_real,        // 21 %ld
1186                    &start,          // 22 UINTX_FORMAT
1187                    &vsize,          // 23 UINTX_FORMAT
1188                    &rss,            // 24 INTX_FORMAT
1189                    &rsslim,         // 25 UINTX_FORMAT
1190                    &scodes,         // 26 UINTX_FORMAT
1191                    &ecode,          // 27 UINTX_FORMAT
1192                    &stack_start);   // 28 UINTX_FORMAT
1193       }
1194 
1195 #undef _UFM
1196 #undef _DFM
1197 
1198       if (i != 28 - 2) {
1199         assert(false, "Bad conversion from /proc/self/stat");
1200         // product mode - assume we are the primordial thread, good luck in the
1201         // embedded case.
1202         warning("Can't detect primordial thread stack location - bad conversion");
1203         stack_start = (uintptr_t) &rlim;
1204       }
1205     } else {
1206       // For some reason we can't open /proc/self/stat (for example, running on
1207       // FreeBSD with a Linux emulator, or inside chroot), this should work for
1208       // most cases, so don't abort:
1209       warning("Can't detect primordial thread stack location - no /proc/self/stat");
1210       stack_start = (uintptr_t) &rlim;
1211     }
1212   }
1213 
1214   // Now we have a pointer (stack_start) very close to the stack top, the
1215   // next thing to do is to figure out the exact location of stack top. We
1216   // can find out the virtual memory area that contains stack_start by
1217   // reading /proc/self/maps, it should be the last vma in /proc/self/maps,
1218   // and its upper limit is the real stack top. (again, this would fail if
1219   // running inside chroot, because /proc may not exist.)
1220 
1221   uintptr_t stack_top;
1222   address low, high;
1223   if (find_vma((address)stack_start, &low, &high)) {
1224     // success, "high" is the true stack top. (ignore "low", because initial
1225     // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.)
1226     stack_top = (uintptr_t)high;
1227   } else {
1228     // failed, likely because /proc/self/maps does not exist
1229     warning("Can't detect primordial thread stack location - find_vma failed");
1230     // best effort: stack_start is normally within a few pages below the real
1231     // stack top, use it as stack top, and reduce stack size so we won't put
1232     // guard page outside stack.
1233     stack_top = stack_start;
1234     stack_size -= 16 * page_size();
1235   }
1236 
1237   // stack_top could be partially down the page so align it
1238   stack_top = align_up(stack_top, page_size());
1239 
1240   // Allowed stack value is minimum of max_size and what we derived from rlimit
1241   if (max_size > 0) {
1242     _initial_thread_stack_size = MIN2(max_size, stack_size);
1243   } else {
1244     // Accept the rlimit max, but if stack is unlimited then it will be huge, so
1245     // clamp it at 8MB as we do on Solaris
1246     _initial_thread_stack_size = MIN2(stack_size, 8*M);
1247   }
1248   _initial_thread_stack_size = align_down(_initial_thread_stack_size, page_size());
1249   _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size;
1250 
1251   assert(_initial_thread_stack_bottom < (address)stack_top, "overflow!");
1252 
1253   if (log_is_enabled(Info, os, thread)) {
1254     // See if we seem to be on primordial process thread
1255     bool primordial = uintptr_t(&rlim) > uintptr_t(_initial_thread_stack_bottom) &&
1256                       uintptr_t(&rlim) < stack_top;
1257 
1258     log_info(os, thread)("Capturing initial stack in %s thread: req. size: " SIZE_FORMAT "K, actual size: "
1259                          SIZE_FORMAT "K, top=" INTPTR_FORMAT ", bottom=" INTPTR_FORMAT,
1260                          primordial ? "primordial" : "user", max_size / K,  _initial_thread_stack_size / K,
1261                          stack_top, intptr_t(_initial_thread_stack_bottom));
1262   }
1263 }
1264 
1265 ////////////////////////////////////////////////////////////////////////////////
1266 // time support
1267 double os::elapsedVTime() {
1268   struct rusage usage;
1269   int retval = getrusage(RUSAGE_THREAD, &usage);
1270   if (retval == 0) {
1271     return (double) (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + (double) (usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / (1000 * 1000);
1272   } else {
1273     // better than nothing, but not much
1274     return elapsedTime();
1275   }
1276 }
1277 
1278 void os::Linux::fast_thread_clock_init() {
1279   if (!UseLinuxPosixThreadCPUClocks) {
1280     return;
1281   }
1282   clockid_t clockid;
1283   struct timespec tp;
1284   int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) =
1285       (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid");
1286 
1287   // Switch to using fast clocks for thread cpu time if
1288   // the clock_getres() returns 0 error code.
1289   // Note, that some kernels may support the current thread
1290   // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks
1291   // returned by the pthread_getcpuclockid().
1292   // If the fast Posix clocks are supported then the clock_getres()
1293   // must return at least tp.tv_sec == 0 which means a resolution
1294   // better than 1 sec. This is extra check for reliability.
1295 
1296   if (pthread_getcpuclockid_func &&
1297       pthread_getcpuclockid_func(_main_thread, &clockid) == 0 &&
1298       clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) {
1299     _supports_fast_thread_cpu_time = true;
1300     _pthread_getcpuclockid = pthread_getcpuclockid_func;
1301   }
1302 }
1303 
1304 // thread_id is kernel thread id (similar to Solaris LWP id)
1305 intx os::current_thread_id() { return os::Linux::gettid(); }
1306 int os::current_process_id() {
1307   return ::getpid();
1308 }
1309 
1310 // DLL functions
1311 
1312 const char* os::dll_file_extension() { return ".so"; }
1313 
1314 // This must be hard coded because it's the system's temporary
1315 // directory not the java application's temp directory, ala java.io.tmpdir.
1316 const char* os::get_temp_directory() { return "/tmp"; }
1317 
1318 // check if addr is inside libjvm.so
1319 bool os::address_is_in_vm(address addr) {
1320   static address libjvm_base_addr;
1321   Dl_info dlinfo;
1322 
1323   if (libjvm_base_addr == NULL) {
1324     if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) {
1325       libjvm_base_addr = (address)dlinfo.dli_fbase;
1326     }
1327     assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm");
1328   }
1329 
1330   if (dladdr((void *)addr, &dlinfo) != 0) {
1331     if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true;
1332   }
1333 
1334   return false;
1335 }
1336 
1337 bool os::dll_address_to_function_name(address addr, char *buf,
1338                                       int buflen, int *offset,
1339                                       bool demangle) {
1340   // buf is not optional, but offset is optional
1341   assert(buf != NULL, "sanity check");
1342 
1343   Dl_info dlinfo;
1344 
1345   if (dladdr((void*)addr, &dlinfo) != 0) {
1346     // see if we have a matching symbol
1347     if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) {
1348       if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) {
1349         jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname);
1350       }
1351       if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr;
1352       return true;
1353     }
1354     // no matching symbol so try for just file info
1355     if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) {
1356       if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase),
1357                           buf, buflen, offset, dlinfo.dli_fname, demangle)) {
1358         return true;
1359       }
1360     }
1361   }
1362 
1363   buf[0] = '\0';
1364   if (offset != NULL) *offset = -1;
1365   return false;
1366 }
1367 
1368 struct _address_to_library_name {
1369   address addr;          // input : memory address
1370   size_t  buflen;        //         size of fname
1371   char*   fname;         // output: library name
1372   address base;          //         library base addr
1373 };
1374 
1375 static int address_to_library_name_callback(struct dl_phdr_info *info,
1376                                             size_t size, void *data) {
1377   int i;
1378   bool found = false;
1379   address libbase = NULL;
1380   struct _address_to_library_name * d = (struct _address_to_library_name *)data;
1381 
1382   // iterate through all loadable segments
1383   for (i = 0; i < info->dlpi_phnum; i++) {
1384     address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1385     if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1386       // base address of a library is the lowest address of its loaded
1387       // segments.
1388       if (libbase == NULL || libbase > segbase) {
1389         libbase = segbase;
1390       }
1391       // see if 'addr' is within current segment
1392       if (segbase <= d->addr &&
1393           d->addr < segbase + info->dlpi_phdr[i].p_memsz) {
1394         found = true;
1395       }
1396     }
1397   }
1398 
1399   // dlpi_name is NULL or empty if the ELF file is executable, return 0
1400   // so dll_address_to_library_name() can fall through to use dladdr() which
1401   // can figure out executable name from argv[0].
1402   if (found && info->dlpi_name && info->dlpi_name[0]) {
1403     d->base = libbase;
1404     if (d->fname) {
1405       jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name);
1406     }
1407     return 1;
1408   }
1409   return 0;
1410 }
1411 
1412 bool os::dll_address_to_library_name(address addr, char* buf,
1413                                      int buflen, int* offset) {
1414   // buf is not optional, but offset is optional
1415   assert(buf != NULL, "sanity check");
1416 
1417   Dl_info dlinfo;
1418   struct _address_to_library_name data;
1419 
1420   // There is a bug in old glibc dladdr() implementation that it could resolve
1421   // to wrong library name if the .so file has a base address != NULL. Here
1422   // we iterate through the program headers of all loaded libraries to find
1423   // out which library 'addr' really belongs to. This workaround can be
1424   // removed once the minimum requirement for glibc is moved to 2.3.x.
1425   data.addr = addr;
1426   data.fname = buf;
1427   data.buflen = buflen;
1428   data.base = NULL;
1429   int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data);
1430 
1431   if (rslt) {
1432     // buf already contains library name
1433     if (offset) *offset = addr - data.base;
1434     return true;
1435   }
1436   if (dladdr((void*)addr, &dlinfo) != 0) {
1437     if (dlinfo.dli_fname != NULL) {
1438       jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname);
1439     }
1440     if (dlinfo.dli_fbase != NULL && offset != NULL) {
1441       *offset = addr - (address)dlinfo.dli_fbase;
1442     }
1443     return true;
1444   }
1445 
1446   buf[0] = '\0';
1447   if (offset) *offset = -1;
1448   return false;
1449 }
1450 
1451 // Loads .dll/.so and
1452 // in case of error it checks if .dll/.so was built for the
1453 // same architecture as Hotspot is running on
1454 
1455 
1456 // Remember the stack's state. The Linux dynamic linker will change
1457 // the stack to 'executable' at most once, so we must safepoint only once.
1458 bool os::Linux::_stack_is_executable = false;
1459 
1460 // VM operation that loads a library.  This is necessary if stack protection
1461 // of the Java stacks can be lost during loading the library.  If we
1462 // do not stop the Java threads, they can stack overflow before the stacks
1463 // are protected again.
1464 class VM_LinuxDllLoad: public VM_Operation {
1465  private:
1466   const char *_filename;
1467   char *_ebuf;
1468   int _ebuflen;
1469   void *_lib;
1470  public:
1471   VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
1472     _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}
1473   VMOp_Type type() const { return VMOp_LinuxDllLoad; }
1474   void doit() {
1475     _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
1476     os::Linux::_stack_is_executable = true;
1477   }
1478   void* loaded_library() { return _lib; }
1479 };
1480 
1481 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) {
1482   void * result = NULL;
1483   bool load_attempted = false;
1484 
1485   log_info(os)("attempting shared library load of %s", filename);
1486 
1487   // Check whether the library to load might change execution rights
1488   // of the stack. If they are changed, the protection of the stack
1489   // guard pages will be lost. We need a safepoint to fix this.
1490   //
1491   // See Linux man page execstack(8) for more info.
1492   if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
1493     if (!ElfFile::specifies_noexecstack(filename)) {
1494       if (!is_init_completed()) {
1495         os::Linux::_stack_is_executable = true;
1496         // This is OK - No Java threads have been created yet, and hence no
1497         // stack guard pages to fix.
1498         //
1499         // Dynamic loader will make all stacks executable after
1500         // this function returns, and will not do that again.
1501         assert(Threads::number_of_threads() == 0, "no Java threads should exist yet.");
1502       } else {
1503         warning("You have loaded library %s which might have disabled stack guard. "
1504                 "The VM will try to fix the stack guard now.\n"
1505                 "It's highly recommended that you fix the library with "
1506                 "'execstack -c <libfile>', or link it with '-z noexecstack'.",
1507                 filename);
1508 
1509         JavaThread *jt = JavaThread::current();
1510         if (jt->thread_state() != _thread_in_native) {
1511           // This happens when a compiler thread tries to load a hsdis-<arch>.so file
1512           // that requires ExecStack. Cannot enter safe point. Let's give up.
1513           warning("Unable to fix stack guard. Giving up.");
1514         } else {
1515           if (!LoadExecStackDllInVMThread) {
1516             // This is for the case where the DLL has an static
1517             // constructor function that executes JNI code. We cannot
1518             // load such DLLs in the VMThread.
1519             result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1520           }
1521 
1522           ThreadInVMfromNative tiv(jt);
1523           debug_only(VMNativeEntryWrapper vew;)
1524 
1525           VM_LinuxDllLoad op(filename, ebuf, ebuflen);
1526           VMThread::execute(&op);
1527           if (LoadExecStackDllInVMThread) {
1528             result = op.loaded_library();
1529           }
1530           load_attempted = true;
1531         }
1532       }
1533     }
1534   }
1535 
1536   if (!load_attempted) {
1537     result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
1538   }
1539 
1540   if (result != NULL) {
1541     // Successful loading
1542     return result;
1543   }
1544 
1545   Elf32_Ehdr elf_head;
1546   int diag_msg_max_length=ebuflen-strlen(ebuf);
1547   char* diag_msg_buf=ebuf+strlen(ebuf);
1548 
1549   if (diag_msg_max_length==0) {
1550     // No more space in ebuf for additional diagnostics message
1551     return NULL;
1552   }
1553 
1554 
1555   int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK);
1556 
1557   if (file_descriptor < 0) {
1558     // Can't open library, report dlerror() message
1559     return NULL;
1560   }
1561 
1562   bool failed_to_read_elf_head=
1563     (sizeof(elf_head)!=
1564      (::read(file_descriptor, &elf_head,sizeof(elf_head))));
1565 
1566   ::close(file_descriptor);
1567   if (failed_to_read_elf_head) {
1568     // file i/o error - report dlerror() msg
1569     return NULL;
1570   }
1571 
1572   if (elf_head.e_ident[EI_DATA] != LITTLE_ENDIAN_ONLY(ELFDATA2LSB) BIG_ENDIAN_ONLY(ELFDATA2MSB)) {
1573     // handle invalid/out of range endianness values
1574     if (elf_head.e_ident[EI_DATA] == 0 || elf_head.e_ident[EI_DATA] > 2) {
1575       return NULL;
1576     }
1577 
1578 #if defined(VM_LITTLE_ENDIAN)
1579     // VM is LE, shared object BE
1580     elf_head.e_machine = be16toh(elf_head.e_machine);
1581 #else
1582     // VM is BE, shared object LE
1583     elf_head.e_machine = le16toh(elf_head.e_machine);
1584 #endif
1585   }
1586 
1587   typedef struct {
1588     Elf32_Half    code;         // Actual value as defined in elf.h
1589     Elf32_Half    compat_class; // Compatibility of archs at VM's sense
1590     unsigned char elf_class;    // 32 or 64 bit
1591     unsigned char endianness;   // MSB or LSB
1592     char*         name;         // String representation
1593   } arch_t;
1594 
1595 #ifndef EM_AARCH64
1596   #define EM_AARCH64    183               /* ARM AARCH64 */
1597 #endif
1598 #ifndef EM_RISCV
1599   #define EM_RISCV      243               /* RISC-V */
1600 #endif
1601 #ifndef EM_LOONGARCH
1602   #define EM_LOONGARCH  258               /* LoongArch */
1603 #endif
1604 
1605   static const arch_t arch_array[]={
1606     {EM_386,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1607     {EM_486,         EM_386,     ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"},
1608     {EM_IA_64,       EM_IA_64,   ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"},
1609     {EM_X86_64,      EM_X86_64,  ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"},
1610     {EM_SPARC,       EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1611     {EM_SPARC32PLUS, EM_SPARC,   ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"},
1612     {EM_SPARCV9,     EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"},
1613     {EM_PPC,         EM_PPC,     ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"},
1614 #if defined(VM_LITTLE_ENDIAN)
1615     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2LSB, (char*)"Power PC 64 LE"},
1616     {EM_SH,          EM_SH,      ELFCLASS32, ELFDATA2LSB, (char*)"SuperH"},
1617 #else
1618     {EM_PPC64,       EM_PPC64,   ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"},
1619     {EM_SH,          EM_SH,      ELFCLASS32, ELFDATA2MSB, (char*)"SuperH BE"},
1620 #endif
1621     {EM_ARM,         EM_ARM,     ELFCLASS32, ELFDATA2LSB, (char*)"ARM"},
1622     // we only support 64 bit z architecture
1623     {EM_S390,        EM_S390,    ELFCLASS64, ELFDATA2MSB, (char*)"IBM System/390"},
1624     {EM_ALPHA,       EM_ALPHA,   ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"},
1625     {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"},
1626     {EM_MIPS,        EM_MIPS,    ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"},
1627     {EM_PARISC,      EM_PARISC,  ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"},
1628     {EM_68K,         EM_68K,     ELFCLASS32, ELFDATA2MSB, (char*)"M68k"},
1629     {EM_AARCH64,     EM_AARCH64, ELFCLASS64, ELFDATA2LSB, (char*)"AARCH64"},
1630     {EM_RISCV,       EM_RISCV,   ELFCLASS64, ELFDATA2LSB, (char*)"RISC-V"},
1631     {EM_LOONGARCH,   EM_LOONGARCH, ELFCLASS64, ELFDATA2LSB, (char*)"LoongArch"},
1632   };
1633 
1634 #if  (defined IA32)
1635   static  Elf32_Half running_arch_code=EM_386;
1636 #elif   (defined AMD64) || (defined X32)
1637   static  Elf32_Half running_arch_code=EM_X86_64;
1638 #elif  (defined IA64)
1639   static  Elf32_Half running_arch_code=EM_IA_64;
1640 #elif  (defined __sparc) && (defined _LP64)
1641   static  Elf32_Half running_arch_code=EM_SPARCV9;
1642 #elif  (defined __sparc) && (!defined _LP64)
1643   static  Elf32_Half running_arch_code=EM_SPARC;
1644 #elif  (defined __powerpc64__)
1645   static  Elf32_Half running_arch_code=EM_PPC64;
1646 #elif  (defined __powerpc__)
1647   static  Elf32_Half running_arch_code=EM_PPC;
1648 #elif  (defined AARCH64)
1649   static  Elf32_Half running_arch_code=EM_AARCH64;
1650 #elif  (defined ARM)
1651   static  Elf32_Half running_arch_code=EM_ARM;
1652 #elif  (defined S390)
1653   static  Elf32_Half running_arch_code=EM_S390;
1654 #elif  (defined ALPHA)
1655   static  Elf32_Half running_arch_code=EM_ALPHA;
1656 #elif  (defined MIPSEL)
1657   static  Elf32_Half running_arch_code=EM_MIPS_RS3_LE;
1658 #elif  (defined PARISC)
1659   static  Elf32_Half running_arch_code=EM_PARISC;
1660 #elif  (defined MIPS)
1661   static  Elf32_Half running_arch_code=EM_MIPS;
1662 #elif  (defined M68K)
1663   static  Elf32_Half running_arch_code=EM_68K;
1664 #elif  (defined SH)
1665   static  Elf32_Half running_arch_code=EM_SH;
1666 #elif  (defined RISCV)
1667   static  Elf32_Half running_arch_code=EM_RISCV;
1668 #elif  (defined LOONGARCH)
1669   static  Elf32_Half running_arch_code=EM_LOONGARCH;
1670 #else
1671     #error Method os::dll_load requires that one of following is defined:\
1672         AARCH64, ALPHA, ARM, AMD64, IA32, IA64, LOONGARCH, M68K, MIPS, MIPSEL, PARISC, __powerpc__, __powerpc64__, RISCV, S390, SH, __sparc
1673 #endif
1674 
1675   // Identify compatibility class for VM's architecture and library's architecture
1676   // Obtain string descriptions for architectures
1677 
1678   arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL};
1679   int running_arch_index=-1;
1680 
1681   for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) {
1682     if (running_arch_code == arch_array[i].code) {
1683       running_arch_index    = i;
1684     }
1685     if (lib_arch.code == arch_array[i].code) {
1686       lib_arch.compat_class = arch_array[i].compat_class;
1687       lib_arch.name         = arch_array[i].name;
1688     }
1689   }
1690 
1691   assert(running_arch_index != -1,
1692          "Didn't find running architecture code (running_arch_code) in arch_array");
1693   if (running_arch_index == -1) {
1694     // Even though running architecture detection failed
1695     // we may still continue with reporting dlerror() message
1696     return NULL;
1697   }
1698 
1699   if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) {
1700     if (lib_arch.name != NULL) {
1701       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1702                  " (Possible cause: can't load %s .so on a %s platform)",
1703                  lib_arch.name, arch_array[running_arch_index].name);
1704     } else {
1705       ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1706                  " (Possible cause: can't load this .so (machine code=0x%x) on a %s platform)",
1707                  lib_arch.code, arch_array[running_arch_index].name);
1708     }
1709     return NULL;
1710   }
1711 
1712   if (lib_arch.endianness != arch_array[running_arch_index].endianness) {
1713     ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: endianness mismatch)");
1714     return NULL;
1715   }
1716 
1717   // ELF file class/capacity : 0 - invalid, 1 - 32bit, 2 - 64bit
1718   if (lib_arch.elf_class > 2 || lib_arch.elf_class < 1) {
1719     ::snprintf(diag_msg_buf, diag_msg_max_length-1, " (Possible cause: invalid ELF file class)");
1720     return NULL;
1721   }
1722 
1723   if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) {
1724     ::snprintf(diag_msg_buf, diag_msg_max_length-1,
1725                " (Possible cause: architecture word width mismatch, can't load %d-bit .so on a %d-bit platform)",
1726                (int) lib_arch.elf_class * 32, arch_array[running_arch_index].elf_class * 32);
1727     return NULL;
1728   }
1729 
1730   return NULL;
1731 }
1732 
1733 void * os::Linux::dlopen_helper(const char *filename, char *ebuf,
1734                                 int ebuflen) {
1735   void * result = ::dlopen(filename, RTLD_LAZY);
1736   if (result == NULL) {
1737     const char* error_report = ::dlerror();
1738     if (error_report == NULL) {
1739       error_report = "dlerror returned no error description";
1740     }
1741     if (ebuf != NULL && ebuflen > 0) {
1742       ::strncpy(ebuf, error_report, ebuflen-1);
1743       ebuf[ebuflen-1]='\0';
1744     }
1745     Events::log(NULL, "Loading shared library %s failed, %s", filename, error_report);
1746     log_info(os)("shared library load of %s failed, %s", filename, error_report);
1747   } else {
1748     Events::log(NULL, "Loaded shared library %s", filename);
1749     log_info(os)("shared library load of %s was successful", filename);
1750   }
1751   return result;
1752 }
1753 
1754 void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf,
1755                                        int ebuflen) {
1756   void * result = NULL;
1757   if (LoadExecStackDllInVMThread) {
1758     result = dlopen_helper(filename, ebuf, ebuflen);
1759   }
1760 
1761   // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
1762   // library that requires an executable stack, or which does not have this
1763   // stack attribute set, dlopen changes the stack attribute to executable. The
1764   // read protection of the guard pages gets lost.
1765   //
1766   // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
1767   // may have been queued at the same time.
1768 
1769   if (!_stack_is_executable) {
1770     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1771       StackOverflow* overflow_state = jt->stack_overflow_state();
1772       if (!overflow_state->stack_guard_zone_unused() &&     // Stack not yet fully initialized
1773           overflow_state->stack_guards_enabled()) {         // No pending stack overflow exceptions
1774         if (!os::guard_memory((char *)jt->stack_end(), StackOverflow::stack_guard_zone_size())) {
1775           warning("Attempt to reguard stack yellow zone failed.");
1776         }
1777       }
1778     }
1779   }
1780 
1781   return result;
1782 }
1783 
1784 static bool _print_ascii_file(const char* filename, outputStream* st, const char* hdr = NULL) {
1785   int fd = ::open(filename, O_RDONLY);
1786   if (fd == -1) {
1787     return false;
1788   }
1789 
1790   if (hdr != NULL) {
1791     st->print_cr("%s", hdr);
1792   }
1793 
1794   char buf[33];
1795   int bytes;
1796   buf[32] = '\0';
1797   while ((bytes = ::read(fd, buf, sizeof(buf)-1)) > 0) {
1798     st->print_raw(buf, bytes);
1799   }
1800 
1801   ::close(fd);
1802 
1803   return true;
1804 }
1805 
1806 static void _print_ascii_file_h(const char* header, const char* filename, outputStream* st, bool same_line = true) {
1807   st->print("%s:%c", header, same_line ? ' ' : '\n');
1808   if (!_print_ascii_file(filename, st)) {
1809     st->print_cr("<Not Available>");
1810   }
1811 }
1812 
1813 void os::print_dll_info(outputStream *st) {
1814   st->print_cr("Dynamic libraries:");
1815 
1816   char fname[32];
1817   pid_t pid = os::Linux::gettid();
1818 
1819   jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid);
1820 
1821   if (!_print_ascii_file(fname, st)) {
1822     st->print_cr("Can not get library information for pid = %d", pid);
1823   }
1824 }
1825 
1826 struct loaded_modules_info_param {
1827   os::LoadedModulesCallbackFunc callback;
1828   void *param;
1829 };
1830 
1831 static int dl_iterate_callback(struct dl_phdr_info *info, size_t size, void *data) {
1832   if ((info->dlpi_name == NULL) || (*info->dlpi_name == '\0')) {
1833     return 0;
1834   }
1835 
1836   struct loaded_modules_info_param *callback_param = reinterpret_cast<struct loaded_modules_info_param *>(data);
1837   address base = NULL;
1838   address top = NULL;
1839   for (int idx = 0; idx < info->dlpi_phnum; idx++) {
1840     const ElfW(Phdr) *phdr = info->dlpi_phdr + idx;
1841     if (phdr->p_type == PT_LOAD) {
1842       address raw_phdr_base = reinterpret_cast<address>(info->dlpi_addr + phdr->p_vaddr);
1843 
1844       address phdr_base = align_down(raw_phdr_base, phdr->p_align);
1845       if ((base == NULL) || (base > phdr_base)) {
1846         base = phdr_base;
1847       }
1848 
1849       address phdr_top = align_up(raw_phdr_base + phdr->p_memsz, phdr->p_align);
1850       if ((top == NULL) || (top < phdr_top)) {
1851         top = phdr_top;
1852       }
1853     }
1854   }
1855 
1856   return callback_param->callback(info->dlpi_name, base, top, callback_param->param);
1857 }
1858 
1859 int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) {
1860   struct loaded_modules_info_param callback_param = {callback, param};
1861   return dl_iterate_phdr(&dl_iterate_callback, &callback_param);
1862 }
1863 
1864 void os::print_os_info_brief(outputStream* st) {
1865   os::Linux::print_distro_info(st);
1866 
1867   os::Posix::print_uname_info(st);
1868 
1869   os::Linux::print_libversion_info(st);
1870 
1871 }
1872 
1873 void os::print_os_info(outputStream* st) {
1874   st->print_cr("OS:");
1875 
1876   os::Linux::print_distro_info(st);
1877 
1878   os::Posix::print_uname_info(st);
1879 
1880   os::Linux::print_uptime_info(st);
1881 
1882   // Print warning if unsafe chroot environment detected
1883   if (unsafe_chroot_detected) {
1884     st->print_cr("WARNING!! %s", unstable_chroot_error);
1885   }
1886 
1887   os::Linux::print_libversion_info(st);
1888 
1889   os::Posix::print_rlimit_info(st);
1890 
1891   os::Posix::print_load_average(st);
1892   st->cr();
1893 
1894   os::Linux::print_system_memory_info(st);
1895   st->cr();
1896 
1897   os::Linux::print_process_memory_info(st);
1898   st->cr();
1899 
1900   os::Linux::print_proc_sys_info(st);
1901   st->cr();
1902 
1903   if (os::Linux::print_ld_preload_file(st)) {
1904     st->cr();
1905   }
1906 
1907   if (os::Linux::print_container_info(st)) {
1908     st->cr();
1909   }
1910 
1911   VM_Version::print_platform_virtualization_info(st);
1912 
1913   os::Linux::print_steal_info(st);
1914 }
1915 
1916 // Try to identify popular distros.
1917 // Most Linux distributions have a /etc/XXX-release file, which contains
1918 // the OS version string. Newer Linux distributions have a /etc/lsb-release
1919 // file that also contains the OS version string. Some have more than one
1920 // /etc/XXX-release file (e.g. Mandrake has both /etc/mandrake-release and
1921 // /etc/redhat-release.), so the order is important.
1922 // Any Linux that is based on Redhat (i.e. Oracle, Mandrake, Sun JDS...) have
1923 // their own specific XXX-release file as well as a redhat-release file.
1924 // Because of this the XXX-release file needs to be searched for before the
1925 // redhat-release file.
1926 // Since Red Hat and SuSE have an lsb-release file that is not very descriptive the
1927 // search for redhat-release / SuSE-release needs to be before lsb-release.
1928 // Since the lsb-release file is the new standard it needs to be searched
1929 // before the older style release files.
1930 // Searching system-release (Red Hat) and os-release (other Linuxes) are a
1931 // next to last resort.  The os-release file is a new standard that contains
1932 // distribution information and the system-release file seems to be an old
1933 // standard that has been replaced by the lsb-release and os-release files.
1934 // Searching for the debian_version file is the last resort.  It contains
1935 // an informative string like "6.0.6" or "wheezy/sid". Because of this
1936 // "Debian " is printed before the contents of the debian_version file.
1937 
1938 const char* distro_files[] = {
1939   "/etc/oracle-release",
1940   "/etc/mandriva-release",
1941   "/etc/mandrake-release",
1942   "/etc/sun-release",
1943   "/etc/redhat-release",
1944   "/etc/SuSE-release",
1945   "/etc/lsb-release",
1946   "/etc/turbolinux-release",
1947   "/etc/gentoo-release",
1948   "/etc/ltib-release",
1949   "/etc/angstrom-version",
1950   "/etc/system-release",
1951   "/etc/os-release",
1952   NULL };
1953 
1954 void os::Linux::print_distro_info(outputStream* st) {
1955   for (int i = 0;; i++) {
1956     const char* file = distro_files[i];
1957     if (file == NULL) {
1958       break;  // done
1959     }
1960     // If file prints, we found it.
1961     if (_print_ascii_file(file, st)) {
1962       return;
1963     }
1964   }
1965 
1966   if (file_exists("/etc/debian_version")) {
1967     st->print("Debian ");
1968     _print_ascii_file("/etc/debian_version", st);
1969   } else {
1970     st->print_cr("Linux");
1971   }
1972 }
1973 
1974 static void parse_os_info_helper(FILE* fp, char* distro, size_t length, bool get_first_line) {
1975   char buf[256];
1976   while (fgets(buf, sizeof(buf), fp)) {
1977     // Edit out extra stuff in expected format
1978     if (strstr(buf, "DISTRIB_DESCRIPTION=") != NULL || strstr(buf, "PRETTY_NAME=") != NULL) {
1979       char* ptr = strstr(buf, "\"");  // the name is in quotes
1980       if (ptr != NULL) {
1981         ptr++; // go beyond first quote
1982         char* nl = strchr(ptr, '\"');
1983         if (nl != NULL) *nl = '\0';
1984         strncpy(distro, ptr, length);
1985       } else {
1986         ptr = strstr(buf, "=");
1987         ptr++; // go beyond equals then
1988         char* nl = strchr(ptr, '\n');
1989         if (nl != NULL) *nl = '\0';
1990         strncpy(distro, ptr, length);
1991       }
1992       return;
1993     } else if (get_first_line) {
1994       char* nl = strchr(buf, '\n');
1995       if (nl != NULL) *nl = '\0';
1996       strncpy(distro, buf, length);
1997       return;
1998     }
1999   }
2000   // print last line and close
2001   char* nl = strchr(buf, '\n');
2002   if (nl != NULL) *nl = '\0';
2003   strncpy(distro, buf, length);
2004 }
2005 
2006 static void parse_os_info(char* distro, size_t length, const char* file) {
2007   FILE* fp = fopen(file, "r");
2008   if (fp != NULL) {
2009     // if suse format, print out first line
2010     bool get_first_line = (strcmp(file, "/etc/SuSE-release") == 0);
2011     parse_os_info_helper(fp, distro, length, get_first_line);
2012     fclose(fp);
2013   }
2014 }
2015 
2016 void os::get_summary_os_info(char* buf, size_t buflen) {
2017   for (int i = 0;; i++) {
2018     const char* file = distro_files[i];
2019     if (file == NULL) {
2020       break; // ran out of distro_files
2021     }
2022     if (file_exists(file)) {
2023       parse_os_info(buf, buflen, file);
2024       return;
2025     }
2026   }
2027   // special case for debian
2028   if (file_exists("/etc/debian_version")) {
2029     strncpy(buf, "Debian ", buflen);
2030     if (buflen > 7) {
2031       parse_os_info(&buf[7], buflen-7, "/etc/debian_version");
2032     }
2033   } else {
2034     strncpy(buf, "Linux", buflen);
2035   }
2036 }
2037 
2038 void os::Linux::print_libversion_info(outputStream* st) {
2039   // libc, pthread
2040   st->print("libc: ");
2041   st->print("%s ", os::Linux::libc_version());
2042   st->print("%s ", os::Linux::libpthread_version());
2043   st->cr();
2044 }
2045 
2046 void os::Linux::print_proc_sys_info(outputStream* st) {
2047   _print_ascii_file_h("/proc/sys/kernel/threads-max (system-wide limit on the number of threads)",
2048                       "/proc/sys/kernel/threads-max", st);
2049   _print_ascii_file_h("/proc/sys/vm/max_map_count (maximum number of memory map areas a process may have)",
2050                       "/proc/sys/vm/max_map_count", st);
2051   _print_ascii_file_h("/proc/sys/kernel/pid_max (system-wide limit on number of process identifiers)",
2052                       "/proc/sys/kernel/pid_max", st);
2053 }
2054 
2055 void os::Linux::print_system_memory_info(outputStream* st) {
2056   _print_ascii_file_h("/proc/meminfo", "/proc/meminfo", st, false);
2057   st->cr();
2058 
2059   // some information regarding THPs; for details see
2060   // https://www.kernel.org/doc/Documentation/vm/transhuge.txt
2061   _print_ascii_file_h("/sys/kernel/mm/transparent_hugepage/enabled",
2062                       "/sys/kernel/mm/transparent_hugepage/enabled", st);
2063   _print_ascii_file_h("/sys/kernel/mm/transparent_hugepage/defrag (defrag/compaction efforts parameter)",
2064                       "/sys/kernel/mm/transparent_hugepage/defrag", st);
2065 }
2066 
2067 bool os::Linux::query_process_memory_info(os::Linux::meminfo_t* info) {
2068   FILE* f = ::fopen("/proc/self/status", "r");
2069   const int num_values = sizeof(os::Linux::meminfo_t) / sizeof(size_t);
2070   int num_found = 0;
2071   char buf[256];
2072   info->vmsize = info->vmpeak = info->vmrss = info->vmhwm = info->vmswap =
2073       info->rssanon = info->rssfile = info->rssshmem = -1;
2074   if (f != NULL) {
2075     while (::fgets(buf, sizeof(buf), f) != NULL && num_found < num_values) {
2076       if ( (info->vmsize == -1    && sscanf(buf, "VmSize: " SSIZE_FORMAT " kB", &info->vmsize) == 1) ||
2077            (info->vmpeak == -1    && sscanf(buf, "VmPeak: " SSIZE_FORMAT " kB", &info->vmpeak) == 1) ||
2078            (info->vmswap == -1    && sscanf(buf, "VmSwap: " SSIZE_FORMAT " kB", &info->vmswap) == 1) ||
2079            (info->vmhwm == -1     && sscanf(buf, "VmHWM: " SSIZE_FORMAT " kB", &info->vmhwm) == 1) ||
2080            (info->vmrss == -1     && sscanf(buf, "VmRSS: " SSIZE_FORMAT " kB", &info->vmrss) == 1) ||
2081            (info->rssanon == -1   && sscanf(buf, "RssAnon: " SSIZE_FORMAT " kB", &info->rssanon) == 1) || // Needs Linux 4.5
2082            (info->rssfile == -1   && sscanf(buf, "RssFile: " SSIZE_FORMAT " kB", &info->rssfile) == 1) || // Needs Linux 4.5
2083            (info->rssshmem == -1  && sscanf(buf, "RssShmem: " SSIZE_FORMAT " kB", &info->rssshmem) == 1)  // Needs Linux 4.5
2084            )
2085       {
2086         num_found ++;
2087       }
2088     }
2089     fclose(f);
2090     return true;
2091   }
2092   return false;
2093 }
2094 
2095 void os::Linux::print_process_memory_info(outputStream* st) {
2096 
2097   st->print_cr("Process Memory:");
2098 
2099   // Print virtual and resident set size; peak values; swap; and for
2100   //  rss its components if the kernel is recent enough.
2101   meminfo_t info;
2102   if (query_process_memory_info(&info)) {
2103     st->print_cr("Virtual Size: " SSIZE_FORMAT "K (peak: " SSIZE_FORMAT "K)", info.vmsize, info.vmpeak);
2104     st->print("Resident Set Size: " SSIZE_FORMAT "K (peak: " SSIZE_FORMAT "K)", info.vmrss, info.vmhwm);
2105     if (info.rssanon != -1) { // requires kernel >= 4.5
2106       st->print(" (anon: " SSIZE_FORMAT "K, file: " SSIZE_FORMAT "K, shmem: " SSIZE_FORMAT "K)",
2107                 info.rssanon, info.rssfile, info.rssshmem);
2108     }
2109     st->cr();
2110     if (info.vmswap != -1) { // requires kernel >= 2.6.34
2111       st->print_cr("Swapped out: " SSIZE_FORMAT "K", info.vmswap);
2112     }
2113   } else {
2114     st->print_cr("Could not open /proc/self/status to get process memory related information");
2115   }
2116 
2117   // Print glibc outstanding allocations.
2118   // (note: there is no implementation of mallinfo for muslc)
2119 #ifdef __GLIBC__
2120   size_t total_allocated = 0;
2121   bool might_have_wrapped = false;
2122   if (_mallinfo2 != NULL) {
2123     struct glibc_mallinfo2 mi = _mallinfo2();
2124     total_allocated = mi.uordblks;
2125   } else if (_mallinfo != NULL) {
2126     // mallinfo is an old API. Member names mean next to nothing and, beyond that, are int.
2127     // So values may have wrapped around. Still useful enough to see how much glibc thinks
2128     // we allocated.
2129     struct glibc_mallinfo mi = _mallinfo();
2130     total_allocated = (size_t)(unsigned)mi.uordblks;
2131     // Since mallinfo members are int, glibc values may have wrapped. Warn about this.
2132     might_have_wrapped = (info.vmrss * K) > UINT_MAX && (info.vmrss * K) > (total_allocated + UINT_MAX);
2133   }
2134   if (_mallinfo2 != NULL || _mallinfo != NULL) {
2135     st->print_cr("C-Heap outstanding allocations: " SIZE_FORMAT "K%s",
2136                  total_allocated / K,
2137                  might_have_wrapped ? " (may have wrapped)" : "");
2138   }
2139 #endif // __GLIBC__
2140 
2141 }
2142 
2143 bool os::Linux::print_ld_preload_file(outputStream* st) {
2144   return _print_ascii_file("/etc/ld.so.preload", st, "/etc/ld.so.preload:");
2145 }
2146 
2147 void os::Linux::print_uptime_info(outputStream* st) {
2148   struct sysinfo sinfo;
2149   int ret = sysinfo(&sinfo);
2150   if (ret == 0) {
2151     os::print_dhm(st, "OS uptime:", (long) sinfo.uptime);
2152   }
2153 }
2154 
2155 bool os::Linux::print_container_info(outputStream* st) {
2156   if (!OSContainer::is_containerized()) {
2157     st->print_cr("container information not found.");
2158     return false;
2159   }
2160 
2161   st->print_cr("container (cgroup) information:");
2162 
2163   const char *p_ct = OSContainer::container_type();
2164   st->print_cr("container_type: %s", p_ct != NULL ? p_ct : "not supported");
2165 
2166   char *p = OSContainer::cpu_cpuset_cpus();
2167   st->print_cr("cpu_cpuset_cpus: %s", p != NULL ? p : "not supported");
2168   free(p);
2169 
2170   p = OSContainer::cpu_cpuset_memory_nodes();
2171   st->print_cr("cpu_memory_nodes: %s", p != NULL ? p : "not supported");
2172   free(p);
2173 
2174   int i = OSContainer::active_processor_count();
2175   st->print("active_processor_count: ");
2176   if (i > 0) {
2177     st->print_cr("%d", i);
2178   } else {
2179     st->print_cr("not supported");
2180   }
2181 
2182   i = OSContainer::cpu_quota();
2183   st->print("cpu_quota: ");
2184   if (i > 0) {
2185     st->print_cr("%d", i);
2186   } else {
2187     st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no quota");
2188   }
2189 
2190   i = OSContainer::cpu_period();
2191   st->print("cpu_period: ");
2192   if (i > 0) {
2193     st->print_cr("%d", i);
2194   } else {
2195     st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no period");
2196   }
2197 
2198   i = OSContainer::cpu_shares();
2199   st->print("cpu_shares: ");
2200   if (i > 0) {
2201     st->print_cr("%d", i);
2202   } else {
2203     st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no shares");
2204   }
2205 
2206   jlong j = OSContainer::memory_limit_in_bytes();
2207   st->print("memory_limit_in_bytes: ");
2208   if (j > 0) {
2209     st->print_cr(JLONG_FORMAT, j);
2210   } else {
2211     st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");
2212   }
2213 
2214   j = OSContainer::memory_and_swap_limit_in_bytes();
2215   st->print("memory_and_swap_limit_in_bytes: ");
2216   if (j > 0) {
2217     st->print_cr(JLONG_FORMAT, j);
2218   } else {
2219     st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");
2220   }
2221 
2222   j = OSContainer::memory_soft_limit_in_bytes();
2223   st->print("memory_soft_limit_in_bytes: ");
2224   if (j > 0) {
2225     st->print_cr(JLONG_FORMAT, j);
2226   } else {
2227     st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");
2228   }
2229 
2230   j = OSContainer::OSContainer::memory_usage_in_bytes();
2231   st->print("memory_usage_in_bytes: ");
2232   if (j > 0) {
2233     st->print_cr(JLONG_FORMAT, j);
2234   } else {
2235     st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");
2236   }
2237 
2238   j = OSContainer::OSContainer::memory_max_usage_in_bytes();
2239   st->print("memory_max_usage_in_bytes: ");
2240   if (j > 0) {
2241     st->print_cr(JLONG_FORMAT, j);
2242   } else {
2243     st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");
2244   }
2245 
2246   j = OSContainer::OSContainer::pids_max();
2247   st->print("maximum number of tasks: ");
2248   if (j > 0) {
2249     st->print_cr(JLONG_FORMAT, j);
2250   } else {
2251     st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "unlimited");
2252   }
2253 
2254   j = OSContainer::OSContainer::pids_current();
2255   st->print("current number of tasks: ");
2256   if (j > 0) {
2257     st->print_cr(JLONG_FORMAT, j);
2258   } else {
2259     if (j == OSCONTAINER_ERROR) {
2260       st->print_cr("not supported");
2261     }
2262   }
2263 
2264   return true;
2265 }
2266 
2267 void os::Linux::print_steal_info(outputStream* st) {
2268   if (has_initial_tick_info) {
2269     CPUPerfTicks pticks;
2270     bool res = os::Linux::get_tick_information(&pticks, -1);
2271 
2272     if (res && pticks.has_steal_ticks) {
2273       uint64_t steal_ticks_difference = pticks.steal - initial_steal_ticks;
2274       uint64_t total_ticks_difference = pticks.total - initial_total_ticks;
2275       double steal_ticks_perc = 0.0;
2276       if (total_ticks_difference != 0) {
2277         steal_ticks_perc = (double) steal_ticks_difference / total_ticks_difference;
2278       }
2279       st->print_cr("Steal ticks since vm start: " UINT64_FORMAT, steal_ticks_difference);
2280       st->print_cr("Steal ticks percentage since vm start:%7.3f", steal_ticks_perc);
2281     }
2282   }
2283 }
2284 
2285 void os::print_memory_info(outputStream* st) {
2286 
2287   st->print("Memory:");
2288   st->print(" %dk page", os::vm_page_size()>>10);
2289 
2290   // values in struct sysinfo are "unsigned long"
2291   struct sysinfo si;
2292   sysinfo(&si);
2293 
2294   st->print(", physical " UINT64_FORMAT "k",
2295             os::physical_memory() >> 10);
2296   st->print("(" UINT64_FORMAT "k free)",
2297             os::available_memory() >> 10);
2298   st->print(", swap " UINT64_FORMAT "k",
2299             ((jlong)si.totalswap * si.mem_unit) >> 10);
2300   st->print("(" UINT64_FORMAT "k free)",
2301             ((jlong)si.freeswap * si.mem_unit) >> 10);
2302   st->cr();
2303   st->print("Page Sizes: ");
2304   _page_sizes.print_on(st);
2305   st->cr();
2306 }
2307 
2308 // Print the first "model name" line and the first "flags" line
2309 // that we find and nothing more. We assume "model name" comes
2310 // before "flags" so if we find a second "model name", then the
2311 // "flags" field is considered missing.
2312 static bool print_model_name_and_flags(outputStream* st, char* buf, size_t buflen) {
2313 #if defined(IA32) || defined(AMD64)
2314   // Other platforms have less repetitive cpuinfo files
2315   FILE *fp = fopen("/proc/cpuinfo", "r");
2316   if (fp) {
2317     bool model_name_printed = false;
2318     while (!feof(fp)) {
2319       if (fgets(buf, buflen, fp)) {
2320         // Assume model name comes before flags
2321         if (strstr(buf, "model name") != NULL) {
2322           if (!model_name_printed) {
2323             st->print_raw("CPU Model and flags from /proc/cpuinfo:\n");
2324             st->print_raw(buf);
2325             model_name_printed = true;
2326           } else {
2327             // model name printed but not flags?  Odd, just return
2328             fclose(fp);
2329             return true;
2330           }
2331         }
2332         // print the flags line too
2333         if (strstr(buf, "flags") != NULL) {
2334           st->print_raw(buf);
2335           fclose(fp);
2336           return true;
2337         }
2338       }
2339     }
2340     fclose(fp);
2341   }
2342 #endif // x86 platforms
2343   return false;
2344 }
2345 
2346 // additional information about CPU e.g. available frequency ranges
2347 static void print_sys_devices_cpu_info(outputStream* st, char* buf, size_t buflen) {
2348   _print_ascii_file_h("Online cpus", "/sys/devices/system/cpu/online", st);
2349   _print_ascii_file_h("Offline cpus", "/sys/devices/system/cpu/offline", st);
2350 
2351   if (ExtensiveErrorReports) {
2352     // cache related info (cpu 0, should be similar for other CPUs)
2353     for (unsigned int i=0; i < 10; i++) { // handle max. 10 cache entries
2354       char hbuf_level[60];
2355       char hbuf_type[60];
2356       char hbuf_size[60];
2357       char hbuf_coherency_line_size[80];
2358       snprintf(hbuf_level, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/level", i);
2359       snprintf(hbuf_type, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/type", i);
2360       snprintf(hbuf_size, 60, "/sys/devices/system/cpu/cpu0/cache/index%u/size", i);
2361       snprintf(hbuf_coherency_line_size, 80, "/sys/devices/system/cpu/cpu0/cache/index%u/coherency_line_size", i);
2362       if (os::file_exists(hbuf_level)) {
2363         _print_ascii_file_h("cache level", hbuf_level, st);
2364         _print_ascii_file_h("cache type", hbuf_type, st);
2365         _print_ascii_file_h("cache size", hbuf_size, st);
2366         _print_ascii_file_h("cache coherency line size", hbuf_coherency_line_size, st);
2367       }
2368     }
2369   }
2370 
2371   // we miss the cpufreq entries on Power and s390x
2372 #if defined(IA32) || defined(AMD64)
2373   _print_ascii_file_h("BIOS frequency limitation", "/sys/devices/system/cpu/cpu0/cpufreq/bios_limit", st);
2374   _print_ascii_file_h("Frequency switch latency (ns)", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_transition_latency", st);
2375   _print_ascii_file_h("Available cpu frequencies", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies", st);
2376   // min and max should be in the Available range but still print them (not all info might be available for all kernels)
2377   if (ExtensiveErrorReports) {
2378     _print_ascii_file_h("Maximum cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", st);
2379     _print_ascii_file_h("Minimum cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq", st);
2380     _print_ascii_file_h("Current cpu frequency", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", st);
2381   }
2382   // governors are power schemes, see https://wiki.archlinux.org/index.php/CPU_frequency_scaling
2383   if (ExtensiveErrorReports) {
2384     _print_ascii_file_h("Available governors", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors", st);
2385   }
2386   _print_ascii_file_h("Current governor", "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", st);
2387   // Core performance boost, see https://www.kernel.org/doc/Documentation/cpu-freq/boost.txt
2388   // Raise operating frequency of some cores in a multi-core package if certain conditions apply, e.g.
2389   // whole chip is not fully utilized
2390   _print_ascii_file_h("Core performance/turbo boost", "/sys/devices/system/cpu/cpufreq/boost", st);
2391 #endif
2392 }
2393 
2394 void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) {
2395   // Only print the model name if the platform provides this as a summary
2396   if (!print_model_name_and_flags(st, buf, buflen)) {
2397     _print_ascii_file_h("/proc/cpuinfo", "/proc/cpuinfo", st, false);
2398   }
2399   st->cr();
2400   print_sys_devices_cpu_info(st, buf, buflen);
2401 }
2402 
2403 #if defined(AMD64) || defined(IA32) || defined(X32)
2404 const char* search_string = "model name";
2405 #elif defined(M68K)
2406 const char* search_string = "CPU";
2407 #elif defined(PPC64)
2408 const char* search_string = "cpu";
2409 #elif defined(S390)
2410 const char* search_string = "machine =";
2411 #elif defined(SPARC)
2412 const char* search_string = "cpu";
2413 #else
2414 const char* search_string = "Processor";
2415 #endif
2416 
2417 // Parses the cpuinfo file for string representing the model name.
2418 void os::get_summary_cpu_info(char* cpuinfo, size_t length) {
2419   FILE* fp = fopen("/proc/cpuinfo", "r");
2420   if (fp != NULL) {
2421     while (!feof(fp)) {
2422       char buf[256];
2423       if (fgets(buf, sizeof(buf), fp)) {
2424         char* start = strstr(buf, search_string);
2425         if (start != NULL) {
2426           char *ptr = start + strlen(search_string);
2427           char *end = buf + strlen(buf);
2428           while (ptr != end) {
2429              // skip whitespace and colon for the rest of the name.
2430              if (*ptr != ' ' && *ptr != '\t' && *ptr != ':') {
2431                break;
2432              }
2433              ptr++;
2434           }
2435           if (ptr != end) {
2436             // reasonable string, get rid of newline and keep the rest
2437             char* nl = strchr(buf, '\n');
2438             if (nl != NULL) *nl = '\0';
2439             strncpy(cpuinfo, ptr, length);
2440             fclose(fp);
2441             return;
2442           }
2443         }
2444       }
2445     }
2446     fclose(fp);
2447   }
2448   // cpuinfo not found or parsing failed, just print generic string.  The entire
2449   // /proc/cpuinfo file will be printed later in the file (or enough of it for x86)
2450 #if   defined(AARCH64)
2451   strncpy(cpuinfo, "AArch64", length);
2452 #elif defined(AMD64)
2453   strncpy(cpuinfo, "x86_64", length);
2454 #elif defined(ARM)  // Order wrt. AARCH64 is relevant!
2455   strncpy(cpuinfo, "ARM", length);
2456 #elif defined(IA32)
2457   strncpy(cpuinfo, "x86_32", length);
2458 #elif defined(IA64)
2459   strncpy(cpuinfo, "IA64", length);
2460 #elif defined(PPC)
2461   strncpy(cpuinfo, "PPC64", length);
2462 #elif defined(RISCV)
2463   strncpy(cpuinfo, "RISCV64", length);
2464 #elif defined(S390)
2465   strncpy(cpuinfo, "S390", length);
2466 #elif defined(SPARC)
2467   strncpy(cpuinfo, "sparcv9", length);
2468 #elif defined(ZERO_LIBARCH)
2469   strncpy(cpuinfo, ZERO_LIBARCH, length);
2470 #else
2471   strncpy(cpuinfo, "unknown", length);
2472 #endif
2473 }
2474 
2475 static char saved_jvm_path[MAXPATHLEN] = {0};
2476 
2477 // Find the full path to the current module, libjvm.so
2478 void os::jvm_path(char *buf, jint buflen) {
2479   // Error checking.
2480   if (buflen < MAXPATHLEN) {
2481     assert(false, "must use a large-enough buffer");
2482     buf[0] = '\0';
2483     return;
2484   }
2485   // Lazy resolve the path to current module.
2486   if (saved_jvm_path[0] != 0) {
2487     strcpy(buf, saved_jvm_path);
2488     return;
2489   }
2490 
2491   char dli_fname[MAXPATHLEN];
2492   dli_fname[0] = '\0';
2493   bool ret = dll_address_to_library_name(
2494                                          CAST_FROM_FN_PTR(address, os::jvm_path),
2495                                          dli_fname, sizeof(dli_fname), NULL);
2496   assert(ret, "cannot locate libjvm");
2497   char *rp = NULL;
2498   if (ret && dli_fname[0] != '\0') {
2499     rp = os::Posix::realpath(dli_fname, buf, buflen);
2500   }
2501   if (rp == NULL) {
2502     return;
2503   }
2504 
2505   if (Arguments::sun_java_launcher_is_altjvm()) {
2506     // Support for the java launcher's '-XXaltjvm=<path>' option. Typical
2507     // value for buf is "<JAVA_HOME>/jre/lib/<vmtype>/libjvm.so".
2508     // If "/jre/lib/" appears at the right place in the string, then
2509     // assume we are installed in a JDK and we're done. Otherwise, check
2510     // for a JAVA_HOME environment variable and fix up the path so it
2511     // looks like libjvm.so is installed there (append a fake suffix
2512     // hotspot/libjvm.so).
2513     const char *p = buf + strlen(buf) - 1;
2514     for (int count = 0; p > buf && count < 5; ++count) {
2515       for (--p; p > buf && *p != '/'; --p)
2516         /* empty */ ;
2517     }
2518 
2519     if (strncmp(p, "/jre/lib/", 9) != 0) {
2520       // Look for JAVA_HOME in the environment.
2521       char* java_home_var = ::getenv("JAVA_HOME");
2522       if (java_home_var != NULL && java_home_var[0] != 0) {
2523         char* jrelib_p;
2524         int len;
2525 
2526         // Check the current module name "libjvm.so".
2527         p = strrchr(buf, '/');
2528         if (p == NULL) {
2529           return;
2530         }
2531         assert(strstr(p, "/libjvm") == p, "invalid library name");
2532 
2533         rp = os::Posix::realpath(java_home_var, buf, buflen);
2534         if (rp == NULL) {
2535           return;
2536         }
2537 
2538         // determine if this is a legacy image or modules image
2539         // modules image doesn't have "jre" subdirectory
2540         len = strlen(buf);
2541         assert(len < buflen, "Ran out of buffer room");
2542         jrelib_p = buf + len;
2543         snprintf(jrelib_p, buflen-len, "/jre/lib");
2544         if (0 != access(buf, F_OK)) {
2545           snprintf(jrelib_p, buflen-len, "/lib");
2546         }
2547 
2548         if (0 == access(buf, F_OK)) {
2549           // Use current module name "libjvm.so"
2550           len = strlen(buf);
2551           snprintf(buf + len, buflen-len, "/hotspot/libjvm.so");
2552         } else {
2553           // Go back to path of .so
2554           rp = os::Posix::realpath(dli_fname, buf, buflen);
2555           if (rp == NULL) {
2556             return;
2557           }
2558         }
2559       }
2560     }
2561   }
2562 
2563   strncpy(saved_jvm_path, buf, MAXPATHLEN);
2564   saved_jvm_path[MAXPATHLEN - 1] = '\0';
2565 }
2566 
2567 void os::print_jni_name_prefix_on(outputStream* st, int args_size) {
2568   // no prefix required, not even "_"
2569 }
2570 
2571 void os::print_jni_name_suffix_on(outputStream* st, int args_size) {
2572   // no suffix required
2573 }
2574 
2575 ////////////////////////////////////////////////////////////////////////////////
2576 // Virtual Memory
2577 
2578 int os::vm_page_size() {
2579   // Seems redundant as all get out
2580   assert(os::Linux::page_size() != -1, "must call os::init");
2581   return os::Linux::page_size();
2582 }
2583 
2584 // Solaris allocates memory by pages.
2585 int os::vm_allocation_granularity() {
2586   assert(os::Linux::page_size() != -1, "must call os::init");
2587   return os::Linux::page_size();
2588 }
2589 
2590 // Rationale behind this function:
2591 //  current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable
2592 //  mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get
2593 //  samples for JITted code. Here we create private executable mapping over the code cache
2594 //  and then we can use standard (well, almost, as mapping can change) way to provide
2595 //  info for the reporting script by storing timestamp and location of symbol
2596 void linux_wrap_code(char* base, size_t size) {
2597   static volatile jint cnt = 0;
2598 
2599   if (!UseOprofile) {
2600     return;
2601   }
2602 
2603   char buf[PATH_MAX+1];
2604   int num = Atomic::add(&cnt, 1);
2605 
2606   snprintf(buf, sizeof(buf), "%s/hs-vm-%d-%d",
2607            os::get_temp_directory(), os::current_process_id(), num);
2608   unlink(buf);
2609 
2610   int fd = ::open(buf, O_CREAT | O_RDWR, S_IRWXU);
2611 
2612   if (fd != -1) {
2613     off_t rv = ::lseek(fd, size-2, SEEK_SET);
2614     if (rv != (off_t)-1) {
2615       if (::write(fd, "", 1) == 1) {
2616         mmap(base, size,
2617              PROT_READ|PROT_WRITE|PROT_EXEC,
2618              MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0);
2619       }
2620     }
2621     ::close(fd);
2622     unlink(buf);
2623   }
2624 }
2625 
2626 static bool recoverable_mmap_error(int err) {
2627   // See if the error is one we can let the caller handle. This
2628   // list of errno values comes from JBS-6843484. I can't find a
2629   // Linux man page that documents this specific set of errno
2630   // values so while this list currently matches Solaris, it may
2631   // change as we gain experience with this failure mode.
2632   switch (err) {
2633   case EBADF:
2634   case EINVAL:
2635   case ENOTSUP:
2636     // let the caller deal with these errors
2637     return true;
2638 
2639   default:
2640     // Any remaining errors on this OS can cause our reserved mapping
2641     // to be lost. That can cause confusion where different data
2642     // structures think they have the same memory mapped. The worst
2643     // scenario is if both the VM and a library think they have the
2644     // same memory mapped.
2645     return false;
2646   }
2647 }
2648 
2649 static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
2650                                     int err) {
2651   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2652           ", %d) failed; error='%s' (errno=%d)", p2i(addr), size, exec,
2653           os::strerror(err), err);
2654 }
2655 
2656 static void warn_fail_commit_memory(char* addr, size_t size,
2657                                     size_t alignment_hint, bool exec,
2658                                     int err) {
2659   warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
2660           ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", p2i(addr), size,
2661           alignment_hint, exec, os::strerror(err), err);
2662 }
2663 
2664 // NOTE: Linux kernel does not really reserve the pages for us.
2665 //       All it does is to check if there are enough free pages
2666 //       left at the time of mmap(). This could be a potential
2667 //       problem.
2668 int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {
2669   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
2670   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
2671                                      MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
2672   if (res != (uintptr_t) MAP_FAILED) {
2673     if (UseNUMAInterleaving) {
2674       numa_make_global(addr, size);
2675     }
2676     return 0;
2677   }
2678 
2679   int err = errno;  // save errno from mmap() call above
2680 
2681   if (!recoverable_mmap_error(err)) {
2682     warn_fail_commit_memory(addr, size, exec, err);
2683     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory.");
2684   }
2685 
2686   return err;
2687 }
2688 
2689 bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
2690   return os::Linux::commit_memory_impl(addr, size, exec) == 0;
2691 }
2692 
2693 void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
2694                                   const char* mesg) {
2695   assert(mesg != NULL, "mesg must be specified");
2696   int err = os::Linux::commit_memory_impl(addr, size, exec);
2697   if (err != 0) {
2698     // the caller wants all commit errors to exit with the specified mesg:
2699     warn_fail_commit_memory(addr, size, exec, err);
2700     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
2701   }
2702 }
2703 
2704 // Define MAP_HUGETLB here so we can build HotSpot on old systems.
2705 #ifndef MAP_HUGETLB
2706   #define MAP_HUGETLB 0x40000
2707 #endif
2708 
2709 // If mmap flags are set with MAP_HUGETLB and the system supports multiple
2710 // huge page sizes, flag bits [26:31] can be used to encode the log2 of the
2711 // desired huge page size. Otherwise, the system's default huge page size will be used.
2712 // See mmap(2) man page for more info (since Linux 3.8).
2713 // https://lwn.net/Articles/533499/
2714 #ifndef MAP_HUGE_SHIFT
2715   #define MAP_HUGE_SHIFT 26
2716 #endif
2717 
2718 // Define MADV_HUGEPAGE here so we can build HotSpot on old systems.
2719 #ifndef MADV_HUGEPAGE
2720   #define MADV_HUGEPAGE 14
2721 #endif
2722 
2723 int os::Linux::commit_memory_impl(char* addr, size_t size,
2724                                   size_t alignment_hint, bool exec) {
2725   int err = os::Linux::commit_memory_impl(addr, size, exec);
2726   if (err == 0) {
2727     realign_memory(addr, size, alignment_hint);
2728   }
2729   return err;
2730 }
2731 
2732 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
2733                           bool exec) {
2734   return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;
2735 }
2736 
2737 void os::pd_commit_memory_or_exit(char* addr, size_t size,
2738                                   size_t alignment_hint, bool exec,
2739                                   const char* mesg) {
2740   assert(mesg != NULL, "mesg must be specified");
2741   int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);
2742   if (err != 0) {
2743     // the caller wants all commit errors to exit with the specified mesg:
2744     warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
2745     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "%s", mesg);
2746   }
2747 }
2748 
2749 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
2750   if (UseTransparentHugePages && alignment_hint > (size_t)vm_page_size()) {
2751     // We don't check the return value: madvise(MADV_HUGEPAGE) may not
2752     // be supported or the memory may already be backed by huge pages.
2753     ::madvise(addr, bytes, MADV_HUGEPAGE);
2754   }
2755 }
2756 
2757 void os::pd_free_memory(char *addr, size_t bytes, size_t alignment_hint) {
2758   // This method works by doing an mmap over an existing mmaping and effectively discarding
2759   // the existing pages. However it won't work for SHM-based large pages that cannot be
2760   // uncommitted at all. We don't do anything in this case to avoid creating a segment with
2761   // small pages on top of the SHM segment. This method always works for small pages, so we
2762   // allow that in any case.
2763   if (alignment_hint <= (size_t)os::vm_page_size() || can_commit_large_page_memory()) {
2764     commit_memory(addr, bytes, alignment_hint, !ExecMem);
2765   }
2766 }
2767 
2768 void os::numa_make_global(char *addr, size_t bytes) {
2769   Linux::numa_interleave_memory(addr, bytes);
2770 }
2771 
2772 // Define for numa_set_bind_policy(int). Setting the argument to 0 will set the
2773 // bind policy to MPOL_PREFERRED for the current thread.
2774 #define USE_MPOL_PREFERRED 0
2775 
2776 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) {
2777   // To make NUMA and large pages more robust when both enabled, we need to ease
2778   // the requirements on where the memory should be allocated. MPOL_BIND is the
2779   // default policy and it will force memory to be allocated on the specified
2780   // node. Changing this to MPOL_PREFERRED will prefer to allocate the memory on
2781   // the specified node, but will not force it. Using this policy will prevent
2782   // getting SIGBUS when trying to allocate large pages on NUMA nodes with no
2783   // free large pages.
2784   Linux::numa_set_bind_policy(USE_MPOL_PREFERRED);
2785   Linux::numa_tonode_memory(addr, bytes, lgrp_hint);
2786 }
2787 
2788 bool os::numa_topology_changed() { return false; }
2789 
2790 size_t os::numa_get_groups_num() {
2791   // Return just the number of nodes in which it's possible to allocate memory
2792   // (in numa terminology, configured nodes).
2793   return Linux::numa_num_configured_nodes();
2794 }
2795 
2796 int os::numa_get_group_id() {
2797   int cpu_id = Linux::sched_getcpu();
2798   if (cpu_id != -1) {
2799     int lgrp_id = Linux::get_node_by_cpu(cpu_id);
2800     if (lgrp_id != -1) {
2801       return lgrp_id;
2802     }
2803   }
2804   return 0;
2805 }
2806 
2807 int os::numa_get_group_id_for_address(const void* address) {
2808   void** pages = const_cast<void**>(&address);
2809   int id = -1;
2810 
2811   if (os::Linux::numa_move_pages(0, 1, pages, NULL, &id, 0) == -1) {
2812     return -1;
2813   }
2814   if (id < 0) {
2815     return -1;
2816   }
2817   return id;
2818 }
2819 
2820 int os::Linux::get_existing_num_nodes() {
2821   int node;
2822   int highest_node_number = Linux::numa_max_node();
2823   int num_nodes = 0;
2824 
2825   // Get the total number of nodes in the system including nodes without memory.
2826   for (node = 0; node <= highest_node_number; node++) {
2827     if (is_node_in_existing_nodes(node)) {
2828       num_nodes++;
2829     }
2830   }
2831   return num_nodes;
2832 }
2833 
2834 size_t os::numa_get_leaf_groups(int *ids, size_t size) {
2835   int highest_node_number = Linux::numa_max_node();
2836   size_t i = 0;
2837 
2838   // Map all node ids in which it is possible to allocate memory. Also nodes are
2839   // not always consecutively available, i.e. available from 0 to the highest
2840   // node number. If the nodes have been bound explicitly using numactl membind,
2841   // then allocate memory from those nodes only.
2842   for (int node = 0; node <= highest_node_number; node++) {
2843     if (Linux::is_node_in_bound_nodes((unsigned int)node)) {
2844       ids[i++] = node;
2845     }
2846   }
2847   return i;
2848 }
2849 
2850 bool os::get_page_info(char *start, page_info* info) {
2851   return false;
2852 }
2853 
2854 char *os::scan_pages(char *start, char* end, page_info* page_expected,
2855                      page_info* page_found) {
2856   return end;
2857 }
2858 
2859 
2860 int os::Linux::sched_getcpu_syscall(void) {
2861   unsigned int cpu = 0;
2862   int retval = -1;
2863 
2864 #if defined(IA32)
2865   #ifndef SYS_getcpu
2866     #define SYS_getcpu 318
2867   #endif
2868   retval = syscall(SYS_getcpu, &cpu, NULL, NULL);
2869 #elif defined(AMD64)
2870 // Unfortunately we have to bring all these macros here from vsyscall.h
2871 // to be able to compile on old linuxes.
2872   #define __NR_vgetcpu 2
2873   #define VSYSCALL_START (-10UL << 20)
2874   #define VSYSCALL_SIZE 1024
2875   #define VSYSCALL_ADDR(vsyscall_nr) (VSYSCALL_START+VSYSCALL_SIZE*(vsyscall_nr))
2876   typedef long (*vgetcpu_t)(unsigned int *cpu, unsigned int *node, unsigned long *tcache);
2877   vgetcpu_t vgetcpu = (vgetcpu_t)VSYSCALL_ADDR(__NR_vgetcpu);
2878   retval = vgetcpu(&cpu, NULL, NULL);
2879 #endif
2880 
2881   return (retval == -1) ? retval : cpu;
2882 }
2883 
2884 void os::Linux::sched_getcpu_init() {
2885   // sched_getcpu() should be in libc.
2886   set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2887                                   dlsym(RTLD_DEFAULT, "sched_getcpu")));
2888 
2889   // If it's not, try a direct syscall.
2890   if (sched_getcpu() == -1) {
2891     set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t,
2892                                     (void*)&sched_getcpu_syscall));
2893   }
2894 
2895   if (sched_getcpu() == -1) {
2896     vm_exit_during_initialization("getcpu(2) system call not supported by kernel");
2897   }
2898 }
2899 
2900 // Something to do with the numa-aware allocator needs these symbols
2901 extern "C" JNIEXPORT void numa_warn(int number, char *where, ...) { }
2902 extern "C" JNIEXPORT void numa_error(char *where) { }
2903 
2904 // Handle request to load libnuma symbol version 1.1 (API v1). If it fails
2905 // load symbol from base version instead.
2906 void* os::Linux::libnuma_dlsym(void* handle, const char *name) {
2907   void *f = dlvsym(handle, name, "libnuma_1.1");
2908   if (f == NULL) {
2909     f = dlsym(handle, name);
2910   }
2911   return f;
2912 }
2913 
2914 // Handle request to load libnuma symbol version 1.2 (API v2) only.
2915 // Return NULL if the symbol is not defined in this particular version.
2916 void* os::Linux::libnuma_v2_dlsym(void* handle, const char* name) {
2917   return dlvsym(handle, name, "libnuma_1.2");
2918 }
2919 
2920 // Check numa dependent syscalls
2921 static bool numa_syscall_check() {
2922   // NUMA APIs depend on several syscalls. E.g., get_mempolicy is required for numa_get_membind and
2923   // numa_get_interleave_mask. But these dependent syscalls can be unsupported for various reasons.
2924   // Especially in dockers, get_mempolicy is not allowed with the default configuration. So it's necessary
2925   // to check whether the syscalls are available. Currently, only get_mempolicy is checked since checking
2926   // others like mbind would cause unexpected side effects.
2927 #ifdef SYS_get_mempolicy
2928   int dummy = 0;
2929   if (syscall(SYS_get_mempolicy, &dummy, NULL, 0, (void*)&dummy, 3) == -1) {
2930     return false;
2931   }
2932 #endif
2933 
2934   return true;
2935 }
2936 
2937 bool os::Linux::libnuma_init() {
2938   // Requires sched_getcpu() and numa dependent syscalls support
2939   if ((sched_getcpu() != -1) && numa_syscall_check()) {
2940     void *handle = dlopen("libnuma.so.1", RTLD_LAZY);
2941     if (handle != NULL) {
2942       set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t,
2943                                            libnuma_dlsym(handle, "numa_node_to_cpus")));
2944       set_numa_node_to_cpus_v2(CAST_TO_FN_PTR(numa_node_to_cpus_v2_func_t,
2945                                               libnuma_v2_dlsym(handle, "numa_node_to_cpus")));
2946       set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t,
2947                                        libnuma_dlsym(handle, "numa_max_node")));
2948       set_numa_num_configured_nodes(CAST_TO_FN_PTR(numa_num_configured_nodes_func_t,
2949                                                    libnuma_dlsym(handle, "numa_num_configured_nodes")));
2950       set_numa_available(CAST_TO_FN_PTR(numa_available_func_t,
2951                                         libnuma_dlsym(handle, "numa_available")));
2952       set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t,
2953                                             libnuma_dlsym(handle, "numa_tonode_memory")));
2954       set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t,
2955                                                 libnuma_dlsym(handle, "numa_interleave_memory")));
2956       set_numa_interleave_memory_v2(CAST_TO_FN_PTR(numa_interleave_memory_v2_func_t,
2957                                                 libnuma_v2_dlsym(handle, "numa_interleave_memory")));
2958       set_numa_set_bind_policy(CAST_TO_FN_PTR(numa_set_bind_policy_func_t,
2959                                               libnuma_dlsym(handle, "numa_set_bind_policy")));
2960       set_numa_bitmask_isbitset(CAST_TO_FN_PTR(numa_bitmask_isbitset_func_t,
2961                                                libnuma_dlsym(handle, "numa_bitmask_isbitset")));
2962       set_numa_distance(CAST_TO_FN_PTR(numa_distance_func_t,
2963                                        libnuma_dlsym(handle, "numa_distance")));
2964       set_numa_get_membind(CAST_TO_FN_PTR(numa_get_membind_func_t,
2965                                           libnuma_v2_dlsym(handle, "numa_get_membind")));
2966       set_numa_get_interleave_mask(CAST_TO_FN_PTR(numa_get_interleave_mask_func_t,
2967                                                   libnuma_v2_dlsym(handle, "numa_get_interleave_mask")));
2968       set_numa_move_pages(CAST_TO_FN_PTR(numa_move_pages_func_t,
2969                                          libnuma_dlsym(handle, "numa_move_pages")));
2970       set_numa_set_preferred(CAST_TO_FN_PTR(numa_set_preferred_func_t,
2971                                             libnuma_dlsym(handle, "numa_set_preferred")));
2972 
2973       if (numa_available() != -1) {
2974         set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes"));
2975         set_numa_all_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_all_nodes_ptr"));
2976         set_numa_nodes_ptr((struct bitmask **)libnuma_dlsym(handle, "numa_nodes_ptr"));
2977         set_numa_interleave_bitmask(_numa_get_interleave_mask());
2978         set_numa_membind_bitmask(_numa_get_membind());
2979         // Create an index -> node mapping, since nodes are not always consecutive
2980         _nindex_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, mtInternal);
2981         rebuild_nindex_to_node_map();
2982         // Create a cpu -> node mapping
2983         _cpu_to_node = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<int>(0, mtInternal);
2984         rebuild_cpu_to_node_map();
2985         return true;
2986       }
2987     }
2988   }
2989   return false;
2990 }
2991 
2992 size_t os::Linux::default_guard_size(os::ThreadType thr_type) {
2993   // Creating guard page is very expensive. Java thread has HotSpot
2994   // guard pages, only enable glibc guard page for non-Java threads.
2995   // (Remember: compiler thread is a Java thread, too!)
2996   return ((thr_type == java_thread || thr_type == compiler_thread) ? 0 : page_size());
2997 }
2998 
2999 void os::Linux::rebuild_nindex_to_node_map() {
3000   int highest_node_number = Linux::numa_max_node();
3001 
3002   nindex_to_node()->clear();
3003   for (int node = 0; node <= highest_node_number; node++) {
3004     if (Linux::is_node_in_existing_nodes(node)) {
3005       nindex_to_node()->append(node);
3006     }
3007   }
3008 }
3009 
3010 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id.
3011 // The table is later used in get_node_by_cpu().
3012 void os::Linux::rebuild_cpu_to_node_map() {
3013   const size_t NCPUS = 32768; // Since the buffer size computation is very obscure
3014                               // in libnuma (possible values are starting from 16,
3015                               // and continuing up with every other power of 2, but less
3016                               // than the maximum number of CPUs supported by kernel), and
3017                               // is a subject to change (in libnuma version 2 the requirements
3018                               // are more reasonable) we'll just hardcode the number they use
3019                               // in the library.
3020   const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
3021 
3022   size_t cpu_num = processor_count();
3023   size_t cpu_map_size = NCPUS / BitsPerCLong;
3024   size_t cpu_map_valid_size =
3025     MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
3026 
3027   cpu_to_node()->clear();
3028   cpu_to_node()->at_grow(cpu_num - 1);
3029 
3030   size_t node_num = get_existing_num_nodes();
3031 
3032   int distance = 0;
3033   int closest_distance = INT_MAX;
3034   int closest_node = 0;
3035   unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size, mtInternal);
3036   for (size_t i = 0; i < node_num; i++) {
3037     // Check if node is configured (not a memory-less node). If it is not, find
3038     // the closest configured node. Check also if node is bound, i.e. it's allowed
3039     // to allocate memory from the node. If it's not allowed, map cpus in that node
3040     // to the closest node from which memory allocation is allowed.
3041     if (!is_node_in_configured_nodes(nindex_to_node()->at(i)) ||
3042         !is_node_in_bound_nodes(nindex_to_node()->at(i))) {
3043       closest_distance = INT_MAX;
3044       // Check distance from all remaining nodes in the system. Ignore distance
3045       // from itself, from another non-configured node, and from another non-bound
3046       // node.
3047       for (size_t m = 0; m < node_num; m++) {
3048         if (m != i &&
3049             is_node_in_configured_nodes(nindex_to_node()->at(m)) &&
3050             is_node_in_bound_nodes(nindex_to_node()->at(m))) {
3051           distance = numa_distance(nindex_to_node()->at(i), nindex_to_node()->at(m));
3052           // If a closest node is found, update. There is always at least one
3053           // configured and bound node in the system so there is always at least
3054           // one node close.
3055           if (distance != 0 && distance < closest_distance) {
3056             closest_distance = distance;
3057             closest_node = nindex_to_node()->at(m);
3058           }
3059         }
3060       }
3061      } else {
3062        // Current node is already a configured node.
3063        closest_node = nindex_to_node()->at(i);
3064      }
3065 
3066     // Get cpus from the original node and map them to the closest node. If node
3067     // is a configured node (not a memory-less node), then original node and
3068     // closest node are the same.
3069     if (numa_node_to_cpus(nindex_to_node()->at(i), cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) {
3070       for (size_t j = 0; j < cpu_map_valid_size; j++) {
3071         if (cpu_map[j] != 0) {
3072           for (size_t k = 0; k < BitsPerCLong; k++) {
3073             if (cpu_map[j] & (1UL << k)) {
3074               int cpu_index = j * BitsPerCLong + k;
3075 
3076 #ifndef PRODUCT
3077               if (UseDebuggerErgo1 && cpu_index >= (int)cpu_num) {
3078                 // Some debuggers limit the processor count without
3079                 // intercepting the NUMA APIs. Just fake the values.
3080                 cpu_index = 0;
3081               }
3082 #endif
3083 
3084               cpu_to_node()->at_put(cpu_index, closest_node);
3085             }
3086           }
3087         }
3088       }
3089     }
3090   }
3091   FREE_C_HEAP_ARRAY(unsigned long, cpu_map);
3092 }
3093 
3094 int os::Linux::numa_node_to_cpus(int node, unsigned long *buffer, int bufferlen) {
3095   // use the latest version of numa_node_to_cpus if available
3096   if (_numa_node_to_cpus_v2 != NULL) {
3097 
3098     // libnuma bitmask struct
3099     struct bitmask {
3100       unsigned long size; /* number of bits in the map */
3101       unsigned long *maskp;
3102     };
3103 
3104     struct bitmask mask;
3105     mask.maskp = (unsigned long *)buffer;
3106     mask.size = bufferlen * 8;
3107     return _numa_node_to_cpus_v2(node, &mask);
3108   } else if (_numa_node_to_cpus != NULL) {
3109     return _numa_node_to_cpus(node, buffer, bufferlen);
3110   }
3111   return -1;
3112 }
3113 
3114 int os::Linux::get_node_by_cpu(int cpu_id) {
3115   if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) {
3116     return cpu_to_node()->at(cpu_id);
3117   }
3118   return -1;
3119 }
3120 
3121 GrowableArray<int>* os::Linux::_cpu_to_node;
3122 GrowableArray<int>* os::Linux::_nindex_to_node;
3123 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu;
3124 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus;
3125 os::Linux::numa_node_to_cpus_v2_func_t os::Linux::_numa_node_to_cpus_v2;
3126 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node;
3127 os::Linux::numa_num_configured_nodes_func_t os::Linux::_numa_num_configured_nodes;
3128 os::Linux::numa_available_func_t os::Linux::_numa_available;
3129 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory;
3130 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory;
3131 os::Linux::numa_interleave_memory_v2_func_t os::Linux::_numa_interleave_memory_v2;
3132 os::Linux::numa_set_bind_policy_func_t os::Linux::_numa_set_bind_policy;
3133 os::Linux::numa_bitmask_isbitset_func_t os::Linux::_numa_bitmask_isbitset;
3134 os::Linux::numa_distance_func_t os::Linux::_numa_distance;
3135 os::Linux::numa_get_membind_func_t os::Linux::_numa_get_membind;
3136 os::Linux::numa_get_interleave_mask_func_t os::Linux::_numa_get_interleave_mask;
3137 os::Linux::numa_move_pages_func_t os::Linux::_numa_move_pages;
3138 os::Linux::numa_set_preferred_func_t os::Linux::_numa_set_preferred;
3139 os::Linux::NumaAllocationPolicy os::Linux::_current_numa_policy;
3140 unsigned long* os::Linux::_numa_all_nodes;
3141 struct bitmask* os::Linux::_numa_all_nodes_ptr;
3142 struct bitmask* os::Linux::_numa_nodes_ptr;
3143 struct bitmask* os::Linux::_numa_interleave_bitmask;
3144 struct bitmask* os::Linux::_numa_membind_bitmask;
3145 
3146 bool os::pd_uncommit_memory(char* addr, size_t size, bool exec) {
3147   uintptr_t res = (uintptr_t) ::mmap(addr, size, PROT_NONE,
3148                                      MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0);
3149   return res  != (uintptr_t) MAP_FAILED;
3150 }
3151 
3152 static address get_stack_commited_bottom(address bottom, size_t size) {
3153   address nbot = bottom;
3154   address ntop = bottom + size;
3155 
3156   size_t page_sz = os::vm_page_size();
3157   unsigned pages = size / page_sz;
3158 
3159   unsigned char vec[1];
3160   unsigned imin = 1, imax = pages + 1, imid;
3161   int mincore_return_value = 0;
3162 
3163   assert(imin <= imax, "Unexpected page size");
3164 
3165   while (imin < imax) {
3166     imid = (imax + imin) / 2;
3167     nbot = ntop - (imid * page_sz);
3168 
3169     // Use a trick with mincore to check whether the page is mapped or not.
3170     // mincore sets vec to 1 if page resides in memory and to 0 if page
3171     // is swapped output but if page we are asking for is unmapped
3172     // it returns -1,ENOMEM
3173     mincore_return_value = mincore(nbot, page_sz, vec);
3174 
3175     if (mincore_return_value == -1) {
3176       // Page is not mapped go up
3177       // to find first mapped page
3178       if (errno != EAGAIN) {
3179         assert(errno == ENOMEM, "Unexpected mincore errno");
3180         imax = imid;
3181       }
3182     } else {
3183       // Page is mapped go down
3184       // to find first not mapped page
3185       imin = imid + 1;
3186     }
3187   }
3188 
3189   nbot = nbot + page_sz;
3190 
3191   // Adjust stack bottom one page up if last checked page is not mapped
3192   if (mincore_return_value == -1) {
3193     nbot = nbot + page_sz;
3194   }
3195 
3196   return nbot;
3197 }
3198 
3199 bool os::committed_in_range(address start, size_t size, address& committed_start, size_t& committed_size) {
3200   int mincore_return_value;
3201   const size_t stripe = 1024;  // query this many pages each time
3202   unsigned char vec[stripe + 1];
3203   // set a guard
3204   vec[stripe] = 'X';
3205 
3206   const size_t page_sz = os::vm_page_size();
3207   size_t pages = size / page_sz;
3208 
3209   assert(is_aligned(start, page_sz), "Start address must be page aligned");
3210   assert(is_aligned(size, page_sz), "Size must be page aligned");
3211 
3212   committed_start = NULL;
3213 
3214   int loops = (pages + stripe - 1) / stripe;
3215   int committed_pages = 0;
3216   address loop_base = start;
3217   bool found_range = false;
3218 
3219   for (int index = 0; index < loops && !found_range; index ++) {
3220     assert(pages > 0, "Nothing to do");
3221     int pages_to_query = (pages >= stripe) ? stripe : pages;
3222     pages -= pages_to_query;
3223 
3224     // Get stable read
3225     while ((mincore_return_value = mincore(loop_base, pages_to_query * page_sz, vec)) == -1 && errno == EAGAIN);
3226 
3227     // During shutdown, some memory goes away without properly notifying NMT,
3228     // E.g. ConcurrentGCThread/WatcherThread can exit without deleting thread object.
3229     // Bailout and return as not committed for now.
3230     if (mincore_return_value == -1 && errno == ENOMEM) {
3231       return false;
3232     }
3233 
3234     assert(vec[stripe] == 'X', "overflow guard");
3235     assert(mincore_return_value == 0, "Range must be valid");
3236     // Process this stripe
3237     for (int vecIdx = 0; vecIdx < pages_to_query; vecIdx ++) {
3238       if ((vec[vecIdx] & 0x01) == 0) { // not committed
3239         // End of current contiguous region
3240         if (committed_start != NULL) {
3241           found_range = true;
3242           break;
3243         }
3244       } else { // committed
3245         // Start of region
3246         if (committed_start == NULL) {
3247           committed_start = loop_base + page_sz * vecIdx;
3248         }
3249         committed_pages ++;
3250       }
3251     }
3252 
3253     loop_base += pages_to_query * page_sz;
3254   }
3255 
3256   if (committed_start != NULL) {
3257     assert(committed_pages > 0, "Must have committed region");
3258     assert(committed_pages <= int(size / page_sz), "Can not commit more than it has");
3259     assert(committed_start >= start && committed_start < start + size, "Out of range");
3260     committed_size = page_sz * committed_pages;
3261     return true;
3262   } else {
3263     assert(committed_pages == 0, "Should not have committed region");
3264     return false;
3265   }
3266 }
3267 
3268 
3269 // Linux uses a growable mapping for the stack, and if the mapping for
3270 // the stack guard pages is not removed when we detach a thread the
3271 // stack cannot grow beyond the pages where the stack guard was
3272 // mapped.  If at some point later in the process the stack expands to
3273 // that point, the Linux kernel cannot expand the stack any further
3274 // because the guard pages are in the way, and a segfault occurs.
3275 //
3276 // However, it's essential not to split the stack region by unmapping
3277 // a region (leaving a hole) that's already part of the stack mapping,
3278 // so if the stack mapping has already grown beyond the guard pages at
3279 // the time we create them, we have to truncate the stack mapping.
3280 // So, we need to know the extent of the stack mapping when
3281 // create_stack_guard_pages() is called.
3282 
3283 // We only need this for stacks that are growable: at the time of
3284 // writing thread stacks don't use growable mappings (i.e. those
3285 // creeated with MAP_GROWSDOWN), and aren't marked "[stack]", so this
3286 // only applies to the main thread.
3287 
3288 // If the (growable) stack mapping already extends beyond the point
3289 // where we're going to put our guard pages, truncate the mapping at
3290 // that point by munmap()ping it.  This ensures that when we later
3291 // munmap() the guard pages we don't leave a hole in the stack
3292 // mapping. This only affects the main/primordial thread
3293 
3294 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
3295   if (os::is_primordial_thread()) {
3296     // As we manually grow stack up to bottom inside create_attached_thread(),
3297     // it's likely that os::Linux::initial_thread_stack_bottom is mapped and
3298     // we don't need to do anything special.
3299     // Check it first, before calling heavy function.
3300     uintptr_t stack_extent = (uintptr_t) os::Linux::initial_thread_stack_bottom();
3301     unsigned char vec[1];
3302 
3303     if (mincore((address)stack_extent, os::vm_page_size(), vec) == -1) {
3304       // Fallback to slow path on all errors, including EAGAIN
3305       assert((uintptr_t)addr >= stack_extent,
3306              "Sanity: addr should be larger than extent, " PTR_FORMAT " >= " PTR_FORMAT,
3307              p2i(addr), stack_extent);
3308       stack_extent = (uintptr_t) get_stack_commited_bottom(
3309                                                            os::Linux::initial_thread_stack_bottom(),
3310                                                            (size_t)addr - stack_extent);
3311     }
3312 
3313     if (stack_extent < (uintptr_t)addr) {
3314       ::munmap((void*)stack_extent, (uintptr_t)(addr - stack_extent));
3315     }
3316   }
3317 
3318   return os::commit_memory(addr, size, !ExecMem);
3319 }
3320 
3321 // If this is a growable mapping, remove the guard pages entirely by
3322 // munmap()ping them.  If not, just call uncommit_memory(). This only
3323 // affects the main/primordial thread, but guard against future OS changes.
3324 // It's safe to always unmap guard pages for primordial thread because we
3325 // always place it right after end of the mapped region.
3326 
3327 bool os::remove_stack_guard_pages(char* addr, size_t size) {
3328   uintptr_t stack_extent, stack_base;
3329 
3330   if (os::is_primordial_thread()) {
3331     return ::munmap(addr, size) == 0;
3332   }
3333 
3334   return os::uncommit_memory(addr, size);
3335 }
3336 
3337 // 'requested_addr' is only treated as a hint, the return value may or
3338 // may not start from the requested address. Unlike Linux mmap(), this
3339 // function returns NULL to indicate failure.
3340 static char* anon_mmap(char* requested_addr, size_t bytes) {
3341   // MAP_FIXED is intentionally left out, to leave existing mappings intact.
3342   const int flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS;
3343 
3344   // Map reserved/uncommitted pages PROT_NONE so we fail early if we
3345   // touch an uncommitted page. Otherwise, the read/write might
3346   // succeed if we have enough swap space to back the physical page.
3347   char* addr = (char*)::mmap(requested_addr, bytes, PROT_NONE, flags, -1, 0);
3348 
3349   return addr == MAP_FAILED ? NULL : addr;
3350 }
3351 
3352 // Allocate (using mmap, NO_RESERVE, with small pages) at either a given request address
3353 //   (req_addr != NULL) or with a given alignment.
3354 //  - bytes shall be a multiple of alignment.
3355 //  - req_addr can be NULL. If not NULL, it must be a multiple of alignment.
3356 //  - alignment sets the alignment at which memory shall be allocated.
3357 //     It must be a multiple of allocation granularity.
3358 // Returns address of memory or NULL. If req_addr was not NULL, will only return
3359 //  req_addr or NULL.
3360 static char* anon_mmap_aligned(char* req_addr, size_t bytes, size_t alignment) {
3361   size_t extra_size = bytes;
3362   if (req_addr == NULL && alignment > 0) {
3363     extra_size += alignment;
3364   }
3365 
3366   char* start = anon_mmap(req_addr, extra_size);
3367   if (start != NULL) {
3368     if (req_addr != NULL) {
3369       if (start != req_addr) {
3370         ::munmap(start, extra_size);
3371         start = NULL;
3372       }
3373     } else {
3374       char* const start_aligned = align_up(start, alignment);
3375       char* const end_aligned = start_aligned + bytes;
3376       char* const end = start + extra_size;
3377       if (start_aligned > start) {
3378         ::munmap(start, start_aligned - start);
3379       }
3380       if (end_aligned < end) {
3381         ::munmap(end_aligned, end - end_aligned);
3382       }
3383       start = start_aligned;
3384     }
3385   }
3386   return start;
3387 }
3388 
3389 static int anon_munmap(char * addr, size_t size) {
3390   return ::munmap(addr, size) == 0;
3391 }
3392 
3393 char* os::pd_reserve_memory(size_t bytes, bool exec) {
3394   return anon_mmap(NULL, bytes);
3395 }
3396 
3397 bool os::pd_release_memory(char* addr, size_t size) {
3398   return anon_munmap(addr, size);
3399 }
3400 
3401 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
3402 extern char* g_assert_poison; // assertion poison page address
3403 #endif
3404 
3405 static bool linux_mprotect(char* addr, size_t size, int prot) {
3406   // Linux wants the mprotect address argument to be page aligned.
3407   char* bottom = (char*)align_down((intptr_t)addr, os::Linux::page_size());
3408 
3409   // According to SUSv3, mprotect() should only be used with mappings
3410   // established by mmap(), and mmap() always maps whole pages. Unaligned
3411   // 'addr' likely indicates problem in the VM (e.g. trying to change
3412   // protection of malloc'ed or statically allocated memory). Check the
3413   // caller if you hit this assert.
3414   assert(addr == bottom, "sanity check");
3415 
3416   size = align_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size());
3417   // Don't log anything if we're executing in the poison page signal handling
3418   // context. It can lead to reentrant use of other parts of the VM code.
3419 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
3420   if (addr != g_assert_poison)
3421 #endif
3422   Events::log(NULL, "Protecting memory [" INTPTR_FORMAT "," INTPTR_FORMAT "] with protection modes %x", p2i(bottom), p2i(bottom+size), prot);
3423   return ::mprotect(bottom, size, prot) == 0;
3424 }
3425 
3426 // Set protections specified
3427 bool os::protect_memory(char* addr, size_t bytes, ProtType prot,
3428                         bool is_committed) {
3429   unsigned int p = 0;
3430   switch (prot) {
3431   case MEM_PROT_NONE: p = PROT_NONE; break;
3432   case MEM_PROT_READ: p = PROT_READ; break;
3433   case MEM_PROT_RW:   p = PROT_READ|PROT_WRITE; break;
3434   case MEM_PROT_RWX:  p = PROT_READ|PROT_WRITE|PROT_EXEC; break;
3435   default:
3436     ShouldNotReachHere();
3437   }
3438   // is_committed is unused.
3439   return linux_mprotect(addr, bytes, p);
3440 }
3441 
3442 bool os::guard_memory(char* addr, size_t size) {
3443   return linux_mprotect(addr, size, PROT_NONE);
3444 }
3445 
3446 bool os::unguard_memory(char* addr, size_t size) {
3447   return linux_mprotect(addr, size, PROT_READ|PROT_WRITE);
3448 }
3449 
3450 bool os::Linux::transparent_huge_pages_sanity_check(bool warn,
3451                                                     size_t page_size) {
3452   bool result = false;
3453   void *p = mmap(NULL, page_size * 2, PROT_READ|PROT_WRITE,
3454                  MAP_ANONYMOUS|MAP_PRIVATE,
3455                  -1, 0);
3456   if (p != MAP_FAILED) {
3457     void *aligned_p = align_up(p, page_size);
3458 
3459     result = madvise(aligned_p, page_size, MADV_HUGEPAGE) == 0;
3460 
3461     munmap(p, page_size * 2);
3462   }
3463 
3464   if (warn && !result) {
3465     warning("TransparentHugePages is not supported by the operating system.");
3466   }
3467 
3468   return result;
3469 }
3470 
3471 int os::Linux::hugetlbfs_page_size_flag(size_t page_size) {
3472   if (page_size != default_large_page_size()) {
3473     return (exact_log2(page_size) << MAP_HUGE_SHIFT);
3474   }
3475   return 0;
3476 }
3477 
3478 bool os::Linux::hugetlbfs_sanity_check(bool warn, size_t page_size) {
3479   // Include the page size flag to ensure we sanity check the correct page size.
3480   int flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_HUGETLB | hugetlbfs_page_size_flag(page_size);
3481   void *p = mmap(NULL, page_size, PROT_READ|PROT_WRITE, flags, -1, 0);
3482 
3483   if (p != MAP_FAILED) {
3484     // Mapping succeeded, sanity check passed.
3485     munmap(p, page_size);
3486     return true;
3487   } else {
3488       log_info(pagesize)("Large page size (" SIZE_FORMAT "%s) failed sanity check, "
3489                          "checking if smaller large page sizes are usable",
3490                          byte_size_in_exact_unit(page_size),
3491                          exact_unit_for_byte_size(page_size));
3492       for (size_t page_size_ = _page_sizes.next_smaller(page_size);
3493           page_size_ != (size_t)os::vm_page_size();
3494           page_size_ = _page_sizes.next_smaller(page_size_)) {
3495         flags = MAP_ANONYMOUS | MAP_PRIVATE | MAP_HUGETLB | hugetlbfs_page_size_flag(page_size_);
3496         p = mmap(NULL, page_size_, PROT_READ|PROT_WRITE, flags, -1, 0);
3497         if (p != MAP_FAILED) {
3498           // Mapping succeeded, sanity check passed.
3499           munmap(p, page_size_);
3500           log_info(pagesize)("Large page size (" SIZE_FORMAT "%s) passed sanity check",
3501                              byte_size_in_exact_unit(page_size_),
3502                              exact_unit_for_byte_size(page_size_));
3503           return true;
3504         }
3505       }
3506   }
3507 
3508   if (warn) {
3509     warning("HugeTLBFS is not configured or not supported by the operating system.");
3510   }
3511 
3512   return false;
3513 }
3514 
3515 bool os::Linux::shm_hugetlbfs_sanity_check(bool warn, size_t page_size) {
3516   // Try to create a large shared memory segment.
3517   int shmid = shmget(IPC_PRIVATE, page_size, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3518   if (shmid == -1) {
3519     // Possible reasons for shmget failure:
3520     // 1. shmmax is too small for the request.
3521     //    > check shmmax value: cat /proc/sys/kernel/shmmax
3522     //    > increase shmmax value: echo "new_value" > /proc/sys/kernel/shmmax
3523     // 2. not enough large page memory.
3524     //    > check available large pages: cat /proc/meminfo
3525     //    > increase amount of large pages:
3526     //          sysctl -w vm.nr_hugepages=new_value
3527     //    > For more information regarding large pages please refer to:
3528     //      https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt
3529     if (warn) {
3530       warning("Large pages using UseSHM are not configured on this system.");
3531     }
3532     return false;
3533   }
3534   // Managed to create a segment, now delete it.
3535   shmctl(shmid, IPC_RMID, NULL);
3536   return true;
3537 }
3538 
3539 // From the coredump_filter documentation:
3540 //
3541 // - (bit 0) anonymous private memory
3542 // - (bit 1) anonymous shared memory
3543 // - (bit 2) file-backed private memory
3544 // - (bit 3) file-backed shared memory
3545 // - (bit 4) ELF header pages in file-backed private memory areas (it is
3546 //           effective only if the bit 2 is cleared)
3547 // - (bit 5) hugetlb private memory
3548 // - (bit 6) hugetlb shared memory
3549 // - (bit 7) dax private memory
3550 // - (bit 8) dax shared memory
3551 //
3552 static void set_coredump_filter(CoredumpFilterBit bit) {
3553   FILE *f;
3554   long cdm;
3555 
3556   if ((f = fopen("/proc/self/coredump_filter", "r+")) == NULL) {
3557     return;
3558   }
3559 
3560   if (fscanf(f, "%lx", &cdm) != 1) {
3561     fclose(f);
3562     return;
3563   }
3564 
3565   long saved_cdm = cdm;
3566   rewind(f);
3567   cdm |= bit;
3568 
3569   if (cdm != saved_cdm) {
3570     fprintf(f, "%#lx", cdm);
3571   }
3572 
3573   fclose(f);
3574 }
3575 
3576 // Large page support
3577 
3578 static size_t _large_page_size = 0;
3579 
3580 static size_t scan_default_large_page_size() {
3581   size_t default_large_page_size = 0;
3582 
3583   // large_page_size on Linux is used to round up heap size. x86 uses either
3584   // 2M or 4M page, depending on whether PAE (Physical Address Extensions)
3585   // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use
3586   // page as large as 1G.
3587   //
3588   // Here we try to figure out page size by parsing /proc/meminfo and looking
3589   // for a line with the following format:
3590   //    Hugepagesize:     2048 kB
3591   //
3592   // If we can't determine the value (e.g. /proc is not mounted, or the text
3593   // format has been changed), we'll set largest page size to 0
3594 
3595   FILE *fp = fopen("/proc/meminfo", "r");
3596   if (fp) {
3597     while (!feof(fp)) {
3598       int x = 0;
3599       char buf[16];
3600       if (fscanf(fp, "Hugepagesize: %d", &x) == 1) {
3601         if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) {
3602           default_large_page_size = x * K;
3603           break;
3604         }
3605       } else {
3606         // skip to next line
3607         for (;;) {
3608           int ch = fgetc(fp);
3609           if (ch == EOF || ch == (int)'\n') break;
3610         }
3611       }
3612     }
3613     fclose(fp);
3614   }
3615 
3616   return default_large_page_size;
3617 }
3618 
3619 static os::PageSizes scan_multiple_page_support() {
3620   // Scan /sys/kernel/mm/hugepages
3621   // to discover the available page sizes
3622   const char* sys_hugepages = "/sys/kernel/mm/hugepages";
3623   os::PageSizes page_sizes;
3624 
3625   DIR *dir = opendir(sys_hugepages);
3626 
3627   struct dirent *entry;
3628   size_t page_size;
3629   while ((entry = readdir(dir)) != NULL) {
3630     if (entry->d_type == DT_DIR &&
3631         sscanf(entry->d_name, "hugepages-%zukB", &page_size) == 1) {
3632       // The kernel is using kB, hotspot uses bytes
3633       // Add each found Large Page Size to page_sizes
3634       page_sizes.add(page_size * K);
3635     }
3636   }
3637   closedir(dir);
3638 
3639   LogTarget(Debug, pagesize) lt;
3640   if (lt.is_enabled()) {
3641     LogStream ls(lt);
3642     ls.print("Large Page sizes: ");
3643     page_sizes.print_on(&ls);
3644   }
3645 
3646   return page_sizes;
3647 }
3648 
3649 size_t os::Linux::default_large_page_size() {
3650   return _default_large_page_size;
3651 }
3652 
3653 void warn_no_large_pages_configured() {
3654   if (!FLAG_IS_DEFAULT(UseLargePages)) {
3655     log_warning(pagesize)("UseLargePages disabled, no large pages configured and available on the system.");
3656   }
3657 }
3658 
3659 bool os::Linux::setup_large_page_type(size_t page_size) {
3660   if (FLAG_IS_DEFAULT(UseHugeTLBFS) &&
3661       FLAG_IS_DEFAULT(UseSHM) &&
3662       FLAG_IS_DEFAULT(UseTransparentHugePages)) {
3663 
3664     // The type of large pages has not been specified by the user.
3665 
3666     // Try UseHugeTLBFS and then UseSHM.
3667     UseHugeTLBFS = UseSHM = true;
3668 
3669     // Don't try UseTransparentHugePages since there are known
3670     // performance issues with it turned on. This might change in the future.
3671     UseTransparentHugePages = false;
3672   }
3673 
3674   if (UseTransparentHugePages) {
3675     bool warn_on_failure = !FLAG_IS_DEFAULT(UseTransparentHugePages);
3676     if (transparent_huge_pages_sanity_check(warn_on_failure, page_size)) {
3677       UseHugeTLBFS = false;
3678       UseSHM = false;
3679       return true;
3680     }
3681     UseTransparentHugePages = false;
3682   }
3683 
3684   if (UseHugeTLBFS) {
3685     bool warn_on_failure = !FLAG_IS_DEFAULT(UseHugeTLBFS);
3686     if (hugetlbfs_sanity_check(warn_on_failure, page_size)) {
3687       UseSHM = false;
3688       return true;
3689     }
3690     UseHugeTLBFS = false;
3691   }
3692 
3693   if (UseSHM) {
3694     bool warn_on_failure = !FLAG_IS_DEFAULT(UseSHM);
3695     if (shm_hugetlbfs_sanity_check(warn_on_failure, page_size)) {
3696       return true;
3697     }
3698     UseSHM = false;
3699   }
3700 
3701   warn_no_large_pages_configured();
3702   return false;
3703 }
3704 
3705 void os::large_page_init() {
3706   // 1) Handle the case where we do not want to use huge pages and hence
3707   //    there is no need to scan the OS for related info
3708   if (!UseLargePages &&
3709       !UseTransparentHugePages &&
3710       !UseHugeTLBFS &&
3711       !UseSHM) {
3712     // Not using large pages.
3713     return;
3714   }
3715 
3716   if (!FLAG_IS_DEFAULT(UseLargePages) && !UseLargePages) {
3717     // The user explicitly turned off large pages.
3718     // Ignore the rest of the large pages flags.
3719     UseTransparentHugePages = false;
3720     UseHugeTLBFS = false;
3721     UseSHM = false;
3722     return;
3723   }
3724 
3725   // 2) Scan OS info
3726   size_t default_large_page_size = scan_default_large_page_size();
3727   os::Linux::_default_large_page_size = default_large_page_size;
3728   if (default_large_page_size == 0) {
3729     // No large pages configured, return.
3730     warn_no_large_pages_configured();
3731     UseLargePages = false;
3732     UseTransparentHugePages = false;
3733     UseHugeTLBFS = false;
3734     UseSHM = false;
3735     return;
3736   }
3737   os::PageSizes all_large_pages = scan_multiple_page_support();
3738 
3739   // 3) Consistency check and post-processing
3740 
3741   // It is unclear if /sys/kernel/mm/hugepages/ and /proc/meminfo could disagree. Manually
3742   // re-add the default page size to the list of page sizes to be sure.
3743   all_large_pages.add(default_large_page_size);
3744 
3745   // Check LargePageSizeInBytes matches an available page size and if so set _large_page_size
3746   // using LargePageSizeInBytes as the maximum allowed large page size. If LargePageSizeInBytes
3747   // doesn't match an available page size set _large_page_size to default_large_page_size
3748   // and use it as the maximum.
3749  if (FLAG_IS_DEFAULT(LargePageSizeInBytes) ||
3750       LargePageSizeInBytes == 0 ||
3751       LargePageSizeInBytes == default_large_page_size) {
3752     _large_page_size = default_large_page_size;
3753     log_info(pagesize)("Using the default large page size: " SIZE_FORMAT "%s",
3754                        byte_size_in_exact_unit(_large_page_size),
3755                        exact_unit_for_byte_size(_large_page_size));
3756   } else {
3757     if (all_large_pages.contains(LargePageSizeInBytes)) {
3758       _large_page_size = LargePageSizeInBytes;
3759       log_info(pagesize)("Overriding default large page size (" SIZE_FORMAT "%s) "
3760                          "using LargePageSizeInBytes: " SIZE_FORMAT "%s",
3761                          byte_size_in_exact_unit(default_large_page_size),
3762                          exact_unit_for_byte_size(default_large_page_size),
3763                          byte_size_in_exact_unit(_large_page_size),
3764                          exact_unit_for_byte_size(_large_page_size));
3765     } else {
3766       _large_page_size = default_large_page_size;
3767       log_info(pagesize)("LargePageSizeInBytes is not a valid large page size (" SIZE_FORMAT "%s) "
3768                          "using the default large page size: " SIZE_FORMAT "%s",
3769                          byte_size_in_exact_unit(LargePageSizeInBytes),
3770                          exact_unit_for_byte_size(LargePageSizeInBytes),
3771                          byte_size_in_exact_unit(_large_page_size),
3772                          exact_unit_for_byte_size(_large_page_size));
3773     }
3774   }
3775 
3776   // Populate _page_sizes with large page sizes less than or equal to
3777   // _large_page_size.
3778   for (size_t page_size = _large_page_size; page_size != 0;
3779          page_size = all_large_pages.next_smaller(page_size)) {
3780     _page_sizes.add(page_size);
3781   }
3782 
3783   LogTarget(Info, pagesize) lt;
3784   if (lt.is_enabled()) {
3785     LogStream ls(lt);
3786     ls.print("Usable page sizes: ");
3787     _page_sizes.print_on(&ls);
3788   }
3789 
3790   // Now determine the type of large pages to use:
3791   UseLargePages = os::Linux::setup_large_page_type(_large_page_size);
3792 
3793   set_coredump_filter(LARGEPAGES_BIT);
3794 }
3795 
3796 #ifndef SHM_HUGETLB
3797   #define SHM_HUGETLB 04000
3798 #endif
3799 
3800 #define shm_warning_format(format, ...)              \
3801   do {                                               \
3802     if (UseLargePages &&                             \
3803         (!FLAG_IS_DEFAULT(UseLargePages) ||          \
3804          !FLAG_IS_DEFAULT(UseSHM) ||                 \
3805          !FLAG_IS_DEFAULT(LargePageSizeInBytes))) {  \
3806       warning(format, __VA_ARGS__);                  \
3807     }                                                \
3808   } while (0)
3809 
3810 #define shm_warning(str) shm_warning_format("%s", str)
3811 
3812 #define shm_warning_with_errno(str)                \
3813   do {                                             \
3814     int err = errno;                               \
3815     shm_warning_format(str " (error = %d)", err);  \
3816   } while (0)
3817 
3818 static char* shmat_with_alignment(int shmid, size_t bytes, size_t alignment) {
3819   assert(is_aligned(bytes, alignment), "Must be divisible by the alignment");
3820 
3821   if (!is_aligned(alignment, SHMLBA)) {
3822     assert(false, "Code below assumes that alignment is at least SHMLBA aligned");
3823     return NULL;
3824   }
3825 
3826   // To ensure that we get 'alignment' aligned memory from shmat,
3827   // we pre-reserve aligned virtual memory and then attach to that.
3828 
3829   char* pre_reserved_addr = anon_mmap_aligned(NULL /* req_addr */, bytes, alignment);
3830   if (pre_reserved_addr == NULL) {
3831     // Couldn't pre-reserve aligned memory.
3832     shm_warning("Failed to pre-reserve aligned memory for shmat.");
3833     return NULL;
3834   }
3835 
3836   // SHM_REMAP is needed to allow shmat to map over an existing mapping.
3837   char* addr = (char*)shmat(shmid, pre_reserved_addr, SHM_REMAP);
3838 
3839   if ((intptr_t)addr == -1) {
3840     int err = errno;
3841     shm_warning_with_errno("Failed to attach shared memory.");
3842 
3843     assert(err != EACCES, "Unexpected error");
3844     assert(err != EIDRM,  "Unexpected error");
3845     assert(err != EINVAL, "Unexpected error");
3846 
3847     // Since we don't know if the kernel unmapped the pre-reserved memory area
3848     // we can't unmap it, since that would potentially unmap memory that was
3849     // mapped from other threads.
3850     return NULL;
3851   }
3852 
3853   return addr;
3854 }
3855 
3856 static char* shmat_at_address(int shmid, char* req_addr) {
3857   if (!is_aligned(req_addr, SHMLBA)) {
3858     assert(false, "Requested address needs to be SHMLBA aligned");
3859     return NULL;
3860   }
3861 
3862   char* addr = (char*)shmat(shmid, req_addr, 0);
3863 
3864   if ((intptr_t)addr == -1) {
3865     shm_warning_with_errno("Failed to attach shared memory.");
3866     return NULL;
3867   }
3868 
3869   return addr;
3870 }
3871 
3872 static char* shmat_large_pages(int shmid, size_t bytes, size_t alignment, char* req_addr) {
3873   // If a req_addr has been provided, we assume that the caller has already aligned the address.
3874   if (req_addr != NULL) {
3875     assert(is_aligned(req_addr, os::large_page_size()), "Must be divisible by the large page size");
3876     assert(is_aligned(req_addr, alignment), "Must be divisible by given alignment");
3877     return shmat_at_address(shmid, req_addr);
3878   }
3879 
3880   // Since shmid has been setup with SHM_HUGETLB, shmat will automatically
3881   // return large page size aligned memory addresses when req_addr == NULL.
3882   // However, if the alignment is larger than the large page size, we have
3883   // to manually ensure that the memory returned is 'alignment' aligned.
3884   if (alignment > os::large_page_size()) {
3885     assert(is_aligned(alignment, os::large_page_size()), "Must be divisible by the large page size");
3886     return shmat_with_alignment(shmid, bytes, alignment);
3887   } else {
3888     return shmat_at_address(shmid, NULL);
3889   }
3890 }
3891 
3892 char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment,
3893                                             char* req_addr, bool exec) {
3894   // "exec" is passed in but not used.  Creating the shared image for
3895   // the code cache doesn't have an SHM_X executable permission to check.
3896   assert(UseLargePages && UseSHM, "only for SHM large pages");
3897   assert(is_aligned(req_addr, os::large_page_size()), "Unaligned address");
3898   assert(is_aligned(req_addr, alignment), "Unaligned address");
3899 
3900   if (!is_aligned(bytes, os::large_page_size())) {
3901     return NULL; // Fallback to small pages.
3902   }
3903 
3904   // Create a large shared memory region to attach to based on size.
3905   // Currently, size is the total size of the heap.
3906   int shmid = shmget(IPC_PRIVATE, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
3907   if (shmid == -1) {
3908     // Possible reasons for shmget failure:
3909     // 1. shmmax is too small for the request.
3910     //    > check shmmax value: cat /proc/sys/kernel/shmmax
3911     //    > increase shmmax value: echo "new_value" > /proc/sys/kernel/shmmax
3912     // 2. not enough large page memory.
3913     //    > check available large pages: cat /proc/meminfo
3914     //    > increase amount of large pages:
3915     //          sysctl -w vm.nr_hugepages=new_value
3916     //    > For more information regarding large pages please refer to:
3917     //      https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt
3918     //      Note 1: different Linux may use different name for this property,
3919     //            e.g. on Redhat AS-3 it is "hugetlb_pool".
3920     //      Note 2: it's possible there's enough physical memory available but
3921     //            they are so fragmented after a long run that they can't
3922     //            coalesce into large pages. Try to reserve large pages when
3923     //            the system is still "fresh".
3924     shm_warning_with_errno("Failed to reserve shared memory.");
3925     return NULL;
3926   }
3927 
3928   // Attach to the region.
3929   char* addr = shmat_large_pages(shmid, bytes, alignment, req_addr);
3930 
3931   // Remove shmid. If shmat() is successful, the actual shared memory segment
3932   // will be deleted when it's detached by shmdt() or when the process
3933   // terminates. If shmat() is not successful this will remove the shared
3934   // segment immediately.
3935   shmctl(shmid, IPC_RMID, NULL);
3936 
3937   return addr;
3938 }
3939 
3940 static void warn_on_commit_special_failure(char* req_addr, size_t bytes,
3941                                            size_t page_size, int error) {
3942   assert(error == ENOMEM, "Only expect to fail if no memory is available");
3943 
3944   bool warn_on_failure = UseLargePages &&
3945       (!FLAG_IS_DEFAULT(UseLargePages) ||
3946        !FLAG_IS_DEFAULT(UseHugeTLBFS) ||
3947        !FLAG_IS_DEFAULT(LargePageSizeInBytes));
3948 
3949   if (warn_on_failure) {
3950     char msg[128];
3951     jio_snprintf(msg, sizeof(msg), "Failed to reserve and commit memory. req_addr: "
3952                                    PTR_FORMAT " bytes: " SIZE_FORMAT " page size: "
3953                                    SIZE_FORMAT " (errno = %d).",
3954                                    req_addr, bytes, page_size, error);
3955     warning("%s", msg);
3956   }
3957 }
3958 
3959 bool os::Linux::commit_memory_special(size_t bytes,
3960                                       size_t page_size,
3961                                       char* req_addr,
3962                                       bool exec) {
3963   assert(UseLargePages && UseHugeTLBFS, "Should only get here when HugeTLBFS large pages are used");
3964   assert(is_aligned(bytes, page_size), "Unaligned size");
3965   assert(is_aligned(req_addr, page_size), "Unaligned address");
3966   assert(req_addr != NULL, "Must have a requested address for special mappings");
3967 
3968   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
3969   int flags = MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED;
3970 
3971   // For large pages additional flags are required.
3972   if (page_size > (size_t) os::vm_page_size()) {
3973     flags |= MAP_HUGETLB | hugetlbfs_page_size_flag(page_size);
3974   }
3975   char* addr = (char*)::mmap(req_addr, bytes, prot, flags, -1, 0);
3976 
3977   if (addr == MAP_FAILED) {
3978     warn_on_commit_special_failure(req_addr, bytes, page_size, errno);
3979     return false;
3980   }
3981 
3982   log_debug(pagesize)("Commit special mapping: " PTR_FORMAT ", size=" SIZE_FORMAT "%s, page size="
3983                       SIZE_FORMAT "%s",
3984                       p2i(addr), byte_size_in_exact_unit(bytes),
3985                       exact_unit_for_byte_size(bytes),
3986                       byte_size_in_exact_unit(page_size),
3987                       exact_unit_for_byte_size(page_size));
3988   assert(is_aligned(addr, page_size), "Must be");
3989   return true;
3990 }
3991 
3992 char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes,
3993                                                    size_t alignment,
3994                                                    size_t page_size,
3995                                                    char* req_addr,
3996                                                    bool exec) {
3997   assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
3998   assert(is_aligned(req_addr, alignment), "Must be");
3999   assert(is_aligned(req_addr, page_size), "Must be");
4000   assert(is_aligned(alignment, os::vm_allocation_granularity()), "Must be");
4001   assert(_page_sizes.contains(page_size), "Must be a valid page size");
4002   assert(page_size > (size_t)os::vm_page_size(), "Must be a large page size");
4003   assert(bytes >= page_size, "Shouldn't allocate large pages for small sizes");
4004 
4005   // We only end up here when at least 1 large page can be used.
4006   // If the size is not a multiple of the large page size, we
4007   // will mix the type of pages used, but in a decending order.
4008   // Start off by reserving a range of the given size that is
4009   // properly aligned. At this point no pages are committed. If
4010   // a requested address is given it will be used and it must be
4011   // aligned to both the large page size and the given alignment.
4012   // The larger of the two will be used.
4013   size_t required_alignment = MAX(page_size, alignment);
4014   char* const aligned_start = anon_mmap_aligned(req_addr, bytes, required_alignment);
4015   if (aligned_start == NULL) {
4016     return NULL;
4017   }
4018 
4019   // First commit using large pages.
4020   size_t large_bytes = align_down(bytes, page_size);
4021   bool large_committed = commit_memory_special(large_bytes, page_size, aligned_start, exec);
4022 
4023   if (large_committed && bytes == large_bytes) {
4024     // The size was large page aligned so no additional work is
4025     // needed even if the commit failed.
4026     return aligned_start;
4027   }
4028 
4029   // The requested size requires some small pages as well.
4030   char* small_start = aligned_start + large_bytes;
4031   size_t small_size = bytes - large_bytes;
4032   if (!large_committed) {
4033     // Failed to commit large pages, so we need to unmap the
4034     // reminder of the orinal reservation.
4035     ::munmap(small_start, small_size);
4036     return NULL;
4037   }
4038 
4039   // Commit the remaining bytes using small pages.
4040   bool small_committed = commit_memory_special(small_size, os::vm_page_size(), small_start, exec);
4041   if (!small_committed) {
4042     // Failed to commit the remaining size, need to unmap
4043     // the large pages part of the reservation.
4044     ::munmap(aligned_start, large_bytes);
4045     return NULL;
4046   }
4047   return aligned_start;
4048 }
4049 
4050 char* os::pd_reserve_memory_special(size_t bytes, size_t alignment, size_t page_size,
4051                                     char* req_addr, bool exec) {
4052   assert(UseLargePages, "only for large pages");
4053 
4054   char* addr;
4055   if (UseSHM) {
4056     // No support for using specific page sizes with SHM.
4057     addr = os::Linux::reserve_memory_special_shm(bytes, alignment, req_addr, exec);
4058   } else {
4059     assert(UseHugeTLBFS, "must be");
4060     addr = os::Linux::reserve_memory_special_huge_tlbfs(bytes, alignment, page_size, req_addr, exec);
4061   }
4062 
4063   if (addr != NULL) {
4064     if (UseNUMAInterleaving) {
4065       numa_make_global(addr, bytes);
4066     }
4067   }
4068 
4069   return addr;
4070 }
4071 
4072 bool os::Linux::release_memory_special_shm(char* base, size_t bytes) {
4073   // detaching the SHM segment will also delete it, see reserve_memory_special_shm()
4074   return shmdt(base) == 0;
4075 }
4076 
4077 bool os::Linux::release_memory_special_huge_tlbfs(char* base, size_t bytes) {
4078   return pd_release_memory(base, bytes);
4079 }
4080 
4081 bool os::pd_release_memory_special(char* base, size_t bytes) {
4082   assert(UseLargePages, "only for large pages");
4083   bool res;
4084 
4085   if (UseSHM) {
4086     res = os::Linux::release_memory_special_shm(base, bytes);
4087   } else {
4088     assert(UseHugeTLBFS, "must be");
4089     res = os::Linux::release_memory_special_huge_tlbfs(base, bytes);
4090   }
4091   return res;
4092 }
4093 
4094 size_t os::large_page_size() {
4095   return _large_page_size;
4096 }
4097 
4098 // With SysV SHM the entire memory region must be allocated as shared
4099 // memory.
4100 // HugeTLBFS allows application to commit large page memory on demand.
4101 // However, when committing memory with HugeTLBFS fails, the region
4102 // that was supposed to be committed will lose the old reservation
4103 // and allow other threads to steal that memory region. Because of this
4104 // behavior we can't commit HugeTLBFS memory.
4105 bool os::can_commit_large_page_memory() {
4106   return UseTransparentHugePages;
4107 }
4108 
4109 bool os::can_execute_large_page_memory() {
4110   return UseTransparentHugePages || UseHugeTLBFS;
4111 }
4112 
4113 char* os::pd_attempt_map_memory_to_file_at(char* requested_addr, size_t bytes, int file_desc) {
4114   assert(file_desc >= 0, "file_desc is not valid");
4115   char* result = pd_attempt_reserve_memory_at(requested_addr, bytes, !ExecMem);
4116   if (result != NULL) {
4117     if (replace_existing_mapping_with_file_mapping(result, bytes, file_desc) == NULL) {
4118       vm_exit_during_initialization(err_msg("Error in mapping Java heap at the given filesystem directory"));
4119     }
4120   }
4121   return result;
4122 }
4123 
4124 // Reserve memory at an arbitrary address, only if that area is
4125 // available (and not reserved for something else).
4126 
4127 char* os::pd_attempt_reserve_memory_at(char* requested_addr, size_t bytes, bool exec) {
4128   // Assert only that the size is a multiple of the page size, since
4129   // that's all that mmap requires, and since that's all we really know
4130   // about at this low abstraction level.  If we need higher alignment,
4131   // we can either pass an alignment to this method or verify alignment
4132   // in one of the methods further up the call chain.  See bug 5044738.
4133   assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block");
4134 
4135   // Repeatedly allocate blocks until the block is allocated at the
4136   // right spot.
4137 
4138   // Linux mmap allows caller to pass an address as hint; give it a try first,
4139   // if kernel honors the hint then we can return immediately.
4140   char * addr = anon_mmap(requested_addr, bytes);
4141   if (addr == requested_addr) {
4142     return requested_addr;
4143   }
4144 
4145   if (addr != NULL) {
4146     // mmap() is successful but it fails to reserve at the requested address
4147     anon_munmap(addr, bytes);
4148   }
4149 
4150   return NULL;
4151 }
4152 
4153 // Sleep forever; naked call to OS-specific sleep; use with CAUTION
4154 void os::infinite_sleep() {
4155   while (true) {    // sleep forever ...
4156     ::sleep(100);   // ... 100 seconds at a time
4157   }
4158 }
4159 
4160 // Used to convert frequent JVM_Yield() to nops
4161 bool os::dont_yield() {
4162   return DontYieldALot;
4163 }
4164 
4165 // Linux CFS scheduler (since 2.6.23) does not guarantee sched_yield(2) will
4166 // actually give up the CPU. Since skip buddy (v2.6.28):
4167 //
4168 // * Sets the yielding task as skip buddy for current CPU's run queue.
4169 // * Picks next from run queue, if empty, picks a skip buddy (can be the yielding task).
4170 // * Clears skip buddies for this run queue (yielding task no longer a skip buddy).
4171 //
4172 // An alternative is calling os::naked_short_nanosleep with a small number to avoid
4173 // getting re-scheduled immediately.
4174 //
4175 void os::naked_yield() {
4176   sched_yield();
4177 }
4178 
4179 ////////////////////////////////////////////////////////////////////////////////
4180 // thread priority support
4181 
4182 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER
4183 // only supports dynamic priority, static priority must be zero. For real-time
4184 // applications, Linux supports SCHED_RR which allows static priority (1-99).
4185 // However, for large multi-threaded applications, SCHED_RR is not only slower
4186 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out
4187 // of 5 runs - Sep 2005).
4188 //
4189 // The following code actually changes the niceness of kernel-thread/LWP. It
4190 // has an assumption that setpriority() only modifies one kernel-thread/LWP,
4191 // not the entire user process, and user level threads are 1:1 mapped to kernel
4192 // threads. It has always been the case, but could change in the future. For
4193 // this reason, the code should not be used as default (ThreadPriorityPolicy=0).
4194 // It is only used when ThreadPriorityPolicy=1 and may require system level permission
4195 // (e.g., root privilege or CAP_SYS_NICE capability).
4196 
4197 int os::java_to_os_priority[CriticalPriority + 1] = {
4198   19,              // 0 Entry should never be used
4199 
4200    4,              // 1 MinPriority
4201    3,              // 2
4202    2,              // 3
4203 
4204    1,              // 4
4205    0,              // 5 NormPriority
4206   -1,              // 6
4207 
4208   -2,              // 7
4209   -3,              // 8
4210   -4,              // 9 NearMaxPriority
4211 
4212   -5,              // 10 MaxPriority
4213 
4214   -5               // 11 CriticalPriority
4215 };
4216 
4217 static int prio_init() {
4218   if (ThreadPriorityPolicy == 1) {
4219     if (geteuid() != 0) {
4220       if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy) && !FLAG_IS_JIMAGE_RESOURCE(ThreadPriorityPolicy)) {
4221         warning("-XX:ThreadPriorityPolicy=1 may require system level permission, " \
4222                 "e.g., being the root user. If the necessary permission is not " \
4223                 "possessed, changes to priority will be silently ignored.");
4224       }
4225     }
4226   }
4227   if (UseCriticalJavaThreadPriority) {
4228     os::java_to_os_priority[MaxPriority] = os::java_to_os_priority[CriticalPriority];
4229   }
4230   return 0;
4231 }
4232 
4233 OSReturn os::set_native_priority(Thread* thread, int newpri) {
4234   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) return OS_OK;
4235 
4236   int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri);
4237   return (ret == 0) ? OS_OK : OS_ERR;
4238 }
4239 
4240 OSReturn os::get_native_priority(const Thread* const thread,
4241                                  int *priority_ptr) {
4242   if (!UseThreadPriorities || ThreadPriorityPolicy == 0) {
4243     *priority_ptr = java_to_os_priority[NormPriority];
4244     return OS_OK;
4245   }
4246 
4247   errno = 0;
4248   *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id());
4249   return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR);
4250 }
4251 
4252 // This is the fastest way to get thread cpu time on Linux.
4253 // Returns cpu time (user+sys) for any thread, not only for current.
4254 // POSIX compliant clocks are implemented in the kernels 2.6.16+.
4255 // It might work on 2.6.10+ with a special kernel/glibc patch.
4256 // For reference, please, see IEEE Std 1003.1-2004:
4257 //   http://www.unix.org/single_unix_specification
4258 
4259 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) {
4260   struct timespec tp;
4261   int status = clock_gettime(clockid, &tp);
4262   assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
4263   return (tp.tv_sec * NANOSECS_PER_SEC) + tp.tv_nsec;
4264 }
4265 
4266 // Determine if the vmid is the parent pid for a child in a PID namespace.
4267 // Return the namespace pid if so, otherwise -1.
4268 int os::Linux::get_namespace_pid(int vmid) {
4269   char fname[24];
4270   int retpid = -1;
4271 
4272   snprintf(fname, sizeof(fname), "/proc/%d/status", vmid);
4273   FILE *fp = fopen(fname, "r");
4274 
4275   if (fp) {
4276     int pid, nspid;
4277     int ret;
4278     while (!feof(fp) && !ferror(fp)) {
4279       ret = fscanf(fp, "NSpid: %d %d", &pid, &nspid);
4280       if (ret == 1) {
4281         break;
4282       }
4283       if (ret == 2) {
4284         retpid = nspid;
4285         break;
4286       }
4287       for (;;) {
4288         int ch = fgetc(fp);
4289         if (ch == EOF || ch == (int)'\n') break;
4290       }
4291     }
4292     fclose(fp);
4293   }
4294   return retpid;
4295 }
4296 
4297 extern void report_error(char* file_name, int line_no, char* title,
4298                          char* format, ...);
4299 
4300 // Some linux distributions (notably: Alpine Linux) include the
4301 // grsecurity in the kernel. Of particular interest from a JVM perspective
4302 // is PaX (https://pax.grsecurity.net/), which adds some security features
4303 // related to page attributes. Specifically, the MPROTECT PaX functionality
4304 // (https://pax.grsecurity.net/docs/mprotect.txt) prevents dynamic
4305 // code generation by disallowing a (previously) writable page to be
4306 // marked as executable. This is, of course, exactly what HotSpot does
4307 // for both JIT compiled method, as well as for stubs, adapters, etc.
4308 //
4309 // Instead of crashing "lazily" when trying to make a page executable,
4310 // this code probes for the presence of PaX and reports the failure
4311 // eagerly.
4312 static void check_pax(void) {
4313   // Zero doesn't generate code dynamically, so no need to perform the PaX check
4314 #ifndef ZERO
4315   size_t size = os::Linux::page_size();
4316 
4317   void* p = ::mmap(NULL, size, PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
4318   if (p == MAP_FAILED) {
4319     log_debug(os)("os_linux.cpp: check_pax: mmap failed (%s)" , os::strerror(errno));
4320     vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "failed to allocate memory for PaX check.");
4321   }
4322 
4323   int res = ::mprotect(p, size, PROT_WRITE|PROT_EXEC);
4324   if (res == -1) {
4325     log_debug(os)("os_linux.cpp: check_pax: mprotect failed (%s)" , os::strerror(errno));
4326     vm_exit_during_initialization(
4327       "Failed to mark memory page as executable - check if grsecurity/PaX is enabled");
4328   }
4329 
4330   ::munmap(p, size);
4331 #endif
4332 }
4333 
4334 // this is called _before_ most of the global arguments have been parsed
4335 void os::init(void) {
4336   char dummy;   // used to get a guess on initial stack address
4337 
4338   clock_tics_per_sec = sysconf(_SC_CLK_TCK);
4339 
4340   Linux::set_page_size(sysconf(_SC_PAGESIZE));
4341   if (Linux::page_size() == -1) {
4342     fatal("os_linux.cpp: os::init: sysconf failed (%s)",
4343           os::strerror(errno));
4344   }
4345   _page_sizes.add(Linux::page_size());
4346 
4347   Linux::initialize_system_info();
4348 
4349 #ifdef __GLIBC__
4350   Linux::_mallinfo = CAST_TO_FN_PTR(Linux::mallinfo_func_t, dlsym(RTLD_DEFAULT, "mallinfo"));
4351   Linux::_mallinfo2 = CAST_TO_FN_PTR(Linux::mallinfo2_func_t, dlsym(RTLD_DEFAULT, "mallinfo2"));
4352 #endif // __GLIBC__
4353 
4354   os::Linux::CPUPerfTicks pticks;
4355   bool res = os::Linux::get_tick_information(&pticks, -1);
4356 
4357   if (res && pticks.has_steal_ticks) {
4358     has_initial_tick_info = true;
4359     initial_total_ticks = pticks.total;
4360     initial_steal_ticks = pticks.steal;
4361   }
4362 
4363   // _main_thread points to the thread that created/loaded the JVM.
4364   Linux::_main_thread = pthread_self();
4365 
4366   // retrieve entry point for pthread_setname_np
4367   Linux::_pthread_setname_np =
4368     (int(*)(pthread_t, const char*))dlsym(RTLD_DEFAULT, "pthread_setname_np");
4369 
4370   check_pax();
4371 
4372   os::Posix::init();
4373 }
4374 
4375 // To install functions for atexit system call
4376 extern "C" {
4377   static void perfMemory_exit_helper() {
4378     perfMemory_exit();
4379   }
4380 }
4381 
4382 void os::pd_init_container_support() {
4383   OSContainer::init();
4384 }
4385 
4386 void os::Linux::numa_init() {
4387 
4388   // Java can be invoked as
4389   // 1. Without numactl and heap will be allocated/configured on all nodes as
4390   //    per the system policy.
4391   // 2. With numactl --interleave:
4392   //      Use numa_get_interleave_mask(v2) API to get nodes bitmask. The same
4393   //      API for membind case bitmask is reset.
4394   //      Interleave is only hint and Kernel can fallback to other nodes if
4395   //      no memory is available on the target nodes.
4396   // 3. With numactl --membind:
4397   //      Use numa_get_membind(v2) API to get nodes bitmask. The same API for
4398   //      interleave case returns bitmask of all nodes.
4399   // numa_all_nodes_ptr holds bitmask of all nodes.
4400   // numa_get_interleave_mask(v2) and numa_get_membind(v2) APIs returns correct
4401   // bitmask when externally configured to run on all or fewer nodes.
4402 
4403   if (!Linux::libnuma_init()) {
4404     FLAG_SET_ERGO(UseNUMA, false);
4405     FLAG_SET_ERGO(UseNUMAInterleaving, false); // Also depends on libnuma.
4406   } else {
4407     if ((Linux::numa_max_node() < 1) || Linux::is_bound_to_single_node()) {
4408       // If there's only one node (they start from 0) or if the process
4409       // is bound explicitly to a single node using membind, disable NUMA
4410       UseNUMA = false;
4411     } else {
4412       LogTarget(Info,os) log;
4413       LogStream ls(log);
4414 
4415       Linux::set_configured_numa_policy(Linux::identify_numa_policy());
4416 
4417       struct bitmask* bmp = Linux::_numa_membind_bitmask;
4418       const char* numa_mode = "membind";
4419 
4420       if (Linux::is_running_in_interleave_mode()) {
4421         bmp = Linux::_numa_interleave_bitmask;
4422         numa_mode = "interleave";
4423       }
4424 
4425       ls.print("UseNUMA is enabled and invoked in '%s' mode."
4426                " Heap will be configured using NUMA memory nodes:", numa_mode);
4427 
4428       for (int node = 0; node <= Linux::numa_max_node(); node++) {
4429         if (Linux::_numa_bitmask_isbitset(bmp, node)) {
4430           ls.print(" %d", node);
4431         }
4432       }
4433     }
4434   }
4435 
4436   // When NUMA requested, not-NUMA-aware allocations default to interleaving.
4437   if (UseNUMA && !UseNUMAInterleaving) {
4438     FLAG_SET_ERGO_IF_DEFAULT(UseNUMAInterleaving, true);
4439   }
4440 
4441   if (UseParallelGC && UseNUMA && UseLargePages && !can_commit_large_page_memory()) {
4442     // With SHM and HugeTLBFS large pages we cannot uncommit a page, so there's no way
4443     // we can make the adaptive lgrp chunk resizing work. If the user specified both
4444     // UseNUMA and UseLargePages (or UseSHM/UseHugeTLBFS) on the command line - warn
4445     // and disable adaptive resizing.
4446     if (UseAdaptiveSizePolicy || UseAdaptiveNUMAChunkSizing) {
4447       warning("UseNUMA is not fully compatible with SHM/HugeTLBFS large pages, "
4448               "disabling adaptive resizing (-XX:-UseAdaptiveSizePolicy -XX:-UseAdaptiveNUMAChunkSizing)");
4449       UseAdaptiveSizePolicy = false;
4450       UseAdaptiveNUMAChunkSizing = false;
4451     }
4452   }
4453 }
4454 
4455 // this is called _after_ the global arguments have been parsed
4456 jint os::init_2(void) {
4457 
4458   // This could be set after os::Posix::init() but all platforms
4459   // have to set it the same so we have to mirror Solaris.
4460   DEBUG_ONLY(os::set_mutex_init_done();)
4461 
4462   os::Posix::init_2();
4463 
4464   Linux::fast_thread_clock_init();
4465 
4466   if (PosixSignals::init() == JNI_ERR) {
4467     return JNI_ERR;
4468   }
4469 
4470   if (AdjustStackSizeForTLS) {
4471     get_minstack_init();
4472   }
4473 
4474   // Check and sets minimum stack sizes against command line options
4475   if (Posix::set_minimum_stack_sizes() == JNI_ERR) {
4476     return JNI_ERR;
4477   }
4478 
4479 #if defined(IA32) && !defined(ZERO)
4480   // Need to ensure we've determined the process's initial stack to
4481   // perform the workaround
4482   Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4483   workaround_expand_exec_shield_cs_limit();
4484 #else
4485   suppress_primordial_thread_resolution = Arguments::created_by_java_launcher();
4486   if (!suppress_primordial_thread_resolution) {
4487     Linux::capture_initial_stack(JavaThread::stack_size_at_create());
4488   }
4489 #endif
4490 
4491   Linux::libpthread_init();
4492   Linux::sched_getcpu_init();
4493   log_info(os)("HotSpot is running with %s, %s",
4494                Linux::libc_version(), Linux::libpthread_version());
4495 
4496   if (UseNUMA || UseNUMAInterleaving) {
4497     Linux::numa_init();
4498   }
4499 
4500   if (MaxFDLimit) {
4501     // set the number of file descriptors to max. print out error
4502     // if getrlimit/setrlimit fails but continue regardless.
4503     struct rlimit nbr_files;
4504     int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
4505     if (status != 0) {
4506       log_info(os)("os::init_2 getrlimit failed: %s", os::strerror(errno));
4507     } else {
4508       nbr_files.rlim_cur = nbr_files.rlim_max;
4509       status = setrlimit(RLIMIT_NOFILE, &nbr_files);
4510       if (status != 0) {
4511         log_info(os)("os::init_2 setrlimit failed: %s", os::strerror(errno));
4512       }
4513     }
4514   }
4515 
4516   // at-exit methods are called in the reverse order of their registration.
4517   // atexit functions are called on return from main or as a result of a
4518   // call to exit(3C). There can be only 32 of these functions registered
4519   // and atexit() does not set errno.
4520 
4521   if (PerfAllowAtExitRegistration) {
4522     // only register atexit functions if PerfAllowAtExitRegistration is set.
4523     // atexit functions can be delayed until process exit time, which
4524     // can be problematic for embedded VM situations. Embedded VMs should
4525     // call DestroyJavaVM() to assure that VM resources are released.
4526 
4527     // note: perfMemory_exit_helper atexit function may be removed in
4528     // the future if the appropriate cleanup code can be added to the
4529     // VM_Exit VMOperation's doit method.
4530     if (atexit(perfMemory_exit_helper) != 0) {
4531       warning("os::init_2 atexit(perfMemory_exit_helper) failed");
4532     }
4533   }
4534 
4535   // initialize thread priority policy
4536   prio_init();
4537 
4538   if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
4539     set_coredump_filter(DAX_SHARED_BIT);
4540   }
4541 
4542   if (DumpPrivateMappingsInCore) {
4543     set_coredump_filter(FILE_BACKED_PVT_BIT);
4544   }
4545 
4546   if (DumpSharedMappingsInCore) {
4547     set_coredump_filter(FILE_BACKED_SHARED_BIT);
4548   }
4549 
4550   if (DumpPerfMapAtExit && FLAG_IS_DEFAULT(UseCodeCacheFlushing)) {
4551     // Disable code cache flushing to ensure the map file written at
4552     // exit contains all nmethods generated during execution.
4553     FLAG_SET_DEFAULT(UseCodeCacheFlushing, false);
4554   }
4555 
4556   return JNI_OK;
4557 }
4558 
4559 // older glibc versions don't have this macro (which expands to
4560 // an optimized bit-counting function) so we have to roll our own
4561 #ifndef CPU_COUNT
4562 
4563 static int _cpu_count(const cpu_set_t* cpus) {
4564   int count = 0;
4565   // only look up to the number of configured processors
4566   for (int i = 0; i < os::processor_count(); i++) {
4567     if (CPU_ISSET(i, cpus)) {
4568       count++;
4569     }
4570   }
4571   return count;
4572 }
4573 
4574 #define CPU_COUNT(cpus) _cpu_count(cpus)
4575 
4576 #endif // CPU_COUNT
4577 
4578 // Get the current number of available processors for this process.
4579 // This value can change at any time during a process's lifetime.
4580 // sched_getaffinity gives an accurate answer as it accounts for cpusets.
4581 // If it appears there may be more than 1024 processors then we do a
4582 // dynamic check - see 6515172 for details.
4583 // If anything goes wrong we fallback to returning the number of online
4584 // processors - which can be greater than the number available to the process.
4585 int os::Linux::active_processor_count() {
4586   cpu_set_t cpus;  // can represent at most 1024 (CPU_SETSIZE) processors
4587   cpu_set_t* cpus_p = &cpus;
4588   int cpus_size = sizeof(cpu_set_t);
4589 
4590   int configured_cpus = os::processor_count();  // upper bound on available cpus
4591   int cpu_count = 0;
4592 
4593 // old build platforms may not support dynamic cpu sets
4594 #ifdef CPU_ALLOC
4595 
4596   // To enable easy testing of the dynamic path on different platforms we
4597   // introduce a diagnostic flag: UseCpuAllocPath
4598   if (configured_cpus >= CPU_SETSIZE || UseCpuAllocPath) {
4599     // kernel may use a mask bigger than cpu_set_t
4600     log_trace(os)("active_processor_count: using dynamic path %s"
4601                   "- configured processors: %d",
4602                   UseCpuAllocPath ? "(forced) " : "",
4603                   configured_cpus);
4604     cpus_p = CPU_ALLOC(configured_cpus);
4605     if (cpus_p != NULL) {
4606       cpus_size = CPU_ALLOC_SIZE(configured_cpus);
4607       // zero it just to be safe
4608       CPU_ZERO_S(cpus_size, cpus_p);
4609     }
4610     else {
4611        // failed to allocate so fallback to online cpus
4612        int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
4613        log_trace(os)("active_processor_count: "
4614                      "CPU_ALLOC failed (%s) - using "
4615                      "online processor count: %d",
4616                      os::strerror(errno), online_cpus);
4617        return online_cpus;
4618     }
4619   }
4620   else {
4621     log_trace(os)("active_processor_count: using static path - configured processors: %d",
4622                   configured_cpus);
4623   }
4624 #else // CPU_ALLOC
4625 // these stubs won't be executed
4626 #define CPU_COUNT_S(size, cpus) -1
4627 #define CPU_FREE(cpus)
4628 
4629   log_trace(os)("active_processor_count: only static path available - configured processors: %d",
4630                 configured_cpus);
4631 #endif // CPU_ALLOC
4632 
4633   // pid 0 means the current thread - which we have to assume represents the process
4634   if (sched_getaffinity(0, cpus_size, cpus_p) == 0) {
4635     if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used
4636       cpu_count = CPU_COUNT_S(cpus_size, cpus_p);
4637     }
4638     else {
4639       cpu_count = CPU_COUNT(cpus_p);
4640     }
4641     log_trace(os)("active_processor_count: sched_getaffinity processor count: %d", cpu_count);
4642   }
4643   else {
4644     cpu_count = ::sysconf(_SC_NPROCESSORS_ONLN);
4645     warning("sched_getaffinity failed (%s)- using online processor count (%d) "
4646             "which may exceed available processors", os::strerror(errno), cpu_count);
4647   }
4648 
4649   if (cpus_p != &cpus) { // can only be true when CPU_ALLOC used
4650     CPU_FREE(cpus_p);
4651   }
4652 
4653   assert(cpu_count > 0 && cpu_count <= os::processor_count(), "sanity check");
4654   return cpu_count;
4655 }
4656 
4657 // Determine the active processor count from one of
4658 // three different sources:
4659 //
4660 // 1. User option -XX:ActiveProcessorCount
4661 // 2. kernel os calls (sched_getaffinity or sysconf(_SC_NPROCESSORS_ONLN)
4662 // 3. extracted from cgroup cpu subsystem (shares and quotas)
4663 //
4664 // Option 1, if specified, will always override.
4665 // If the cgroup subsystem is active and configured, we
4666 // will return the min of the cgroup and option 2 results.
4667 // This is required since tools, such as numactl, that
4668 // alter cpu affinity do not update cgroup subsystem
4669 // cpuset configuration files.
4670 int os::active_processor_count() {
4671   // User has overridden the number of active processors
4672   if (ActiveProcessorCount > 0) {
4673     log_trace(os)("active_processor_count: "
4674                   "active processor count set by user : %d",
4675                   ActiveProcessorCount);
4676     return ActiveProcessorCount;
4677   }
4678 
4679   int active_cpus;
4680   if (OSContainer::is_containerized()) {
4681     active_cpus = OSContainer::active_processor_count();
4682     log_trace(os)("active_processor_count: determined by OSContainer: %d",
4683                    active_cpus);
4684   } else {
4685     active_cpus = os::Linux::active_processor_count();
4686   }
4687 
4688   return active_cpus;
4689 }
4690 
4691 static bool should_warn_invalid_processor_id() {
4692   if (os::processor_count() == 1) {
4693     // Don't warn if we only have one processor
4694     return false;
4695   }
4696 
4697   static volatile int warn_once = 1;
4698 
4699   if (Atomic::load(&warn_once) == 0 ||
4700       Atomic::xchg(&warn_once, 0) == 0) {
4701     // Don't warn more than once
4702     return false;
4703   }
4704 
4705   return true;
4706 }
4707 
4708 uint os::processor_id() {
4709   const int id = Linux::sched_getcpu();
4710 
4711   if (id < processor_count()) {
4712     return (uint)id;
4713   }
4714 
4715   // Some environments (e.g. openvz containers and the rr debugger) incorrectly
4716   // report a processor id that is higher than the number of processors available.
4717   // This is problematic, for example, when implementing CPU-local data structures,
4718   // where the processor id is used to index into an array of length processor_count().
4719   // If this happens we return 0 here. This is is safe since we always have at least
4720   // one processor, but it's not optimal for performance if we're actually executing
4721   // in an environment with more than one processor.
4722   if (should_warn_invalid_processor_id()) {
4723     log_warning(os)("Invalid processor id reported by the operating system "
4724                     "(got processor id %d, valid processor id range is 0-%d)",
4725                     id, processor_count() - 1);
4726     log_warning(os)("Falling back to assuming processor id is 0. "
4727                     "This could have a negative impact on performance.");
4728   }
4729 
4730   return 0;
4731 }
4732 
4733 void os::set_native_thread_name(const char *name) {
4734   if (Linux::_pthread_setname_np) {
4735     char buf [16]; // according to glibc manpage, 16 chars incl. '/0'
4736     snprintf(buf, sizeof(buf), "%s", name);
4737     buf[sizeof(buf) - 1] = '\0';
4738     const int rc = Linux::_pthread_setname_np(pthread_self(), buf);
4739     // ERANGE should not happen; all other errors should just be ignored.
4740     assert(rc != ERANGE, "pthread_setname_np failed");
4741   }
4742 }
4743 
4744 ////////////////////////////////////////////////////////////////////////////////
4745 // debug support
4746 
4747 bool os::find(address addr, outputStream* st) {
4748   Dl_info dlinfo;
4749   memset(&dlinfo, 0, sizeof(dlinfo));
4750   if (dladdr(addr, &dlinfo) != 0) {
4751     st->print(PTR_FORMAT ": ", p2i(addr));
4752     if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) {
4753       st->print("%s+" PTR_FORMAT, dlinfo.dli_sname,
4754                 p2i(addr) - p2i(dlinfo.dli_saddr));
4755     } else if (dlinfo.dli_fbase != NULL) {
4756       st->print("<offset " PTR_FORMAT ">", p2i(addr) - p2i(dlinfo.dli_fbase));
4757     } else {
4758       st->print("<absolute address>");
4759     }
4760     if (dlinfo.dli_fname != NULL) {
4761       st->print(" in %s", dlinfo.dli_fname);
4762     }
4763     if (dlinfo.dli_fbase != NULL) {
4764       st->print(" at " PTR_FORMAT, p2i(dlinfo.dli_fbase));
4765     }
4766     st->cr();
4767 
4768     if (Verbose) {
4769       // decode some bytes around the PC
4770       address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
4771       address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
4772       address       lowest = (address) dlinfo.dli_sname;
4773       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
4774       if (begin < lowest)  begin = lowest;
4775       Dl_info dlinfo2;
4776       if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr
4777           && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) {
4778         end = (address) dlinfo2.dli_saddr;
4779       }
4780       Disassembler::decode(begin, end, st);
4781     }
4782     return true;
4783   }
4784   return false;
4785 }
4786 
4787 ////////////////////////////////////////////////////////////////////////////////
4788 // misc
4789 
4790 // This does not do anything on Linux. This is basically a hook for being
4791 // able to use structured exception handling (thread-local exception filters)
4792 // on, e.g., Win32.
4793 void
4794 os::os_exception_wrapper(java_call_t f, JavaValue* value, const methodHandle& method,
4795                          JavaCallArguments* args, JavaThread* thread) {
4796   f(value, method, args, thread);
4797 }
4798 
4799 void os::print_statistics() {
4800 }
4801 
4802 bool os::message_box(const char* title, const char* message) {
4803   int i;
4804   fdStream err(defaultStream::error_fd());
4805   for (i = 0; i < 78; i++) err.print_raw("=");
4806   err.cr();
4807   err.print_raw_cr(title);
4808   for (i = 0; i < 78; i++) err.print_raw("-");
4809   err.cr();
4810   err.print_raw_cr(message);
4811   for (i = 0; i < 78; i++) err.print_raw("=");
4812   err.cr();
4813 
4814   char buf[16];
4815   // Prevent process from exiting upon "read error" without consuming all CPU
4816   while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); }
4817 
4818   return buf[0] == 'y' || buf[0] == 'Y';
4819 }
4820 
4821 // Is a (classpath) directory empty?
4822 bool os::dir_is_empty(const char* path) {
4823   DIR *dir = NULL;
4824   struct dirent *ptr;
4825 
4826   dir = opendir(path);
4827   if (dir == NULL) return true;
4828 
4829   // Scan the directory
4830   bool result = true;
4831   while (result && (ptr = readdir(dir)) != NULL) {
4832     if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
4833       result = false;
4834     }
4835   }
4836   closedir(dir);
4837   return result;
4838 }
4839 
4840 // This code originates from JDK's sysOpen and open64_w
4841 // from src/solaris/hpi/src/system_md.c
4842 
4843 int os::open(const char *path, int oflag, int mode) {
4844   if (strlen(path) > MAX_PATH - 1) {
4845     errno = ENAMETOOLONG;
4846     return -1;
4847   }
4848 
4849   // All file descriptors that are opened in the Java process and not
4850   // specifically destined for a subprocess should have the close-on-exec
4851   // flag set.  If we don't set it, then careless 3rd party native code
4852   // might fork and exec without closing all appropriate file descriptors
4853   // (e.g. as we do in closeDescriptors in UNIXProcess.c), and this in
4854   // turn might:
4855   //
4856   // - cause end-of-file to fail to be detected on some file
4857   //   descriptors, resulting in mysterious hangs, or
4858   //
4859   // - might cause an fopen in the subprocess to fail on a system
4860   //   suffering from bug 1085341.
4861   //
4862   // (Yes, the default setting of the close-on-exec flag is a Unix
4863   // design flaw)
4864   //
4865   // See:
4866   // 1085341: 32-bit stdio routines should support file descriptors >255
4867   // 4843136: (process) pipe file descriptor from Runtime.exec not being closed
4868   // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9
4869   //
4870   // Modern Linux kernels (after 2.6.23 2007) support O_CLOEXEC with open().
4871   // O_CLOEXEC is preferable to using FD_CLOEXEC on an open file descriptor
4872   // because it saves a system call and removes a small window where the flag
4873   // is unset.  On ancient Linux kernels the O_CLOEXEC flag will be ignored
4874   // and we fall back to using FD_CLOEXEC (see below).
4875 #ifdef O_CLOEXEC
4876   oflag |= O_CLOEXEC;
4877 #endif
4878 
4879   int fd = ::open64(path, oflag, mode);
4880   if (fd == -1) return -1;
4881 
4882   //If the open succeeded, the file might still be a directory
4883   {
4884     struct stat64 buf64;
4885     int ret = ::fstat64(fd, &buf64);
4886     int st_mode = buf64.st_mode;
4887 
4888     if (ret != -1) {
4889       if ((st_mode & S_IFMT) == S_IFDIR) {
4890         errno = EISDIR;
4891         ::close(fd);
4892         return -1;
4893       }
4894     } else {
4895       ::close(fd);
4896       return -1;
4897     }
4898   }
4899 
4900 #ifdef FD_CLOEXEC
4901   // Validate that the use of the O_CLOEXEC flag on open above worked.
4902   // With recent kernels, we will perform this check exactly once.
4903   static sig_atomic_t O_CLOEXEC_is_known_to_work = 0;
4904   if (!O_CLOEXEC_is_known_to_work) {
4905     int flags = ::fcntl(fd, F_GETFD);
4906     if (flags != -1) {
4907       if ((flags & FD_CLOEXEC) != 0)
4908         O_CLOEXEC_is_known_to_work = 1;
4909       else
4910         ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4911     }
4912   }
4913 #endif
4914 
4915   return fd;
4916 }
4917 
4918 
4919 // create binary file, rewriting existing file if required
4920 int os::create_binary_file(const char* path, bool rewrite_existing) {
4921   int oflags = O_WRONLY | O_CREAT;
4922   oflags |= rewrite_existing ? O_TRUNC : O_EXCL;
4923   return ::open64(path, oflags, S_IREAD | S_IWRITE);
4924 }
4925 
4926 // return current position of file pointer
4927 jlong os::current_file_offset(int fd) {
4928   return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR);
4929 }
4930 
4931 // move file pointer to the specified offset
4932 jlong os::seek_to_file_offset(int fd, jlong offset) {
4933   return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET);
4934 }
4935 
4936 // This code originates from JDK's sysAvailable
4937 // from src/solaris/hpi/src/native_threads/src/sys_api_td.c
4938 
4939 int os::available(int fd, jlong *bytes) {
4940   jlong cur, end;
4941   int mode;
4942   struct stat64 buf64;
4943 
4944   if (::fstat64(fd, &buf64) >= 0) {
4945     mode = buf64.st_mode;
4946     if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) {
4947       int n;
4948       if (::ioctl(fd, FIONREAD, &n) >= 0) {
4949         *bytes = n;
4950         return 1;
4951       }
4952     }
4953   }
4954   if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) {
4955     return 0;
4956   } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) {
4957     return 0;
4958   } else if (::lseek64(fd, cur, SEEK_SET) == -1) {
4959     return 0;
4960   }
4961   *bytes = end - cur;
4962   return 1;
4963 }
4964 
4965 // Map a block of memory.
4966 char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset,
4967                         char *addr, size_t bytes, bool read_only,
4968                         bool allow_exec) {
4969   int prot;
4970   int flags = MAP_PRIVATE;
4971 
4972   if (read_only) {
4973     prot = PROT_READ;
4974   } else {
4975     prot = PROT_READ | PROT_WRITE;
4976   }
4977 
4978   if (allow_exec) {
4979     prot |= PROT_EXEC;
4980   }
4981 
4982   if (addr != NULL) {
4983     flags |= MAP_FIXED;
4984   }
4985 
4986   char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags,
4987                                      fd, file_offset);
4988   if (mapped_address == MAP_FAILED) {
4989     return NULL;
4990   }
4991   return mapped_address;
4992 }
4993 
4994 
4995 // Remap a block of memory.
4996 char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset,
4997                           char *addr, size_t bytes, bool read_only,
4998                           bool allow_exec) {
4999   // same as map_memory() on this OS
5000   return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only,
5001                         allow_exec);
5002 }
5003 
5004 
5005 // Unmap a block of memory.
5006 bool os::pd_unmap_memory(char* addr, size_t bytes) {
5007   return munmap(addr, bytes) == 0;
5008 }
5009 
5010 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time);
5011 
5012 static jlong fast_cpu_time(Thread *thread) {
5013     clockid_t clockid;
5014     int rc = os::Linux::pthread_getcpuclockid(thread->osthread()->pthread_id(),
5015                                               &clockid);
5016     if (rc == 0) {
5017       return os::Linux::fast_thread_cpu_time(clockid);
5018     } else {
5019       // It's possible to encounter a terminated native thread that failed
5020       // to detach itself from the VM - which should result in ESRCH.
5021       assert_status(rc == ESRCH, rc, "pthread_getcpuclockid failed");
5022       return -1;
5023     }
5024 }
5025 
5026 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool)
5027 // are used by JVM M&M and JVMTI to get user+sys or user CPU time
5028 // of a thread.
5029 //
5030 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns
5031 // the fast estimate available on the platform.
5032 
5033 jlong os::current_thread_cpu_time() {
5034   if (os::Linux::supports_fast_thread_cpu_time()) {
5035     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5036   } else {
5037     // return user + sys since the cost is the same
5038     return slow_thread_cpu_time(Thread::current(), true /* user + sys */);
5039   }
5040 }
5041 
5042 jlong os::thread_cpu_time(Thread* thread) {
5043   // consistent with what current_thread_cpu_time() returns
5044   if (os::Linux::supports_fast_thread_cpu_time()) {
5045     return fast_cpu_time(thread);
5046   } else {
5047     return slow_thread_cpu_time(thread, true /* user + sys */);
5048   }
5049 }
5050 
5051 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
5052   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5053     return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID);
5054   } else {
5055     return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time);
5056   }
5057 }
5058 
5059 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5060   if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) {
5061     return fast_cpu_time(thread);
5062   } else {
5063     return slow_thread_cpu_time(thread, user_sys_cpu_time);
5064   }
5065 }
5066 
5067 //  -1 on error.
5068 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
5069   pid_t  tid = thread->osthread()->thread_id();
5070   char *s;
5071   char stat[2048];
5072   int statlen;
5073   char proc_name[64];
5074   int count;
5075   long sys_time, user_time;
5076   char cdummy;
5077   int idummy;
5078   long ldummy;
5079   FILE *fp;
5080 
5081   snprintf(proc_name, 64, "/proc/self/task/%d/stat", tid);
5082   fp = fopen(proc_name, "r");
5083   if (fp == NULL) return -1;
5084   statlen = fread(stat, 1, 2047, fp);
5085   stat[statlen] = '\0';
5086   fclose(fp);
5087 
5088   // Skip pid and the command string. Note that we could be dealing with
5089   // weird command names, e.g. user could decide to rename java launcher
5090   // to "java 1.4.2 :)", then the stat file would look like
5091   //                1234 (java 1.4.2 :)) R ... ...
5092   // We don't really need to know the command string, just find the last
5093   // occurrence of ")" and then start parsing from there. See bug 4726580.
5094   s = strrchr(stat, ')');
5095   if (s == NULL) return -1;
5096 
5097   // Skip blank chars
5098   do { s++; } while (s && isspace(*s));
5099 
5100   count = sscanf(s,"%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu",
5101                  &cdummy, &idummy, &idummy, &idummy, &idummy, &idummy,
5102                  &ldummy, &ldummy, &ldummy, &ldummy, &ldummy,
5103                  &user_time, &sys_time);
5104   if (count != 13) return -1;
5105   if (user_sys_cpu_time) {
5106     return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
5107   } else {
5108     return (jlong)user_time * (1000000000 / clock_tics_per_sec);
5109   }
5110 }
5111 
5112 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5113   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5114   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5115   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5116   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5117 }
5118 
5119 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) {
5120   info_ptr->max_value = ALL_64_BITS;       // will not wrap in less than 64 bits
5121   info_ptr->may_skip_backward = false;     // elapsed time not wall time
5122   info_ptr->may_skip_forward = false;      // elapsed time not wall time
5123   info_ptr->kind = JVMTI_TIMER_TOTAL_CPU;  // user+system time is returned
5124 }
5125 
5126 bool os::is_thread_cpu_time_supported() {
5127   return true;
5128 }
5129 
5130 // System loadavg support.  Returns -1 if load average cannot be obtained.
5131 // Linux doesn't yet have a (official) notion of processor sets,
5132 // so just return the system wide load average.
5133 int os::loadavg(double loadavg[], int nelem) {
5134   return ::getloadavg(loadavg, nelem);
5135 }
5136 
5137 void os::pause() {
5138   char filename[MAX_PATH];
5139   if (PauseAtStartupFile && PauseAtStartupFile[0]) {
5140     jio_snprintf(filename, MAX_PATH, "%s", PauseAtStartupFile);
5141   } else {
5142     jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id());
5143   }
5144 
5145   int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
5146   if (fd != -1) {
5147     struct stat buf;
5148     ::close(fd);
5149     while (::stat(filename, &buf) == 0) {
5150       (void)::poll(NULL, 0, 100);
5151     }
5152   } else {
5153     jio_fprintf(stderr,
5154                 "Could not open pause file '%s', continuing immediately.\n", filename);
5155   }
5156 }
5157 
5158 // Get the default path to the core file
5159 // Returns the length of the string
5160 int os::get_core_path(char* buffer, size_t bufferSize) {
5161   /*
5162    * Max length of /proc/sys/kernel/core_pattern is 128 characters.
5163    * See https://www.kernel.org/doc/Documentation/sysctl/kernel.txt
5164    */
5165   const int core_pattern_len = 129;
5166   char core_pattern[core_pattern_len] = {0};
5167 
5168   int core_pattern_file = ::open("/proc/sys/kernel/core_pattern", O_RDONLY);
5169   if (core_pattern_file == -1) {
5170     return -1;
5171   }
5172 
5173   ssize_t ret = ::read(core_pattern_file, core_pattern, core_pattern_len);
5174   ::close(core_pattern_file);
5175   if (ret <= 0 || ret >= core_pattern_len || core_pattern[0] == '\n') {
5176     return -1;
5177   }
5178   if (core_pattern[ret-1] == '\n') {
5179     core_pattern[ret-1] = '\0';
5180   } else {
5181     core_pattern[ret] = '\0';
5182   }
5183 
5184   // Replace the %p in the core pattern with the process id. NOTE: we do this
5185   // only if the pattern doesn't start with "|", and we support only one %p in
5186   // the pattern.
5187   char *pid_pos = strstr(core_pattern, "%p");
5188   const char* tail = (pid_pos != NULL) ? (pid_pos + 2) : "";  // skip over the "%p"
5189   int written;
5190 
5191   if (core_pattern[0] == '/') {
5192     if (pid_pos != NULL) {
5193       *pid_pos = '\0';
5194       written = jio_snprintf(buffer, bufferSize, "%s%d%s", core_pattern,
5195                              current_process_id(), tail);
5196     } else {
5197       written = jio_snprintf(buffer, bufferSize, "%s", core_pattern);
5198     }
5199   } else {
5200     char cwd[PATH_MAX];
5201 
5202     const char* p = get_current_directory(cwd, PATH_MAX);
5203     if (p == NULL) {
5204       return -1;
5205     }
5206 
5207     if (core_pattern[0] == '|') {
5208       written = jio_snprintf(buffer, bufferSize,
5209                              "\"%s\" (or dumping to %s/core.%d)",
5210                              &core_pattern[1], p, current_process_id());
5211     } else if (pid_pos != NULL) {
5212       *pid_pos = '\0';
5213       written = jio_snprintf(buffer, bufferSize, "%s/%s%d%s", p, core_pattern,
5214                              current_process_id(), tail);
5215     } else {
5216       written = jio_snprintf(buffer, bufferSize, "%s/%s", p, core_pattern);
5217     }
5218   }
5219 
5220   if (written < 0) {
5221     return -1;
5222   }
5223 
5224   if (((size_t)written < bufferSize) && (pid_pos == NULL) && (core_pattern[0] != '|')) {
5225     int core_uses_pid_file = ::open("/proc/sys/kernel/core_uses_pid", O_RDONLY);
5226 
5227     if (core_uses_pid_file != -1) {
5228       char core_uses_pid = 0;
5229       ssize_t ret = ::read(core_uses_pid_file, &core_uses_pid, 1);
5230       ::close(core_uses_pid_file);
5231 
5232       if (core_uses_pid == '1') {
5233         jio_snprintf(buffer + written, bufferSize - written,
5234                                           ".%d", current_process_id());
5235       }
5236     }
5237   }
5238 
5239   return strlen(buffer);
5240 }
5241 
5242 bool os::start_debugging(char *buf, int buflen) {
5243   int len = (int)strlen(buf);
5244   char *p = &buf[len];
5245 
5246   jio_snprintf(p, buflen-len,
5247                "\n\n"
5248                "Do you want to debug the problem?\n\n"
5249                "To debug, run 'gdb /proc/%d/exe %d'; then switch to thread " UINTX_FORMAT " (" INTPTR_FORMAT ")\n"
5250                "Enter 'yes' to launch gdb automatically (PATH must include gdb)\n"
5251                "Otherwise, press RETURN to abort...",
5252                os::current_process_id(), os::current_process_id(),
5253                os::current_thread_id(), os::current_thread_id());
5254 
5255   bool yes = os::message_box("Unexpected Error", buf);
5256 
5257   if (yes) {
5258     // yes, user asked VM to launch debugger
5259     jio_snprintf(buf, sizeof(char)*buflen, "gdb /proc/%d/exe %d",
5260                  os::current_process_id(), os::current_process_id());
5261 
5262     os::fork_and_exec(buf);
5263     yes = false;
5264   }
5265   return yes;
5266 }
5267 
5268 
5269 // Java/Compiler thread:
5270 //
5271 //   Low memory addresses
5272 // P0 +------------------------+
5273 //    |                        |\  Java thread created by VM does not have glibc
5274 //    |    glibc guard page    | - guard page, attached Java thread usually has
5275 //    |                        |/  1 glibc guard page.
5276 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
5277 //    |                        |\
5278 //    |  HotSpot Guard Pages   | - red, yellow and reserved pages
5279 //    |                        |/
5280 //    +------------------------+ StackOverflow::stack_reserved_zone_base()
5281 //    |                        |\
5282 //    |      Normal Stack      | -
5283 //    |                        |/
5284 // P2 +------------------------+ Thread::stack_base()
5285 //
5286 // Non-Java thread:
5287 //
5288 //   Low memory addresses
5289 // P0 +------------------------+
5290 //    |                        |\
5291 //    |  glibc guard page      | - usually 1 page
5292 //    |                        |/
5293 // P1 +------------------------+ Thread::stack_base() - Thread::stack_size()
5294 //    |                        |\
5295 //    |      Normal Stack      | -
5296 //    |                        |/
5297 // P2 +------------------------+ Thread::stack_base()
5298 //
5299 // ** P1 (aka bottom) and size (P2 = P1 - size) are the address and stack size
5300 //    returned from pthread_attr_getstack().
5301 // ** Due to NPTL implementation error, linux takes the glibc guard page out
5302 //    of the stack size given in pthread_attr. We work around this for
5303 //    threads created by the VM. (We adapt bottom to be P1 and size accordingly.)
5304 //
5305 #ifndef ZERO
5306 static void current_stack_region(address * bottom, size_t * size) {
5307   if (os::is_primordial_thread()) {
5308     // primordial thread needs special handling because pthread_getattr_np()
5309     // may return bogus value.
5310     *bottom = os::Linux::initial_thread_stack_bottom();
5311     *size   = os::Linux::initial_thread_stack_size();
5312   } else {
5313     pthread_attr_t attr;
5314 
5315     int rslt = pthread_getattr_np(pthread_self(), &attr);
5316 
5317     // JVM needs to know exact stack location, abort if it fails
5318     if (rslt != 0) {
5319       if (rslt == ENOMEM) {
5320         vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "pthread_getattr_np");
5321       } else {
5322         fatal("pthread_getattr_np failed with error = %d", rslt);
5323       }
5324     }
5325 
5326     if (pthread_attr_getstack(&attr, (void **)bottom, size) != 0) {
5327       fatal("Cannot locate current stack attributes!");
5328     }
5329 
5330     // Work around NPTL stack guard error.
5331     size_t guard_size = 0;
5332     rslt = pthread_attr_getguardsize(&attr, &guard_size);
5333     if (rslt != 0) {
5334       fatal("pthread_attr_getguardsize failed with error = %d", rslt);
5335     }
5336     *bottom += guard_size;
5337     *size   -= guard_size;
5338 
5339     pthread_attr_destroy(&attr);
5340 
5341   }
5342   assert(os::current_stack_pointer() >= *bottom &&
5343          os::current_stack_pointer() < *bottom + *size, "just checking");
5344 }
5345 
5346 address os::current_stack_base() {
5347   address bottom;
5348   size_t size;
5349   current_stack_region(&bottom, &size);
5350   return (bottom + size);
5351 }
5352 
5353 size_t os::current_stack_size() {
5354   // This stack size includes the usable stack and HotSpot guard pages
5355   // (for the threads that have Hotspot guard pages).
5356   address bottom;
5357   size_t size;
5358   current_stack_region(&bottom, &size);
5359   return size;
5360 }
5361 #endif
5362 
5363 static inline struct timespec get_mtime(const char* filename) {
5364   struct stat st;
5365   int ret = os::stat(filename, &st);
5366   assert(ret == 0, "failed to stat() file '%s': %s", filename, os::strerror(errno));
5367   return st.st_mtim;
5368 }
5369 
5370 int os::compare_file_modified_times(const char* file1, const char* file2) {
5371   struct timespec filetime1 = get_mtime(file1);
5372   struct timespec filetime2 = get_mtime(file2);
5373   int diff = filetime1.tv_sec - filetime2.tv_sec;
5374   if (diff == 0) {
5375     return filetime1.tv_nsec - filetime2.tv_nsec;
5376   }
5377   return diff;
5378 }
5379 
5380 bool os::supports_map_sync() {
5381   return true;
5382 }
5383 
5384 void os::print_memory_mappings(char* addr, size_t bytes, outputStream* st) {
5385   unsigned long long start = (unsigned long long)addr;
5386   unsigned long long end = start + bytes;
5387   FILE* f = ::fopen("/proc/self/maps", "r");
5388   int num_found = 0;
5389   if (f != NULL) {
5390     st->print("Range [%llx-%llx) contains: ", start, end);
5391     char line[512];
5392     while(fgets(line, sizeof(line), f) == line) {
5393       unsigned long long a1 = 0;
5394       unsigned long long a2 = 0;
5395       if (::sscanf(line, "%llx-%llx", &a1, &a2) == 2) {
5396         // Lets print out every range which touches ours.
5397         if ((a1 >= start && a1 < end) || // left leg in
5398             (a2 >= start && a2 < end) || // right leg in
5399             (a1 < start && a2 >= end)) { // superimposition
5400           num_found ++;
5401           st->print("%s", line); // line includes \n
5402         }
5403       }
5404     }
5405     ::fclose(f);
5406     if (num_found == 0) {
5407       st->print("nothing.");
5408     }
5409     st->cr();
5410   }
5411 }