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