os_solaris.cpp revision 10367:1c53edac6621
1/* 2 * Copyright (c) 1997, 2015, 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 "classfile/classLoader.hpp" 27#include "classfile/systemDictionary.hpp" 28#include "classfile/vmSymbols.hpp" 29#include "code/icBuffer.hpp" 30#include "code/vtableStubs.hpp" 31#include "compiler/compileBroker.hpp" 32#include "compiler/disassembler.hpp" 33#include "interpreter/interpreter.hpp" 34#include "jvm_solaris.h" 35#include "logging/log.hpp" 36#include "memory/allocation.inline.hpp" 37#include "memory/filemap.hpp" 38#include "mutex_solaris.inline.hpp" 39#include "oops/oop.inline.hpp" 40#include "os_share_solaris.hpp" 41#include "os_solaris.inline.hpp" 42#include "prims/jniFastGetField.hpp" 43#include "prims/jvm.h" 44#include "prims/jvm_misc.hpp" 45#include "runtime/arguments.hpp" 46#include "runtime/atomic.inline.hpp" 47#include "runtime/extendedPC.hpp" 48#include "runtime/globals.hpp" 49#include "runtime/interfaceSupport.hpp" 50#include "runtime/java.hpp" 51#include "runtime/javaCalls.hpp" 52#include "runtime/mutexLocker.hpp" 53#include "runtime/objectMonitor.hpp" 54#include "runtime/orderAccess.inline.hpp" 55#include "runtime/osThread.hpp" 56#include "runtime/perfMemory.hpp" 57#include "runtime/sharedRuntime.hpp" 58#include "runtime/statSampler.hpp" 59#include "runtime/stubRoutines.hpp" 60#include "runtime/thread.inline.hpp" 61#include "runtime/threadCritical.hpp" 62#include "runtime/timer.hpp" 63#include "runtime/vm_version.hpp" 64#include "semaphore_posix.hpp" 65#include "services/attachListener.hpp" 66#include "services/memTracker.hpp" 67#include "services/runtimeService.hpp" 68#include "utilities/decoder.hpp" 69#include "utilities/defaultStream.hpp" 70#include "utilities/events.hpp" 71#include "utilities/growableArray.hpp" 72#include "utilities/macros.hpp" 73#include "utilities/vmError.hpp" 74 75// put OS-includes here 76# include <dlfcn.h> 77# include <errno.h> 78# include <exception> 79# include <link.h> 80# include <poll.h> 81# include <pthread.h> 82# include <pwd.h> 83# include <schedctl.h> 84# include <setjmp.h> 85# include <signal.h> 86# include <stdio.h> 87# include <alloca.h> 88# include <sys/filio.h> 89# include <sys/ipc.h> 90# include <sys/lwp.h> 91# include <sys/machelf.h> // for elf Sym structure used by dladdr1 92# include <sys/mman.h> 93# include <sys/processor.h> 94# include <sys/procset.h> 95# include <sys/pset.h> 96# include <sys/resource.h> 97# include <sys/shm.h> 98# include <sys/socket.h> 99# include <sys/stat.h> 100# include <sys/systeminfo.h> 101# include <sys/time.h> 102# include <sys/times.h> 103# include <sys/types.h> 104# include <sys/wait.h> 105# include <sys/utsname.h> 106# include <thread.h> 107# include <unistd.h> 108# include <sys/priocntl.h> 109# include <sys/rtpriocntl.h> 110# include <sys/tspriocntl.h> 111# include <sys/iapriocntl.h> 112# include <sys/fxpriocntl.h> 113# include <sys/loadavg.h> 114# include <string.h> 115# include <stdio.h> 116 117# define _STRUCTURED_PROC 1 // this gets us the new structured proc interfaces of 5.6 & later 118# include <sys/procfs.h> // see comment in <sys/procfs.h> 119 120#define MAX_PATH (2 * K) 121 122// for timer info max values which include all bits 123#define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) 124 125 126// Here are some liblgrp types from sys/lgrp_user.h to be able to 127// compile on older systems without this header file. 128 129#ifndef MADV_ACCESS_LWP 130 #define MADV_ACCESS_LWP 7 /* next LWP to access heavily */ 131#endif 132#ifndef MADV_ACCESS_MANY 133 #define MADV_ACCESS_MANY 8 /* many processes to access heavily */ 134#endif 135 136#ifndef LGRP_RSRC_CPU 137 #define LGRP_RSRC_CPU 0 /* CPU resources */ 138#endif 139#ifndef LGRP_RSRC_MEM 140 #define LGRP_RSRC_MEM 1 /* memory resources */ 141#endif 142 143// Values for ThreadPriorityPolicy == 1 144int prio_policy1[CriticalPriority+1] = { 145 -99999, 0, 16, 32, 48, 64, 146 80, 96, 112, 124, 127, 127 }; 147 148// System parameters used internally 149static clock_t clock_tics_per_sec = 100; 150 151// Track if we have called enable_extended_FILE_stdio (on Solaris 10u4+) 152static bool enabled_extended_FILE_stdio = false; 153 154// For diagnostics to print a message once. see run_periodic_checks 155static bool check_addr0_done = false; 156static sigset_t check_signal_done; 157static bool check_signals = true; 158 159address os::Solaris::handler_start; // start pc of thr_sighndlrinfo 160address os::Solaris::handler_end; // end pc of thr_sighndlrinfo 161 162address os::Solaris::_main_stack_base = NULL; // 4352906 workaround 163 164 165// "default" initializers for missing libc APIs 166extern "C" { 167 static int lwp_mutex_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; } 168 static int lwp_mutex_destroy(mutex_t *mx) { return 0; } 169 170 static int lwp_cond_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; } 171 static int lwp_cond_destroy(cond_t *cv) { return 0; } 172} 173 174// "default" initializers for pthread-based synchronization 175extern "C" { 176 static int pthread_mutex_default_init(mutex_t *mx, int scope, void *arg) { memset(mx, 0, sizeof(mutex_t)); return 0; } 177 static int pthread_cond_default_init(cond_t *cv, int scope, void *arg){ memset(cv, 0, sizeof(cond_t)); return 0; } 178} 179 180static void unpackTime(timespec* absTime, bool isAbsolute, jlong time); 181 182static inline size_t adjust_stack_size(address base, size_t size) { 183 if ((ssize_t)size < 0) { 184 // 4759953: Compensate for ridiculous stack size. 185 size = max_intx; 186 } 187 if (size > (size_t)base) { 188 // 4812466: Make sure size doesn't allow the stack to wrap the address space. 189 size = (size_t)base; 190 } 191 return size; 192} 193 194static inline stack_t get_stack_info() { 195 stack_t st; 196 int retval = thr_stksegment(&st); 197 st.ss_size = adjust_stack_size((address)st.ss_sp, st.ss_size); 198 assert(retval == 0, "incorrect return value from thr_stksegment"); 199 assert((address)&st < (address)st.ss_sp, "Invalid stack base returned"); 200 assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned"); 201 return st; 202} 203 204address os::current_stack_base() { 205 int r = thr_main(); 206 guarantee(r == 0 || r == 1, "CR6501650 or CR6493689"); 207 bool is_primordial_thread = r; 208 209 // Workaround 4352906, avoid calls to thr_stksegment by 210 // thr_main after the first one (it looks like we trash 211 // some data, causing the value for ss_sp to be incorrect). 212 if (!is_primordial_thread || os::Solaris::_main_stack_base == NULL) { 213 stack_t st = get_stack_info(); 214 if (is_primordial_thread) { 215 // cache initial value of stack base 216 os::Solaris::_main_stack_base = (address)st.ss_sp; 217 } 218 return (address)st.ss_sp; 219 } else { 220 guarantee(os::Solaris::_main_stack_base != NULL, "Attempt to use null cached stack base"); 221 return os::Solaris::_main_stack_base; 222 } 223} 224 225size_t os::current_stack_size() { 226 size_t size; 227 228 int r = thr_main(); 229 guarantee(r == 0 || r == 1, "CR6501650 or CR6493689"); 230 if (!r) { 231 size = get_stack_info().ss_size; 232 } else { 233 struct rlimit limits; 234 getrlimit(RLIMIT_STACK, &limits); 235 size = adjust_stack_size(os::Solaris::_main_stack_base, (size_t)limits.rlim_cur); 236 } 237 // base may not be page aligned 238 address base = current_stack_base(); 239 address bottom = (address)align_size_up((intptr_t)(base - size), os::vm_page_size());; 240 return (size_t)(base - bottom); 241} 242 243struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { 244 return localtime_r(clock, res); 245} 246 247void os::Solaris::try_enable_extended_io() { 248 typedef int (*enable_extended_FILE_stdio_t)(int, int); 249 250 if (!UseExtendedFileIO) { 251 return; 252 } 253 254 enable_extended_FILE_stdio_t enabler = 255 (enable_extended_FILE_stdio_t) dlsym(RTLD_DEFAULT, 256 "enable_extended_FILE_stdio"); 257 if (enabler) { 258 enabler(-1, -1); 259 } 260} 261 262static int _processors_online = 0; 263 264jint os::Solaris::_os_thread_limit = 0; 265volatile jint os::Solaris::_os_thread_count = 0; 266 267julong os::available_memory() { 268 return Solaris::available_memory(); 269} 270 271julong os::Solaris::available_memory() { 272 return (julong)sysconf(_SC_AVPHYS_PAGES) * os::vm_page_size(); 273} 274 275julong os::Solaris::_physical_memory = 0; 276 277julong os::physical_memory() { 278 return Solaris::physical_memory(); 279} 280 281static hrtime_t first_hrtime = 0; 282static const hrtime_t hrtime_hz = 1000*1000*1000; 283static volatile hrtime_t max_hrtime = 0; 284 285 286void os::Solaris::initialize_system_info() { 287 set_processor_count(sysconf(_SC_NPROCESSORS_CONF)); 288 _processors_online = sysconf(_SC_NPROCESSORS_ONLN); 289 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * 290 (julong)sysconf(_SC_PAGESIZE); 291} 292 293int os::active_processor_count() { 294 int online_cpus = sysconf(_SC_NPROCESSORS_ONLN); 295 pid_t pid = getpid(); 296 psetid_t pset = PS_NONE; 297 // Are we running in a processor set or is there any processor set around? 298 if (pset_bind(PS_QUERY, P_PID, pid, &pset) == 0) { 299 uint_t pset_cpus; 300 // Query the number of cpus available to us. 301 if (pset_info(pset, NULL, &pset_cpus, NULL) == 0) { 302 assert(pset_cpus > 0 && pset_cpus <= online_cpus, "sanity check"); 303 _processors_online = pset_cpus; 304 return pset_cpus; 305 } 306 } 307 // Otherwise return number of online cpus 308 return online_cpus; 309} 310 311static bool find_processors_in_pset(psetid_t pset, 312 processorid_t** id_array, 313 uint_t* id_length) { 314 bool result = false; 315 // Find the number of processors in the processor set. 316 if (pset_info(pset, NULL, id_length, NULL) == 0) { 317 // Make up an array to hold their ids. 318 *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal); 319 // Fill in the array with their processor ids. 320 if (pset_info(pset, NULL, id_length, *id_array) == 0) { 321 result = true; 322 } 323 } 324 return result; 325} 326 327// Callers of find_processors_online() must tolerate imprecise results -- 328// the system configuration can change asynchronously because of DR 329// or explicit psradm operations. 330// 331// We also need to take care that the loop (below) terminates as the 332// number of processors online can change between the _SC_NPROCESSORS_ONLN 333// request and the loop that builds the list of processor ids. Unfortunately 334// there's no reliable way to determine the maximum valid processor id, 335// so we use a manifest constant, MAX_PROCESSOR_ID, instead. See p_online 336// man pages, which claim the processor id set is "sparse, but 337// not too sparse". MAX_PROCESSOR_ID is used to ensure that we eventually 338// exit the loop. 339// 340// In the future we'll be able to use sysconf(_SC_CPUID_MAX), but that's 341// not available on S8.0. 342 343static bool find_processors_online(processorid_t** id_array, 344 uint* id_length) { 345 const processorid_t MAX_PROCESSOR_ID = 100000; 346 // Find the number of processors online. 347 *id_length = sysconf(_SC_NPROCESSORS_ONLN); 348 // Make up an array to hold their ids. 349 *id_array = NEW_C_HEAP_ARRAY(processorid_t, *id_length, mtInternal); 350 // Processors need not be numbered consecutively. 351 long found = 0; 352 processorid_t next = 0; 353 while (found < *id_length && next < MAX_PROCESSOR_ID) { 354 processor_info_t info; 355 if (processor_info(next, &info) == 0) { 356 // NB, PI_NOINTR processors are effectively online ... 357 if (info.pi_state == P_ONLINE || info.pi_state == P_NOINTR) { 358 (*id_array)[found] = next; 359 found += 1; 360 } 361 } 362 next += 1; 363 } 364 if (found < *id_length) { 365 // The loop above didn't identify the expected number of processors. 366 // We could always retry the operation, calling sysconf(_SC_NPROCESSORS_ONLN) 367 // and re-running the loop, above, but there's no guarantee of progress 368 // if the system configuration is in flux. Instead, we just return what 369 // we've got. Note that in the worst case find_processors_online() could 370 // return an empty set. (As a fall-back in the case of the empty set we 371 // could just return the ID of the current processor). 372 *id_length = found; 373 } 374 375 return true; 376} 377 378static bool assign_distribution(processorid_t* id_array, 379 uint id_length, 380 uint* distribution, 381 uint distribution_length) { 382 // We assume we can assign processorid_t's to uint's. 383 assert(sizeof(processorid_t) == sizeof(uint), 384 "can't convert processorid_t to uint"); 385 // Quick check to see if we won't succeed. 386 if (id_length < distribution_length) { 387 return false; 388 } 389 // Assign processor ids to the distribution. 390 // Try to shuffle processors to distribute work across boards, 391 // assuming 4 processors per board. 392 const uint processors_per_board = ProcessDistributionStride; 393 // Find the maximum processor id. 394 processorid_t max_id = 0; 395 for (uint m = 0; m < id_length; m += 1) { 396 max_id = MAX2(max_id, id_array[m]); 397 } 398 // The next id, to limit loops. 399 const processorid_t limit_id = max_id + 1; 400 // Make up markers for available processors. 401 bool* available_id = NEW_C_HEAP_ARRAY(bool, limit_id, mtInternal); 402 for (uint c = 0; c < limit_id; c += 1) { 403 available_id[c] = false; 404 } 405 for (uint a = 0; a < id_length; a += 1) { 406 available_id[id_array[a]] = true; 407 } 408 // Step by "boards", then by "slot", copying to "assigned". 409 // NEEDS_CLEANUP: The assignment of processors should be stateful, 410 // remembering which processors have been assigned by 411 // previous calls, etc., so as to distribute several 412 // independent calls of this method. What we'd like is 413 // It would be nice to have an API that let us ask 414 // how many processes are bound to a processor, 415 // but we don't have that, either. 416 // In the short term, "board" is static so that 417 // subsequent distributions don't all start at board 0. 418 static uint board = 0; 419 uint assigned = 0; 420 // Until we've found enough processors .... 421 while (assigned < distribution_length) { 422 // ... find the next available processor in the board. 423 for (uint slot = 0; slot < processors_per_board; slot += 1) { 424 uint try_id = board * processors_per_board + slot; 425 if ((try_id < limit_id) && (available_id[try_id] == true)) { 426 distribution[assigned] = try_id; 427 available_id[try_id] = false; 428 assigned += 1; 429 break; 430 } 431 } 432 board += 1; 433 if (board * processors_per_board + 0 >= limit_id) { 434 board = 0; 435 } 436 } 437 if (available_id != NULL) { 438 FREE_C_HEAP_ARRAY(bool, available_id); 439 } 440 return true; 441} 442 443void os::set_native_thread_name(const char *name) { 444 // Not yet implemented. 445 return; 446} 447 448bool os::distribute_processes(uint length, uint* distribution) { 449 bool result = false; 450 // Find the processor id's of all the available CPUs. 451 processorid_t* id_array = NULL; 452 uint id_length = 0; 453 // There are some races between querying information and using it, 454 // since processor sets can change dynamically. 455 psetid_t pset = PS_NONE; 456 // Are we running in a processor set? 457 if ((pset_bind(PS_QUERY, P_PID, P_MYID, &pset) == 0) && pset != PS_NONE) { 458 result = find_processors_in_pset(pset, &id_array, &id_length); 459 } else { 460 result = find_processors_online(&id_array, &id_length); 461 } 462 if (result == true) { 463 if (id_length >= length) { 464 result = assign_distribution(id_array, id_length, distribution, length); 465 } else { 466 result = false; 467 } 468 } 469 if (id_array != NULL) { 470 FREE_C_HEAP_ARRAY(processorid_t, id_array); 471 } 472 return result; 473} 474 475bool os::bind_to_processor(uint processor_id) { 476 // We assume that a processorid_t can be stored in a uint. 477 assert(sizeof(uint) == sizeof(processorid_t), 478 "can't convert uint to processorid_t"); 479 int bind_result = 480 processor_bind(P_LWPID, // bind LWP. 481 P_MYID, // bind current LWP. 482 (processorid_t) processor_id, // id. 483 NULL); // don't return old binding. 484 return (bind_result == 0); 485} 486 487// Return true if user is running as root. 488 489bool os::have_special_privileges() { 490 static bool init = false; 491 static bool privileges = false; 492 if (!init) { 493 privileges = (getuid() != geteuid()) || (getgid() != getegid()); 494 init = true; 495 } 496 return privileges; 497} 498 499 500void os::init_system_properties_values() { 501 // The next steps are taken in the product version: 502 // 503 // Obtain the JAVA_HOME value from the location of libjvm.so. 504 // This library should be located at: 505 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm.so. 506 // 507 // If "/jre/lib/" appears at the right place in the path, then we 508 // assume libjvm.so is installed in a JDK and we use this path. 509 // 510 // Otherwise exit with message: "Could not create the Java virtual machine." 511 // 512 // The following extra steps are taken in the debugging version: 513 // 514 // If "/jre/lib/" does NOT appear at the right place in the path 515 // instead of exit check for $JAVA_HOME environment variable. 516 // 517 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, 518 // then we append a fake suffix "hotspot/libjvm.so" to this path so 519 // it looks like libjvm.so is installed there 520 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm.so. 521 // 522 // Otherwise exit. 523 // 524 // Important note: if the location of libjvm.so changes this 525 // code needs to be changed accordingly. 526 527// Base path of extensions installed on the system. 528#define SYS_EXT_DIR "/usr/jdk/packages" 529#define EXTENSIONS_DIR "/lib/ext" 530 531 char cpu_arch[12]; 532 // Buffer that fits several sprintfs. 533 // Note that the space for the colon and the trailing null are provided 534 // by the nulls included by the sizeof operator. 535 const size_t bufsize = 536 MAX3((size_t)MAXPATHLEN, // For dll_dir & friends. 537 sizeof(SYS_EXT_DIR) + sizeof("/lib/") + strlen(cpu_arch), // invariant ld_library_path 538 (size_t)MAXPATHLEN + sizeof(EXTENSIONS_DIR) + sizeof(SYS_EXT_DIR) + sizeof(EXTENSIONS_DIR)); // extensions dir 539 char *buf = (char *)NEW_C_HEAP_ARRAY(char, bufsize, mtInternal); 540 541 // sysclasspath, java_home, dll_dir 542 { 543 char *pslash; 544 os::jvm_path(buf, bufsize); 545 546 // Found the full path to libjvm.so. 547 // Now cut the path to <java_home>/jre if we can. 548 *(strrchr(buf, '/')) = '\0'; // Get rid of /libjvm.so. 549 pslash = strrchr(buf, '/'); 550 if (pslash != NULL) { 551 *pslash = '\0'; // Get rid of /{client|server|hotspot}. 552 } 553 Arguments::set_dll_dir(buf); 554 555 if (pslash != NULL) { 556 pslash = strrchr(buf, '/'); 557 if (pslash != NULL) { 558 *pslash = '\0'; // Get rid of /<arch>. 559 pslash = strrchr(buf, '/'); 560 if (pslash != NULL) { 561 *pslash = '\0'; // Get rid of /lib. 562 } 563 } 564 } 565 Arguments::set_java_home(buf); 566 set_boot_path('/', ':'); 567 } 568 569 // Where to look for native libraries. 570 { 571 // Use dlinfo() to determine the correct java.library.path. 572 // 573 // If we're launched by the Java launcher, and the user 574 // does not set java.library.path explicitly on the commandline, 575 // the Java launcher sets LD_LIBRARY_PATH for us and unsets 576 // LD_LIBRARY_PATH_32 and LD_LIBRARY_PATH_64. In this case 577 // dlinfo returns LD_LIBRARY_PATH + crle settings (including 578 // /usr/lib), which is exactly what we want. 579 // 580 // If the user does set java.library.path, it completely 581 // overwrites this setting, and always has. 582 // 583 // If we're not launched by the Java launcher, we may 584 // get here with any/all of the LD_LIBRARY_PATH[_32|64] 585 // settings. Again, dlinfo does exactly what we want. 586 587 Dl_serinfo info_sz, *info = &info_sz; 588 Dl_serpath *path; 589 char *library_path; 590 char *common_path = buf; 591 592 // Determine search path count and required buffer size. 593 if (dlinfo(RTLD_SELF, RTLD_DI_SERINFOSIZE, (void *)info) == -1) { 594 FREE_C_HEAP_ARRAY(char, buf); 595 vm_exit_during_initialization("dlinfo SERINFOSIZE request", dlerror()); 596 } 597 598 // Allocate new buffer and initialize. 599 info = (Dl_serinfo*)NEW_C_HEAP_ARRAY(char, info_sz.dls_size, mtInternal); 600 info->dls_size = info_sz.dls_size; 601 info->dls_cnt = info_sz.dls_cnt; 602 603 // Obtain search path information. 604 if (dlinfo(RTLD_SELF, RTLD_DI_SERINFO, (void *)info) == -1) { 605 FREE_C_HEAP_ARRAY(char, buf); 606 FREE_C_HEAP_ARRAY(char, info); 607 vm_exit_during_initialization("dlinfo SERINFO request", dlerror()); 608 } 609 610 path = &info->dls_serpath[0]; 611 612 // Note: Due to a legacy implementation, most of the library path 613 // is set in the launcher. This was to accomodate linking restrictions 614 // on legacy Solaris implementations (which are no longer supported). 615 // Eventually, all the library path setting will be done here. 616 // 617 // However, to prevent the proliferation of improperly built native 618 // libraries, the new path component /usr/jdk/packages is added here. 619 620 // Determine the actual CPU architecture. 621 sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch)); 622#ifdef _LP64 623 // If we are a 64-bit vm, perform the following translations: 624 // sparc -> sparcv9 625 // i386 -> amd64 626 if (strcmp(cpu_arch, "sparc") == 0) { 627 strcat(cpu_arch, "v9"); 628 } else if (strcmp(cpu_arch, "i386") == 0) { 629 strcpy(cpu_arch, "amd64"); 630 } 631#endif 632 633 // Construct the invariant part of ld_library_path. 634 sprintf(common_path, SYS_EXT_DIR "/lib/%s", cpu_arch); 635 636 // Struct size is more than sufficient for the path components obtained 637 // through the dlinfo() call, so only add additional space for the path 638 // components explicitly added here. 639 size_t library_path_size = info->dls_size + strlen(common_path); 640 library_path = (char *)NEW_C_HEAP_ARRAY(char, library_path_size, mtInternal); 641 library_path[0] = '\0'; 642 643 // Construct the desired Java library path from the linker's library 644 // search path. 645 // 646 // For compatibility, it is optimal that we insert the additional path 647 // components specific to the Java VM after those components specified 648 // in LD_LIBRARY_PATH (if any) but before those added by the ld.so 649 // infrastructure. 650 if (info->dls_cnt == 0) { // Not sure this can happen, but allow for it. 651 strcpy(library_path, common_path); 652 } else { 653 int inserted = 0; 654 int i; 655 for (i = 0; i < info->dls_cnt; i++, path++) { 656 uint_t flags = path->dls_flags & LA_SER_MASK; 657 if (((flags & LA_SER_LIBPATH) == 0) && !inserted) { 658 strcat(library_path, common_path); 659 strcat(library_path, os::path_separator()); 660 inserted = 1; 661 } 662 strcat(library_path, path->dls_name); 663 strcat(library_path, os::path_separator()); 664 } 665 // Eliminate trailing path separator. 666 library_path[strlen(library_path)-1] = '\0'; 667 } 668 669 // happens before argument parsing - can't use a trace flag 670 // tty->print_raw("init_system_properties_values: native lib path: "); 671 // tty->print_raw_cr(library_path); 672 673 // Callee copies into its own buffer. 674 Arguments::set_library_path(library_path); 675 676 FREE_C_HEAP_ARRAY(char, library_path); 677 FREE_C_HEAP_ARRAY(char, info); 678 } 679 680 // Extensions directories. 681 sprintf(buf, "%s" EXTENSIONS_DIR ":" SYS_EXT_DIR EXTENSIONS_DIR, Arguments::get_java_home()); 682 Arguments::set_ext_dirs(buf); 683 684 FREE_C_HEAP_ARRAY(char, buf); 685 686#undef SYS_EXT_DIR 687#undef EXTENSIONS_DIR 688} 689 690void os::breakpoint() { 691 BREAKPOINT; 692} 693 694bool os::obsolete_option(const JavaVMOption *option) { 695 if (!strncmp(option->optionString, "-Xt", 3)) { 696 return true; 697 } else if (!strncmp(option->optionString, "-Xtm", 4)) { 698 return true; 699 } else if (!strncmp(option->optionString, "-Xverifyheap", 12)) { 700 return true; 701 } else if (!strncmp(option->optionString, "-Xmaxjitcodesize", 16)) { 702 return true; 703 } 704 return false; 705} 706 707bool os::Solaris::valid_stack_address(Thread* thread, address sp) { 708 address stackStart = (address)thread->stack_base(); 709 address stackEnd = (address)(stackStart - (address)thread->stack_size()); 710 if (sp < stackStart && sp >= stackEnd) return true; 711 return false; 712} 713 714extern "C" void breakpoint() { 715 // use debugger to set breakpoint here 716} 717 718static thread_t main_thread; 719 720// Thread start routine for all new Java threads 721extern "C" void* java_start(void* thread_addr) { 722 // Try to randomize the cache line index of hot stack frames. 723 // This helps when threads of the same stack traces evict each other's 724 // cache lines. The threads can be either from the same JVM instance, or 725 // from different JVM instances. The benefit is especially true for 726 // processors with hyperthreading technology. 727 static int counter = 0; 728 int pid = os::current_process_id(); 729 alloca(((pid ^ counter++) & 7) * 128); 730 731 int prio; 732 Thread* thread = (Thread*)thread_addr; 733 734 thread->initialize_thread_current(); 735 736 OSThread* osthr = thread->osthread(); 737 738 osthr->set_lwp_id(_lwp_self()); // Store lwp in case we are bound 739 thread->_schedctl = (void *) schedctl_init(); 740 741 log_info(os, thread)("Thread is alive (tid: " UINTX_FORMAT ").", 742 os::current_thread_id()); 743 744 if (UseNUMA) { 745 int lgrp_id = os::numa_get_group_id(); 746 if (lgrp_id != -1) { 747 thread->set_lgrp_id(lgrp_id); 748 } 749 } 750 751 // If the creator called set priority before we started, 752 // we need to call set_native_priority now that we have an lwp. 753 // We used to get the priority from thr_getprio (we called 754 // thr_setprio way back in create_thread) and pass it to 755 // set_native_priority, but Solaris scales the priority 756 // in java_to_os_priority, so when we read it back here, 757 // we pass trash to set_native_priority instead of what's 758 // in java_to_os_priority. So we save the native priority 759 // in the osThread and recall it here. 760 761 if (osthr->thread_id() != -1) { 762 if (UseThreadPriorities) { 763 int prio = osthr->native_priority(); 764 if (ThreadPriorityVerbose) { 765 tty->print_cr("Starting Thread " INTPTR_FORMAT ", LWP is " 766 INTPTR_FORMAT ", setting priority: %d\n", 767 osthr->thread_id(), osthr->lwp_id(), prio); 768 } 769 os::set_native_priority(thread, prio); 770 } 771 } else if (ThreadPriorityVerbose) { 772 warning("Can't set priority in _start routine, thread id hasn't been set\n"); 773 } 774 775 assert(osthr->get_state() == RUNNABLE, "invalid os thread state"); 776 777 // initialize signal mask for this thread 778 os::Solaris::hotspot_sigmask(thread); 779 780 thread->run(); 781 782 // One less thread is executing 783 // When the VMThread gets here, the main thread may have already exited 784 // which frees the CodeHeap containing the Atomic::dec code 785 if (thread != VMThread::vm_thread() && VMThread::vm_thread() != NULL) { 786 Atomic::dec(&os::Solaris::_os_thread_count); 787 } 788 789 log_info(os, thread)("Thread finished (tid: " UINTX_FORMAT ").", os::current_thread_id()); 790 791 if (UseDetachedThreads) { 792 thr_exit(NULL); 793 ShouldNotReachHere(); 794 } 795 return NULL; 796} 797 798static OSThread* create_os_thread(Thread* thread, thread_t thread_id) { 799 // Allocate the OSThread object 800 OSThread* osthread = new OSThread(NULL, NULL); 801 if (osthread == NULL) return NULL; 802 803 // Store info on the Solaris thread into the OSThread 804 osthread->set_thread_id(thread_id); 805 osthread->set_lwp_id(_lwp_self()); 806 thread->_schedctl = (void *) schedctl_init(); 807 808 if (UseNUMA) { 809 int lgrp_id = os::numa_get_group_id(); 810 if (lgrp_id != -1) { 811 thread->set_lgrp_id(lgrp_id); 812 } 813 } 814 815 if (ThreadPriorityVerbose) { 816 tty->print_cr("In create_os_thread, Thread " INTPTR_FORMAT ", LWP is " INTPTR_FORMAT "\n", 817 osthread->thread_id(), osthread->lwp_id()); 818 } 819 820 // Initial thread state is INITIALIZED, not SUSPENDED 821 osthread->set_state(INITIALIZED); 822 823 return osthread; 824} 825 826void os::Solaris::hotspot_sigmask(Thread* thread) { 827 //Save caller's signal mask 828 sigset_t sigmask; 829 pthread_sigmask(SIG_SETMASK, NULL, &sigmask); 830 OSThread *osthread = thread->osthread(); 831 osthread->set_caller_sigmask(sigmask); 832 833 pthread_sigmask(SIG_UNBLOCK, os::Solaris::unblocked_signals(), NULL); 834 if (!ReduceSignalUsage) { 835 if (thread->is_VM_thread()) { 836 // Only the VM thread handles BREAK_SIGNAL ... 837 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); 838 } else { 839 // ... all other threads block BREAK_SIGNAL 840 assert(!sigismember(vm_signals(), SIGINT), "SIGINT should not be blocked"); 841 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); 842 } 843 } 844} 845 846bool os::create_attached_thread(JavaThread* thread) { 847#ifdef ASSERT 848 thread->verify_not_published(); 849#endif 850 OSThread* osthread = create_os_thread(thread, thr_self()); 851 if (osthread == NULL) { 852 return false; 853 } 854 855 // Initial thread state is RUNNABLE 856 osthread->set_state(RUNNABLE); 857 thread->set_osthread(osthread); 858 859 // initialize signal mask for this thread 860 // and save the caller's signal mask 861 os::Solaris::hotspot_sigmask(thread); 862 863 log_info(os, thread)("Thread attached (tid: " UINTX_FORMAT ").", 864 os::current_thread_id()); 865 866 return true; 867} 868 869bool os::create_main_thread(JavaThread* thread) { 870#ifdef ASSERT 871 thread->verify_not_published(); 872#endif 873 if (_starting_thread == NULL) { 874 _starting_thread = create_os_thread(thread, main_thread); 875 if (_starting_thread == NULL) { 876 return false; 877 } 878 } 879 880 // The primodial thread is runnable from the start 881 _starting_thread->set_state(RUNNABLE); 882 883 thread->set_osthread(_starting_thread); 884 885 // initialize signal mask for this thread 886 // and save the caller's signal mask 887 os::Solaris::hotspot_sigmask(thread); 888 889 return true; 890} 891 892// Helper function to trace thread attributes, similar to os::Posix::describe_pthread_attr() 893static char* describe_thr_create_attributes(char* buf, size_t buflen, 894 size_t stacksize, long flags) 895{ 896 stringStream ss(buf, buflen); 897 ss.print("stacksize: " SIZE_FORMAT "k, ", stacksize / 1024); 898 ss.print("flags: "); 899 #define PRINT_FLAG(f) if (flags & f) ss.print( XSTR(f) " "); 900 #define ALL(X) \ 901 X(THR_SUSPENDED) \ 902 X(THR_DETACHED) \ 903 X(THR_BOUND) \ 904 X(THR_NEW_LWP) \ 905 X(THR_DAEMON) 906 ALL(PRINT_FLAG) 907 #undef ALL 908 #undef PRINT_FLAG 909 return buf; 910} 911 912bool os::create_thread(Thread* thread, ThreadType thr_type, 913 size_t stack_size) { 914 // Allocate the OSThread object 915 OSThread* osthread = new OSThread(NULL, NULL); 916 if (osthread == NULL) { 917 return false; 918 } 919 920 if (ThreadPriorityVerbose) { 921 char *thrtyp; 922 switch (thr_type) { 923 case vm_thread: 924 thrtyp = (char *)"vm"; 925 break; 926 case cgc_thread: 927 thrtyp = (char *)"cgc"; 928 break; 929 case pgc_thread: 930 thrtyp = (char *)"pgc"; 931 break; 932 case java_thread: 933 thrtyp = (char *)"java"; 934 break; 935 case compiler_thread: 936 thrtyp = (char *)"compiler"; 937 break; 938 case watcher_thread: 939 thrtyp = (char *)"watcher"; 940 break; 941 default: 942 thrtyp = (char *)"unknown"; 943 break; 944 } 945 tty->print_cr("In create_thread, creating a %s thread\n", thrtyp); 946 } 947 948 // Calculate stack size if it's not specified by caller. 949 if (stack_size == 0) { 950 // The default stack size 1M (2M for LP64). 951 stack_size = (BytesPerWord >> 2) * K * K; 952 953 switch (thr_type) { 954 case os::java_thread: 955 // Java threads use ThreadStackSize which default value can be changed with the flag -Xss 956 if (JavaThread::stack_size_at_create() > 0) stack_size = JavaThread::stack_size_at_create(); 957 break; 958 case os::compiler_thread: 959 if (CompilerThreadStackSize > 0) { 960 stack_size = (size_t)(CompilerThreadStackSize * K); 961 break; 962 } // else fall through: 963 // use VMThreadStackSize if CompilerThreadStackSize is not defined 964 case os::vm_thread: 965 case os::pgc_thread: 966 case os::cgc_thread: 967 case os::watcher_thread: 968 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); 969 break; 970 } 971 } 972 stack_size = MAX2(stack_size, os::Solaris::min_stack_allowed); 973 974 // Initial state is ALLOCATED but not INITIALIZED 975 osthread->set_state(ALLOCATED); 976 977 if (os::Solaris::_os_thread_count > os::Solaris::_os_thread_limit) { 978 // We got lots of threads. Check if we still have some address space left. 979 // Need to be at least 5Mb of unreserved address space. We do check by 980 // trying to reserve some. 981 const size_t VirtualMemoryBangSize = 20*K*K; 982 char* mem = os::reserve_memory(VirtualMemoryBangSize); 983 if (mem == NULL) { 984 delete osthread; 985 return false; 986 } else { 987 // Release the memory again 988 os::release_memory(mem, VirtualMemoryBangSize); 989 } 990 } 991 992 // Setup osthread because the child thread may need it. 993 thread->set_osthread(osthread); 994 995 // Create the Solaris thread 996 thread_t tid = 0; 997 long flags = (UseDetachedThreads ? THR_DETACHED : 0) | THR_SUSPENDED; 998 int status; 999 1000 // Mark that we don't have an lwp or thread id yet. 1001 // In case we attempt to set the priority before the thread starts. 1002 osthread->set_lwp_id(-1); 1003 osthread->set_thread_id(-1); 1004 1005 status = thr_create(NULL, stack_size, java_start, thread, flags, &tid); 1006 1007 char buf[64]; 1008 if (status == 0) { 1009 log_info(os, thread)("Thread started (pthread id: " UINTX_FORMAT ", attributes: %s). ", 1010 (uintx) tid, describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags)); 1011 } else { 1012 log_warning(os, thread)("Failed to start thread - thr_create failed (%s) for attributes: %s.", 1013 strerror(status), describe_thr_create_attributes(buf, sizeof(buf), stack_size, flags)); 1014 } 1015 1016 if (status != 0) { 1017 thread->set_osthread(NULL); 1018 // Need to clean up stuff we've allocated so far 1019 delete osthread; 1020 return false; 1021 } 1022 1023 Atomic::inc(&os::Solaris::_os_thread_count); 1024 1025 // Store info on the Solaris thread into the OSThread 1026 osthread->set_thread_id(tid); 1027 1028 // Remember that we created this thread so we can set priority on it 1029 osthread->set_vm_created(); 1030 1031 // Initial thread state is INITIALIZED, not SUSPENDED 1032 osthread->set_state(INITIALIZED); 1033 1034 // The thread is returned suspended (in state INITIALIZED), and is started higher up in the call chain 1035 return true; 1036} 1037 1038// defined for >= Solaris 10. This allows builds on earlier versions 1039// of Solaris to take advantage of the newly reserved Solaris JVM signals. 1040// With SIGJVM1, SIGJVM2, ASYNC_SIGNAL is SIGJVM2. Previously INTERRUPT_SIGNAL 1041// was SIGJVM1. 1042// 1043#if !defined(SIGJVM1) 1044 #define SIGJVM1 39 1045 #define SIGJVM2 40 1046#endif 1047 1048debug_only(static bool signal_sets_initialized = false); 1049static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; 1050 1051int os::Solaris::_SIGasync = ASYNC_SIGNAL; 1052 1053bool os::Solaris::is_sig_ignored(int sig) { 1054 struct sigaction oact; 1055 sigaction(sig, (struct sigaction*)NULL, &oact); 1056 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) 1057 : CAST_FROM_FN_PTR(void*, oact.sa_handler); 1058 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) { 1059 return true; 1060 } else { 1061 return false; 1062 } 1063} 1064 1065// Note: SIGRTMIN is a macro that calls sysconf() so it will 1066// dynamically detect SIGRTMIN value for the system at runtime, not buildtime 1067static bool isJVM1available() { 1068 return SIGJVM1 < SIGRTMIN; 1069} 1070 1071void os::Solaris::signal_sets_init() { 1072 // Should also have an assertion stating we are still single-threaded. 1073 assert(!signal_sets_initialized, "Already initialized"); 1074 // Fill in signals that are necessarily unblocked for all threads in 1075 // the VM. Currently, we unblock the following signals: 1076 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden 1077 // by -Xrs (=ReduceSignalUsage)); 1078 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all 1079 // other threads. The "ReduceSignalUsage" boolean tells us not to alter 1080 // the dispositions or masks wrt these signals. 1081 // Programs embedding the VM that want to use the above signals for their 1082 // own purposes must, at this time, use the "-Xrs" option to prevent 1083 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. 1084 // (See bug 4345157, and other related bugs). 1085 // In reality, though, unblocking these signals is really a nop, since 1086 // these signals are not blocked by default. 1087 sigemptyset(&unblocked_sigs); 1088 sigemptyset(&allowdebug_blocked_sigs); 1089 sigaddset(&unblocked_sigs, SIGILL); 1090 sigaddset(&unblocked_sigs, SIGSEGV); 1091 sigaddset(&unblocked_sigs, SIGBUS); 1092 sigaddset(&unblocked_sigs, SIGFPE); 1093 1094 // Always true on Solaris 10+ 1095 guarantee(isJVM1available(), "SIGJVM1/2 missing!"); 1096 os::Solaris::set_SIGasync(SIGJVM2); 1097 1098 sigaddset(&unblocked_sigs, os::Solaris::SIGasync()); 1099 1100 if (!ReduceSignalUsage) { 1101 if (!os::Solaris::is_sig_ignored(SHUTDOWN1_SIGNAL)) { 1102 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); 1103 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); 1104 } 1105 if (!os::Solaris::is_sig_ignored(SHUTDOWN2_SIGNAL)) { 1106 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); 1107 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); 1108 } 1109 if (!os::Solaris::is_sig_ignored(SHUTDOWN3_SIGNAL)) { 1110 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); 1111 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); 1112 } 1113 } 1114 // Fill in signals that are blocked by all but the VM thread. 1115 sigemptyset(&vm_sigs); 1116 if (!ReduceSignalUsage) { 1117 sigaddset(&vm_sigs, BREAK_SIGNAL); 1118 } 1119 debug_only(signal_sets_initialized = true); 1120 1121 // For diagnostics only used in run_periodic_checks 1122 sigemptyset(&check_signal_done); 1123} 1124 1125// These are signals that are unblocked while a thread is running Java. 1126// (For some reason, they get blocked by default.) 1127sigset_t* os::Solaris::unblocked_signals() { 1128 assert(signal_sets_initialized, "Not initialized"); 1129 return &unblocked_sigs; 1130} 1131 1132// These are the signals that are blocked while a (non-VM) thread is 1133// running Java. Only the VM thread handles these signals. 1134sigset_t* os::Solaris::vm_signals() { 1135 assert(signal_sets_initialized, "Not initialized"); 1136 return &vm_sigs; 1137} 1138 1139// These are signals that are blocked during cond_wait to allow debugger in 1140sigset_t* os::Solaris::allowdebug_blocked_signals() { 1141 assert(signal_sets_initialized, "Not initialized"); 1142 return &allowdebug_blocked_sigs; 1143} 1144 1145 1146void _handle_uncaught_cxx_exception() { 1147 VMError::report_and_die("An uncaught C++ exception"); 1148} 1149 1150 1151// First crack at OS-specific initialization, from inside the new thread. 1152void os::initialize_thread(Thread* thr) { 1153 int r = thr_main(); 1154 guarantee(r == 0 || r == 1, "CR6501650 or CR6493689"); 1155 if (r) { 1156 JavaThread* jt = (JavaThread *)thr; 1157 assert(jt != NULL, "Sanity check"); 1158 size_t stack_size; 1159 address base = jt->stack_base(); 1160 if (Arguments::created_by_java_launcher()) { 1161 // Use 2MB to allow for Solaris 7 64 bit mode. 1162 stack_size = JavaThread::stack_size_at_create() == 0 1163 ? 2048*K : JavaThread::stack_size_at_create(); 1164 1165 // There are rare cases when we may have already used more than 1166 // the basic stack size allotment before this method is invoked. 1167 // Attempt to allow for a normally sized java_stack. 1168 size_t current_stack_offset = (size_t)(base - (address)&stack_size); 1169 stack_size += ReservedSpace::page_align_size_down(current_stack_offset); 1170 } else { 1171 // 6269555: If we were not created by a Java launcher, i.e. if we are 1172 // running embedded in a native application, treat the primordial thread 1173 // as much like a native attached thread as possible. This means using 1174 // the current stack size from thr_stksegment(), unless it is too large 1175 // to reliably setup guard pages. A reasonable max size is 8MB. 1176 size_t current_size = current_stack_size(); 1177 // This should never happen, but just in case.... 1178 if (current_size == 0) current_size = 2 * K * K; 1179 stack_size = current_size > (8 * K * K) ? (8 * K * K) : current_size; 1180 } 1181 address bottom = (address)align_size_up((intptr_t)(base - stack_size), os::vm_page_size());; 1182 stack_size = (size_t)(base - bottom); 1183 1184 assert(stack_size > 0, "Stack size calculation problem"); 1185 1186 if (stack_size > jt->stack_size()) { 1187#ifndef PRODUCT 1188 struct rlimit limits; 1189 getrlimit(RLIMIT_STACK, &limits); 1190 size_t size = adjust_stack_size(base, (size_t)limits.rlim_cur); 1191 assert(size >= jt->stack_size(), "Stack size problem in main thread"); 1192#endif 1193 tty->print_cr("Stack size of %d Kb exceeds current limit of %d Kb.\n" 1194 "(Stack sizes are rounded up to a multiple of the system page size.)\n" 1195 "See limit(1) to increase the stack size limit.", 1196 stack_size / K, jt->stack_size() / K); 1197 vm_exit(1); 1198 } 1199 assert(jt->stack_size() >= stack_size, 1200 "Attempt to map more stack than was allocated"); 1201 jt->set_stack_size(stack_size); 1202 } 1203 1204 // With the T2 libthread (T1 is no longer supported) threads are always bound 1205 // and we use stackbanging in all cases. 1206 1207 os::Solaris::init_thread_fpu_state(); 1208 std::set_terminate(_handle_uncaught_cxx_exception); 1209} 1210 1211 1212 1213// Free Solaris resources related to the OSThread 1214void os::free_thread(OSThread* osthread) { 1215 assert(osthread != NULL, "os::free_thread but osthread not set"); 1216 1217 1218 // We are told to free resources of the argument thread, 1219 // but we can only really operate on the current thread. 1220 // The main thread must take the VMThread down synchronously 1221 // before the main thread exits and frees up CodeHeap 1222 guarantee((Thread::current()->osthread() == osthread 1223 || (osthread == VMThread::vm_thread()->osthread())), "os::free_thread but not current thread"); 1224 if (Thread::current()->osthread() == osthread) { 1225 // Restore caller's signal mask 1226 sigset_t sigmask = osthread->caller_sigmask(); 1227 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); 1228 } 1229 delete osthread; 1230} 1231 1232void os::pd_start_thread(Thread* thread) { 1233 int status = thr_continue(thread->osthread()->thread_id()); 1234 assert_status(status == 0, status, "thr_continue failed"); 1235} 1236 1237 1238intx os::current_thread_id() { 1239 return (intx)thr_self(); 1240} 1241 1242static pid_t _initial_pid = 0; 1243 1244int os::current_process_id() { 1245 return (int)(_initial_pid ? _initial_pid : getpid()); 1246} 1247 1248// gethrtime() should be monotonic according to the documentation, 1249// but some virtualized platforms are known to break this guarantee. 1250// getTimeNanos() must be guaranteed not to move backwards, so we 1251// are forced to add a check here. 1252inline hrtime_t getTimeNanos() { 1253 const hrtime_t now = gethrtime(); 1254 const hrtime_t prev = max_hrtime; 1255 if (now <= prev) { 1256 return prev; // same or retrograde time; 1257 } 1258 const hrtime_t obsv = Atomic::cmpxchg(now, (volatile jlong*)&max_hrtime, prev); 1259 assert(obsv >= prev, "invariant"); // Monotonicity 1260 // If the CAS succeeded then we're done and return "now". 1261 // If the CAS failed and the observed value "obsv" is >= now then 1262 // we should return "obsv". If the CAS failed and now > obsv > prv then 1263 // some other thread raced this thread and installed a new value, in which case 1264 // we could either (a) retry the entire operation, (b) retry trying to install now 1265 // or (c) just return obsv. We use (c). No loop is required although in some cases 1266 // we might discard a higher "now" value in deference to a slightly lower but freshly 1267 // installed obsv value. That's entirely benign -- it admits no new orderings compared 1268 // to (a) or (b) -- and greatly reduces coherence traffic. 1269 // We might also condition (c) on the magnitude of the delta between obsv and now. 1270 // Avoiding excessive CAS operations to hot RW locations is critical. 1271 // See https://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate 1272 return (prev == obsv) ? now : obsv; 1273} 1274 1275// Time since start-up in seconds to a fine granularity. 1276// Used by VMSelfDestructTimer and the MemProfiler. 1277double os::elapsedTime() { 1278 return (double)(getTimeNanos() - first_hrtime) / (double)hrtime_hz; 1279} 1280 1281jlong os::elapsed_counter() { 1282 return (jlong)(getTimeNanos() - first_hrtime); 1283} 1284 1285jlong os::elapsed_frequency() { 1286 return hrtime_hz; 1287} 1288 1289// Return the real, user, and system times in seconds from an 1290// arbitrary fixed point in the past. 1291bool os::getTimesSecs(double* process_real_time, 1292 double* process_user_time, 1293 double* process_system_time) { 1294 struct tms ticks; 1295 clock_t real_ticks = times(&ticks); 1296 1297 if (real_ticks == (clock_t) (-1)) { 1298 return false; 1299 } else { 1300 double ticks_per_second = (double) clock_tics_per_sec; 1301 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; 1302 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; 1303 // For consistency return the real time from getTimeNanos() 1304 // converted to seconds. 1305 *process_real_time = ((double) getTimeNanos()) / ((double) NANOUNITS); 1306 1307 return true; 1308 } 1309} 1310 1311bool os::supports_vtime() { return true; } 1312 1313bool os::enable_vtime() { 1314 int fd = ::open("/proc/self/ctl", O_WRONLY); 1315 if (fd == -1) { 1316 return false; 1317 } 1318 1319 long cmd[] = { PCSET, PR_MSACCT }; 1320 int res = ::write(fd, cmd, sizeof(long) * 2); 1321 ::close(fd); 1322 if (res != sizeof(long) * 2) { 1323 return false; 1324 } 1325 return true; 1326} 1327 1328bool os::vtime_enabled() { 1329 int fd = ::open("/proc/self/status", O_RDONLY); 1330 if (fd == -1) { 1331 return false; 1332 } 1333 1334 pstatus_t status; 1335 int res = os::read(fd, (void*) &status, sizeof(pstatus_t)); 1336 ::close(fd); 1337 if (res != sizeof(pstatus_t)) { 1338 return false; 1339 } 1340 return status.pr_flags & PR_MSACCT; 1341} 1342 1343double os::elapsedVTime() { 1344 return (double)gethrvtime() / (double)hrtime_hz; 1345} 1346 1347// Used internally for comparisons only 1348// getTimeMillis guaranteed to not move backwards on Solaris 1349jlong getTimeMillis() { 1350 jlong nanotime = getTimeNanos(); 1351 return (jlong)(nanotime / NANOSECS_PER_MILLISEC); 1352} 1353 1354// Must return millis since Jan 1 1970 for JVM_CurrentTimeMillis 1355jlong os::javaTimeMillis() { 1356 timeval t; 1357 if (gettimeofday(&t, NULL) == -1) { 1358 fatal("os::javaTimeMillis: gettimeofday (%s)", strerror(errno)); 1359 } 1360 return jlong(t.tv_sec) * 1000 + jlong(t.tv_usec) / 1000; 1361} 1362 1363void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { 1364 timeval t; 1365 if (gettimeofday(&t, NULL) == -1) { 1366 fatal("os::javaTimeSystemUTC: gettimeofday (%s)", strerror(errno)); 1367 } 1368 seconds = jlong(t.tv_sec); 1369 nanos = jlong(t.tv_usec) * 1000; 1370} 1371 1372 1373jlong os::javaTimeNanos() { 1374 return (jlong)getTimeNanos(); 1375} 1376 1377void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { 1378 info_ptr->max_value = ALL_64_BITS; // gethrtime() uses all 64 bits 1379 info_ptr->may_skip_backward = false; // not subject to resetting or drifting 1380 info_ptr->may_skip_forward = false; // not subject to resetting or drifting 1381 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time 1382} 1383 1384char * os::local_time_string(char *buf, size_t buflen) { 1385 struct tm t; 1386 time_t long_time; 1387 time(&long_time); 1388 localtime_r(&long_time, &t); 1389 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", 1390 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, 1391 t.tm_hour, t.tm_min, t.tm_sec); 1392 return buf; 1393} 1394 1395// Note: os::shutdown() might be called very early during initialization, or 1396// called from signal handler. Before adding something to os::shutdown(), make 1397// sure it is async-safe and can handle partially initialized VM. 1398void os::shutdown() { 1399 1400 // allow PerfMemory to attempt cleanup of any persistent resources 1401 perfMemory_exit(); 1402 1403 // needs to remove object in file system 1404 AttachListener::abort(); 1405 1406 // flush buffered output, finish log files 1407 ostream_abort(); 1408 1409 // Check for abort hook 1410 abort_hook_t abort_hook = Arguments::abort_hook(); 1411 if (abort_hook != NULL) { 1412 abort_hook(); 1413 } 1414} 1415 1416// Note: os::abort() might be called very early during initialization, or 1417// called from signal handler. Before adding something to os::abort(), make 1418// sure it is async-safe and can handle partially initialized VM. 1419void os::abort(bool dump_core, void* siginfo, const void* context) { 1420 os::shutdown(); 1421 if (dump_core) { 1422#ifndef PRODUCT 1423 fdStream out(defaultStream::output_fd()); 1424 out.print_raw("Current thread is "); 1425 char buf[16]; 1426 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); 1427 out.print_raw_cr(buf); 1428 out.print_raw_cr("Dumping core ..."); 1429#endif 1430 ::abort(); // dump core (for debugging) 1431 } 1432 1433 ::exit(1); 1434} 1435 1436// Die immediately, no exit hook, no abort hook, no cleanup. 1437void os::die() { 1438 ::abort(); // dump core (for debugging) 1439} 1440 1441// DLL functions 1442 1443const char* os::dll_file_extension() { return ".so"; } 1444 1445// This must be hard coded because it's the system's temporary 1446// directory not the java application's temp directory, ala java.io.tmpdir. 1447const char* os::get_temp_directory() { return "/tmp"; } 1448 1449static bool file_exists(const char* filename) { 1450 struct stat statbuf; 1451 if (filename == NULL || strlen(filename) == 0) { 1452 return false; 1453 } 1454 return os::stat(filename, &statbuf) == 0; 1455} 1456 1457bool os::dll_build_name(char* buffer, size_t buflen, 1458 const char* pname, const char* fname) { 1459 bool retval = false; 1460 const size_t pnamelen = pname ? strlen(pname) : 0; 1461 1462 // Return error on buffer overflow. 1463 if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { 1464 return retval; 1465 } 1466 1467 if (pnamelen == 0) { 1468 snprintf(buffer, buflen, "lib%s.so", fname); 1469 retval = true; 1470 } else if (strchr(pname, *os::path_separator()) != NULL) { 1471 int n; 1472 char** pelements = split_path(pname, &n); 1473 if (pelements == NULL) { 1474 return false; 1475 } 1476 for (int i = 0; i < n; i++) { 1477 // really shouldn't be NULL but what the heck, check can't hurt 1478 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { 1479 continue; // skip the empty path values 1480 } 1481 snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname); 1482 if (file_exists(buffer)) { 1483 retval = true; 1484 break; 1485 } 1486 } 1487 // release the storage 1488 for (int i = 0; i < n; i++) { 1489 if (pelements[i] != NULL) { 1490 FREE_C_HEAP_ARRAY(char, pelements[i]); 1491 } 1492 } 1493 if (pelements != NULL) { 1494 FREE_C_HEAP_ARRAY(char*, pelements); 1495 } 1496 } else { 1497 snprintf(buffer, buflen, "%s/lib%s.so", pname, fname); 1498 retval = true; 1499 } 1500 return retval; 1501} 1502 1503// check if addr is inside libjvm.so 1504bool os::address_is_in_vm(address addr) { 1505 static address libjvm_base_addr; 1506 Dl_info dlinfo; 1507 1508 if (libjvm_base_addr == NULL) { 1509 if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { 1510 libjvm_base_addr = (address)dlinfo.dli_fbase; 1511 } 1512 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); 1513 } 1514 1515 if (dladdr((void *)addr, &dlinfo) != 0) { 1516 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; 1517 } 1518 1519 return false; 1520} 1521 1522typedef int (*dladdr1_func_type)(void *, Dl_info *, void **, int); 1523static dladdr1_func_type dladdr1_func = NULL; 1524 1525bool os::dll_address_to_function_name(address addr, char *buf, 1526 int buflen, int * offset, 1527 bool demangle) { 1528 // buf is not optional, but offset is optional 1529 assert(buf != NULL, "sanity check"); 1530 1531 Dl_info dlinfo; 1532 1533 // dladdr1_func was initialized in os::init() 1534 if (dladdr1_func != NULL) { 1535 // yes, we have dladdr1 1536 1537 // Support for dladdr1 is checked at runtime; it may be 1538 // available even if the vm is built on a machine that does 1539 // not have dladdr1 support. Make sure there is a value for 1540 // RTLD_DL_SYMENT. 1541#ifndef RTLD_DL_SYMENT 1542 #define RTLD_DL_SYMENT 1 1543#endif 1544#ifdef _LP64 1545 Elf64_Sym * info; 1546#else 1547 Elf32_Sym * info; 1548#endif 1549 if (dladdr1_func((void *)addr, &dlinfo, (void **)&info, 1550 RTLD_DL_SYMENT) != 0) { 1551 // see if we have a matching symbol that covers our address 1552 if (dlinfo.dli_saddr != NULL && 1553 (char *)dlinfo.dli_saddr + info->st_size > (char *)addr) { 1554 if (dlinfo.dli_sname != NULL) { 1555 if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) { 1556 jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); 1557 } 1558 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1559 return true; 1560 } 1561 } 1562 // no matching symbol so try for just file info 1563 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1564 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1565 buf, buflen, offset, dlinfo.dli_fname, demangle)) { 1566 return true; 1567 } 1568 } 1569 } 1570 buf[0] = '\0'; 1571 if (offset != NULL) *offset = -1; 1572 return false; 1573 } 1574 1575 // no, only dladdr is available 1576 if (dladdr((void *)addr, &dlinfo) != 0) { 1577 // see if we have a matching symbol 1578 if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { 1579 if (!(demangle && Decoder::demangle(dlinfo.dli_sname, buf, buflen))) { 1580 jio_snprintf(buf, buflen, dlinfo.dli_sname); 1581 } 1582 if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; 1583 return true; 1584 } 1585 // no matching symbol so try for just file info 1586 if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { 1587 if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), 1588 buf, buflen, offset, dlinfo.dli_fname, demangle)) { 1589 return true; 1590 } 1591 } 1592 } 1593 buf[0] = '\0'; 1594 if (offset != NULL) *offset = -1; 1595 return false; 1596} 1597 1598bool os::dll_address_to_library_name(address addr, char* buf, 1599 int buflen, int* offset) { 1600 // buf is not optional, but offset is optional 1601 assert(buf != NULL, "sanity check"); 1602 1603 Dl_info dlinfo; 1604 1605 if (dladdr((void*)addr, &dlinfo) != 0) { 1606 if (dlinfo.dli_fname != NULL) { 1607 jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); 1608 } 1609 if (dlinfo.dli_fbase != NULL && offset != NULL) { 1610 *offset = addr - (address)dlinfo.dli_fbase; 1611 } 1612 return true; 1613 } 1614 1615 buf[0] = '\0'; 1616 if (offset) *offset = -1; 1617 return false; 1618} 1619 1620int os::get_loaded_modules_info(os::LoadedModulesCallbackFunc callback, void *param) { 1621 Dl_info dli; 1622 // Sanity check? 1623 if (dladdr(CAST_FROM_FN_PTR(void *, os::get_loaded_modules_info), &dli) == 0 || 1624 dli.dli_fname == NULL) { 1625 return 1; 1626 } 1627 1628 void * handle = dlopen(dli.dli_fname, RTLD_LAZY); 1629 if (handle == NULL) { 1630 return 1; 1631 } 1632 1633 Link_map *map; 1634 dlinfo(handle, RTLD_DI_LINKMAP, &map); 1635 if (map == NULL) { 1636 dlclose(handle); 1637 return 1; 1638 } 1639 1640 while (map->l_prev != NULL) { 1641 map = map->l_prev; 1642 } 1643 1644 while (map != NULL) { 1645 // Iterate through all map entries and call callback with fields of interest 1646 if(callback(map->l_name, (address)map->l_addr, (address)0, param)) { 1647 dlclose(handle); 1648 return 1; 1649 } 1650 map = map->l_next; 1651 } 1652 1653 dlclose(handle); 1654 return 0; 1655} 1656 1657int _print_dll_info_cb(const char * name, address base_address, address top_address, void * param) { 1658 outputStream * out = (outputStream *) param; 1659 out->print_cr(PTR_FORMAT " \t%s", base_address, name); 1660 return 0; 1661} 1662 1663void os::print_dll_info(outputStream * st) { 1664 st->print_cr("Dynamic libraries:"); st->flush(); 1665 if (get_loaded_modules_info(_print_dll_info_cb, (void *)st)) { 1666 st->print_cr("Error: Cannot print dynamic libraries."); 1667 } 1668} 1669 1670// Loads .dll/.so and 1671// in case of error it checks if .dll/.so was built for the 1672// same architecture as Hotspot is running on 1673 1674void * os::dll_load(const char *filename, char *ebuf, int ebuflen) { 1675 void * result= ::dlopen(filename, RTLD_LAZY); 1676 if (result != NULL) { 1677 // Successful loading 1678 return result; 1679 } 1680 1681 Elf32_Ehdr elf_head; 1682 1683 // Read system error message into ebuf 1684 // It may or may not be overwritten below 1685 ::strncpy(ebuf, ::dlerror(), ebuflen-1); 1686 ebuf[ebuflen-1]='\0'; 1687 int diag_msg_max_length=ebuflen-strlen(ebuf); 1688 char* diag_msg_buf=ebuf+strlen(ebuf); 1689 1690 if (diag_msg_max_length==0) { 1691 // No more space in ebuf for additional diagnostics message 1692 return NULL; 1693 } 1694 1695 1696 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); 1697 1698 if (file_descriptor < 0) { 1699 // Can't open library, report dlerror() message 1700 return NULL; 1701 } 1702 1703 bool failed_to_read_elf_head= 1704 (sizeof(elf_head)!= 1705 (::read(file_descriptor, &elf_head,sizeof(elf_head)))); 1706 1707 ::close(file_descriptor); 1708 if (failed_to_read_elf_head) { 1709 // file i/o error - report dlerror() msg 1710 return NULL; 1711 } 1712 1713 typedef struct { 1714 Elf32_Half code; // Actual value as defined in elf.h 1715 Elf32_Half compat_class; // Compatibility of archs at VM's sense 1716 char elf_class; // 32 or 64 bit 1717 char endianess; // MSB or LSB 1718 char* name; // String representation 1719 } arch_t; 1720 1721 static const arch_t arch_array[]={ 1722 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1723 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, 1724 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, 1725 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, 1726 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1727 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, 1728 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, 1729 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, 1730 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, 1731 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM 32"} 1732 }; 1733 1734#if (defined IA32) 1735 static Elf32_Half running_arch_code=EM_386; 1736#elif (defined AMD64) 1737 static Elf32_Half running_arch_code=EM_X86_64; 1738#elif (defined IA64) 1739 static Elf32_Half running_arch_code=EM_IA_64; 1740#elif (defined __sparc) && (defined _LP64) 1741 static Elf32_Half running_arch_code=EM_SPARCV9; 1742#elif (defined __sparc) && (!defined _LP64) 1743 static Elf32_Half running_arch_code=EM_SPARC; 1744#elif (defined __powerpc64__) 1745 static Elf32_Half running_arch_code=EM_PPC64; 1746#elif (defined __powerpc__) 1747 static Elf32_Half running_arch_code=EM_PPC; 1748#elif (defined ARM) 1749 static Elf32_Half running_arch_code=EM_ARM; 1750#else 1751 #error Method os::dll_load requires that one of following is defined:\ 1752 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, ARM 1753#endif 1754 1755 // Identify compatability class for VM's architecture and library's architecture 1756 // Obtain string descriptions for architectures 1757 1758 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; 1759 int running_arch_index=-1; 1760 1761 for (unsigned int i=0; i < ARRAY_SIZE(arch_array); i++) { 1762 if (running_arch_code == arch_array[i].code) { 1763 running_arch_index = i; 1764 } 1765 if (lib_arch.code == arch_array[i].code) { 1766 lib_arch.compat_class = arch_array[i].compat_class; 1767 lib_arch.name = arch_array[i].name; 1768 } 1769 } 1770 1771 assert(running_arch_index != -1, 1772 "Didn't find running architecture code (running_arch_code) in arch_array"); 1773 if (running_arch_index == -1) { 1774 // Even though running architecture detection failed 1775 // we may still continue with reporting dlerror() message 1776 return NULL; 1777 } 1778 1779 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { 1780 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); 1781 return NULL; 1782 } 1783 1784 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { 1785 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); 1786 return NULL; 1787 } 1788 1789 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { 1790 if (lib_arch.name!=NULL) { 1791 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1792 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", 1793 lib_arch.name, arch_array[running_arch_index].name); 1794 } else { 1795 ::snprintf(diag_msg_buf, diag_msg_max_length-1, 1796 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", 1797 lib_arch.code, 1798 arch_array[running_arch_index].name); 1799 } 1800 } 1801 1802 return NULL; 1803} 1804 1805void* os::dll_lookup(void* handle, const char* name) { 1806 return dlsym(handle, name); 1807} 1808 1809void* os::get_default_process_handle() { 1810 return (void*)::dlopen(NULL, RTLD_LAZY); 1811} 1812 1813int os::stat(const char *path, struct stat *sbuf) { 1814 char pathbuf[MAX_PATH]; 1815 if (strlen(path) > MAX_PATH - 1) { 1816 errno = ENAMETOOLONG; 1817 return -1; 1818 } 1819 os::native_path(strcpy(pathbuf, path)); 1820 return ::stat(pathbuf, sbuf); 1821} 1822 1823static bool _print_ascii_file(const char* filename, outputStream* st) { 1824 int fd = ::open(filename, O_RDONLY); 1825 if (fd == -1) { 1826 return false; 1827 } 1828 1829 char buf[32]; 1830 int bytes; 1831 while ((bytes = ::read(fd, buf, sizeof(buf))) > 0) { 1832 st->print_raw(buf, bytes); 1833 } 1834 1835 ::close(fd); 1836 1837 return true; 1838} 1839 1840void os::print_os_info_brief(outputStream* st) { 1841 os::Solaris::print_distro_info(st); 1842 1843 os::Posix::print_uname_info(st); 1844 1845 os::Solaris::print_libversion_info(st); 1846} 1847 1848void os::print_os_info(outputStream* st) { 1849 st->print("OS:"); 1850 1851 os::Solaris::print_distro_info(st); 1852 1853 os::Posix::print_uname_info(st); 1854 1855 os::Solaris::print_libversion_info(st); 1856 1857 os::Posix::print_rlimit_info(st); 1858 1859 os::Posix::print_load_average(st); 1860} 1861 1862void os::Solaris::print_distro_info(outputStream* st) { 1863 if (!_print_ascii_file("/etc/release", st)) { 1864 st->print("Solaris"); 1865 } 1866 st->cr(); 1867} 1868 1869void os::get_summary_os_info(char* buf, size_t buflen) { 1870 strncpy(buf, "Solaris", buflen); // default to plain solaris 1871 FILE* fp = fopen("/etc/release", "r"); 1872 if (fp != NULL) { 1873 char tmp[256]; 1874 // Only get the first line and chop out everything but the os name. 1875 if (fgets(tmp, sizeof(tmp), fp)) { 1876 char* ptr = tmp; 1877 // skip past whitespace characters 1878 while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')) ptr++; 1879 if (*ptr != '\0') { 1880 char* nl = strchr(ptr, '\n'); 1881 if (nl != NULL) *nl = '\0'; 1882 strncpy(buf, ptr, buflen); 1883 } 1884 } 1885 fclose(fp); 1886 } 1887} 1888 1889void os::Solaris::print_libversion_info(outputStream* st) { 1890 st->print(" (T2 libthread)"); 1891 st->cr(); 1892} 1893 1894static bool check_addr0(outputStream* st) { 1895 jboolean status = false; 1896 int fd = ::open("/proc/self/map",O_RDONLY); 1897 if (fd >= 0) { 1898 prmap_t p; 1899 while (::read(fd, &p, sizeof(p)) > 0) { 1900 if (p.pr_vaddr == 0x0) { 1901 st->print("Warning: Address: 0x%x, Size: %dK, ",p.pr_vaddr, p.pr_size/1024, p.pr_mapname); 1902 st->print("Mapped file: %s, ", p.pr_mapname[0] == '\0' ? "None" : p.pr_mapname); 1903 st->print("Access:"); 1904 st->print("%s",(p.pr_mflags & MA_READ) ? "r" : "-"); 1905 st->print("%s",(p.pr_mflags & MA_WRITE) ? "w" : "-"); 1906 st->print("%s",(p.pr_mflags & MA_EXEC) ? "x" : "-"); 1907 st->cr(); 1908 status = true; 1909 } 1910 } 1911 ::close(fd); 1912 } 1913 return status; 1914} 1915 1916void os::get_summary_cpu_info(char* buf, size_t buflen) { 1917 // Get MHz with system call. We don't seem to already have this. 1918 processor_info_t stats; 1919 processorid_t id = getcpuid(); 1920 int clock = 0; 1921 if (processor_info(id, &stats) != -1) { 1922 clock = stats.pi_clock; // pi_processor_type isn't more informative than below 1923 } 1924#ifdef AMD64 1925 snprintf(buf, buflen, "x86 64 bit %d MHz", clock); 1926#else 1927 // must be sparc 1928 snprintf(buf, buflen, "Sparcv9 64 bit %d MHz", clock); 1929#endif 1930} 1931 1932void os::pd_print_cpu_info(outputStream* st, char* buf, size_t buflen) { 1933 // Nothing to do for now. 1934} 1935 1936void os::print_memory_info(outputStream* st) { 1937 st->print("Memory:"); 1938 st->print(" %dk page", os::vm_page_size()>>10); 1939 st->print(", physical " UINT64_FORMAT "k", os::physical_memory()>>10); 1940 st->print("(" UINT64_FORMAT "k free)", os::available_memory() >> 10); 1941 st->cr(); 1942 (void) check_addr0(st); 1943} 1944 1945// Moved from whole group, because we need them here for diagnostic 1946// prints. 1947#define OLDMAXSIGNUM 32 1948static int Maxsignum = 0; 1949static int *ourSigFlags = NULL; 1950 1951int os::Solaris::get_our_sigflags(int sig) { 1952 assert(ourSigFlags!=NULL, "signal data structure not initialized"); 1953 assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range"); 1954 return ourSigFlags[sig]; 1955} 1956 1957void os::Solaris::set_our_sigflags(int sig, int flags) { 1958 assert(ourSigFlags!=NULL, "signal data structure not initialized"); 1959 assert(sig > 0 && sig < Maxsignum, "vm signal out of expected range"); 1960 ourSigFlags[sig] = flags; 1961} 1962 1963 1964static const char* get_signal_handler_name(address handler, 1965 char* buf, int buflen) { 1966 int offset; 1967 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); 1968 if (found) { 1969 // skip directory names 1970 const char *p1, *p2; 1971 p1 = buf; 1972 size_t len = strlen(os::file_separator()); 1973 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; 1974 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); 1975 } else { 1976 jio_snprintf(buf, buflen, PTR_FORMAT, handler); 1977 } 1978 return buf; 1979} 1980 1981static void print_signal_handler(outputStream* st, int sig, 1982 char* buf, size_t buflen) { 1983 struct sigaction sa; 1984 1985 sigaction(sig, NULL, &sa); 1986 1987 st->print("%s: ", os::exception_name(sig, buf, buflen)); 1988 1989 address handler = (sa.sa_flags & SA_SIGINFO) 1990 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) 1991 : CAST_FROM_FN_PTR(address, sa.sa_handler); 1992 1993 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { 1994 st->print("SIG_DFL"); 1995 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { 1996 st->print("SIG_IGN"); 1997 } else { 1998 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); 1999 } 2000 2001 st->print(", sa_mask[0]="); 2002 os::Posix::print_signal_set_short(st, &sa.sa_mask); 2003 2004 address rh = VMError::get_resetted_sighandler(sig); 2005 // May be, handler was resetted by VMError? 2006 if (rh != NULL) { 2007 handler = rh; 2008 sa.sa_flags = VMError::get_resetted_sigflags(sig); 2009 } 2010 2011 st->print(", sa_flags="); 2012 os::Posix::print_sa_flags(st, sa.sa_flags); 2013 2014 // Check: is it our handler? 2015 if (handler == CAST_FROM_FN_PTR(address, signalHandler)) { 2016 // It is our signal handler 2017 // check for flags 2018 if (sa.sa_flags != os::Solaris::get_our_sigflags(sig)) { 2019 st->print( 2020 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", 2021 os::Solaris::get_our_sigflags(sig)); 2022 } 2023 } 2024 st->cr(); 2025} 2026 2027void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { 2028 st->print_cr("Signal Handlers:"); 2029 print_signal_handler(st, SIGSEGV, buf, buflen); 2030 print_signal_handler(st, SIGBUS , buf, buflen); 2031 print_signal_handler(st, SIGFPE , buf, buflen); 2032 print_signal_handler(st, SIGPIPE, buf, buflen); 2033 print_signal_handler(st, SIGXFSZ, buf, buflen); 2034 print_signal_handler(st, SIGILL , buf, buflen); 2035 print_signal_handler(st, ASYNC_SIGNAL, buf, buflen); 2036 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); 2037 print_signal_handler(st, SHUTDOWN1_SIGNAL , buf, buflen); 2038 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); 2039 print_signal_handler(st, SHUTDOWN3_SIGNAL, buf, buflen); 2040 print_signal_handler(st, os::Solaris::SIGasync(), buf, buflen); 2041} 2042 2043static char saved_jvm_path[MAXPATHLEN] = { 0 }; 2044 2045// Find the full path to the current module, libjvm.so 2046void os::jvm_path(char *buf, jint buflen) { 2047 // Error checking. 2048 if (buflen < MAXPATHLEN) { 2049 assert(false, "must use a large-enough buffer"); 2050 buf[0] = '\0'; 2051 return; 2052 } 2053 // Lazy resolve the path to current module. 2054 if (saved_jvm_path[0] != 0) { 2055 strcpy(buf, saved_jvm_path); 2056 return; 2057 } 2058 2059 Dl_info dlinfo; 2060 int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo); 2061 assert(ret != 0, "cannot locate libjvm"); 2062 if (ret != 0 && dlinfo.dli_fname != NULL) { 2063 realpath((char *)dlinfo.dli_fname, buf); 2064 } else { 2065 buf[0] = '\0'; 2066 return; 2067 } 2068 2069 if (Arguments::sun_java_launcher_is_altjvm()) { 2070 // Support for the java launcher's '-XXaltjvm=<path>' option. Typical 2071 // value for buf is "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". 2072 // If "/jre/lib/" appears at the right place in the string, then 2073 // assume we are installed in a JDK and we're done. Otherwise, check 2074 // for a JAVA_HOME environment variable and fix up the path so it 2075 // looks like libjvm.so is installed there (append a fake suffix 2076 // hotspot/libjvm.so). 2077 const char *p = buf + strlen(buf) - 1; 2078 for (int count = 0; p > buf && count < 5; ++count) { 2079 for (--p; p > buf && *p != '/'; --p) 2080 /* empty */ ; 2081 } 2082 2083 if (strncmp(p, "/jre/lib/", 9) != 0) { 2084 // Look for JAVA_HOME in the environment. 2085 char* java_home_var = ::getenv("JAVA_HOME"); 2086 if (java_home_var != NULL && java_home_var[0] != 0) { 2087 char cpu_arch[12]; 2088 char* jrelib_p; 2089 int len; 2090 sysinfo(SI_ARCHITECTURE, cpu_arch, sizeof(cpu_arch)); 2091#ifdef _LP64 2092 // If we are on sparc running a 64-bit vm, look in jre/lib/sparcv9. 2093 if (strcmp(cpu_arch, "sparc") == 0) { 2094 strcat(cpu_arch, "v9"); 2095 } else if (strcmp(cpu_arch, "i386") == 0) { 2096 strcpy(cpu_arch, "amd64"); 2097 } 2098#endif 2099 // Check the current module name "libjvm.so". 2100 p = strrchr(buf, '/'); 2101 assert(strstr(p, "/libjvm") == p, "invalid library name"); 2102 2103 realpath(java_home_var, buf); 2104 // determine if this is a legacy image or modules image 2105 // modules image doesn't have "jre" subdirectory 2106 len = strlen(buf); 2107 assert(len < buflen, "Ran out of buffer space"); 2108 jrelib_p = buf + len; 2109 snprintf(jrelib_p, buflen-len, "/jre/lib/%s", cpu_arch); 2110 if (0 != access(buf, F_OK)) { 2111 snprintf(jrelib_p, buflen-len, "/lib/%s", cpu_arch); 2112 } 2113 2114 if (0 == access(buf, F_OK)) { 2115 // Use current module name "libjvm.so" 2116 len = strlen(buf); 2117 snprintf(buf + len, buflen-len, "/hotspot/libjvm.so"); 2118 } else { 2119 // Go back to path of .so 2120 realpath((char *)dlinfo.dli_fname, buf); 2121 } 2122 } 2123 } 2124 } 2125 2126 strncpy(saved_jvm_path, buf, MAXPATHLEN); 2127 saved_jvm_path[MAXPATHLEN - 1] = '\0'; 2128} 2129 2130 2131void os::print_jni_name_prefix_on(outputStream* st, int args_size) { 2132 // no prefix required, not even "_" 2133} 2134 2135 2136void os::print_jni_name_suffix_on(outputStream* st, int args_size) { 2137 // no suffix required 2138} 2139 2140// This method is a copy of JDK's sysGetLastErrorString 2141// from src/solaris/hpi/src/system_md.c 2142 2143size_t os::lasterror(char *buf, size_t len) { 2144 if (errno == 0) return 0; 2145 2146 const char *s = ::strerror(errno); 2147 size_t n = ::strlen(s); 2148 if (n >= len) { 2149 n = len - 1; 2150 } 2151 ::strncpy(buf, s, n); 2152 buf[n] = '\0'; 2153 return n; 2154} 2155 2156 2157// sun.misc.Signal 2158 2159extern "C" { 2160 static void UserHandler(int sig, void *siginfo, void *context) { 2161 // Ctrl-C is pressed during error reporting, likely because the error 2162 // handler fails to abort. Let VM die immediately. 2163 if (sig == SIGINT && is_error_reported()) { 2164 os::die(); 2165 } 2166 2167 os::signal_notify(sig); 2168 // We do not need to reinstate the signal handler each time... 2169 } 2170} 2171 2172void* os::user_handler() { 2173 return CAST_FROM_FN_PTR(void*, UserHandler); 2174} 2175 2176struct timespec PosixSemaphore::create_timespec(unsigned int sec, int nsec) { 2177 struct timespec ts; 2178 unpackTime(&ts, false, (sec * NANOSECS_PER_SEC) + nsec); 2179 2180 return ts; 2181} 2182 2183extern "C" { 2184 typedef void (*sa_handler_t)(int); 2185 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); 2186} 2187 2188void* os::signal(int signal_number, void* handler) { 2189 struct sigaction sigAct, oldSigAct; 2190 sigfillset(&(sigAct.sa_mask)); 2191 sigAct.sa_flags = SA_RESTART & ~SA_RESETHAND; 2192 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); 2193 2194 if (sigaction(signal_number, &sigAct, &oldSigAct)) { 2195 // -1 means registration failed 2196 return (void *)-1; 2197 } 2198 2199 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); 2200} 2201 2202void os::signal_raise(int signal_number) { 2203 raise(signal_number); 2204} 2205 2206// The following code is moved from os.cpp for making this 2207// code platform specific, which it is by its very nature. 2208 2209// a counter for each possible signal value 2210static int Sigexit = 0; 2211static int Maxlibjsigsigs; 2212static jint *pending_signals = NULL; 2213static int *preinstalled_sigs = NULL; 2214static struct sigaction *chainedsigactions = NULL; 2215static sema_t sig_sem; 2216typedef int (*version_getting_t)(); 2217version_getting_t os::Solaris::get_libjsig_version = NULL; 2218static int libjsigversion = NULL; 2219 2220int os::sigexitnum_pd() { 2221 assert(Sigexit > 0, "signal memory not yet initialized"); 2222 return Sigexit; 2223} 2224 2225void os::Solaris::init_signal_mem() { 2226 // Initialize signal structures 2227 Maxsignum = SIGRTMAX; 2228 Sigexit = Maxsignum+1; 2229 assert(Maxsignum >0, "Unable to obtain max signal number"); 2230 2231 Maxlibjsigsigs = Maxsignum; 2232 2233 // pending_signals has one int per signal 2234 // The additional signal is for SIGEXIT - exit signal to signal_thread 2235 pending_signals = (jint *)os::malloc(sizeof(jint) * (Sigexit+1), mtInternal); 2236 memset(pending_signals, 0, (sizeof(jint) * (Sigexit+1))); 2237 2238 if (UseSignalChaining) { 2239 chainedsigactions = (struct sigaction *)malloc(sizeof(struct sigaction) 2240 * (Maxsignum + 1), mtInternal); 2241 memset(chainedsigactions, 0, (sizeof(struct sigaction) * (Maxsignum + 1))); 2242 preinstalled_sigs = (int *)os::malloc(sizeof(int) * (Maxsignum + 1), mtInternal); 2243 memset(preinstalled_sigs, 0, (sizeof(int) * (Maxsignum + 1))); 2244 } 2245 ourSigFlags = (int*)malloc(sizeof(int) * (Maxsignum + 1), mtInternal); 2246 memset(ourSigFlags, 0, sizeof(int) * (Maxsignum + 1)); 2247} 2248 2249void os::signal_init_pd() { 2250 int ret; 2251 2252 ret = ::sema_init(&sig_sem, 0, NULL, NULL); 2253 assert(ret == 0, "sema_init() failed"); 2254} 2255 2256void os::signal_notify(int signal_number) { 2257 int ret; 2258 2259 Atomic::inc(&pending_signals[signal_number]); 2260 ret = ::sema_post(&sig_sem); 2261 assert(ret == 0, "sema_post() failed"); 2262} 2263 2264static int check_pending_signals(bool wait_for_signal) { 2265 int ret; 2266 while (true) { 2267 for (int i = 0; i < Sigexit + 1; i++) { 2268 jint n = pending_signals[i]; 2269 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { 2270 return i; 2271 } 2272 } 2273 if (!wait_for_signal) { 2274 return -1; 2275 } 2276 JavaThread *thread = JavaThread::current(); 2277 ThreadBlockInVM tbivm(thread); 2278 2279 bool threadIsSuspended; 2280 do { 2281 thread->set_suspend_equivalent(); 2282 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 2283 while ((ret = ::sema_wait(&sig_sem)) == EINTR) 2284 ; 2285 assert(ret == 0, "sema_wait() failed"); 2286 2287 // were we externally suspended while we were waiting? 2288 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); 2289 if (threadIsSuspended) { 2290 // The semaphore has been incremented, but while we were waiting 2291 // another thread suspended us. We don't want to continue running 2292 // while suspended because that would surprise the thread that 2293 // suspended us. 2294 ret = ::sema_post(&sig_sem); 2295 assert(ret == 0, "sema_post() failed"); 2296 2297 thread->java_suspend_self(); 2298 } 2299 } while (threadIsSuspended); 2300 } 2301} 2302 2303int os::signal_lookup() { 2304 return check_pending_signals(false); 2305} 2306 2307int os::signal_wait() { 2308 return check_pending_signals(true); 2309} 2310 2311//////////////////////////////////////////////////////////////////////////////// 2312// Virtual Memory 2313 2314static int page_size = -1; 2315 2316// The mmap MAP_ALIGN flag is supported on Solaris 9 and later. init_2() will 2317// clear this var if support is not available. 2318static bool has_map_align = true; 2319 2320int os::vm_page_size() { 2321 assert(page_size != -1, "must call os::init"); 2322 return page_size; 2323} 2324 2325// Solaris allocates memory by pages. 2326int os::vm_allocation_granularity() { 2327 assert(page_size != -1, "must call os::init"); 2328 return page_size; 2329} 2330 2331static bool recoverable_mmap_error(int err) { 2332 // See if the error is one we can let the caller handle. This 2333 // list of errno values comes from the Solaris mmap(2) man page. 2334 switch (err) { 2335 case EBADF: 2336 case EINVAL: 2337 case ENOTSUP: 2338 // let the caller deal with these errors 2339 return true; 2340 2341 default: 2342 // Any remaining errors on this OS can cause our reserved mapping 2343 // to be lost. That can cause confusion where different data 2344 // structures think they have the same memory mapped. The worst 2345 // scenario is if both the VM and a library think they have the 2346 // same memory mapped. 2347 return false; 2348 } 2349} 2350 2351static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec, 2352 int err) { 2353 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2354 ", %d) failed; error='%s' (errno=%d)", addr, bytes, exec, 2355 strerror(err), err); 2356} 2357 2358static void warn_fail_commit_memory(char* addr, size_t bytes, 2359 size_t alignment_hint, bool exec, 2360 int err) { 2361 warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT 2362 ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes, 2363 alignment_hint, exec, strerror(err), err); 2364} 2365 2366int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) { 2367 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; 2368 size_t size = bytes; 2369 char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot); 2370 if (res != NULL) { 2371 if (UseNUMAInterleaving) { 2372 numa_make_global(addr, bytes); 2373 } 2374 return 0; 2375 } 2376 2377 int err = errno; // save errno from mmap() call in mmap_chunk() 2378 2379 if (!recoverable_mmap_error(err)) { 2380 warn_fail_commit_memory(addr, bytes, exec, err); 2381 vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory."); 2382 } 2383 2384 return err; 2385} 2386 2387bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) { 2388 return Solaris::commit_memory_impl(addr, bytes, exec) == 0; 2389} 2390 2391void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec, 2392 const char* mesg) { 2393 assert(mesg != NULL, "mesg must be specified"); 2394 int err = os::Solaris::commit_memory_impl(addr, bytes, exec); 2395 if (err != 0) { 2396 // the caller wants all commit errors to exit with the specified mesg: 2397 warn_fail_commit_memory(addr, bytes, exec, err); 2398 vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg); 2399 } 2400} 2401 2402size_t os::Solaris::page_size_for_alignment(size_t alignment) { 2403 assert(is_size_aligned(alignment, (size_t) vm_page_size()), 2404 SIZE_FORMAT " is not aligned to " SIZE_FORMAT, 2405 alignment, (size_t) vm_page_size()); 2406 2407 for (int i = 0; _page_sizes[i] != 0; i++) { 2408 if (is_size_aligned(alignment, _page_sizes[i])) { 2409 return _page_sizes[i]; 2410 } 2411 } 2412 2413 return (size_t) vm_page_size(); 2414} 2415 2416int os::Solaris::commit_memory_impl(char* addr, size_t bytes, 2417 size_t alignment_hint, bool exec) { 2418 int err = Solaris::commit_memory_impl(addr, bytes, exec); 2419 if (err == 0 && UseLargePages && alignment_hint > 0) { 2420 assert(is_size_aligned(bytes, alignment_hint), 2421 SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, alignment_hint); 2422 2423 // The syscall memcntl requires an exact page size (see man memcntl for details). 2424 size_t page_size = page_size_for_alignment(alignment_hint); 2425 if (page_size > (size_t) vm_page_size()) { 2426 (void)Solaris::setup_large_pages(addr, bytes, page_size); 2427 } 2428 } 2429 return err; 2430} 2431 2432bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint, 2433 bool exec) { 2434 return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0; 2435} 2436 2437void os::pd_commit_memory_or_exit(char* addr, size_t bytes, 2438 size_t alignment_hint, bool exec, 2439 const char* mesg) { 2440 assert(mesg != NULL, "mesg must be specified"); 2441 int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec); 2442 if (err != 0) { 2443 // the caller wants all commit errors to exit with the specified mesg: 2444 warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err); 2445 vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "%s", mesg); 2446 } 2447} 2448 2449// Uncommit the pages in a specified region. 2450void os::pd_free_memory(char* addr, size_t bytes, size_t alignment_hint) { 2451 if (madvise(addr, bytes, MADV_FREE) < 0) { 2452 debug_only(warning("MADV_FREE failed.")); 2453 return; 2454 } 2455} 2456 2457bool os::pd_create_stack_guard_pages(char* addr, size_t size) { 2458 return os::commit_memory(addr, size, !ExecMem); 2459} 2460 2461bool os::remove_stack_guard_pages(char* addr, size_t size) { 2462 return os::uncommit_memory(addr, size); 2463} 2464 2465// Change the page size in a given range. 2466void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { 2467 assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned."); 2468 assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned."); 2469 if (UseLargePages) { 2470 size_t page_size = Solaris::page_size_for_alignment(alignment_hint); 2471 if (page_size > (size_t) vm_page_size()) { 2472 Solaris::setup_large_pages(addr, bytes, page_size); 2473 } 2474 } 2475} 2476 2477// Tell the OS to make the range local to the first-touching LWP 2478void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { 2479 assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned."); 2480 if (madvise(addr, bytes, MADV_ACCESS_LWP) < 0) { 2481 debug_only(warning("MADV_ACCESS_LWP failed.")); 2482 } 2483} 2484 2485// Tell the OS that this range would be accessed from different LWPs. 2486void os::numa_make_global(char *addr, size_t bytes) { 2487 assert((intptr_t)addr % os::vm_page_size() == 0, "Address should be page-aligned."); 2488 if (madvise(addr, bytes, MADV_ACCESS_MANY) < 0) { 2489 debug_only(warning("MADV_ACCESS_MANY failed.")); 2490 } 2491} 2492 2493// Get the number of the locality groups. 2494size_t os::numa_get_groups_num() { 2495 size_t n = Solaris::lgrp_nlgrps(Solaris::lgrp_cookie()); 2496 return n != -1 ? n : 1; 2497} 2498 2499// Get a list of leaf locality groups. A leaf lgroup is group that 2500// doesn't have any children. Typical leaf group is a CPU or a CPU/memory 2501// board. An LWP is assigned to one of these groups upon creation. 2502size_t os::numa_get_leaf_groups(int *ids, size_t size) { 2503 if ((ids[0] = Solaris::lgrp_root(Solaris::lgrp_cookie())) == -1) { 2504 ids[0] = 0; 2505 return 1; 2506 } 2507 int result_size = 0, top = 1, bottom = 0, cur = 0; 2508 for (int k = 0; k < size; k++) { 2509 int r = Solaris::lgrp_children(Solaris::lgrp_cookie(), ids[cur], 2510 (Solaris::lgrp_id_t*)&ids[top], size - top); 2511 if (r == -1) { 2512 ids[0] = 0; 2513 return 1; 2514 } 2515 if (!r) { 2516 // That's a leaf node. 2517 assert(bottom <= cur, "Sanity check"); 2518 // Check if the node has memory 2519 if (Solaris::lgrp_resources(Solaris::lgrp_cookie(), ids[cur], 2520 NULL, 0, LGRP_RSRC_MEM) > 0) { 2521 ids[bottom++] = ids[cur]; 2522 } 2523 } 2524 top += r; 2525 cur++; 2526 } 2527 if (bottom == 0) { 2528 // Handle a situation, when the OS reports no memory available. 2529 // Assume UMA architecture. 2530 ids[0] = 0; 2531 return 1; 2532 } 2533 return bottom; 2534} 2535 2536// Detect the topology change. Typically happens during CPU plugging-unplugging. 2537bool os::numa_topology_changed() { 2538 int is_stale = Solaris::lgrp_cookie_stale(Solaris::lgrp_cookie()); 2539 if (is_stale != -1 && is_stale) { 2540 Solaris::lgrp_fini(Solaris::lgrp_cookie()); 2541 Solaris::lgrp_cookie_t c = Solaris::lgrp_init(Solaris::LGRP_VIEW_CALLER); 2542 assert(c != 0, "Failure to initialize LGRP API"); 2543 Solaris::set_lgrp_cookie(c); 2544 return true; 2545 } 2546 return false; 2547} 2548 2549// Get the group id of the current LWP. 2550int os::numa_get_group_id() { 2551 int lgrp_id = Solaris::lgrp_home(P_LWPID, P_MYID); 2552 if (lgrp_id == -1) { 2553 return 0; 2554 } 2555 const int size = os::numa_get_groups_num(); 2556 int *ids = (int*)alloca(size * sizeof(int)); 2557 2558 // Get the ids of all lgroups with memory; r is the count. 2559 int r = Solaris::lgrp_resources(Solaris::lgrp_cookie(), lgrp_id, 2560 (Solaris::lgrp_id_t*)ids, size, LGRP_RSRC_MEM); 2561 if (r <= 0) { 2562 return 0; 2563 } 2564 return ids[os::random() % r]; 2565} 2566 2567// Request information about the page. 2568bool os::get_page_info(char *start, page_info* info) { 2569 const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE }; 2570 uint64_t addr = (uintptr_t)start; 2571 uint64_t outdata[2]; 2572 uint_t validity = 0; 2573 2574 if (os::Solaris::meminfo(&addr, 1, info_types, 2, outdata, &validity) < 0) { 2575 return false; 2576 } 2577 2578 info->size = 0; 2579 info->lgrp_id = -1; 2580 2581 if ((validity & 1) != 0) { 2582 if ((validity & 2) != 0) { 2583 info->lgrp_id = outdata[0]; 2584 } 2585 if ((validity & 4) != 0) { 2586 info->size = outdata[1]; 2587 } 2588 return true; 2589 } 2590 return false; 2591} 2592 2593// Scan the pages from start to end until a page different than 2594// the one described in the info parameter is encountered. 2595char *os::scan_pages(char *start, char* end, page_info* page_expected, 2596 page_info* page_found) { 2597 const uint_t info_types[] = { MEMINFO_VLGRP, MEMINFO_VPAGESIZE }; 2598 const size_t types = sizeof(info_types) / sizeof(info_types[0]); 2599 uint64_t addrs[MAX_MEMINFO_CNT], outdata[types * MAX_MEMINFO_CNT + 1]; 2600 uint_t validity[MAX_MEMINFO_CNT]; 2601 2602 size_t page_size = MAX2((size_t)os::vm_page_size(), page_expected->size); 2603 uint64_t p = (uint64_t)start; 2604 while (p < (uint64_t)end) { 2605 addrs[0] = p; 2606 size_t addrs_count = 1; 2607 while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) { 2608 addrs[addrs_count] = addrs[addrs_count - 1] + page_size; 2609 addrs_count++; 2610 } 2611 2612 if (os::Solaris::meminfo(addrs, addrs_count, info_types, types, outdata, validity) < 0) { 2613 return NULL; 2614 } 2615 2616 size_t i = 0; 2617 for (; i < addrs_count; i++) { 2618 if ((validity[i] & 1) != 0) { 2619 if ((validity[i] & 4) != 0) { 2620 if (outdata[types * i + 1] != page_expected->size) { 2621 break; 2622 } 2623 } else if (page_expected->size != 0) { 2624 break; 2625 } 2626 2627 if ((validity[i] & 2) != 0 && page_expected->lgrp_id > 0) { 2628 if (outdata[types * i] != page_expected->lgrp_id) { 2629 break; 2630 } 2631 } 2632 } else { 2633 return NULL; 2634 } 2635 } 2636 2637 if (i < addrs_count) { 2638 if ((validity[i] & 2) != 0) { 2639 page_found->lgrp_id = outdata[types * i]; 2640 } else { 2641 page_found->lgrp_id = -1; 2642 } 2643 if ((validity[i] & 4) != 0) { 2644 page_found->size = outdata[types * i + 1]; 2645 } else { 2646 page_found->size = 0; 2647 } 2648 return (char*)addrs[i]; 2649 } 2650 2651 p = addrs[addrs_count - 1] + page_size; 2652 } 2653 return end; 2654} 2655 2656bool os::pd_uncommit_memory(char* addr, size_t bytes) { 2657 size_t size = bytes; 2658 // Map uncommitted pages PROT_NONE so we fail early if we touch an 2659 // uncommitted page. Otherwise, the read/write might succeed if we 2660 // have enough swap space to back the physical page. 2661 return 2662 NULL != Solaris::mmap_chunk(addr, size, 2663 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, 2664 PROT_NONE); 2665} 2666 2667char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) { 2668 char *b = (char *)mmap(addr, size, prot, flags, os::Solaris::_dev_zero_fd, 0); 2669 2670 if (b == MAP_FAILED) { 2671 return NULL; 2672 } 2673 return b; 2674} 2675 2676char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes, 2677 size_t alignment_hint, bool fixed) { 2678 char* addr = requested_addr; 2679 int flags = MAP_PRIVATE | MAP_NORESERVE; 2680 2681 assert(!(fixed && (alignment_hint > 0)), 2682 "alignment hint meaningless with fixed mmap"); 2683 2684 if (fixed) { 2685 flags |= MAP_FIXED; 2686 } else if (has_map_align && (alignment_hint > (size_t) vm_page_size())) { 2687 flags |= MAP_ALIGN; 2688 addr = (char*) alignment_hint; 2689 } 2690 2691 // Map uncommitted pages PROT_NONE so we fail early if we touch an 2692 // uncommitted page. Otherwise, the read/write might succeed if we 2693 // have enough swap space to back the physical page. 2694 return mmap_chunk(addr, bytes, flags, PROT_NONE); 2695} 2696 2697char* os::pd_reserve_memory(size_t bytes, char* requested_addr, 2698 size_t alignment_hint) { 2699 char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint, 2700 (requested_addr != NULL)); 2701 2702 guarantee(requested_addr == NULL || requested_addr == addr, 2703 "OS failed to return requested mmap address."); 2704 return addr; 2705} 2706 2707// Reserve memory at an arbitrary address, only if that area is 2708// available (and not reserved for something else). 2709 2710char* os::pd_attempt_reserve_memory_at(size_t bytes, char* requested_addr) { 2711 const int max_tries = 10; 2712 char* base[max_tries]; 2713 size_t size[max_tries]; 2714 2715 // Solaris adds a gap between mmap'ed regions. The size of the gap 2716 // is dependent on the requested size and the MMU. Our initial gap 2717 // value here is just a guess and will be corrected later. 2718 bool had_top_overlap = false; 2719 bool have_adjusted_gap = false; 2720 size_t gap = 0x400000; 2721 2722 // Assert only that the size is a multiple of the page size, since 2723 // that's all that mmap requires, and since that's all we really know 2724 // about at this low abstraction level. If we need higher alignment, 2725 // we can either pass an alignment to this method or verify alignment 2726 // in one of the methods further up the call chain. See bug 5044738. 2727 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); 2728 2729 // Since snv_84, Solaris attempts to honor the address hint - see 5003415. 2730 // Give it a try, if the kernel honors the hint we can return immediately. 2731 char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false); 2732 2733 volatile int err = errno; 2734 if (addr == requested_addr) { 2735 return addr; 2736 } else if (addr != NULL) { 2737 pd_unmap_memory(addr, bytes); 2738 } 2739 2740 if (PrintMiscellaneous && Verbose) { 2741 char buf[256]; 2742 buf[0] = '\0'; 2743 if (addr == NULL) { 2744 jio_snprintf(buf, sizeof(buf), ": %s", strerror(err)); 2745 } 2746 warning("attempt_reserve_memory_at: couldn't reserve " SIZE_FORMAT " bytes at " 2747 PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT 2748 "%s", bytes, requested_addr, addr, buf); 2749 } 2750 2751 // Address hint method didn't work. Fall back to the old method. 2752 // In theory, once SNV becomes our oldest supported platform, this 2753 // code will no longer be needed. 2754 // 2755 // Repeatedly allocate blocks until the block is allocated at the 2756 // right spot. Give up after max_tries. 2757 int i; 2758 for (i = 0; i < max_tries; ++i) { 2759 base[i] = reserve_memory(bytes); 2760 2761 if (base[i] != NULL) { 2762 // Is this the block we wanted? 2763 if (base[i] == requested_addr) { 2764 size[i] = bytes; 2765 break; 2766 } 2767 2768 // check that the gap value is right 2769 if (had_top_overlap && !have_adjusted_gap) { 2770 size_t actual_gap = base[i-1] - base[i] - bytes; 2771 if (gap != actual_gap) { 2772 // adjust the gap value and retry the last 2 allocations 2773 assert(i > 0, "gap adjustment code problem"); 2774 have_adjusted_gap = true; // adjust the gap only once, just in case 2775 gap = actual_gap; 2776 if (PrintMiscellaneous && Verbose) { 2777 warning("attempt_reserve_memory_at: adjusted gap to 0x%lx", gap); 2778 } 2779 unmap_memory(base[i], bytes); 2780 unmap_memory(base[i-1], size[i-1]); 2781 i-=2; 2782 continue; 2783 } 2784 } 2785 2786 // Does this overlap the block we wanted? Give back the overlapped 2787 // parts and try again. 2788 // 2789 // There is still a bug in this code: if top_overlap == bytes, 2790 // the overlap is offset from requested region by the value of gap. 2791 // In this case giving back the overlapped part will not work, 2792 // because we'll give back the entire block at base[i] and 2793 // therefore the subsequent allocation will not generate a new gap. 2794 // This could be fixed with a new algorithm that used larger 2795 // or variable size chunks to find the requested region - 2796 // but such a change would introduce additional complications. 2797 // It's rare enough that the planets align for this bug, 2798 // so we'll just wait for a fix for 6204603/5003415 which 2799 // will provide a mmap flag to allow us to avoid this business. 2800 2801 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; 2802 if (top_overlap >= 0 && top_overlap < bytes) { 2803 had_top_overlap = true; 2804 unmap_memory(base[i], top_overlap); 2805 base[i] += top_overlap; 2806 size[i] = bytes - top_overlap; 2807 } else { 2808 size_t bottom_overlap = base[i] + bytes - requested_addr; 2809 if (bottom_overlap >= 0 && bottom_overlap < bytes) { 2810 if (PrintMiscellaneous && Verbose && bottom_overlap == 0) { 2811 warning("attempt_reserve_memory_at: possible alignment bug"); 2812 } 2813 unmap_memory(requested_addr, bottom_overlap); 2814 size[i] = bytes - bottom_overlap; 2815 } else { 2816 size[i] = bytes; 2817 } 2818 } 2819 } 2820 } 2821 2822 // Give back the unused reserved pieces. 2823 2824 for (int j = 0; j < i; ++j) { 2825 if (base[j] != NULL) { 2826 unmap_memory(base[j], size[j]); 2827 } 2828 } 2829 2830 return (i < max_tries) ? requested_addr : NULL; 2831} 2832 2833bool os::pd_release_memory(char* addr, size_t bytes) { 2834 size_t size = bytes; 2835 return munmap(addr, size) == 0; 2836} 2837 2838static bool solaris_mprotect(char* addr, size_t bytes, int prot) { 2839 assert(addr == (char*)align_size_down((uintptr_t)addr, os::vm_page_size()), 2840 "addr must be page aligned"); 2841 int retVal = mprotect(addr, bytes, prot); 2842 return retVal == 0; 2843} 2844 2845// Protect memory (Used to pass readonly pages through 2846// JNI GetArray<type>Elements with empty arrays.) 2847// Also, used for serialization page and for compressed oops null pointer 2848// checking. 2849bool os::protect_memory(char* addr, size_t bytes, ProtType prot, 2850 bool is_committed) { 2851 unsigned int p = 0; 2852 switch (prot) { 2853 case MEM_PROT_NONE: p = PROT_NONE; break; 2854 case MEM_PROT_READ: p = PROT_READ; break; 2855 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; 2856 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; 2857 default: 2858 ShouldNotReachHere(); 2859 } 2860 // is_committed is unused. 2861 return solaris_mprotect(addr, bytes, p); 2862} 2863 2864// guard_memory and unguard_memory only happens within stack guard pages. 2865// Since ISM pertains only to the heap, guard and unguard memory should not 2866/// happen with an ISM region. 2867bool os::guard_memory(char* addr, size_t bytes) { 2868 return solaris_mprotect(addr, bytes, PROT_NONE); 2869} 2870 2871bool os::unguard_memory(char* addr, size_t bytes) { 2872 return solaris_mprotect(addr, bytes, PROT_READ|PROT_WRITE); 2873} 2874 2875// Large page support 2876static size_t _large_page_size = 0; 2877 2878// Insertion sort for small arrays (descending order). 2879static void insertion_sort_descending(size_t* array, int len) { 2880 for (int i = 0; i < len; i++) { 2881 size_t val = array[i]; 2882 for (size_t key = i; key > 0 && array[key - 1] < val; --key) { 2883 size_t tmp = array[key]; 2884 array[key] = array[key - 1]; 2885 array[key - 1] = tmp; 2886 } 2887 } 2888} 2889 2890bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) { 2891 const unsigned int usable_count = VM_Version::page_size_count(); 2892 if (usable_count == 1) { 2893 return false; 2894 } 2895 2896 // Find the right getpagesizes interface. When solaris 11 is the minimum 2897 // build platform, getpagesizes() (without the '2') can be called directly. 2898 typedef int (*gps_t)(size_t[], int); 2899 gps_t gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes2")); 2900 if (gps_func == NULL) { 2901 gps_func = CAST_TO_FN_PTR(gps_t, dlsym(RTLD_DEFAULT, "getpagesizes")); 2902 if (gps_func == NULL) { 2903 if (warn) { 2904 warning("MPSS is not supported by the operating system."); 2905 } 2906 return false; 2907 } 2908 } 2909 2910 // Fill the array of page sizes. 2911 int n = (*gps_func)(_page_sizes, page_sizes_max); 2912 assert(n > 0, "Solaris bug?"); 2913 2914 if (n == page_sizes_max) { 2915 // Add a sentinel value (necessary only if the array was completely filled 2916 // since it is static (zeroed at initialization)). 2917 _page_sizes[--n] = 0; 2918 DEBUG_ONLY(warning("increase the size of the os::_page_sizes array.");) 2919 } 2920 assert(_page_sizes[n] == 0, "missing sentinel"); 2921 trace_page_sizes("available page sizes", _page_sizes, n); 2922 2923 if (n == 1) return false; // Only one page size available. 2924 2925 // Skip sizes larger than 4M (or LargePageSizeInBytes if it was set) and 2926 // select up to usable_count elements. First sort the array, find the first 2927 // acceptable value, then copy the usable sizes to the top of the array and 2928 // trim the rest. Make sure to include the default page size :-). 2929 // 2930 // A better policy could get rid of the 4M limit by taking the sizes of the 2931 // important VM memory regions (java heap and possibly the code cache) into 2932 // account. 2933 insertion_sort_descending(_page_sizes, n); 2934 const size_t size_limit = 2935 FLAG_IS_DEFAULT(LargePageSizeInBytes) ? 4 * M : LargePageSizeInBytes; 2936 int beg; 2937 for (beg = 0; beg < n && _page_sizes[beg] > size_limit; ++beg) /* empty */; 2938 const int end = MIN2((int)usable_count, n) - 1; 2939 for (int cur = 0; cur < end; ++cur, ++beg) { 2940 _page_sizes[cur] = _page_sizes[beg]; 2941 } 2942 _page_sizes[end] = vm_page_size(); 2943 _page_sizes[end + 1] = 0; 2944 2945 if (_page_sizes[end] > _page_sizes[end - 1]) { 2946 // Default page size is not the smallest; sort again. 2947 insertion_sort_descending(_page_sizes, end + 1); 2948 } 2949 *page_size = _page_sizes[0]; 2950 2951 trace_page_sizes("usable page sizes", _page_sizes, end + 1); 2952 return true; 2953} 2954 2955void os::large_page_init() { 2956 if (UseLargePages) { 2957 // print a warning if any large page related flag is specified on command line 2958 bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) || 2959 !FLAG_IS_DEFAULT(LargePageSizeInBytes); 2960 2961 UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size); 2962 } 2963} 2964 2965bool os::Solaris::is_valid_page_size(size_t bytes) { 2966 for (int i = 0; _page_sizes[i] != 0; i++) { 2967 if (_page_sizes[i] == bytes) { 2968 return true; 2969 } 2970 } 2971 return false; 2972} 2973 2974bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) { 2975 assert(is_valid_page_size(align), SIZE_FORMAT " is not a valid page size", align); 2976 assert(is_ptr_aligned((void*) start, align), 2977 PTR_FORMAT " is not aligned to " SIZE_FORMAT, p2i((void*) start), align); 2978 assert(is_size_aligned(bytes, align), 2979 SIZE_FORMAT " is not aligned to " SIZE_FORMAT, bytes, align); 2980 2981 // Signal to OS that we want large pages for addresses 2982 // from addr, addr + bytes 2983 struct memcntl_mha mpss_struct; 2984 mpss_struct.mha_cmd = MHA_MAPSIZE_VA; 2985 mpss_struct.mha_pagesize = align; 2986 mpss_struct.mha_flags = 0; 2987 // Upon successful completion, memcntl() returns 0 2988 if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) { 2989 debug_only(warning("Attempt to use MPSS failed.")); 2990 return false; 2991 } 2992 return true; 2993} 2994 2995char* os::reserve_memory_special(size_t size, size_t alignment, char* addr, bool exec) { 2996 fatal("os::reserve_memory_special should not be called on Solaris."); 2997 return NULL; 2998} 2999 3000bool os::release_memory_special(char* base, size_t bytes) { 3001 fatal("os::release_memory_special should not be called on Solaris."); 3002 return false; 3003} 3004 3005size_t os::large_page_size() { 3006 return _large_page_size; 3007} 3008 3009// MPSS allows application to commit large page memory on demand; with ISM 3010// the entire memory region must be allocated as shared memory. 3011bool os::can_commit_large_page_memory() { 3012 return true; 3013} 3014 3015bool os::can_execute_large_page_memory() { 3016 return true; 3017} 3018 3019// Read calls from inside the vm need to perform state transitions 3020size_t os::read(int fd, void *buf, unsigned int nBytes) { 3021 size_t res; 3022 JavaThread* thread = (JavaThread*)Thread::current(); 3023 assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm"); 3024 ThreadBlockInVM tbiv(thread); 3025 RESTARTABLE(::read(fd, buf, (size_t) nBytes), res); 3026 return res; 3027} 3028 3029size_t os::read_at(int fd, void *buf, unsigned int nBytes, jlong offset) { 3030 size_t res; 3031 JavaThread* thread = (JavaThread*)Thread::current(); 3032 assert(thread->thread_state() == _thread_in_vm, "Assumed _thread_in_vm"); 3033 ThreadBlockInVM tbiv(thread); 3034 RESTARTABLE(::pread(fd, buf, (size_t) nBytes, offset), res); 3035 return res; 3036} 3037 3038size_t os::restartable_read(int fd, void *buf, unsigned int nBytes) { 3039 size_t res; 3040 assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native, 3041 "Assumed _thread_in_native"); 3042 RESTARTABLE(::read(fd, buf, (size_t) nBytes), res); 3043 return res; 3044} 3045 3046void os::naked_short_sleep(jlong ms) { 3047 assert(ms < 1000, "Un-interruptable sleep, short time use only"); 3048 3049 // usleep is deprecated and removed from POSIX, in favour of nanosleep, but 3050 // Solaris requires -lrt for this. 3051 usleep((ms * 1000)); 3052 3053 return; 3054} 3055 3056// Sleep forever; naked call to OS-specific sleep; use with CAUTION 3057void os::infinite_sleep() { 3058 while (true) { // sleep forever ... 3059 ::sleep(100); // ... 100 seconds at a time 3060 } 3061} 3062 3063// Used to convert frequent JVM_Yield() to nops 3064bool os::dont_yield() { 3065 if (DontYieldALot) { 3066 static hrtime_t last_time = 0; 3067 hrtime_t diff = getTimeNanos() - last_time; 3068 3069 if (diff < DontYieldALotInterval * 1000000) { 3070 return true; 3071 } 3072 3073 last_time += diff; 3074 3075 return false; 3076 } else { 3077 return false; 3078 } 3079} 3080 3081// Note that yield semantics are defined by the scheduling class to which 3082// the thread currently belongs. Typically, yield will _not yield to 3083// other equal or higher priority threads that reside on the dispatch queues 3084// of other CPUs. 3085 3086void os::naked_yield() { 3087 thr_yield(); 3088} 3089 3090// Interface for setting lwp priorities. If we are using T2 libthread, 3091// which forces the use of BoundThreads or we manually set UseBoundThreads, 3092// all of our threads will be assigned to real lwp's. Using the thr_setprio 3093// function is meaningless in this mode so we must adjust the real lwp's priority 3094// The routines below implement the getting and setting of lwp priorities. 3095// 3096// Note: T2 is now the only supported libthread. UseBoundThreads flag is 3097// being deprecated and all threads are now BoundThreads 3098// 3099// Note: There are three priority scales used on Solaris. Java priotities 3100// which range from 1 to 10, libthread "thr_setprio" scale which range 3101// from 0 to 127, and the current scheduling class of the process we 3102// are running in. This is typically from -60 to +60. 3103// The setting of the lwp priorities in done after a call to thr_setprio 3104// so Java priorities are mapped to libthread priorities and we map from 3105// the latter to lwp priorities. We don't keep priorities stored in 3106// Java priorities since some of our worker threads want to set priorities 3107// higher than all Java threads. 3108// 3109// For related information: 3110// (1) man -s 2 priocntl 3111// (2) man -s 4 priocntl 3112// (3) man dispadmin 3113// = librt.so 3114// = libthread/common/rtsched.c - thrp_setlwpprio(). 3115// = ps -cL <pid> ... to validate priority. 3116// = sched_get_priority_min and _max 3117// pthread_create 3118// sched_setparam 3119// pthread_setschedparam 3120// 3121// Assumptions: 3122// + We assume that all threads in the process belong to the same 3123// scheduling class. IE. an homogenous process. 3124// + Must be root or in IA group to change change "interactive" attribute. 3125// Priocntl() will fail silently. The only indication of failure is when 3126// we read-back the value and notice that it hasn't changed. 3127// + Interactive threads enter the runq at the head, non-interactive at the tail. 3128// + For RT, change timeslice as well. Invariant: 3129// constant "priority integral" 3130// Konst == TimeSlice * (60-Priority) 3131// Given a priority, compute appropriate timeslice. 3132// + Higher numerical values have higher priority. 3133 3134// sched class attributes 3135typedef struct { 3136 int schedPolicy; // classID 3137 int maxPrio; 3138 int minPrio; 3139} SchedInfo; 3140 3141 3142static SchedInfo tsLimits, iaLimits, rtLimits, fxLimits; 3143 3144#ifdef ASSERT 3145static int ReadBackValidate = 1; 3146#endif 3147static int myClass = 0; 3148static int myMin = 0; 3149static int myMax = 0; 3150static int myCur = 0; 3151static bool priocntl_enable = false; 3152 3153static const int criticalPrio = FXCriticalPriority; 3154static int java_MaxPriority_to_os_priority = 0; // Saved mapping 3155 3156 3157// lwp_priocntl_init 3158// 3159// Try to determine the priority scale for our process. 3160// 3161// Return errno or 0 if OK. 3162// 3163static int lwp_priocntl_init() { 3164 int rslt; 3165 pcinfo_t ClassInfo; 3166 pcparms_t ParmInfo; 3167 int i; 3168 3169 if (!UseThreadPriorities) return 0; 3170 3171 // If ThreadPriorityPolicy is 1, switch tables 3172 if (ThreadPriorityPolicy == 1) { 3173 for (i = 0; i < CriticalPriority+1; i++) 3174 os::java_to_os_priority[i] = prio_policy1[i]; 3175 } 3176 if (UseCriticalJavaThreadPriority) { 3177 // MaxPriority always maps to the FX scheduling class and criticalPrio. 3178 // See set_native_priority() and set_lwp_class_and_priority(). 3179 // Save original MaxPriority mapping in case attempt to 3180 // use critical priority fails. 3181 java_MaxPriority_to_os_priority = os::java_to_os_priority[MaxPriority]; 3182 // Set negative to distinguish from other priorities 3183 os::java_to_os_priority[MaxPriority] = -criticalPrio; 3184 } 3185 3186 // Get IDs for a set of well-known scheduling classes. 3187 // TODO-FIXME: GETCLINFO returns the current # of classes in the 3188 // the system. We should have a loop that iterates over the 3189 // classID values, which are known to be "small" integers. 3190 3191 strcpy(ClassInfo.pc_clname, "TS"); 3192 ClassInfo.pc_cid = -1; 3193 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 3194 if (rslt < 0) return errno; 3195 assert(ClassInfo.pc_cid != -1, "cid for TS class is -1"); 3196 tsLimits.schedPolicy = ClassInfo.pc_cid; 3197 tsLimits.maxPrio = ((tsinfo_t*)ClassInfo.pc_clinfo)->ts_maxupri; 3198 tsLimits.minPrio = -tsLimits.maxPrio; 3199 3200 strcpy(ClassInfo.pc_clname, "IA"); 3201 ClassInfo.pc_cid = -1; 3202 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 3203 if (rslt < 0) return errno; 3204 assert(ClassInfo.pc_cid != -1, "cid for IA class is -1"); 3205 iaLimits.schedPolicy = ClassInfo.pc_cid; 3206 iaLimits.maxPrio = ((iainfo_t*)ClassInfo.pc_clinfo)->ia_maxupri; 3207 iaLimits.minPrio = -iaLimits.maxPrio; 3208 3209 strcpy(ClassInfo.pc_clname, "RT"); 3210 ClassInfo.pc_cid = -1; 3211 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 3212 if (rslt < 0) return errno; 3213 assert(ClassInfo.pc_cid != -1, "cid for RT class is -1"); 3214 rtLimits.schedPolicy = ClassInfo.pc_cid; 3215 rtLimits.maxPrio = ((rtinfo_t*)ClassInfo.pc_clinfo)->rt_maxpri; 3216 rtLimits.minPrio = 0; 3217 3218 strcpy(ClassInfo.pc_clname, "FX"); 3219 ClassInfo.pc_cid = -1; 3220 rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); 3221 if (rslt < 0) return errno; 3222 assert(ClassInfo.pc_cid != -1, "cid for FX class is -1"); 3223 fxLimits.schedPolicy = ClassInfo.pc_cid; 3224 fxLimits.maxPrio = ((fxinfo_t*)ClassInfo.pc_clinfo)->fx_maxupri; 3225 fxLimits.minPrio = 0; 3226 3227 // Query our "current" scheduling class. 3228 // This will normally be IA, TS or, rarely, FX or RT. 3229 memset(&ParmInfo, 0, sizeof(ParmInfo)); 3230 ParmInfo.pc_cid = PC_CLNULL; 3231 rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); 3232 if (rslt < 0) return errno; 3233 myClass = ParmInfo.pc_cid; 3234 3235 // We now know our scheduling classId, get specific information 3236 // about the class. 3237 ClassInfo.pc_cid = myClass; 3238 ClassInfo.pc_clname[0] = 0; 3239 rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo); 3240 if (rslt < 0) return errno; 3241 3242 if (ThreadPriorityVerbose) { 3243 tty->print_cr("lwp_priocntl_init: Class=%d(%s)...", myClass, ClassInfo.pc_clname); 3244 } 3245 3246 memset(&ParmInfo, 0, sizeof(pcparms_t)); 3247 ParmInfo.pc_cid = PC_CLNULL; 3248 rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); 3249 if (rslt < 0) return errno; 3250 3251 if (ParmInfo.pc_cid == rtLimits.schedPolicy) { 3252 myMin = rtLimits.minPrio; 3253 myMax = rtLimits.maxPrio; 3254 } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) { 3255 iaparms_t *iaInfo = (iaparms_t*)ParmInfo.pc_clparms; 3256 myMin = iaLimits.minPrio; 3257 myMax = iaLimits.maxPrio; 3258 myMax = MIN2(myMax, (int)iaInfo->ia_uprilim); // clamp - restrict 3259 } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) { 3260 tsparms_t *tsInfo = (tsparms_t*)ParmInfo.pc_clparms; 3261 myMin = tsLimits.minPrio; 3262 myMax = tsLimits.maxPrio; 3263 myMax = MIN2(myMax, (int)tsInfo->ts_uprilim); // clamp - restrict 3264 } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) { 3265 fxparms_t *fxInfo = (fxparms_t*)ParmInfo.pc_clparms; 3266 myMin = fxLimits.minPrio; 3267 myMax = fxLimits.maxPrio; 3268 myMax = MIN2(myMax, (int)fxInfo->fx_uprilim); // clamp - restrict 3269 } else { 3270 // No clue - punt 3271 if (ThreadPriorityVerbose) { 3272 tty->print_cr("Unknown scheduling class: %s ... \n", 3273 ClassInfo.pc_clname); 3274 } 3275 return EINVAL; // no clue, punt 3276 } 3277 3278 if (ThreadPriorityVerbose) { 3279 tty->print_cr("Thread priority Range: [%d..%d]\n", myMin, myMax); 3280 } 3281 3282 priocntl_enable = true; // Enable changing priorities 3283 return 0; 3284} 3285 3286#define IAPRI(x) ((iaparms_t *)((x).pc_clparms)) 3287#define RTPRI(x) ((rtparms_t *)((x).pc_clparms)) 3288#define TSPRI(x) ((tsparms_t *)((x).pc_clparms)) 3289#define FXPRI(x) ((fxparms_t *)((x).pc_clparms)) 3290 3291 3292// scale_to_lwp_priority 3293// 3294// Convert from the libthread "thr_setprio" scale to our current 3295// lwp scheduling class scale. 3296// 3297static int scale_to_lwp_priority(int rMin, int rMax, int x) { 3298 int v; 3299 3300 if (x == 127) return rMax; // avoid round-down 3301 v = (((x*(rMax-rMin)))/128)+rMin; 3302 return v; 3303} 3304 3305 3306// set_lwp_class_and_priority 3307int set_lwp_class_and_priority(int ThreadID, int lwpid, 3308 int newPrio, int new_class, bool scale) { 3309 int rslt; 3310 int Actual, Expected, prv; 3311 pcparms_t ParmInfo; // for GET-SET 3312#ifdef ASSERT 3313 pcparms_t ReadBack; // for readback 3314#endif 3315 3316 // Set priority via PC_GETPARMS, update, PC_SETPARMS 3317 // Query current values. 3318 // TODO: accelerate this by eliminating the PC_GETPARMS call. 3319 // Cache "pcparms_t" in global ParmCache. 3320 // TODO: elide set-to-same-value 3321 3322 // If something went wrong on init, don't change priorities. 3323 if (!priocntl_enable) { 3324 if (ThreadPriorityVerbose) { 3325 tty->print_cr("Trying to set priority but init failed, ignoring"); 3326 } 3327 return EINVAL; 3328 } 3329 3330 // If lwp hasn't started yet, just return 3331 // the _start routine will call us again. 3332 if (lwpid <= 0) { 3333 if (ThreadPriorityVerbose) { 3334 tty->print_cr("deferring the set_lwp_class_and_priority of thread " 3335 INTPTR_FORMAT " to %d, lwpid not set", 3336 ThreadID, newPrio); 3337 } 3338 return 0; 3339 } 3340 3341 if (ThreadPriorityVerbose) { 3342 tty->print_cr ("set_lwp_class_and_priority(" 3343 INTPTR_FORMAT "@" INTPTR_FORMAT " %d) ", 3344 ThreadID, lwpid, newPrio); 3345 } 3346 3347 memset(&ParmInfo, 0, sizeof(pcparms_t)); 3348 ParmInfo.pc_cid = PC_CLNULL; 3349 rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo); 3350 if (rslt < 0) return errno; 3351 3352 int cur_class = ParmInfo.pc_cid; 3353 ParmInfo.pc_cid = (id_t)new_class; 3354 3355 if (new_class == rtLimits.schedPolicy) { 3356 rtparms_t *rtInfo = (rtparms_t*)ParmInfo.pc_clparms; 3357 rtInfo->rt_pri = scale ? scale_to_lwp_priority(rtLimits.minPrio, 3358 rtLimits.maxPrio, newPrio) 3359 : newPrio; 3360 rtInfo->rt_tqsecs = RT_NOCHANGE; 3361 rtInfo->rt_tqnsecs = RT_NOCHANGE; 3362 if (ThreadPriorityVerbose) { 3363 tty->print_cr("RT: %d->%d\n", newPrio, rtInfo->rt_pri); 3364 } 3365 } else if (new_class == iaLimits.schedPolicy) { 3366 iaparms_t* iaInfo = (iaparms_t*)ParmInfo.pc_clparms; 3367 int maxClamped = MIN2(iaLimits.maxPrio, 3368 cur_class == new_class 3369 ? (int)iaInfo->ia_uprilim : iaLimits.maxPrio); 3370 iaInfo->ia_upri = scale ? scale_to_lwp_priority(iaLimits.minPrio, 3371 maxClamped, newPrio) 3372 : newPrio; 3373 iaInfo->ia_uprilim = cur_class == new_class 3374 ? IA_NOCHANGE : (pri_t)iaLimits.maxPrio; 3375 iaInfo->ia_mode = IA_NOCHANGE; 3376 if (ThreadPriorityVerbose) { 3377 tty->print_cr("IA: [%d...%d] %d->%d\n", 3378 iaLimits.minPrio, maxClamped, newPrio, iaInfo->ia_upri); 3379 } 3380 } else if (new_class == tsLimits.schedPolicy) { 3381 tsparms_t* tsInfo = (tsparms_t*)ParmInfo.pc_clparms; 3382 int maxClamped = MIN2(tsLimits.maxPrio, 3383 cur_class == new_class 3384 ? (int)tsInfo->ts_uprilim : tsLimits.maxPrio); 3385 tsInfo->ts_upri = scale ? scale_to_lwp_priority(tsLimits.minPrio, 3386 maxClamped, newPrio) 3387 : newPrio; 3388 tsInfo->ts_uprilim = cur_class == new_class 3389 ? TS_NOCHANGE : (pri_t)tsLimits.maxPrio; 3390 if (ThreadPriorityVerbose) { 3391 tty->print_cr("TS: [%d...%d] %d->%d\n", 3392 tsLimits.minPrio, maxClamped, newPrio, tsInfo->ts_upri); 3393 } 3394 } else if (new_class == fxLimits.schedPolicy) { 3395 fxparms_t* fxInfo = (fxparms_t*)ParmInfo.pc_clparms; 3396 int maxClamped = MIN2(fxLimits.maxPrio, 3397 cur_class == new_class 3398 ? (int)fxInfo->fx_uprilim : fxLimits.maxPrio); 3399 fxInfo->fx_upri = scale ? scale_to_lwp_priority(fxLimits.minPrio, 3400 maxClamped, newPrio) 3401 : newPrio; 3402 fxInfo->fx_uprilim = cur_class == new_class 3403 ? FX_NOCHANGE : (pri_t)fxLimits.maxPrio; 3404 fxInfo->fx_tqsecs = FX_NOCHANGE; 3405 fxInfo->fx_tqnsecs = FX_NOCHANGE; 3406 if (ThreadPriorityVerbose) { 3407 tty->print_cr("FX: [%d...%d] %d->%d\n", 3408 fxLimits.minPrio, maxClamped, newPrio, fxInfo->fx_upri); 3409 } 3410 } else { 3411 if (ThreadPriorityVerbose) { 3412 tty->print_cr("Unknown new scheduling class %d\n", new_class); 3413 } 3414 return EINVAL; // no clue, punt 3415 } 3416 3417 rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo); 3418 if (ThreadPriorityVerbose && rslt) { 3419 tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno); 3420 } 3421 if (rslt < 0) return errno; 3422 3423#ifdef ASSERT 3424 // Sanity check: read back what we just attempted to set. 3425 // In theory it could have changed in the interim ... 3426 // 3427 // The priocntl system call is tricky. 3428 // Sometimes it'll validate the priority value argument and 3429 // return EINVAL if unhappy. At other times it fails silently. 3430 // Readbacks are prudent. 3431 3432 if (!ReadBackValidate) return 0; 3433 3434 memset(&ReadBack, 0, sizeof(pcparms_t)); 3435 ReadBack.pc_cid = PC_CLNULL; 3436 rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack); 3437 assert(rslt >= 0, "priocntl failed"); 3438 Actual = Expected = 0xBAD; 3439 assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match"); 3440 if (ParmInfo.pc_cid == rtLimits.schedPolicy) { 3441 Actual = RTPRI(ReadBack)->rt_pri; 3442 Expected = RTPRI(ParmInfo)->rt_pri; 3443 } else if (ParmInfo.pc_cid == iaLimits.schedPolicy) { 3444 Actual = IAPRI(ReadBack)->ia_upri; 3445 Expected = IAPRI(ParmInfo)->ia_upri; 3446 } else if (ParmInfo.pc_cid == tsLimits.schedPolicy) { 3447 Actual = TSPRI(ReadBack)->ts_upri; 3448 Expected = TSPRI(ParmInfo)->ts_upri; 3449 } else if (ParmInfo.pc_cid == fxLimits.schedPolicy) { 3450 Actual = FXPRI(ReadBack)->fx_upri; 3451 Expected = FXPRI(ParmInfo)->fx_upri; 3452 } else { 3453 if (ThreadPriorityVerbose) { 3454 tty->print_cr("set_lwp_class_and_priority: unexpected class in readback: %d\n", 3455 ParmInfo.pc_cid); 3456 } 3457 } 3458 3459 if (Actual != Expected) { 3460 if (ThreadPriorityVerbose) { 3461 tty->print_cr ("set_lwp_class_and_priority(%d %d) Class=%d: actual=%d vs expected=%d\n", 3462 lwpid, newPrio, ReadBack.pc_cid, Actual, Expected); 3463 } 3464 } 3465#endif 3466 3467 return 0; 3468} 3469 3470// Solaris only gives access to 128 real priorities at a time, 3471// so we expand Java's ten to fill this range. This would be better 3472// if we dynamically adjusted relative priorities. 3473// 3474// The ThreadPriorityPolicy option allows us to select 2 different 3475// priority scales. 3476// 3477// ThreadPriorityPolicy=0 3478// Since the Solaris' default priority is MaximumPriority, we do not 3479// set a priority lower than Max unless a priority lower than 3480// NormPriority is requested. 3481// 3482// ThreadPriorityPolicy=1 3483// This mode causes the priority table to get filled with 3484// linear values. NormPriority get's mapped to 50% of the 3485// Maximum priority an so on. This will cause VM threads 3486// to get unfair treatment against other Solaris processes 3487// which do not explicitly alter their thread priorities. 3488 3489int os::java_to_os_priority[CriticalPriority + 1] = { 3490 -99999, // 0 Entry should never be used 3491 3492 0, // 1 MinPriority 3493 32, // 2 3494 64, // 3 3495 3496 96, // 4 3497 127, // 5 NormPriority 3498 127, // 6 3499 3500 127, // 7 3501 127, // 8 3502 127, // 9 NearMaxPriority 3503 3504 127, // 10 MaxPriority 3505 3506 -criticalPrio // 11 CriticalPriority 3507}; 3508 3509OSReturn os::set_native_priority(Thread* thread, int newpri) { 3510 OSThread* osthread = thread->osthread(); 3511 3512 // Save requested priority in case the thread hasn't been started 3513 osthread->set_native_priority(newpri); 3514 3515 // Check for critical priority request 3516 bool fxcritical = false; 3517 if (newpri == -criticalPrio) { 3518 fxcritical = true; 3519 newpri = criticalPrio; 3520 } 3521 3522 assert(newpri >= MinimumPriority && newpri <= MaximumPriority, "bad priority mapping"); 3523 if (!UseThreadPriorities) return OS_OK; 3524 3525 int status = 0; 3526 3527 if (!fxcritical) { 3528 // Use thr_setprio only if we have a priority that thr_setprio understands 3529 status = thr_setprio(thread->osthread()->thread_id(), newpri); 3530 } 3531 3532 int lwp_status = 3533 set_lwp_class_and_priority(osthread->thread_id(), 3534 osthread->lwp_id(), 3535 newpri, 3536 fxcritical ? fxLimits.schedPolicy : myClass, 3537 !fxcritical); 3538 if (lwp_status != 0 && fxcritical) { 3539 // Try again, this time without changing the scheduling class 3540 newpri = java_MaxPriority_to_os_priority; 3541 lwp_status = set_lwp_class_and_priority(osthread->thread_id(), 3542 osthread->lwp_id(), 3543 newpri, myClass, false); 3544 } 3545 status |= lwp_status; 3546 return (status == 0) ? OS_OK : OS_ERR; 3547} 3548 3549 3550OSReturn os::get_native_priority(const Thread* const thread, 3551 int *priority_ptr) { 3552 int p; 3553 if (!UseThreadPriorities) { 3554 *priority_ptr = NormalPriority; 3555 return OS_OK; 3556 } 3557 int status = thr_getprio(thread->osthread()->thread_id(), &p); 3558 if (status != 0) { 3559 return OS_ERR; 3560 } 3561 *priority_ptr = p; 3562 return OS_OK; 3563} 3564 3565 3566// Hint to the underlying OS that a task switch would not be good. 3567// Void return because it's a hint and can fail. 3568void os::hint_no_preempt() { 3569 schedctl_start(schedctl_init()); 3570} 3571 3572static void resume_clear_context(OSThread *osthread) { 3573 osthread->set_ucontext(NULL); 3574} 3575 3576static void suspend_save_context(OSThread *osthread, ucontext_t* context) { 3577 osthread->set_ucontext(context); 3578} 3579 3580static PosixSemaphore sr_semaphore; 3581 3582void os::Solaris::SR_handler(Thread* thread, ucontext_t* uc) { 3583 // Save and restore errno to avoid confusing native code with EINTR 3584 // after sigsuspend. 3585 int old_errno = errno; 3586 3587 OSThread* osthread = thread->osthread(); 3588 assert(thread->is_VM_thread() || thread->is_Java_thread(), "Must be VMThread or JavaThread"); 3589 3590 os::SuspendResume::State current = osthread->sr.state(); 3591 if (current == os::SuspendResume::SR_SUSPEND_REQUEST) { 3592 suspend_save_context(osthread, uc); 3593 3594 // attempt to switch the state, we assume we had a SUSPEND_REQUEST 3595 os::SuspendResume::State state = osthread->sr.suspended(); 3596 if (state == os::SuspendResume::SR_SUSPENDED) { 3597 sigset_t suspend_set; // signals for sigsuspend() 3598 3599 // get current set of blocked signals and unblock resume signal 3600 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); 3601 sigdelset(&suspend_set, os::Solaris::SIGasync()); 3602 3603 sr_semaphore.signal(); 3604 // wait here until we are resumed 3605 while (1) { 3606 sigsuspend(&suspend_set); 3607 3608 os::SuspendResume::State result = osthread->sr.running(); 3609 if (result == os::SuspendResume::SR_RUNNING) { 3610 sr_semaphore.signal(); 3611 break; 3612 } 3613 } 3614 3615 } else if (state == os::SuspendResume::SR_RUNNING) { 3616 // request was cancelled, continue 3617 } else { 3618 ShouldNotReachHere(); 3619 } 3620 3621 resume_clear_context(osthread); 3622 } else if (current == os::SuspendResume::SR_RUNNING) { 3623 // request was cancelled, continue 3624 } else if (current == os::SuspendResume::SR_WAKEUP_REQUEST) { 3625 // ignore 3626 } else { 3627 // ignore 3628 } 3629 3630 errno = old_errno; 3631} 3632 3633void os::print_statistics() { 3634} 3635 3636bool os::message_box(const char* title, const char* message) { 3637 int i; 3638 fdStream err(defaultStream::error_fd()); 3639 for (i = 0; i < 78; i++) err.print_raw("="); 3640 err.cr(); 3641 err.print_raw_cr(title); 3642 for (i = 0; i < 78; i++) err.print_raw("-"); 3643 err.cr(); 3644 err.print_raw_cr(message); 3645 for (i = 0; i < 78; i++) err.print_raw("="); 3646 err.cr(); 3647 3648 char buf[16]; 3649 // Prevent process from exiting upon "read error" without consuming all CPU 3650 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } 3651 3652 return buf[0] == 'y' || buf[0] == 'Y'; 3653} 3654 3655static int sr_notify(OSThread* osthread) { 3656 int status = thr_kill(osthread->thread_id(), os::Solaris::SIGasync()); 3657 assert_status(status == 0, status, "thr_kill"); 3658 return status; 3659} 3660 3661// "Randomly" selected value for how long we want to spin 3662// before bailing out on suspending a thread, also how often 3663// we send a signal to a thread we want to resume 3664static const int RANDOMLY_LARGE_INTEGER = 1000000; 3665static const int RANDOMLY_LARGE_INTEGER2 = 100; 3666 3667static bool do_suspend(OSThread* osthread) { 3668 assert(osthread->sr.is_running(), "thread should be running"); 3669 assert(!sr_semaphore.trywait(), "semaphore has invalid state"); 3670 3671 // mark as suspended and send signal 3672 if (osthread->sr.request_suspend() != os::SuspendResume::SR_SUSPEND_REQUEST) { 3673 // failed to switch, state wasn't running? 3674 ShouldNotReachHere(); 3675 return false; 3676 } 3677 3678 if (sr_notify(osthread) != 0) { 3679 ShouldNotReachHere(); 3680 } 3681 3682 // managed to send the signal and switch to SUSPEND_REQUEST, now wait for SUSPENDED 3683 while (true) { 3684 if (sr_semaphore.timedwait(0, 2000 * NANOSECS_PER_MILLISEC)) { 3685 break; 3686 } else { 3687 // timeout 3688 os::SuspendResume::State cancelled = osthread->sr.cancel_suspend(); 3689 if (cancelled == os::SuspendResume::SR_RUNNING) { 3690 return false; 3691 } else if (cancelled == os::SuspendResume::SR_SUSPENDED) { 3692 // make sure that we consume the signal on the semaphore as well 3693 sr_semaphore.wait(); 3694 break; 3695 } else { 3696 ShouldNotReachHere(); 3697 return false; 3698 } 3699 } 3700 } 3701 3702 guarantee(osthread->sr.is_suspended(), "Must be suspended"); 3703 return true; 3704} 3705 3706static void do_resume(OSThread* osthread) { 3707 assert(osthread->sr.is_suspended(), "thread should be suspended"); 3708 assert(!sr_semaphore.trywait(), "invalid semaphore state"); 3709 3710 if (osthread->sr.request_wakeup() != os::SuspendResume::SR_WAKEUP_REQUEST) { 3711 // failed to switch to WAKEUP_REQUEST 3712 ShouldNotReachHere(); 3713 return; 3714 } 3715 3716 while (true) { 3717 if (sr_notify(osthread) == 0) { 3718 if (sr_semaphore.timedwait(0, 2 * NANOSECS_PER_MILLISEC)) { 3719 if (osthread->sr.is_running()) { 3720 return; 3721 } 3722 } 3723 } else { 3724 ShouldNotReachHere(); 3725 } 3726 } 3727 3728 guarantee(osthread->sr.is_running(), "Must be running!"); 3729} 3730 3731void os::SuspendedThreadTask::internal_do_task() { 3732 if (do_suspend(_thread->osthread())) { 3733 SuspendedThreadTaskContext context(_thread, _thread->osthread()->ucontext()); 3734 do_task(context); 3735 do_resume(_thread->osthread()); 3736 } 3737} 3738 3739class PcFetcher : public os::SuspendedThreadTask { 3740 public: 3741 PcFetcher(Thread* thread) : os::SuspendedThreadTask(thread) {} 3742 ExtendedPC result(); 3743 protected: 3744 void do_task(const os::SuspendedThreadTaskContext& context); 3745 private: 3746 ExtendedPC _epc; 3747}; 3748 3749ExtendedPC PcFetcher::result() { 3750 guarantee(is_done(), "task is not done yet."); 3751 return _epc; 3752} 3753 3754void PcFetcher::do_task(const os::SuspendedThreadTaskContext& context) { 3755 Thread* thread = context.thread(); 3756 OSThread* osthread = thread->osthread(); 3757 if (osthread->ucontext() != NULL) { 3758 _epc = os::Solaris::ucontext_get_pc((const ucontext_t *) context.ucontext()); 3759 } else { 3760 // NULL context is unexpected, double-check this is the VMThread 3761 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); 3762 } 3763} 3764 3765// A lightweight implementation that does not suspend the target thread and 3766// thus returns only a hint. Used for profiling only! 3767ExtendedPC os::get_thread_pc(Thread* thread) { 3768 // Make sure that it is called by the watcher and the Threads lock is owned. 3769 assert(Thread::current()->is_Watcher_thread(), "Must be watcher and own Threads_lock"); 3770 // For now, is only used to profile the VM Thread 3771 assert(thread->is_VM_thread(), "Can only be called for VMThread"); 3772 PcFetcher fetcher(thread); 3773 fetcher.run(); 3774 return fetcher.result(); 3775} 3776 3777 3778// This does not do anything on Solaris. This is basically a hook for being 3779// able to use structured exception handling (thread-local exception filters) on, e.g., Win32. 3780void os::os_exception_wrapper(java_call_t f, JavaValue* value, 3781 const methodHandle& method, JavaCallArguments* args, 3782 Thread* thread) { 3783 f(value, method, args, thread); 3784} 3785 3786// This routine may be used by user applications as a "hook" to catch signals. 3787// The user-defined signal handler must pass unrecognized signals to this 3788// routine, and if it returns true (non-zero), then the signal handler must 3789// return immediately. If the flag "abort_if_unrecognized" is true, then this 3790// routine will never retun false (zero), but instead will execute a VM panic 3791// routine kill the process. 3792// 3793// If this routine returns false, it is OK to call it again. This allows 3794// the user-defined signal handler to perform checks either before or after 3795// the VM performs its own checks. Naturally, the user code would be making 3796// a serious error if it tried to handle an exception (such as a null check 3797// or breakpoint) that the VM was generating for its own correct operation. 3798// 3799// This routine may recognize any of the following kinds of signals: 3800// SIGBUS, SIGSEGV, SIGILL, SIGFPE, BREAK_SIGNAL, SIGPIPE, SIGXFSZ, 3801// os::Solaris::SIGasync 3802// It should be consulted by handlers for any of those signals. 3803// 3804// The caller of this routine must pass in the three arguments supplied 3805// to the function referred to in the "sa_sigaction" (not the "sa_handler") 3806// field of the structure passed to sigaction(). This routine assumes that 3807// the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. 3808// 3809// Note that the VM will print warnings if it detects conflicting signal 3810// handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". 3811// 3812extern "C" JNIEXPORT int JVM_handle_solaris_signal(int signo, 3813 siginfo_t* siginfo, 3814 void* ucontext, 3815 int abort_if_unrecognized); 3816 3817 3818void signalHandler(int sig, siginfo_t* info, void* ucVoid) { 3819 int orig_errno = errno; // Preserve errno value over signal handler. 3820 JVM_handle_solaris_signal(sig, info, ucVoid, true); 3821 errno = orig_errno; 3822} 3823 3824// This boolean allows users to forward their own non-matching signals 3825// to JVM_handle_solaris_signal, harmlessly. 3826bool os::Solaris::signal_handlers_are_installed = false; 3827 3828// For signal-chaining 3829bool os::Solaris::libjsig_is_loaded = false; 3830typedef struct sigaction *(*get_signal_t)(int); 3831get_signal_t os::Solaris::get_signal_action = NULL; 3832 3833struct sigaction* os::Solaris::get_chained_signal_action(int sig) { 3834 struct sigaction *actp = NULL; 3835 3836 if ((libjsig_is_loaded) && (sig <= Maxlibjsigsigs)) { 3837 // Retrieve the old signal handler from libjsig 3838 actp = (*get_signal_action)(sig); 3839 } 3840 if (actp == NULL) { 3841 // Retrieve the preinstalled signal handler from jvm 3842 actp = get_preinstalled_handler(sig); 3843 } 3844 3845 return actp; 3846} 3847 3848static bool call_chained_handler(struct sigaction *actp, int sig, 3849 siginfo_t *siginfo, void *context) { 3850 // Call the old signal handler 3851 if (actp->sa_handler == SIG_DFL) { 3852 // It's more reasonable to let jvm treat it as an unexpected exception 3853 // instead of taking the default action. 3854 return false; 3855 } else if (actp->sa_handler != SIG_IGN) { 3856 if ((actp->sa_flags & SA_NODEFER) == 0) { 3857 // automaticlly block the signal 3858 sigaddset(&(actp->sa_mask), sig); 3859 } 3860 3861 sa_handler_t hand; 3862 sa_sigaction_t sa; 3863 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; 3864 // retrieve the chained handler 3865 if (siginfo_flag_set) { 3866 sa = actp->sa_sigaction; 3867 } else { 3868 hand = actp->sa_handler; 3869 } 3870 3871 if ((actp->sa_flags & SA_RESETHAND) != 0) { 3872 actp->sa_handler = SIG_DFL; 3873 } 3874 3875 // try to honor the signal mask 3876 sigset_t oset; 3877 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); 3878 3879 // call into the chained handler 3880 if (siginfo_flag_set) { 3881 (*sa)(sig, siginfo, context); 3882 } else { 3883 (*hand)(sig); 3884 } 3885 3886 // restore the signal mask 3887 pthread_sigmask(SIG_SETMASK, &oset, 0); 3888 } 3889 // Tell jvm's signal handler the signal is taken care of. 3890 return true; 3891} 3892 3893bool os::Solaris::chained_handler(int sig, siginfo_t* siginfo, void* context) { 3894 bool chained = false; 3895 // signal-chaining 3896 if (UseSignalChaining) { 3897 struct sigaction *actp = get_chained_signal_action(sig); 3898 if (actp != NULL) { 3899 chained = call_chained_handler(actp, sig, siginfo, context); 3900 } 3901 } 3902 return chained; 3903} 3904 3905struct sigaction* os::Solaris::get_preinstalled_handler(int sig) { 3906 assert((chainedsigactions != (struct sigaction *)NULL) && 3907 (preinstalled_sigs != (int *)NULL), "signals not yet initialized"); 3908 if (preinstalled_sigs[sig] != 0) { 3909 return &chainedsigactions[sig]; 3910 } 3911 return NULL; 3912} 3913 3914void os::Solaris::save_preinstalled_handler(int sig, 3915 struct sigaction& oldAct) { 3916 assert(sig > 0 && sig <= Maxsignum, "vm signal out of expected range"); 3917 assert((chainedsigactions != (struct sigaction *)NULL) && 3918 (preinstalled_sigs != (int *)NULL), "signals not yet initialized"); 3919 chainedsigactions[sig] = oldAct; 3920 preinstalled_sigs[sig] = 1; 3921} 3922 3923void os::Solaris::set_signal_handler(int sig, bool set_installed, 3924 bool oktochain) { 3925 // Check for overwrite. 3926 struct sigaction oldAct; 3927 sigaction(sig, (struct sigaction*)NULL, &oldAct); 3928 void* oldhand = 3929 oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3930 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3931 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && 3932 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && 3933 oldhand != CAST_FROM_FN_PTR(void*, signalHandler)) { 3934 if (AllowUserSignalHandlers || !set_installed) { 3935 // Do not overwrite; user takes responsibility to forward to us. 3936 return; 3937 } else if (UseSignalChaining) { 3938 if (oktochain) { 3939 // save the old handler in jvm 3940 save_preinstalled_handler(sig, oldAct); 3941 } else { 3942 vm_exit_during_initialization("Signal chaining not allowed for VM interrupt signal."); 3943 } 3944 // libjsig also interposes the sigaction() call below and saves the 3945 // old sigaction on it own. 3946 } else { 3947 fatal("Encountered unexpected pre-existing sigaction handler " 3948 "%#lx for signal %d.", (long)oldhand, sig); 3949 } 3950 } 3951 3952 struct sigaction sigAct; 3953 sigfillset(&(sigAct.sa_mask)); 3954 sigAct.sa_handler = SIG_DFL; 3955 3956 sigAct.sa_sigaction = signalHandler; 3957 // Handle SIGSEGV on alternate signal stack if 3958 // not using stack banging 3959 if (!UseStackBanging && sig == SIGSEGV) { 3960 sigAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK; 3961 } else { 3962 sigAct.sa_flags = SA_SIGINFO | SA_RESTART; 3963 } 3964 os::Solaris::set_our_sigflags(sig, sigAct.sa_flags); 3965 3966 sigaction(sig, &sigAct, &oldAct); 3967 3968 void* oldhand2 = oldAct.sa_sigaction ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) 3969 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); 3970 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); 3971} 3972 3973 3974#define DO_SIGNAL_CHECK(sig) \ 3975 do { \ 3976 if (!sigismember(&check_signal_done, sig)) { \ 3977 os::Solaris::check_signal_handler(sig); \ 3978 } \ 3979 } while (0) 3980 3981// This method is a periodic task to check for misbehaving JNI applications 3982// under CheckJNI, we can add any periodic checks here 3983 3984void os::run_periodic_checks() { 3985 // A big source of grief is hijacking virt. addr 0x0 on Solaris, 3986 // thereby preventing a NULL checks. 3987 if (!check_addr0_done) check_addr0_done = check_addr0(tty); 3988 3989 if (check_signals == false) return; 3990 3991 // SEGV and BUS if overridden could potentially prevent 3992 // generation of hs*.log in the event of a crash, debugging 3993 // such a case can be very challenging, so we absolutely 3994 // check for the following for a good measure: 3995 DO_SIGNAL_CHECK(SIGSEGV); 3996 DO_SIGNAL_CHECK(SIGILL); 3997 DO_SIGNAL_CHECK(SIGFPE); 3998 DO_SIGNAL_CHECK(SIGBUS); 3999 DO_SIGNAL_CHECK(SIGPIPE); 4000 DO_SIGNAL_CHECK(SIGXFSZ); 4001 4002 // ReduceSignalUsage allows the user to override these handlers 4003 // see comments at the very top and jvm_solaris.h 4004 if (!ReduceSignalUsage) { 4005 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); 4006 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); 4007 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); 4008 DO_SIGNAL_CHECK(BREAK_SIGNAL); 4009 } 4010 4011 // See comments above for using JVM1/JVM2 4012 DO_SIGNAL_CHECK(os::Solaris::SIGasync()); 4013 4014} 4015 4016typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); 4017 4018static os_sigaction_t os_sigaction = NULL; 4019 4020void os::Solaris::check_signal_handler(int sig) { 4021 char buf[O_BUFLEN]; 4022 address jvmHandler = NULL; 4023 4024 struct sigaction act; 4025 if (os_sigaction == NULL) { 4026 // only trust the default sigaction, in case it has been interposed 4027 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); 4028 if (os_sigaction == NULL) return; 4029 } 4030 4031 os_sigaction(sig, (struct sigaction*)NULL, &act); 4032 4033 address thisHandler = (act.sa_flags & SA_SIGINFO) 4034 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) 4035 : CAST_FROM_FN_PTR(address, act.sa_handler); 4036 4037 4038 switch (sig) { 4039 case SIGSEGV: 4040 case SIGBUS: 4041 case SIGFPE: 4042 case SIGPIPE: 4043 case SIGXFSZ: 4044 case SIGILL: 4045 jvmHandler = CAST_FROM_FN_PTR(address, signalHandler); 4046 break; 4047 4048 case SHUTDOWN1_SIGNAL: 4049 case SHUTDOWN2_SIGNAL: 4050 case SHUTDOWN3_SIGNAL: 4051 case BREAK_SIGNAL: 4052 jvmHandler = (address)user_handler(); 4053 break; 4054 4055 default: 4056 int asynsig = os::Solaris::SIGasync(); 4057 4058 if (sig == asynsig) { 4059 jvmHandler = CAST_FROM_FN_PTR(address, signalHandler); 4060 } else { 4061 return; 4062 } 4063 break; 4064 } 4065 4066 4067 if (thisHandler != jvmHandler) { 4068 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); 4069 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); 4070 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); 4071 // No need to check this sig any longer 4072 sigaddset(&check_signal_done, sig); 4073 // Running under non-interactive shell, SHUTDOWN2_SIGNAL will be reassigned SIG_IGN 4074 if (sig == SHUTDOWN2_SIGNAL && !isatty(fileno(stdin))) { 4075 tty->print_cr("Running in non-interactive shell, %s handler is replaced by shell", 4076 exception_name(sig, buf, O_BUFLEN)); 4077 } 4078 } else if(os::Solaris::get_our_sigflags(sig) != 0 && act.sa_flags != os::Solaris::get_our_sigflags(sig)) { 4079 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); 4080 tty->print("expected:"); 4081 os::Posix::print_sa_flags(tty, os::Solaris::get_our_sigflags(sig)); 4082 tty->cr(); 4083 tty->print(" found:"); 4084 os::Posix::print_sa_flags(tty, act.sa_flags); 4085 tty->cr(); 4086 // No need to check this sig any longer 4087 sigaddset(&check_signal_done, sig); 4088 } 4089 4090 // Print all the signal handler state 4091 if (sigismember(&check_signal_done, sig)) { 4092 print_signal_handlers(tty, buf, O_BUFLEN); 4093 } 4094 4095} 4096 4097void os::Solaris::install_signal_handlers() { 4098 bool libjsigdone = false; 4099 signal_handlers_are_installed = true; 4100 4101 // signal-chaining 4102 typedef void (*signal_setting_t)(); 4103 signal_setting_t begin_signal_setting = NULL; 4104 signal_setting_t end_signal_setting = NULL; 4105 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4106 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); 4107 if (begin_signal_setting != NULL) { 4108 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, 4109 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); 4110 get_signal_action = CAST_TO_FN_PTR(get_signal_t, 4111 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); 4112 get_libjsig_version = CAST_TO_FN_PTR(version_getting_t, 4113 dlsym(RTLD_DEFAULT, "JVM_get_libjsig_version")); 4114 libjsig_is_loaded = true; 4115 if (os::Solaris::get_libjsig_version != NULL) { 4116 libjsigversion = (*os::Solaris::get_libjsig_version)(); 4117 } 4118 assert(UseSignalChaining, "should enable signal-chaining"); 4119 } 4120 if (libjsig_is_loaded) { 4121 // Tell libjsig jvm is setting signal handlers 4122 (*begin_signal_setting)(); 4123 } 4124 4125 set_signal_handler(SIGSEGV, true, true); 4126 set_signal_handler(SIGPIPE, true, true); 4127 set_signal_handler(SIGXFSZ, true, true); 4128 set_signal_handler(SIGBUS, true, true); 4129 set_signal_handler(SIGILL, true, true); 4130 set_signal_handler(SIGFPE, true, true); 4131 4132 4133 if (os::Solaris::SIGasync() > OLDMAXSIGNUM) { 4134 // Pre-1.4.1 Libjsig limited to signal chaining signals <= 32 so 4135 // can not register overridable signals which might be > 32 4136 if (libjsig_is_loaded && libjsigversion <= JSIG_VERSION_1_4_1) { 4137 // Tell libjsig jvm has finished setting signal handlers 4138 (*end_signal_setting)(); 4139 libjsigdone = true; 4140 } 4141 } 4142 4143 set_signal_handler(os::Solaris::SIGasync(), true, true); 4144 4145 if (libjsig_is_loaded && !libjsigdone) { 4146 // Tell libjsig jvm finishes setting signal handlers 4147 (*end_signal_setting)(); 4148 } 4149 4150 // We don't activate signal checker if libjsig is in place, we trust ourselves 4151 // and if UserSignalHandler is installed all bets are off. 4152 // Log that signal checking is off only if -verbose:jni is specified. 4153 if (CheckJNICalls) { 4154 if (libjsig_is_loaded) { 4155 if (PrintJNIResolving) { 4156 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); 4157 } 4158 check_signals = false; 4159 } 4160 if (AllowUserSignalHandlers) { 4161 if (PrintJNIResolving) { 4162 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); 4163 } 4164 check_signals = false; 4165 } 4166 } 4167} 4168 4169 4170void report_error(const char* file_name, int line_no, const char* title, 4171 const char* format, ...); 4172 4173// (Static) wrapper for getisax(2) call. 4174os::Solaris::getisax_func_t os::Solaris::_getisax = 0; 4175 4176// (Static) wrappers for the liblgrp API 4177os::Solaris::lgrp_home_func_t os::Solaris::_lgrp_home; 4178os::Solaris::lgrp_init_func_t os::Solaris::_lgrp_init; 4179os::Solaris::lgrp_fini_func_t os::Solaris::_lgrp_fini; 4180os::Solaris::lgrp_root_func_t os::Solaris::_lgrp_root; 4181os::Solaris::lgrp_children_func_t os::Solaris::_lgrp_children; 4182os::Solaris::lgrp_resources_func_t os::Solaris::_lgrp_resources; 4183os::Solaris::lgrp_nlgrps_func_t os::Solaris::_lgrp_nlgrps; 4184os::Solaris::lgrp_cookie_stale_func_t os::Solaris::_lgrp_cookie_stale; 4185os::Solaris::lgrp_cookie_t os::Solaris::_lgrp_cookie = 0; 4186 4187// (Static) wrapper for meminfo() call. 4188os::Solaris::meminfo_func_t os::Solaris::_meminfo = 0; 4189 4190static address resolve_symbol_lazy(const char* name) { 4191 address addr = (address) dlsym(RTLD_DEFAULT, name); 4192 if (addr == NULL) { 4193 // RTLD_DEFAULT was not defined on some early versions of 2.5.1 4194 addr = (address) dlsym(RTLD_NEXT, name); 4195 } 4196 return addr; 4197} 4198 4199static address resolve_symbol(const char* name) { 4200 address addr = resolve_symbol_lazy(name); 4201 if (addr == NULL) { 4202 fatal(dlerror()); 4203 } 4204 return addr; 4205} 4206 4207void os::Solaris::libthread_init() { 4208 address func = (address)dlsym(RTLD_DEFAULT, "_thr_suspend_allmutators"); 4209 4210 lwp_priocntl_init(); 4211 4212 // RTLD_DEFAULT was not defined on some early versions of 5.5.1 4213 if (func == NULL) { 4214 func = (address) dlsym(RTLD_NEXT, "_thr_suspend_allmutators"); 4215 // Guarantee that this VM is running on an new enough OS (5.6 or 4216 // later) that it will have a new enough libthread.so. 4217 guarantee(func != NULL, "libthread.so is too old."); 4218 } 4219 4220 int size; 4221 void (*handler_info_func)(address *, int *); 4222 handler_info_func = CAST_TO_FN_PTR(void (*)(address *, int *), resolve_symbol("thr_sighndlrinfo")); 4223 handler_info_func(&handler_start, &size); 4224 handler_end = handler_start + size; 4225} 4226 4227 4228int_fnP_mutex_tP os::Solaris::_mutex_lock; 4229int_fnP_mutex_tP os::Solaris::_mutex_trylock; 4230int_fnP_mutex_tP os::Solaris::_mutex_unlock; 4231int_fnP_mutex_tP_i_vP os::Solaris::_mutex_init; 4232int_fnP_mutex_tP os::Solaris::_mutex_destroy; 4233int os::Solaris::_mutex_scope = USYNC_THREAD; 4234 4235int_fnP_cond_tP_mutex_tP_timestruc_tP os::Solaris::_cond_timedwait; 4236int_fnP_cond_tP_mutex_tP os::Solaris::_cond_wait; 4237int_fnP_cond_tP os::Solaris::_cond_signal; 4238int_fnP_cond_tP os::Solaris::_cond_broadcast; 4239int_fnP_cond_tP_i_vP os::Solaris::_cond_init; 4240int_fnP_cond_tP os::Solaris::_cond_destroy; 4241int os::Solaris::_cond_scope = USYNC_THREAD; 4242 4243void os::Solaris::synchronization_init() { 4244 if (UseLWPSynchronization) { 4245 os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_lock"))); 4246 os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_trylock"))); 4247 os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("_lwp_mutex_unlock"))); 4248 os::Solaris::set_mutex_init(lwp_mutex_init); 4249 os::Solaris::set_mutex_destroy(lwp_mutex_destroy); 4250 os::Solaris::set_mutex_scope(USYNC_THREAD); 4251 4252 os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("_lwp_cond_timedwait"))); 4253 os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("_lwp_cond_wait"))); 4254 os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_signal"))); 4255 os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("_lwp_cond_broadcast"))); 4256 os::Solaris::set_cond_init(lwp_cond_init); 4257 os::Solaris::set_cond_destroy(lwp_cond_destroy); 4258 os::Solaris::set_cond_scope(USYNC_THREAD); 4259 } else { 4260 os::Solaris::set_mutex_scope(USYNC_THREAD); 4261 os::Solaris::set_cond_scope(USYNC_THREAD); 4262 4263 if (UsePthreads) { 4264 os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_lock"))); 4265 os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_trylock"))); 4266 os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_unlock"))); 4267 os::Solaris::set_mutex_init(pthread_mutex_default_init); 4268 os::Solaris::set_mutex_destroy(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("pthread_mutex_destroy"))); 4269 4270 os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("pthread_cond_timedwait"))); 4271 os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("pthread_cond_wait"))); 4272 os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_signal"))); 4273 os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_broadcast"))); 4274 os::Solaris::set_cond_init(pthread_cond_default_init); 4275 os::Solaris::set_cond_destroy(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("pthread_cond_destroy"))); 4276 } else { 4277 os::Solaris::set_mutex_lock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_lock"))); 4278 os::Solaris::set_mutex_trylock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_trylock"))); 4279 os::Solaris::set_mutex_unlock(CAST_TO_FN_PTR(int_fnP_mutex_tP, resolve_symbol("mutex_unlock"))); 4280 os::Solaris::set_mutex_init(::mutex_init); 4281 os::Solaris::set_mutex_destroy(::mutex_destroy); 4282 4283 os::Solaris::set_cond_timedwait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP_timestruc_tP, resolve_symbol("cond_timedwait"))); 4284 os::Solaris::set_cond_wait(CAST_TO_FN_PTR(int_fnP_cond_tP_mutex_tP, resolve_symbol("cond_wait"))); 4285 os::Solaris::set_cond_signal(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_signal"))); 4286 os::Solaris::set_cond_broadcast(CAST_TO_FN_PTR(int_fnP_cond_tP, resolve_symbol("cond_broadcast"))); 4287 os::Solaris::set_cond_init(::cond_init); 4288 os::Solaris::set_cond_destroy(::cond_destroy); 4289 } 4290 } 4291} 4292 4293bool os::Solaris::liblgrp_init() { 4294 void *handle = dlopen("liblgrp.so.1", RTLD_LAZY); 4295 if (handle != NULL) { 4296 os::Solaris::set_lgrp_home(CAST_TO_FN_PTR(lgrp_home_func_t, dlsym(handle, "lgrp_home"))); 4297 os::Solaris::set_lgrp_init(CAST_TO_FN_PTR(lgrp_init_func_t, dlsym(handle, "lgrp_init"))); 4298 os::Solaris::set_lgrp_fini(CAST_TO_FN_PTR(lgrp_fini_func_t, dlsym(handle, "lgrp_fini"))); 4299 os::Solaris::set_lgrp_root(CAST_TO_FN_PTR(lgrp_root_func_t, dlsym(handle, "lgrp_root"))); 4300 os::Solaris::set_lgrp_children(CAST_TO_FN_PTR(lgrp_children_func_t, dlsym(handle, "lgrp_children"))); 4301 os::Solaris::set_lgrp_resources(CAST_TO_FN_PTR(lgrp_resources_func_t, dlsym(handle, "lgrp_resources"))); 4302 os::Solaris::set_lgrp_nlgrps(CAST_TO_FN_PTR(lgrp_nlgrps_func_t, dlsym(handle, "lgrp_nlgrps"))); 4303 os::Solaris::set_lgrp_cookie_stale(CAST_TO_FN_PTR(lgrp_cookie_stale_func_t, 4304 dlsym(handle, "lgrp_cookie_stale"))); 4305 4306 lgrp_cookie_t c = lgrp_init(LGRP_VIEW_CALLER); 4307 set_lgrp_cookie(c); 4308 return true; 4309 } 4310 return false; 4311} 4312 4313void os::Solaris::misc_sym_init() { 4314 address func; 4315 4316 // getisax 4317 func = resolve_symbol_lazy("getisax"); 4318 if (func != NULL) { 4319 os::Solaris::_getisax = CAST_TO_FN_PTR(getisax_func_t, func); 4320 } 4321 4322 // meminfo 4323 func = resolve_symbol_lazy("meminfo"); 4324 if (func != NULL) { 4325 os::Solaris::set_meminfo(CAST_TO_FN_PTR(meminfo_func_t, func)); 4326 } 4327} 4328 4329uint_t os::Solaris::getisax(uint32_t* array, uint_t n) { 4330 assert(_getisax != NULL, "_getisax not set"); 4331 return _getisax(array, n); 4332} 4333 4334// int pset_getloadavg(psetid_t pset, double loadavg[], int nelem); 4335typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem); 4336static pset_getloadavg_type pset_getloadavg_ptr = NULL; 4337 4338void init_pset_getloadavg_ptr(void) { 4339 pset_getloadavg_ptr = 4340 (pset_getloadavg_type)dlsym(RTLD_DEFAULT, "pset_getloadavg"); 4341 if (PrintMiscellaneous && Verbose && pset_getloadavg_ptr == NULL) { 4342 warning("pset_getloadavg function not found"); 4343 } 4344} 4345 4346int os::Solaris::_dev_zero_fd = -1; 4347 4348// this is called _before_ the global arguments have been parsed 4349void os::init(void) { 4350 _initial_pid = getpid(); 4351 4352 max_hrtime = first_hrtime = gethrtime(); 4353 4354 init_random(1234567); 4355 4356 page_size = sysconf(_SC_PAGESIZE); 4357 if (page_size == -1) { 4358 fatal("os_solaris.cpp: os::init: sysconf failed (%s)", strerror(errno)); 4359 } 4360 init_page_sizes((size_t) page_size); 4361 4362 Solaris::initialize_system_info(); 4363 4364 // Initialize misc. symbols as soon as possible, so we can use them 4365 // if we need them. 4366 Solaris::misc_sym_init(); 4367 4368 int fd = ::open("/dev/zero", O_RDWR); 4369 if (fd < 0) { 4370 fatal("os::init: cannot open /dev/zero (%s)", strerror(errno)); 4371 } else { 4372 Solaris::set_dev_zero_fd(fd); 4373 4374 // Close on exec, child won't inherit. 4375 fcntl(fd, F_SETFD, FD_CLOEXEC); 4376 } 4377 4378 clock_tics_per_sec = CLK_TCK; 4379 4380 // check if dladdr1() exists; dladdr1 can provide more information than 4381 // dladdr for os::dll_address_to_function_name. It comes with SunOS 5.9 4382 // and is available on linker patches for 5.7 and 5.8. 4383 // libdl.so must have been loaded, this call is just an entry lookup 4384 void * hdl = dlopen("libdl.so", RTLD_NOW); 4385 if (hdl) { 4386 dladdr1_func = CAST_TO_FN_PTR(dladdr1_func_type, dlsym(hdl, "dladdr1")); 4387 } 4388 4389 // (Solaris only) this switches to calls that actually do locking. 4390 ThreadCritical::initialize(); 4391 4392 main_thread = thr_self(); 4393 4394 // Constant minimum stack size allowed. It must be at least 4395 // the minimum of what the OS supports (thr_min_stack()), and 4396 // enough to allow the thread to get to user bytecode execution. 4397 Solaris::min_stack_allowed = MAX2(thr_min_stack(), Solaris::min_stack_allowed); 4398} 4399 4400// To install functions for atexit system call 4401extern "C" { 4402 static void perfMemory_exit_helper() { 4403 perfMemory_exit(); 4404 } 4405} 4406 4407// this is called _after_ the global arguments have been parsed 4408jint os::init_2(void) { 4409 // try to enable extended file IO ASAP, see 6431278 4410 os::Solaris::try_enable_extended_io(); 4411 4412 // Allocate a single page and mark it as readable for safepoint polling. Also 4413 // use this first mmap call to check support for MAP_ALIGN. 4414 address polling_page = (address)Solaris::mmap_chunk((char*)page_size, 4415 page_size, 4416 MAP_PRIVATE | MAP_ALIGN, 4417 PROT_READ); 4418 if (polling_page == NULL) { 4419 has_map_align = false; 4420 polling_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE, 4421 PROT_READ); 4422 } 4423 4424 os::set_polling_page(polling_page); 4425 4426#ifndef PRODUCT 4427 if (Verbose && PrintMiscellaneous) { 4428 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", 4429 (intptr_t)polling_page); 4430 } 4431#endif 4432 4433 if (!UseMembar) { 4434 address mem_serialize_page = (address)Solaris::mmap_chunk(NULL, page_size, MAP_PRIVATE, PROT_READ | PROT_WRITE); 4435 guarantee(mem_serialize_page != NULL, "mmap Failed for memory serialize page"); 4436 os::set_memory_serialize_page(mem_serialize_page); 4437 4438#ifndef PRODUCT 4439 if (Verbose && PrintMiscellaneous) { 4440 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", 4441 (intptr_t)mem_serialize_page); 4442 } 4443#endif 4444 } 4445 4446 // Check minimum allowable stack size for thread creation and to initialize 4447 // the java system classes, including StackOverflowError - depends on page 4448 // size. Add a page for compiler2 recursion in main thread. 4449 // Add in 2*BytesPerWord times page size to account for VM stack during 4450 // class initialization depending on 32 or 64 bit VM. 4451 os::Solaris::min_stack_allowed = MAX2(os::Solaris::min_stack_allowed, 4452 JavaThread::stack_guard_zone_size() + 4453 JavaThread::stack_shadow_zone_size() + 4454 (2*BytesPerWord COMPILER2_PRESENT(+1)) * page_size); 4455 4456 size_t threadStackSizeInBytes = ThreadStackSize * K; 4457 if (threadStackSizeInBytes != 0 && 4458 threadStackSizeInBytes < os::Solaris::min_stack_allowed) { 4459 tty->print_cr("\nThe stack size specified is too small, Specify at least %dk", 4460 os::Solaris::min_stack_allowed/K); 4461 return JNI_ERR; 4462 } 4463 4464 // For 64kbps there will be a 64kb page size, which makes 4465 // the usable default stack size quite a bit less. Increase the 4466 // stack for 64kb (or any > than 8kb) pages, this increases 4467 // virtual memory fragmentation (since we're not creating the 4468 // stack on a power of 2 boundary. The real fix for this 4469 // should be to fix the guard page mechanism. 4470 4471 if (vm_page_size() > 8*K) { 4472 threadStackSizeInBytes = (threadStackSizeInBytes != 0) 4473 ? threadStackSizeInBytes + 4474 JavaThread::stack_red_zone_size() + 4475 JavaThread::stack_yellow_zone_size() 4476 : 0; 4477 ThreadStackSize = threadStackSizeInBytes/K; 4478 } 4479 4480 // Make the stack size a multiple of the page size so that 4481 // the yellow/red zones can be guarded. 4482 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, 4483 vm_page_size())); 4484 4485 Solaris::libthread_init(); 4486 4487 if (UseNUMA) { 4488 if (!Solaris::liblgrp_init()) { 4489 UseNUMA = false; 4490 } else { 4491 size_t lgrp_limit = os::numa_get_groups_num(); 4492 int *lgrp_ids = NEW_C_HEAP_ARRAY(int, lgrp_limit, mtInternal); 4493 size_t lgrp_num = os::numa_get_leaf_groups(lgrp_ids, lgrp_limit); 4494 FREE_C_HEAP_ARRAY(int, lgrp_ids); 4495 if (lgrp_num < 2) { 4496 // There's only one locality group, disable NUMA. 4497 UseNUMA = false; 4498 } 4499 } 4500 if (!UseNUMA && ForceNUMA) { 4501 UseNUMA = true; 4502 } 4503 } 4504 4505 Solaris::signal_sets_init(); 4506 Solaris::init_signal_mem(); 4507 Solaris::install_signal_handlers(); 4508 4509 if (libjsigversion < JSIG_VERSION_1_4_1) { 4510 Maxlibjsigsigs = OLDMAXSIGNUM; 4511 } 4512 4513 // initialize synchronization primitives to use either thread or 4514 // lwp synchronization (controlled by UseLWPSynchronization) 4515 Solaris::synchronization_init(); 4516 4517 if (MaxFDLimit) { 4518 // set the number of file descriptors to max. print out error 4519 // if getrlimit/setrlimit fails but continue regardless. 4520 struct rlimit nbr_files; 4521 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); 4522 if (status != 0) { 4523 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4524 perror("os::init_2 getrlimit failed"); 4525 } 4526 } else { 4527 nbr_files.rlim_cur = nbr_files.rlim_max; 4528 status = setrlimit(RLIMIT_NOFILE, &nbr_files); 4529 if (status != 0) { 4530 if (PrintMiscellaneous && (Verbose || WizardMode)) { 4531 perror("os::init_2 setrlimit failed"); 4532 } 4533 } 4534 } 4535 } 4536 4537 // Calculate theoretical max. size of Threads to guard gainst 4538 // artifical out-of-memory situations, where all available address- 4539 // space has been reserved by thread stacks. Default stack size is 1Mb. 4540 size_t pre_thread_stack_size = (JavaThread::stack_size_at_create()) ? 4541 JavaThread::stack_size_at_create() : (1*K*K); 4542 assert(pre_thread_stack_size != 0, "Must have a stack"); 4543 // Solaris has a maximum of 4Gb of user programs. Calculate the thread limit when 4544 // we should start doing Virtual Memory banging. Currently when the threads will 4545 // have used all but 200Mb of space. 4546 size_t max_address_space = ((unsigned int)4 * K * K * K) - (200 * K * K); 4547 Solaris::_os_thread_limit = max_address_space / pre_thread_stack_size; 4548 4549 // at-exit methods are called in the reverse order of their registration. 4550 // In Solaris 7 and earlier, atexit functions are called on return from 4551 // main or as a result of a call to exit(3C). There can be only 32 of 4552 // these functions registered and atexit() does not set errno. In Solaris 4553 // 8 and later, there is no limit to the number of functions registered 4554 // and atexit() sets errno. In addition, in Solaris 8 and later, atexit 4555 // functions are called upon dlclose(3DL) in addition to return from main 4556 // and exit(3C). 4557 4558 if (PerfAllowAtExitRegistration) { 4559 // only register atexit functions if PerfAllowAtExitRegistration is set. 4560 // atexit functions can be delayed until process exit time, which 4561 // can be problematic for embedded VM situations. Embedded VMs should 4562 // call DestroyJavaVM() to assure that VM resources are released. 4563 4564 // note: perfMemory_exit_helper atexit function may be removed in 4565 // the future if the appropriate cleanup code can be added to the 4566 // VM_Exit VMOperation's doit method. 4567 if (atexit(perfMemory_exit_helper) != 0) { 4568 warning("os::init2 atexit(perfMemory_exit_helper) failed"); 4569 } 4570 } 4571 4572 // Init pset_loadavg function pointer 4573 init_pset_getloadavg_ptr(); 4574 4575 return JNI_OK; 4576} 4577 4578// Mark the polling page as unreadable 4579void os::make_polling_page_unreadable(void) { 4580 if (mprotect((char *)_polling_page, page_size, PROT_NONE) != 0) { 4581 fatal("Could not disable polling page"); 4582 } 4583} 4584 4585// Mark the polling page as readable 4586void os::make_polling_page_readable(void) { 4587 if (mprotect((char *)_polling_page, page_size, PROT_READ) != 0) { 4588 fatal("Could not enable polling page"); 4589 } 4590} 4591 4592// OS interface. 4593 4594bool os::check_heap(bool force) { return true; } 4595 4596// Is a (classpath) directory empty? 4597bool os::dir_is_empty(const char* path) { 4598 DIR *dir = NULL; 4599 struct dirent *ptr; 4600 4601 dir = opendir(path); 4602 if (dir == NULL) return true; 4603 4604 // Scan the directory 4605 bool result = true; 4606 char buf[sizeof(struct dirent) + MAX_PATH]; 4607 struct dirent *dbuf = (struct dirent *) buf; 4608 while (result && (ptr = readdir(dir, dbuf)) != NULL) { 4609 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { 4610 result = false; 4611 } 4612 } 4613 closedir(dir); 4614 return result; 4615} 4616 4617// This code originates from JDK's sysOpen and open64_w 4618// from src/solaris/hpi/src/system_md.c 4619 4620int os::open(const char *path, int oflag, int mode) { 4621 if (strlen(path) > MAX_PATH - 1) { 4622 errno = ENAMETOOLONG; 4623 return -1; 4624 } 4625 int fd; 4626 4627 fd = ::open64(path, oflag, mode); 4628 if (fd == -1) return -1; 4629 4630 // If the open succeeded, the file might still be a directory 4631 { 4632 struct stat64 buf64; 4633 int ret = ::fstat64(fd, &buf64); 4634 int st_mode = buf64.st_mode; 4635 4636 if (ret != -1) { 4637 if ((st_mode & S_IFMT) == S_IFDIR) { 4638 errno = EISDIR; 4639 ::close(fd); 4640 return -1; 4641 } 4642 } else { 4643 ::close(fd); 4644 return -1; 4645 } 4646 } 4647 4648 // 32-bit Solaris systems suffer from: 4649 // 4650 // - an historical default soft limit of 256 per-process file 4651 // descriptors that is too low for many Java programs. 4652 // 4653 // - a design flaw where file descriptors created using stdio 4654 // fopen must be less than 256, _even_ when the first limit above 4655 // has been raised. This can cause calls to fopen (but not calls to 4656 // open, for example) to fail mysteriously, perhaps in 3rd party 4657 // native code (although the JDK itself uses fopen). One can hardly 4658 // criticize them for using this most standard of all functions. 4659 // 4660 // We attempt to make everything work anyways by: 4661 // 4662 // - raising the soft limit on per-process file descriptors beyond 4663 // 256 4664 // 4665 // - As of Solaris 10u4, we can request that Solaris raise the 256 4666 // stdio fopen limit by calling function enable_extended_FILE_stdio. 4667 // This is done in init_2 and recorded in enabled_extended_FILE_stdio 4668 // 4669 // - If we are stuck on an old (pre 10u4) Solaris system, we can 4670 // workaround the bug by remapping non-stdio file descriptors below 4671 // 256 to ones beyond 256, which is done below. 4672 // 4673 // See: 4674 // 1085341: 32-bit stdio routines should support file descriptors >255 4675 // 6533291: Work around 32-bit Solaris stdio limit of 256 open files 4676 // 6431278: Netbeans crash on 32 bit Solaris: need to call 4677 // enable_extended_FILE_stdio() in VM initialisation 4678 // Giri Mandalika's blog 4679 // http://technopark02.blogspot.com/2005_05_01_archive.html 4680 // 4681#ifndef _LP64 4682 if ((!enabled_extended_FILE_stdio) && fd < 256) { 4683 int newfd = ::fcntl(fd, F_DUPFD, 256); 4684 if (newfd != -1) { 4685 ::close(fd); 4686 fd = newfd; 4687 } 4688 } 4689#endif // 32-bit Solaris 4690 4691 // All file descriptors that are opened in the JVM and not 4692 // specifically destined for a subprocess should have the 4693 // close-on-exec flag set. If we don't set it, then careless 3rd 4694 // party native code might fork and exec without closing all 4695 // appropriate file descriptors (e.g. as we do in closeDescriptors in 4696 // UNIXProcess.c), and this in turn might: 4697 // 4698 // - cause end-of-file to fail to be detected on some file 4699 // descriptors, resulting in mysterious hangs, or 4700 // 4701 // - might cause an fopen in the subprocess to fail on a system 4702 // suffering from bug 1085341. 4703 // 4704 // (Yes, the default setting of the close-on-exec flag is a Unix 4705 // design flaw) 4706 // 4707 // See: 4708 // 1085341: 32-bit stdio routines should support file descriptors >255 4709 // 4843136: (process) pipe file descriptor from Runtime.exec not being closed 4710 // 6339493: (process) Runtime.exec does not close all file descriptors on Solaris 9 4711 // 4712#ifdef FD_CLOEXEC 4713 { 4714 int flags = ::fcntl(fd, F_GETFD); 4715 if (flags != -1) { 4716 ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); 4717 } 4718 } 4719#endif 4720 4721 return fd; 4722} 4723 4724// create binary file, rewriting existing file if required 4725int os::create_binary_file(const char* path, bool rewrite_existing) { 4726 int oflags = O_WRONLY | O_CREAT; 4727 if (!rewrite_existing) { 4728 oflags |= O_EXCL; 4729 } 4730 return ::open64(path, oflags, S_IREAD | S_IWRITE); 4731} 4732 4733// return current position of file pointer 4734jlong os::current_file_offset(int fd) { 4735 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); 4736} 4737 4738// move file pointer to the specified offset 4739jlong os::seek_to_file_offset(int fd, jlong offset) { 4740 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); 4741} 4742 4743jlong os::lseek(int fd, jlong offset, int whence) { 4744 return (jlong) ::lseek64(fd, offset, whence); 4745} 4746 4747char * os::native_path(char *path) { 4748 return path; 4749} 4750 4751int os::ftruncate(int fd, jlong length) { 4752 return ::ftruncate64(fd, length); 4753} 4754 4755int os::fsync(int fd) { 4756 RESTARTABLE_RETURN_INT(::fsync(fd)); 4757} 4758 4759int os::available(int fd, jlong *bytes) { 4760 assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native, 4761 "Assumed _thread_in_native"); 4762 jlong cur, end; 4763 int mode; 4764 struct stat64 buf64; 4765 4766 if (::fstat64(fd, &buf64) >= 0) { 4767 mode = buf64.st_mode; 4768 if (S_ISCHR(mode) || S_ISFIFO(mode) || S_ISSOCK(mode)) { 4769 int n,ioctl_return; 4770 4771 RESTARTABLE(::ioctl(fd, FIONREAD, &n), ioctl_return); 4772 if (ioctl_return>= 0) { 4773 *bytes = n; 4774 return 1; 4775 } 4776 } 4777 } 4778 if ((cur = ::lseek64(fd, 0L, SEEK_CUR)) == -1) { 4779 return 0; 4780 } else if ((end = ::lseek64(fd, 0L, SEEK_END)) == -1) { 4781 return 0; 4782 } else if (::lseek64(fd, cur, SEEK_SET) == -1) { 4783 return 0; 4784 } 4785 *bytes = end - cur; 4786 return 1; 4787} 4788 4789// Map a block of memory. 4790char* os::pd_map_memory(int fd, const char* file_name, size_t file_offset, 4791 char *addr, size_t bytes, bool read_only, 4792 bool allow_exec) { 4793 int prot; 4794 int flags; 4795 4796 if (read_only) { 4797 prot = PROT_READ; 4798 flags = MAP_SHARED; 4799 } else { 4800 prot = PROT_READ | PROT_WRITE; 4801 flags = MAP_PRIVATE; 4802 } 4803 4804 if (allow_exec) { 4805 prot |= PROT_EXEC; 4806 } 4807 4808 if (addr != NULL) { 4809 flags |= MAP_FIXED; 4810 } 4811 4812 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, 4813 fd, file_offset); 4814 if (mapped_address == MAP_FAILED) { 4815 return NULL; 4816 } 4817 return mapped_address; 4818} 4819 4820 4821// Remap a block of memory. 4822char* os::pd_remap_memory(int fd, const char* file_name, size_t file_offset, 4823 char *addr, size_t bytes, bool read_only, 4824 bool allow_exec) { 4825 // same as map_memory() on this OS 4826 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, 4827 allow_exec); 4828} 4829 4830 4831// Unmap a block of memory. 4832bool os::pd_unmap_memory(char* addr, size_t bytes) { 4833 return munmap(addr, bytes) == 0; 4834} 4835 4836void os::pause() { 4837 char filename[MAX_PATH]; 4838 if (PauseAtStartupFile && PauseAtStartupFile[0]) { 4839 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); 4840 } else { 4841 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); 4842 } 4843 4844 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); 4845 if (fd != -1) { 4846 struct stat buf; 4847 ::close(fd); 4848 while (::stat(filename, &buf) == 0) { 4849 (void)::poll(NULL, 0, 100); 4850 } 4851 } else { 4852 jio_fprintf(stderr, 4853 "Could not open pause file '%s', continuing immediately.\n", filename); 4854 } 4855} 4856 4857#ifndef PRODUCT 4858#ifdef INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS 4859// Turn this on if you need to trace synch operations. 4860// Set RECORD_SYNCH_LIMIT to a large-enough value, 4861// and call record_synch_enable and record_synch_disable 4862// around the computation of interest. 4863 4864void record_synch(char* name, bool returning); // defined below 4865 4866class RecordSynch { 4867 char* _name; 4868 public: 4869 RecordSynch(char* name) :_name(name) { record_synch(_name, false); } 4870 ~RecordSynch() { record_synch(_name, true); } 4871}; 4872 4873#define CHECK_SYNCH_OP(ret, name, params, args, inner) \ 4874extern "C" ret name params { \ 4875 typedef ret name##_t params; \ 4876 static name##_t* implem = NULL; \ 4877 static int callcount = 0; \ 4878 if (implem == NULL) { \ 4879 implem = (name##_t*) dlsym(RTLD_NEXT, #name); \ 4880 if (implem == NULL) fatal(dlerror()); \ 4881 } \ 4882 ++callcount; \ 4883 RecordSynch _rs(#name); \ 4884 inner; \ 4885 return implem args; \ 4886} 4887// in dbx, examine callcounts this way: 4888// for n in $(eval whereis callcount | awk '{print $2}'); do print $n; done 4889 4890#define CHECK_POINTER_OK(p) \ 4891 (!Universe::is_fully_initialized() || !Universe::is_reserved_heap((oop)(p))) 4892#define CHECK_MU \ 4893 if (!CHECK_POINTER_OK(mu)) fatal("Mutex must be in C heap only."); 4894#define CHECK_CV \ 4895 if (!CHECK_POINTER_OK(cv)) fatal("Condvar must be in C heap only."); 4896#define CHECK_P(p) \ 4897 if (!CHECK_POINTER_OK(p)) fatal(false, "Pointer must be in C heap only."); 4898 4899#define CHECK_MUTEX(mutex_op) \ 4900 CHECK_SYNCH_OP(int, mutex_op, (mutex_t *mu), (mu), CHECK_MU); 4901 4902CHECK_MUTEX( mutex_lock) 4903CHECK_MUTEX( _mutex_lock) 4904CHECK_MUTEX( mutex_unlock) 4905CHECK_MUTEX(_mutex_unlock) 4906CHECK_MUTEX( mutex_trylock) 4907CHECK_MUTEX(_mutex_trylock) 4908 4909#define CHECK_COND(cond_op) \ 4910 CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu), (cv, mu), CHECK_MU; CHECK_CV); 4911 4912CHECK_COND( cond_wait); 4913CHECK_COND(_cond_wait); 4914CHECK_COND(_cond_wait_cancel); 4915 4916#define CHECK_COND2(cond_op) \ 4917 CHECK_SYNCH_OP(int, cond_op, (cond_t *cv, mutex_t *mu, timestruc_t* ts), (cv, mu, ts), CHECK_MU; CHECK_CV); 4918 4919CHECK_COND2( cond_timedwait); 4920CHECK_COND2(_cond_timedwait); 4921CHECK_COND2(_cond_timedwait_cancel); 4922 4923// do the _lwp_* versions too 4924#define mutex_t lwp_mutex_t 4925#define cond_t lwp_cond_t 4926CHECK_MUTEX( _lwp_mutex_lock) 4927CHECK_MUTEX( _lwp_mutex_unlock) 4928CHECK_MUTEX( _lwp_mutex_trylock) 4929CHECK_MUTEX( __lwp_mutex_lock) 4930CHECK_MUTEX( __lwp_mutex_unlock) 4931CHECK_MUTEX( __lwp_mutex_trylock) 4932CHECK_MUTEX(___lwp_mutex_lock) 4933CHECK_MUTEX(___lwp_mutex_unlock) 4934 4935CHECK_COND( _lwp_cond_wait); 4936CHECK_COND( __lwp_cond_wait); 4937CHECK_COND(___lwp_cond_wait); 4938 4939CHECK_COND2( _lwp_cond_timedwait); 4940CHECK_COND2( __lwp_cond_timedwait); 4941#undef mutex_t 4942#undef cond_t 4943 4944CHECK_SYNCH_OP(int, _lwp_suspend2, (int lwp, int *n), (lwp, n), 0); 4945CHECK_SYNCH_OP(int,__lwp_suspend2, (int lwp, int *n), (lwp, n), 0); 4946CHECK_SYNCH_OP(int, _lwp_kill, (int lwp, int n), (lwp, n), 0); 4947CHECK_SYNCH_OP(int,__lwp_kill, (int lwp, int n), (lwp, n), 0); 4948CHECK_SYNCH_OP(int, _lwp_sema_wait, (lwp_sema_t* p), (p), CHECK_P(p)); 4949CHECK_SYNCH_OP(int,__lwp_sema_wait, (lwp_sema_t* p), (p), CHECK_P(p)); 4950CHECK_SYNCH_OP(int, _lwp_cond_broadcast, (lwp_cond_t* cv), (cv), CHECK_CV); 4951CHECK_SYNCH_OP(int,__lwp_cond_broadcast, (lwp_cond_t* cv), (cv), CHECK_CV); 4952 4953 4954// recording machinery: 4955 4956enum { RECORD_SYNCH_LIMIT = 200 }; 4957char* record_synch_name[RECORD_SYNCH_LIMIT]; 4958void* record_synch_arg0ptr[RECORD_SYNCH_LIMIT]; 4959bool record_synch_returning[RECORD_SYNCH_LIMIT]; 4960thread_t record_synch_thread[RECORD_SYNCH_LIMIT]; 4961int record_synch_count = 0; 4962bool record_synch_enabled = false; 4963 4964// in dbx, examine recorded data this way: 4965// for n in name arg0ptr returning thread; do print record_synch_$n[0..record_synch_count-1]; done 4966 4967void record_synch(char* name, bool returning) { 4968 if (record_synch_enabled) { 4969 if (record_synch_count < RECORD_SYNCH_LIMIT) { 4970 record_synch_name[record_synch_count] = name; 4971 record_synch_returning[record_synch_count] = returning; 4972 record_synch_thread[record_synch_count] = thr_self(); 4973 record_synch_arg0ptr[record_synch_count] = &name; 4974 record_synch_count++; 4975 } 4976 // put more checking code here: 4977 // ... 4978 } 4979} 4980 4981void record_synch_enable() { 4982 // start collecting trace data, if not already doing so 4983 if (!record_synch_enabled) record_synch_count = 0; 4984 record_synch_enabled = true; 4985} 4986 4987void record_synch_disable() { 4988 // stop collecting trace data 4989 record_synch_enabled = false; 4990} 4991 4992#endif // INTERPOSE_ON_SYSTEM_SYNCH_FUNCTIONS 4993#endif // PRODUCT 4994 4995const intptr_t thr_time_off = (intptr_t)(&((prusage_t *)(NULL))->pr_utime); 4996const intptr_t thr_time_size = (intptr_t)(&((prusage_t *)(NULL))->pr_ttime) - 4997 (intptr_t)(&((prusage_t *)(NULL))->pr_utime); 4998 4999 5000// JVMTI & JVM monitoring and management support 5001// The thread_cpu_time() and current_thread_cpu_time() are only 5002// supported if is_thread_cpu_time_supported() returns true. 5003// They are not supported on Solaris T1. 5004 5005// current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) 5006// are used by JVM M&M and JVMTI to get user+sys or user CPU time 5007// of a thread. 5008// 5009// current_thread_cpu_time() and thread_cpu_time(Thread *) 5010// returns the fast estimate available on the platform. 5011 5012// hrtime_t gethrvtime() return value includes 5013// user time but does not include system time 5014jlong os::current_thread_cpu_time() { 5015 return (jlong) gethrvtime(); 5016} 5017 5018jlong os::thread_cpu_time(Thread *thread) { 5019 // return user level CPU time only to be consistent with 5020 // what current_thread_cpu_time returns. 5021 // thread_cpu_time_info() must be changed if this changes 5022 return os::thread_cpu_time(thread, false /* user time only */); 5023} 5024 5025jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { 5026 if (user_sys_cpu_time) { 5027 return os::thread_cpu_time(Thread::current(), user_sys_cpu_time); 5028 } else { 5029 return os::current_thread_cpu_time(); 5030 } 5031} 5032 5033jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { 5034 char proc_name[64]; 5035 int count; 5036 prusage_t prusage; 5037 jlong lwp_time; 5038 int fd; 5039 5040 sprintf(proc_name, "/proc/%d/lwp/%d/lwpusage", 5041 getpid(), 5042 thread->osthread()->lwp_id()); 5043 fd = ::open(proc_name, O_RDONLY); 5044 if (fd == -1) return -1; 5045 5046 do { 5047 count = ::pread(fd, 5048 (void *)&prusage.pr_utime, 5049 thr_time_size, 5050 thr_time_off); 5051 } while (count < 0 && errno == EINTR); 5052 ::close(fd); 5053 if (count < 0) return -1; 5054 5055 if (user_sys_cpu_time) { 5056 // user + system CPU time 5057 lwp_time = (((jlong)prusage.pr_stime.tv_sec + 5058 (jlong)prusage.pr_utime.tv_sec) * (jlong)1000000000) + 5059 (jlong)prusage.pr_stime.tv_nsec + 5060 (jlong)prusage.pr_utime.tv_nsec; 5061 } else { 5062 // user level CPU time only 5063 lwp_time = ((jlong)prusage.pr_utime.tv_sec * (jlong)1000000000) + 5064 (jlong)prusage.pr_utime.tv_nsec; 5065 } 5066 5067 return (lwp_time); 5068} 5069 5070void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5071 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5072 info_ptr->may_skip_backward = false; // elapsed time not wall time 5073 info_ptr->may_skip_forward = false; // elapsed time not wall time 5074 info_ptr->kind = JVMTI_TIMER_USER_CPU; // only user time is returned 5075} 5076 5077void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { 5078 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits 5079 info_ptr->may_skip_backward = false; // elapsed time not wall time 5080 info_ptr->may_skip_forward = false; // elapsed time not wall time 5081 info_ptr->kind = JVMTI_TIMER_USER_CPU; // only user time is returned 5082} 5083 5084bool os::is_thread_cpu_time_supported() { 5085 return true; 5086} 5087 5088// System loadavg support. Returns -1 if load average cannot be obtained. 5089// Return the load average for our processor set if the primitive exists 5090// (Solaris 9 and later). Otherwise just return system wide loadavg. 5091int os::loadavg(double loadavg[], int nelem) { 5092 if (pset_getloadavg_ptr != NULL) { 5093 return (*pset_getloadavg_ptr)(PS_MYID, loadavg, nelem); 5094 } else { 5095 return ::getloadavg(loadavg, nelem); 5096 } 5097} 5098 5099//--------------------------------------------------------------------------------- 5100 5101bool os::find(address addr, outputStream* st) { 5102 Dl_info dlinfo; 5103 memset(&dlinfo, 0, sizeof(dlinfo)); 5104 if (dladdr(addr, &dlinfo) != 0) { 5105 st->print(PTR_FORMAT ": ", addr); 5106 if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { 5107 st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr); 5108 } else if (dlinfo.dli_fbase != NULL) { 5109 st->print("<offset %#lx>", addr-(intptr_t)dlinfo.dli_fbase); 5110 } else { 5111 st->print("<absolute address>"); 5112 } 5113 if (dlinfo.dli_fname != NULL) { 5114 st->print(" in %s", dlinfo.dli_fname); 5115 } 5116 if (dlinfo.dli_fbase != NULL) { 5117 st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); 5118 } 5119 st->cr(); 5120 5121 if (Verbose) { 5122 // decode some bytes around the PC 5123 address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size()); 5124 address end = clamp_address_in_page(addr+40, addr, os::vm_page_size()); 5125 address lowest = (address) dlinfo.dli_sname; 5126 if (!lowest) lowest = (address) dlinfo.dli_fbase; 5127 if (begin < lowest) begin = lowest; 5128 Dl_info dlinfo2; 5129 if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr 5130 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) { 5131 end = (address) dlinfo2.dli_saddr; 5132 } 5133 Disassembler::decode(begin, end, st); 5134 } 5135 return true; 5136 } 5137 return false; 5138} 5139 5140// Following function has been added to support HotSparc's libjvm.so running 5141// under Solaris production JDK 1.2.2 / 1.3.0. These came from 5142// src/solaris/hpi/native_threads in the EVM codebase. 5143// 5144// NOTE: This is no longer needed in the 1.3.1 and 1.4 production release 5145// libraries and should thus be removed. We will leave it behind for a while 5146// until we no longer want to able to run on top of 1.3.0 Solaris production 5147// JDK. See 4341971. 5148 5149#define STACK_SLACK 0x800 5150 5151extern "C" { 5152 intptr_t sysThreadAvailableStackWithSlack() { 5153 stack_t st; 5154 intptr_t retval, stack_top; 5155 retval = thr_stksegment(&st); 5156 assert(retval == 0, "incorrect return value from thr_stksegment"); 5157 assert((address)&st < (address)st.ss_sp, "Invalid stack base returned"); 5158 assert((address)&st > (address)st.ss_sp-st.ss_size, "Invalid stack size returned"); 5159 stack_top=(intptr_t)st.ss_sp-st.ss_size; 5160 return ((intptr_t)&stack_top - stack_top - STACK_SLACK); 5161 } 5162} 5163 5164// ObjectMonitor park-unpark infrastructure ... 5165// 5166// We implement Solaris and Linux PlatformEvents with the 5167// obvious condvar-mutex-flag triple. 5168// Another alternative that works quite well is pipes: 5169// Each PlatformEvent consists of a pipe-pair. 5170// The thread associated with the PlatformEvent 5171// calls park(), which reads from the input end of the pipe. 5172// Unpark() writes into the other end of the pipe. 5173// The write-side of the pipe must be set NDELAY. 5174// Unfortunately pipes consume a large # of handles. 5175// Native solaris lwp_park() and lwp_unpark() work nicely, too. 5176// Using pipes for the 1st few threads might be workable, however. 5177// 5178// park() is permitted to return spuriously. 5179// Callers of park() should wrap the call to park() in 5180// an appropriate loop. A litmus test for the correct 5181// usage of park is the following: if park() were modified 5182// to immediately return 0 your code should still work, 5183// albeit degenerating to a spin loop. 5184// 5185// In a sense, park()-unpark() just provides more polite spinning 5186// and polling with the key difference over naive spinning being 5187// that a parked thread needs to be explicitly unparked() in order 5188// to wake up and to poll the underlying condition. 5189// 5190// Assumption: 5191// Only one parker can exist on an event, which is why we allocate 5192// them per-thread. Multiple unparkers can coexist. 5193// 5194// _Event transitions in park() 5195// -1 => -1 : illegal 5196// 1 => 0 : pass - return immediately 5197// 0 => -1 : block; then set _Event to 0 before returning 5198// 5199// _Event transitions in unpark() 5200// 0 => 1 : just return 5201// 1 => 1 : just return 5202// -1 => either 0 or 1; must signal target thread 5203// That is, we can safely transition _Event from -1 to either 5204// 0 or 1. 5205// 5206// _Event serves as a restricted-range semaphore. 5207// -1 : thread is blocked, i.e. there is a waiter 5208// 0 : neutral: thread is running or ready, 5209// could have been signaled after a wait started 5210// 1 : signaled - thread is running or ready 5211// 5212// Another possible encoding of _Event would be with 5213// explicit "PARKED" == 01b and "SIGNALED" == 10b bits. 5214// 5215// TODO-FIXME: add DTRACE probes for: 5216// 1. Tx parks 5217// 2. Ty unparks Tx 5218// 3. Tx resumes from park 5219 5220 5221// value determined through experimentation 5222#define ROUNDINGFIX 11 5223 5224// utility to compute the abstime argument to timedwait. 5225// TODO-FIXME: switch from compute_abstime() to unpackTime(). 5226 5227static timestruc_t* compute_abstime(timestruc_t* abstime, jlong millis) { 5228 // millis is the relative timeout time 5229 // abstime will be the absolute timeout time 5230 if (millis < 0) millis = 0; 5231 struct timeval now; 5232 int status = gettimeofday(&now, NULL); 5233 assert(status == 0, "gettimeofday"); 5234 jlong seconds = millis / 1000; 5235 jlong max_wait_period; 5236 5237 if (UseLWPSynchronization) { 5238 // forward port of fix for 4275818 (not sleeping long enough) 5239 // There was a bug in Solaris 6, 7 and pre-patch 5 of 8 where 5240 // _lwp_cond_timedwait() used a round_down algorithm rather 5241 // than a round_up. For millis less than our roundfactor 5242 // it rounded down to 0 which doesn't meet the spec. 5243 // For millis > roundfactor we may return a bit sooner, but 5244 // since we can not accurately identify the patch level and 5245 // this has already been fixed in Solaris 9 and 8 we will 5246 // leave it alone rather than always rounding down. 5247 5248 if (millis > 0 && millis < ROUNDINGFIX) millis = ROUNDINGFIX; 5249 // It appears that when we go directly through Solaris _lwp_cond_timedwait() 5250 // the acceptable max time threshold is smaller than for libthread on 2.5.1 and 2.6 5251 max_wait_period = 21000000; 5252 } else { 5253 max_wait_period = 50000000; 5254 } 5255 millis %= 1000; 5256 if (seconds > max_wait_period) { // see man cond_timedwait(3T) 5257 seconds = max_wait_period; 5258 } 5259 abstime->tv_sec = now.tv_sec + seconds; 5260 long usec = now.tv_usec + millis * 1000; 5261 if (usec >= 1000000) { 5262 abstime->tv_sec += 1; 5263 usec -= 1000000; 5264 } 5265 abstime->tv_nsec = usec * 1000; 5266 return abstime; 5267} 5268 5269void os::PlatformEvent::park() { // AKA: down() 5270 // Transitions for _Event: 5271 // -1 => -1 : illegal 5272 // 1 => 0 : pass - return immediately 5273 // 0 => -1 : block; then set _Event to 0 before returning 5274 5275 // Invariant: Only the thread associated with the Event/PlatformEvent 5276 // may call park(). 5277 assert(_nParked == 0, "invariant"); 5278 5279 int v; 5280 for (;;) { 5281 v = _Event; 5282 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 5283 } 5284 guarantee(v >= 0, "invariant"); 5285 if (v == 0) { 5286 // Do this the hard way by blocking ... 5287 // See http://monaco.sfbay/detail.jsf?cr=5094058. 5288 // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking. 5289 // Only for SPARC >= V8PlusA 5290#if defined(__sparc) && defined(COMPILER2) 5291 if (ClearFPUAtPark) { _mark_fpu_nosave(); } 5292#endif 5293 int status = os::Solaris::mutex_lock(_mutex); 5294 assert_status(status == 0, status, "mutex_lock"); 5295 guarantee(_nParked == 0, "invariant"); 5296 ++_nParked; 5297 while (_Event < 0) { 5298 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... 5299 // Treat this the same as if the wait was interrupted 5300 // With usr/lib/lwp going to kernel, always handle ETIME 5301 status = os::Solaris::cond_wait(_cond, _mutex); 5302 if (status == ETIME) status = EINTR; 5303 assert_status(status == 0 || status == EINTR, status, "cond_wait"); 5304 } 5305 --_nParked; 5306 _Event = 0; 5307 status = os::Solaris::mutex_unlock(_mutex); 5308 assert_status(status == 0, status, "mutex_unlock"); 5309 // Paranoia to ensure our locked and lock-free paths interact 5310 // correctly with each other. 5311 OrderAccess::fence(); 5312 } 5313} 5314 5315int os::PlatformEvent::park(jlong millis) { 5316 // Transitions for _Event: 5317 // -1 => -1 : illegal 5318 // 1 => 0 : pass - return immediately 5319 // 0 => -1 : block; then set _Event to 0 before returning 5320 5321 guarantee(_nParked == 0, "invariant"); 5322 int v; 5323 for (;;) { 5324 v = _Event; 5325 if (Atomic::cmpxchg(v-1, &_Event, v) == v) break; 5326 } 5327 guarantee(v >= 0, "invariant"); 5328 if (v != 0) return OS_OK; 5329 5330 int ret = OS_TIMEOUT; 5331 timestruc_t abst; 5332 compute_abstime(&abst, millis); 5333 5334 // See http://monaco.sfbay/detail.jsf?cr=5094058. 5335 // For Solaris SPARC set fprs.FEF=0 prior to parking. 5336 // Only for SPARC >= V8PlusA 5337#if defined(__sparc) && defined(COMPILER2) 5338 if (ClearFPUAtPark) { _mark_fpu_nosave(); } 5339#endif 5340 int status = os::Solaris::mutex_lock(_mutex); 5341 assert_status(status == 0, status, "mutex_lock"); 5342 guarantee(_nParked == 0, "invariant"); 5343 ++_nParked; 5344 while (_Event < 0) { 5345 int status = os::Solaris::cond_timedwait(_cond, _mutex, &abst); 5346 assert_status(status == 0 || status == EINTR || 5347 status == ETIME || status == ETIMEDOUT, 5348 status, "cond_timedwait"); 5349 if (!FilterSpuriousWakeups) break; // previous semantics 5350 if (status == ETIME || status == ETIMEDOUT) break; 5351 // We consume and ignore EINTR and spurious wakeups. 5352 } 5353 --_nParked; 5354 if (_Event >= 0) ret = OS_OK; 5355 _Event = 0; 5356 status = os::Solaris::mutex_unlock(_mutex); 5357 assert_status(status == 0, status, "mutex_unlock"); 5358 // Paranoia to ensure our locked and lock-free paths interact 5359 // correctly with each other. 5360 OrderAccess::fence(); 5361 return ret; 5362} 5363 5364void os::PlatformEvent::unpark() { 5365 // Transitions for _Event: 5366 // 0 => 1 : just return 5367 // 1 => 1 : just return 5368 // -1 => either 0 or 1; must signal target thread 5369 // That is, we can safely transition _Event from -1 to either 5370 // 0 or 1. 5371 // See also: "Semaphores in Plan 9" by Mullender & Cox 5372 // 5373 // Note: Forcing a transition from "-1" to "1" on an unpark() means 5374 // that it will take two back-to-back park() calls for the owning 5375 // thread to block. This has the benefit of forcing a spurious return 5376 // from the first park() call after an unpark() call which will help 5377 // shake out uses of park() and unpark() without condition variables. 5378 5379 if (Atomic::xchg(1, &_Event) >= 0) return; 5380 5381 // If the thread associated with the event was parked, wake it. 5382 // Wait for the thread assoc with the PlatformEvent to vacate. 5383 int status = os::Solaris::mutex_lock(_mutex); 5384 assert_status(status == 0, status, "mutex_lock"); 5385 int AnyWaiters = _nParked; 5386 status = os::Solaris::mutex_unlock(_mutex); 5387 assert_status(status == 0, status, "mutex_unlock"); 5388 guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant"); 5389 if (AnyWaiters != 0) { 5390 // Note that we signal() *after* dropping the lock for "immortal" Events. 5391 // This is safe and avoids a common class of futile wakeups. In rare 5392 // circumstances this can cause a thread to return prematurely from 5393 // cond_{timed}wait() but the spurious wakeup is benign and the victim 5394 // will simply re-test the condition and re-park itself. 5395 // This provides particular benefit if the underlying platform does not 5396 // provide wait morphing. 5397 status = os::Solaris::cond_signal(_cond); 5398 assert_status(status == 0, status, "cond_signal"); 5399 } 5400} 5401 5402// JSR166 5403// ------------------------------------------------------- 5404 5405// The solaris and linux implementations of park/unpark are fairly 5406// conservative for now, but can be improved. They currently use a 5407// mutex/condvar pair, plus _counter. 5408// Park decrements _counter if > 0, else does a condvar wait. Unpark 5409// sets count to 1 and signals condvar. Only one thread ever waits 5410// on the condvar. Contention seen when trying to park implies that someone 5411// is unparking you, so don't wait. And spurious returns are fine, so there 5412// is no need to track notifications. 5413 5414#define MAX_SECS 100000000 5415 5416// This code is common to linux and solaris and will be moved to a 5417// common place in dolphin. 5418// 5419// The passed in time value is either a relative time in nanoseconds 5420// or an absolute time in milliseconds. Either way it has to be unpacked 5421// into suitable seconds and nanoseconds components and stored in the 5422// given timespec structure. 5423// Given time is a 64-bit value and the time_t used in the timespec is only 5424// a signed-32-bit value (except on 64-bit Linux) we have to watch for 5425// overflow if times way in the future are given. Further on Solaris versions 5426// prior to 10 there is a restriction (see cond_timedwait) that the specified 5427// number of seconds, in abstime, is less than current_time + 100,000,000. 5428// As it will be 28 years before "now + 100000000" will overflow we can 5429// ignore overflow and just impose a hard-limit on seconds using the value 5430// of "now + 100,000,000". This places a limit on the timeout of about 3.17 5431// years from "now". 5432// 5433static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { 5434 assert(time > 0, "convertTime"); 5435 5436 struct timeval now; 5437 int status = gettimeofday(&now, NULL); 5438 assert(status == 0, "gettimeofday"); 5439 5440 time_t max_secs = now.tv_sec + MAX_SECS; 5441 5442 if (isAbsolute) { 5443 jlong secs = time / 1000; 5444 if (secs > max_secs) { 5445 absTime->tv_sec = max_secs; 5446 } else { 5447 absTime->tv_sec = secs; 5448 } 5449 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; 5450 } else { 5451 jlong secs = time / NANOSECS_PER_SEC; 5452 if (secs >= MAX_SECS) { 5453 absTime->tv_sec = max_secs; 5454 absTime->tv_nsec = 0; 5455 } else { 5456 absTime->tv_sec = now.tv_sec + secs; 5457 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; 5458 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { 5459 absTime->tv_nsec -= NANOSECS_PER_SEC; 5460 ++absTime->tv_sec; // note: this must be <= max_secs 5461 } 5462 } 5463 } 5464 assert(absTime->tv_sec >= 0, "tv_sec < 0"); 5465 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); 5466 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); 5467 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); 5468} 5469 5470void Parker::park(bool isAbsolute, jlong time) { 5471 // Ideally we'd do something useful while spinning, such 5472 // as calling unpackTime(). 5473 5474 // Optional fast-path check: 5475 // Return immediately if a permit is available. 5476 // We depend on Atomic::xchg() having full barrier semantics 5477 // since we are doing a lock-free update to _counter. 5478 if (Atomic::xchg(0, &_counter) > 0) return; 5479 5480 // Optional fast-exit: Check interrupt before trying to wait 5481 Thread* thread = Thread::current(); 5482 assert(thread->is_Java_thread(), "Must be JavaThread"); 5483 JavaThread *jt = (JavaThread *)thread; 5484 if (Thread::is_interrupted(thread, false)) { 5485 return; 5486 } 5487 5488 // First, demultiplex/decode time arguments 5489 timespec absTime; 5490 if (time < 0 || (isAbsolute && time == 0)) { // don't wait at all 5491 return; 5492 } 5493 if (time > 0) { 5494 // Warning: this code might be exposed to the old Solaris time 5495 // round-down bugs. Grep "roundingFix" for details. 5496 unpackTime(&absTime, isAbsolute, time); 5497 } 5498 5499 // Enter safepoint region 5500 // Beware of deadlocks such as 6317397. 5501 // The per-thread Parker:: _mutex is a classic leaf-lock. 5502 // In particular a thread must never block on the Threads_lock while 5503 // holding the Parker:: mutex. If safepoints are pending both the 5504 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. 5505 ThreadBlockInVM tbivm(jt); 5506 5507 // Don't wait if cannot get lock since interference arises from 5508 // unblocking. Also. check interrupt before trying wait 5509 if (Thread::is_interrupted(thread, false) || 5510 os::Solaris::mutex_trylock(_mutex) != 0) { 5511 return; 5512 } 5513 5514 int status; 5515 5516 if (_counter > 0) { // no wait needed 5517 _counter = 0; 5518 status = os::Solaris::mutex_unlock(_mutex); 5519 assert(status == 0, "invariant"); 5520 // Paranoia to ensure our locked and lock-free paths interact 5521 // correctly with each other and Java-level accesses. 5522 OrderAccess::fence(); 5523 return; 5524 } 5525 5526#ifdef ASSERT 5527 // Don't catch signals while blocked; let the running threads have the signals. 5528 // (This allows a debugger to break into the running thread.) 5529 sigset_t oldsigs; 5530 sigset_t* allowdebug_blocked = os::Solaris::allowdebug_blocked_signals(); 5531 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); 5532#endif 5533 5534 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); 5535 jt->set_suspend_equivalent(); 5536 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() 5537 5538 // Do this the hard way by blocking ... 5539 // See http://monaco.sfbay/detail.jsf?cr=5094058. 5540 // TODO-FIXME: for Solaris SPARC set fprs.FEF=0 prior to parking. 5541 // Only for SPARC >= V8PlusA 5542#if defined(__sparc) && defined(COMPILER2) 5543 if (ClearFPUAtPark) { _mark_fpu_nosave(); } 5544#endif 5545 5546 if (time == 0) { 5547 status = os::Solaris::cond_wait(_cond, _mutex); 5548 } else { 5549 status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime); 5550 } 5551 // Note that an untimed cond_wait() can sometimes return ETIME on older 5552 // versions of the Solaris. 5553 assert_status(status == 0 || status == EINTR || 5554 status == ETIME || status == ETIMEDOUT, 5555 status, "cond_timedwait"); 5556 5557#ifdef ASSERT 5558 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); 5559#endif 5560 _counter = 0; 5561 status = os::Solaris::mutex_unlock(_mutex); 5562 assert_status(status == 0, status, "mutex_unlock"); 5563 // Paranoia to ensure our locked and lock-free paths interact 5564 // correctly with each other and Java-level accesses. 5565 OrderAccess::fence(); 5566 5567 // If externally suspended while waiting, re-suspend 5568 if (jt->handle_special_suspend_equivalent_condition()) { 5569 jt->java_suspend_self(); 5570 } 5571} 5572 5573void Parker::unpark() { 5574 int status = os::Solaris::mutex_lock(_mutex); 5575 assert(status == 0, "invariant"); 5576 const int s = _counter; 5577 _counter = 1; 5578 status = os::Solaris::mutex_unlock(_mutex); 5579 assert(status == 0, "invariant"); 5580 5581 if (s < 1) { 5582 status = os::Solaris::cond_signal(_cond); 5583 assert(status == 0, "invariant"); 5584 } 5585} 5586 5587extern char** environ; 5588 5589// Run the specified command in a separate process. Return its exit value, 5590// or -1 on failure (e.g. can't fork a new process). 5591// Unlike system(), this function can be called from signal handler. It 5592// doesn't block SIGINT et al. 5593int os::fork_and_exec(char* cmd) { 5594 char * argv[4]; 5595 argv[0] = (char *)"sh"; 5596 argv[1] = (char *)"-c"; 5597 argv[2] = cmd; 5598 argv[3] = NULL; 5599 5600 // fork is async-safe, fork1 is not so can't use in signal handler 5601 pid_t pid; 5602 Thread* t = Thread::current_or_null_safe(); 5603 if (t != NULL && t->is_inside_signal_handler()) { 5604 pid = fork(); 5605 } else { 5606 pid = fork1(); 5607 } 5608 5609 if (pid < 0) { 5610 // fork failed 5611 warning("fork failed: %s", strerror(errno)); 5612 return -1; 5613 5614 } else if (pid == 0) { 5615 // child process 5616 5617 // try to be consistent with system(), which uses "/usr/bin/sh" on Solaris 5618 execve("/usr/bin/sh", argv, environ); 5619 5620 // execve failed 5621 _exit(-1); 5622 5623 } else { 5624 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't 5625 // care about the actual exit code, for now. 5626 5627 int status; 5628 5629 // Wait for the child process to exit. This returns immediately if 5630 // the child has already exited. */ 5631 while (waitpid(pid, &status, 0) < 0) { 5632 switch (errno) { 5633 case ECHILD: return 0; 5634 case EINTR: break; 5635 default: return -1; 5636 } 5637 } 5638 5639 if (WIFEXITED(status)) { 5640 // The child exited normally; get its exit code. 5641 return WEXITSTATUS(status); 5642 } else if (WIFSIGNALED(status)) { 5643 // The child exited because of a signal 5644 // The best value to return is 0x80 + signal number, 5645 // because that is what all Unix shells do, and because 5646 // it allows callers to distinguish between process exit and 5647 // process death by signal. 5648 return 0x80 + WTERMSIG(status); 5649 } else { 5650 // Unknown exit code; pass it through 5651 return status; 5652 } 5653 } 5654} 5655 5656// is_headless_jre() 5657// 5658// Test for the existence of xawt/libmawt.so or libawt_xawt.so 5659// in order to report if we are running in a headless jre 5660// 5661// Since JDK8 xawt/libmawt.so was moved into the same directory 5662// as libawt.so, and renamed libawt_xawt.so 5663// 5664bool os::is_headless_jre() { 5665 struct stat statbuf; 5666 char buf[MAXPATHLEN]; 5667 char libmawtpath[MAXPATHLEN]; 5668 const char *xawtstr = "/xawt/libmawt.so"; 5669 const char *new_xawtstr = "/libawt_xawt.so"; 5670 char *p; 5671 5672 // Get path to libjvm.so 5673 os::jvm_path(buf, sizeof(buf)); 5674 5675 // Get rid of libjvm.so 5676 p = strrchr(buf, '/'); 5677 if (p == NULL) { 5678 return false; 5679 } else { 5680 *p = '\0'; 5681 } 5682 5683 // Get rid of client or server 5684 p = strrchr(buf, '/'); 5685 if (p == NULL) { 5686 return false; 5687 } else { 5688 *p = '\0'; 5689 } 5690 5691 // check xawt/libmawt.so 5692 strcpy(libmawtpath, buf); 5693 strcat(libmawtpath, xawtstr); 5694 if (::stat(libmawtpath, &statbuf) == 0) return false; 5695 5696 // check libawt_xawt.so 5697 strcpy(libmawtpath, buf); 5698 strcat(libmawtpath, new_xawtstr); 5699 if (::stat(libmawtpath, &statbuf) == 0) return false; 5700 5701 return true; 5702} 5703 5704size_t os::write(int fd, const void *buf, unsigned int nBytes) { 5705 size_t res; 5706 RESTARTABLE((size_t) ::write(fd, buf, (size_t) nBytes), res); 5707 return res; 5708} 5709 5710int os::close(int fd) { 5711 return ::close(fd); 5712} 5713 5714int os::socket_close(int fd) { 5715 return ::close(fd); 5716} 5717 5718int os::recv(int fd, char* buf, size_t nBytes, uint flags) { 5719 assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native, 5720 "Assumed _thread_in_native"); 5721 RESTARTABLE_RETURN_INT((int)::recv(fd, buf, nBytes, flags)); 5722} 5723 5724int os::send(int fd, char* buf, size_t nBytes, uint flags) { 5725 assert(((JavaThread*)Thread::current())->thread_state() == _thread_in_native, 5726 "Assumed _thread_in_native"); 5727 RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags)); 5728} 5729 5730int os::raw_send(int fd, char* buf, size_t nBytes, uint flags) { 5731 RESTARTABLE_RETURN_INT((int)::send(fd, buf, nBytes, flags)); 5732} 5733 5734// As both poll and select can be interrupted by signals, we have to be 5735// prepared to restart the system call after updating the timeout, unless 5736// a poll() is done with timeout == -1, in which case we repeat with this 5737// "wait forever" value. 5738 5739int os::connect(int fd, struct sockaddr *him, socklen_t len) { 5740 int _result; 5741 _result = ::connect(fd, him, len); 5742 5743 // On Solaris, when a connect() call is interrupted, the connection 5744 // can be established asynchronously (see 6343810). Subsequent calls 5745 // to connect() must check the errno value which has the semantic 5746 // described below (copied from the connect() man page). Handling 5747 // of asynchronously established connections is required for both 5748 // blocking and non-blocking sockets. 5749 // EINTR The connection attempt was interrupted 5750 // before any data arrived by the delivery of 5751 // a signal. The connection, however, will be 5752 // established asynchronously. 5753 // 5754 // EINPROGRESS The socket is non-blocking, and the connec- 5755 // tion cannot be completed immediately. 5756 // 5757 // EALREADY The socket is non-blocking, and a previous 5758 // connection attempt has not yet been com- 5759 // pleted. 5760 // 5761 // EISCONN The socket is already connected. 5762 if (_result == OS_ERR && errno == EINTR) { 5763 // restarting a connect() changes its errno semantics 5764 RESTARTABLE(::connect(fd, him, len), _result); 5765 // undo these changes 5766 if (_result == OS_ERR) { 5767 if (errno == EALREADY) { 5768 errno = EINPROGRESS; // fall through 5769 } else if (errno == EISCONN) { 5770 errno = 0; 5771 return OS_OK; 5772 } 5773 } 5774 } 5775 return _result; 5776} 5777 5778// Get the default path to the core file 5779// Returns the length of the string 5780int os::get_core_path(char* buffer, size_t bufferSize) { 5781 const char* p = get_current_directory(buffer, bufferSize); 5782 5783 if (p == NULL) { 5784 assert(p != NULL, "failed to get current directory"); 5785 return 0; 5786 } 5787 5788 jio_snprintf(buffer, bufferSize, "%s/core or core.%d", 5789 p, current_process_id()); 5790 5791 return strlen(buffer); 5792} 5793 5794#ifndef PRODUCT 5795void TestReserveMemorySpecial_test() { 5796 // No tests available for this platform 5797} 5798#endif 5799 5800bool os::start_debugging(char *buf, int buflen) { 5801 int len = (int)strlen(buf); 5802 char *p = &buf[len]; 5803 5804 jio_snprintf(p, buflen-len, 5805 "\n\n" 5806 "Do you want to debug the problem?\n\n" 5807 "To debug, run 'dbx - %d'; then switch to thread " INTX_FORMAT "\n" 5808 "Enter 'yes' to launch dbx automatically (PATH must include dbx)\n" 5809 "Otherwise, press RETURN to abort...", 5810 os::current_process_id(), os::current_thread_id()); 5811 5812 bool yes = os::message_box("Unexpected Error", buf); 5813 5814 if (yes) { 5815 // yes, user asked VM to launch debugger 5816 jio_snprintf(buf, sizeof(buf), "dbx - %d", os::current_process_id()); 5817 5818 os::fork_and_exec(buf); 5819 yes = false; 5820 } 5821 return yes; 5822} 5823