Mercurial > hg > graal-compiler
annotate src/os/linux/vm/os_linux.cpp @ 1150:f62a22282a47
6914622: Print values of all flags for product VM
Summary: Change the flag -XX:+PrintFlagsFinal to product and add new product flag -XX:+PrintFlagsInitial.
Reviewed-by: phh, ysr
Contributed-by: gbenson@redhat.com
author | kvn |
---|---|
date | Thu, 07 Jan 2010 16:24:17 -0800 |
parents | 167c2986d91b |
children | 3b3d12e645e7 |
rev | line source |
---|---|
0 | 1 /* |
579 | 2 * Copyright 1999-2009 Sun Microsystems, Inc. All Rights Reserved. |
0 | 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, | |
20 * CA 95054 USA or visit www.sun.com if you need additional information or | |
21 * have any questions. | |
22 * | |
23 */ | |
24 | |
25 // do not include precompiled header file | |
26 # include "incls/_os_linux.cpp.incl" | |
27 | |
28 // put OS-includes here | |
29 # include <sys/types.h> | |
30 # include <sys/mman.h> | |
31 # include <pthread.h> | |
32 # include <signal.h> | |
33 # include <errno.h> | |
34 # include <dlfcn.h> | |
35 # include <stdio.h> | |
36 # include <unistd.h> | |
37 # include <sys/resource.h> | |
38 # include <pthread.h> | |
39 # include <sys/stat.h> | |
40 # include <sys/time.h> | |
41 # include <sys/times.h> | |
42 # include <sys/utsname.h> | |
43 # include <sys/socket.h> | |
44 # include <sys/wait.h> | |
45 # include <pwd.h> | |
46 # include <poll.h> | |
47 # include <semaphore.h> | |
48 # include <fcntl.h> | |
49 # include <string.h> | |
50 # include <syscall.h> | |
51 # include <sys/sysinfo.h> | |
52 # include <gnu/libc-version.h> | |
53 # include <sys/ipc.h> | |
54 # include <sys/shm.h> | |
55 # include <link.h> | |
56 | |
57 #define MAX_PATH (2 * K) | |
58 | |
59 // for timer info max values which include all bits | |
60 #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) | |
61 #define SEC_IN_NANOSECS 1000000000LL | |
62 | |
63 //////////////////////////////////////////////////////////////////////////////// | |
64 // global variables | |
65 julong os::Linux::_physical_memory = 0; | |
66 | |
67 address os::Linux::_initial_thread_stack_bottom = NULL; | |
68 uintptr_t os::Linux::_initial_thread_stack_size = 0; | |
69 | |
70 int (*os::Linux::_clock_gettime)(clockid_t, struct timespec *) = NULL; | |
71 int (*os::Linux::_pthread_getcpuclockid)(pthread_t, clockid_t *) = NULL; | |
72 Mutex* os::Linux::_createThread_lock = NULL; | |
73 pthread_t os::Linux::_main_thread; | |
74 int os::Linux::_page_size = -1; | |
75 bool os::Linux::_is_floating_stack = false; | |
76 bool os::Linux::_is_NPTL = false; | |
77 bool os::Linux::_supports_fast_thread_cpu_time = false; | |
199
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
78 const char * os::Linux::_glibc_version = NULL; |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
79 const char * os::Linux::_libpthread_version = NULL; |
0 | 80 |
81 static jlong initial_time_count=0; | |
82 | |
83 static int clock_tics_per_sec = 100; | |
84 | |
85 // For diagnostics to print a message once. see run_periodic_checks | |
86 static sigset_t check_signal_done; | |
87 static bool check_signals = true;; | |
88 | |
89 static pid_t _initial_pid = 0; | |
90 | |
91 /* Signal number used to suspend/resume a thread */ | |
92 | |
93 /* do not use any signal number less than SIGSEGV, see 4355769 */ | |
94 static int SR_signum = SIGUSR2; | |
95 sigset_t SR_sigset; | |
96 | |
242 | 97 /* Used to protect dlsym() calls */ |
98 static pthread_mutex_t dl_mutex; | |
99 | |
0 | 100 //////////////////////////////////////////////////////////////////////////////// |
101 // utility functions | |
102 | |
103 static int SR_initialize(); | |
104 static int SR_finalize(); | |
105 | |
106 julong os::available_memory() { | |
107 return Linux::available_memory(); | |
108 } | |
109 | |
110 julong os::Linux::available_memory() { | |
111 // values in struct sysinfo are "unsigned long" | |
112 struct sysinfo si; | |
113 sysinfo(&si); | |
114 | |
115 return (julong)si.freeram * si.mem_unit; | |
116 } | |
117 | |
118 julong os::physical_memory() { | |
119 return Linux::physical_memory(); | |
120 } | |
121 | |
20
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
122 julong os::allocatable_physical_memory(julong size) { |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
123 #ifdef _LP64 |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
124 return size; |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
125 #else |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
126 julong result = MIN2(size, (julong)3800*M); |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
127 if (!is_allocatable(result)) { |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
128 // See comments under solaris for alignment considerations |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
129 julong reasonable_size = (julong)2*G - 2 * os::vm_page_size(); |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
130 result = MIN2(size, reasonable_size); |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
131 } |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
132 return result; |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
133 #endif // _LP64 |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
134 } |
e195fe4c40c7
6629887: 64-bit windows should not restrict default heap size to 1400m
phh
parents:
0
diff
changeset
|
135 |
0 | 136 //////////////////////////////////////////////////////////////////////////////// |
137 // environment support | |
138 | |
139 bool os::getenv(const char* name, char* buf, int len) { | |
140 const char* val = ::getenv(name); | |
141 if (val != NULL && strlen(val) < (size_t)len) { | |
142 strcpy(buf, val); | |
143 return true; | |
144 } | |
145 if (len > 0) buf[0] = 0; // return a null string | |
146 return false; | |
147 } | |
148 | |
149 | |
150 // Return true if user is running as root. | |
151 | |
152 bool os::have_special_privileges() { | |
153 static bool init = false; | |
154 static bool privileges = false; | |
155 if (!init) { | |
156 privileges = (getuid() != geteuid()) || (getgid() != getegid()); | |
157 init = true; | |
158 } | |
159 return privileges; | |
160 } | |
161 | |
162 | |
163 #ifndef SYS_gettid | |
164 // i386: 224, ia64: 1105, amd64: 186, sparc 143 | |
165 #ifdef __ia64__ | |
166 #define SYS_gettid 1105 | |
167 #elif __i386__ | |
168 #define SYS_gettid 224 | |
169 #elif __amd64__ | |
170 #define SYS_gettid 186 | |
171 #elif __sparc__ | |
172 #define SYS_gettid 143 | |
173 #else | |
174 #error define gettid for the arch | |
175 #endif | |
176 #endif | |
177 | |
178 // Cpu architecture string | |
1010 | 179 #if defined(ZERO) |
180 static char cpu_arch[] = ZERO_LIBARCH; | |
181 #elif defined(IA64) | |
0 | 182 static char cpu_arch[] = "ia64"; |
183 #elif defined(IA32) | |
184 static char cpu_arch[] = "i386"; | |
185 #elif defined(AMD64) | |
186 static char cpu_arch[] = "amd64"; | |
187 #elif defined(SPARC) | |
188 # ifdef _LP64 | |
189 static char cpu_arch[] = "sparcv9"; | |
190 # else | |
191 static char cpu_arch[] = "sparc"; | |
192 # endif | |
193 #else | |
194 #error Add appropriate cpu_arch setting | |
195 #endif | |
196 | |
197 | |
198 // pid_t gettid() | |
199 // | |
200 // Returns the kernel thread id of the currently running thread. Kernel | |
201 // thread id is used to access /proc. | |
202 // | |
203 // (Note that getpid() on LinuxThreads returns kernel thread id too; but | |
204 // on NPTL, it returns the same pid for all threads, as required by POSIX.) | |
205 // | |
206 pid_t os::Linux::gettid() { | |
207 int rslt = syscall(SYS_gettid); | |
208 if (rslt == -1) { | |
209 // old kernel, no NPTL support | |
210 return getpid(); | |
211 } else { | |
212 return (pid_t)rslt; | |
213 } | |
214 } | |
215 | |
216 // Most versions of linux have a bug where the number of processors are | |
217 // determined by looking at the /proc file system. In a chroot environment, | |
218 // the system call returns 1. This causes the VM to act as if it is | |
219 // a single processor and elide locking (see is_MP() call). | |
220 static bool unsafe_chroot_detected = false; | |
199
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
221 static const char *unstable_chroot_error = "/proc file system not found.\n" |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
222 "Java may be unstable running multithreaded in a chroot " |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
223 "environment on Linux when /proc filesystem is not mounted."; |
0 | 224 |
225 void os::Linux::initialize_system_info() { | |
1123
167c2986d91b
6843629: Make current hotspot build part of jdk5 control build
phh
parents:
1117
diff
changeset
|
226 set_processor_count(sysconf(_SC_NPROCESSORS_CONF)); |
167c2986d91b
6843629: Make current hotspot build part of jdk5 control build
phh
parents:
1117
diff
changeset
|
227 if (processor_count() == 1) { |
0 | 228 pid_t pid = os::Linux::gettid(); |
229 char fname[32]; | |
230 jio_snprintf(fname, sizeof(fname), "/proc/%d", pid); | |
231 FILE *fp = fopen(fname, "r"); | |
232 if (fp == NULL) { | |
233 unsafe_chroot_detected = true; | |
234 } else { | |
235 fclose(fp); | |
236 } | |
237 } | |
238 _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE); | |
1123
167c2986d91b
6843629: Make current hotspot build part of jdk5 control build
phh
parents:
1117
diff
changeset
|
239 assert(processor_count() > 0, "linux error"); |
0 | 240 } |
241 | |
242 void os::init_system_properties_values() { | |
243 // char arch[12]; | |
244 // sysinfo(SI_ARCHITECTURE, arch, sizeof(arch)); | |
245 | |
246 // The next steps are taken in the product version: | |
247 // | |
248 // Obtain the JAVA_HOME value from the location of libjvm[_g].so. | |
249 // This library should be located at: | |
250 // <JAVA_HOME>/jre/lib/<arch>/{client|server}/libjvm[_g].so. | |
251 // | |
252 // If "/jre/lib/" appears at the right place in the path, then we | |
253 // assume libjvm[_g].so is installed in a JDK and we use this path. | |
254 // | |
255 // Otherwise exit with message: "Could not create the Java virtual machine." | |
256 // | |
257 // The following extra steps are taken in the debugging version: | |
258 // | |
259 // If "/jre/lib/" does NOT appear at the right place in the path | |
260 // instead of exit check for $JAVA_HOME environment variable. | |
261 // | |
262 // If it is defined and we are able to locate $JAVA_HOME/jre/lib/<arch>, | |
263 // then we append a fake suffix "hotspot/libjvm[_g].so" to this path so | |
264 // it looks like libjvm[_g].so is installed there | |
265 // <JAVA_HOME>/jre/lib/<arch>/hotspot/libjvm[_g].so. | |
266 // | |
267 // Otherwise exit. | |
268 // | |
269 // Important note: if the location of libjvm.so changes this | |
270 // code needs to be changed accordingly. | |
271 | |
272 // The next few definitions allow the code to be verbatim: | |
273 #define malloc(n) (char*)NEW_C_HEAP_ARRAY(char, (n)) | |
274 #define getenv(n) ::getenv(n) | |
275 | |
276 /* | |
277 * See ld(1): | |
278 * The linker uses the following search paths to locate required | |
279 * shared libraries: | |
280 * 1: ... | |
281 * ... | |
282 * 7: The default directories, normally /lib and /usr/lib. | |
283 */ | |
509
9656bebe85a7
6778662: fixes 64-bits libraries directory search paths on linux
kvn
parents:
477
diff
changeset
|
284 #if defined(AMD64) || defined(_LP64) && (defined(SPARC) || defined(PPC) || defined(S390)) |
9656bebe85a7
6778662: fixes 64-bits libraries directory search paths on linux
kvn
parents:
477
diff
changeset
|
285 #define DEFAULT_LIBPATH "/usr/lib64:/lib64:/lib:/usr/lib" |
9656bebe85a7
6778662: fixes 64-bits libraries directory search paths on linux
kvn
parents:
477
diff
changeset
|
286 #else |
0 | 287 #define DEFAULT_LIBPATH "/lib:/usr/lib" |
509
9656bebe85a7
6778662: fixes 64-bits libraries directory search paths on linux
kvn
parents:
477
diff
changeset
|
288 #endif |
0 | 289 |
290 #define EXTENSIONS_DIR "/lib/ext" | |
291 #define ENDORSED_DIR "/lib/endorsed" | |
292 #define REG_DIR "/usr/java/packages" | |
293 | |
294 { | |
295 /* sysclasspath, java_home, dll_dir */ | |
296 { | |
297 char *home_path; | |
298 char *dll_path; | |
299 char *pslash; | |
300 char buf[MAXPATHLEN]; | |
301 os::jvm_path(buf, sizeof(buf)); | |
302 | |
303 // Found the full path to libjvm.so. | |
304 // Now cut the path to <java_home>/jre if we can. | |
305 *(strrchr(buf, '/')) = '\0'; /* get rid of /libjvm.so */ | |
306 pslash = strrchr(buf, '/'); | |
307 if (pslash != NULL) | |
308 *pslash = '\0'; /* get rid of /{client|server|hotspot} */ | |
309 dll_path = malloc(strlen(buf) + 1); | |
310 if (dll_path == NULL) | |
311 return; | |
312 strcpy(dll_path, buf); | |
313 Arguments::set_dll_dir(dll_path); | |
314 | |
315 if (pslash != NULL) { | |
316 pslash = strrchr(buf, '/'); | |
317 if (pslash != NULL) { | |
318 *pslash = '\0'; /* get rid of /<arch> */ | |
319 pslash = strrchr(buf, '/'); | |
320 if (pslash != NULL) | |
321 *pslash = '\0'; /* get rid of /lib */ | |
322 } | |
323 } | |
324 | |
325 home_path = malloc(strlen(buf) + 1); | |
326 if (home_path == NULL) | |
327 return; | |
328 strcpy(home_path, buf); | |
329 Arguments::set_java_home(home_path); | |
330 | |
331 if (!set_boot_path('/', ':')) | |
332 return; | |
333 } | |
334 | |
335 /* | |
336 * Where to look for native libraries | |
337 * | |
338 * Note: Due to a legacy implementation, most of the library path | |
339 * is set in the launcher. This was to accomodate linking restrictions | |
340 * on legacy Linux implementations (which are no longer supported). | |
341 * Eventually, all the library path setting will be done here. | |
342 * | |
343 * However, to prevent the proliferation of improperly built native | |
344 * libraries, the new path component /usr/java/packages is added here. | |
345 * Eventually, all the library path setting will be done here. | |
346 */ | |
347 { | |
348 char *ld_library_path; | |
349 | |
350 /* | |
351 * Construct the invariant part of ld_library_path. Note that the | |
352 * space for the colon and the trailing null are provided by the | |
353 * nulls included by the sizeof operator (so actually we allocate | |
354 * a byte more than necessary). | |
355 */ | |
356 ld_library_path = (char *) malloc(sizeof(REG_DIR) + sizeof("/lib/") + | |
357 strlen(cpu_arch) + sizeof(DEFAULT_LIBPATH)); | |
358 sprintf(ld_library_path, REG_DIR "/lib/%s:" DEFAULT_LIBPATH, cpu_arch); | |
359 | |
360 /* | |
361 * Get the user setting of LD_LIBRARY_PATH, and prepended it. It | |
362 * should always exist (until the legacy problem cited above is | |
363 * addressed). | |
364 */ | |
365 char *v = getenv("LD_LIBRARY_PATH"); | |
366 if (v != NULL) { | |
367 char *t = ld_library_path; | |
368 /* That's +1 for the colon and +1 for the trailing '\0' */ | |
369 ld_library_path = (char *) malloc(strlen(v) + 1 + strlen(t) + 1); | |
370 sprintf(ld_library_path, "%s:%s", v, t); | |
371 } | |
372 Arguments::set_library_path(ld_library_path); | |
373 } | |
374 | |
375 /* | |
376 * Extensions directories. | |
377 * | |
378 * Note that the space for the colon and the trailing null are provided | |
379 * by the nulls included by the sizeof operator (so actually one byte more | |
380 * than necessary is allocated). | |
381 */ | |
382 { | |
383 char *buf = malloc(strlen(Arguments::get_java_home()) + | |
384 sizeof(EXTENSIONS_DIR) + sizeof(REG_DIR) + sizeof(EXTENSIONS_DIR)); | |
385 sprintf(buf, "%s" EXTENSIONS_DIR ":" REG_DIR EXTENSIONS_DIR, | |
386 Arguments::get_java_home()); | |
387 Arguments::set_ext_dirs(buf); | |
388 } | |
389 | |
390 /* Endorsed standards default directory. */ | |
391 { | |
392 char * buf; | |
393 buf = malloc(strlen(Arguments::get_java_home()) + sizeof(ENDORSED_DIR)); | |
394 sprintf(buf, "%s" ENDORSED_DIR, Arguments::get_java_home()); | |
395 Arguments::set_endorsed_dirs(buf); | |
396 } | |
397 } | |
398 | |
399 #undef malloc | |
400 #undef getenv | |
401 #undef EXTENSIONS_DIR | |
402 #undef ENDORSED_DIR | |
403 | |
404 // Done | |
405 return; | |
406 } | |
407 | |
408 //////////////////////////////////////////////////////////////////////////////// | |
409 // breakpoint support | |
410 | |
411 void os::breakpoint() { | |
412 BREAKPOINT; | |
413 } | |
414 | |
415 extern "C" void breakpoint() { | |
416 // use debugger to set breakpoint here | |
417 } | |
418 | |
419 //////////////////////////////////////////////////////////////////////////////// | |
420 // signal support | |
421 | |
422 debug_only(static bool signal_sets_initialized = false); | |
423 static sigset_t unblocked_sigs, vm_sigs, allowdebug_blocked_sigs; | |
424 | |
425 bool os::Linux::is_sig_ignored(int sig) { | |
426 struct sigaction oact; | |
427 sigaction(sig, (struct sigaction*)NULL, &oact); | |
428 void* ohlr = oact.sa_sigaction ? CAST_FROM_FN_PTR(void*, oact.sa_sigaction) | |
429 : CAST_FROM_FN_PTR(void*, oact.sa_handler); | |
430 if (ohlr == CAST_FROM_FN_PTR(void*, SIG_IGN)) | |
431 return true; | |
432 else | |
433 return false; | |
434 } | |
435 | |
436 void os::Linux::signal_sets_init() { | |
437 // Should also have an assertion stating we are still single-threaded. | |
438 assert(!signal_sets_initialized, "Already initialized"); | |
439 // Fill in signals that are necessarily unblocked for all threads in | |
440 // the VM. Currently, we unblock the following signals: | |
441 // SHUTDOWN{1,2,3}_SIGNAL: for shutdown hooks support (unless over-ridden | |
442 // by -Xrs (=ReduceSignalUsage)); | |
443 // BREAK_SIGNAL which is unblocked only by the VM thread and blocked by all | |
444 // other threads. The "ReduceSignalUsage" boolean tells us not to alter | |
445 // the dispositions or masks wrt these signals. | |
446 // Programs embedding the VM that want to use the above signals for their | |
447 // own purposes must, at this time, use the "-Xrs" option to prevent | |
448 // interference with shutdown hooks and BREAK_SIGNAL thread dumping. | |
449 // (See bug 4345157, and other related bugs). | |
450 // In reality, though, unblocking these signals is really a nop, since | |
451 // these signals are not blocked by default. | |
452 sigemptyset(&unblocked_sigs); | |
453 sigemptyset(&allowdebug_blocked_sigs); | |
454 sigaddset(&unblocked_sigs, SIGILL); | |
455 sigaddset(&unblocked_sigs, SIGSEGV); | |
456 sigaddset(&unblocked_sigs, SIGBUS); | |
457 sigaddset(&unblocked_sigs, SIGFPE); | |
458 sigaddset(&unblocked_sigs, SR_signum); | |
459 | |
460 if (!ReduceSignalUsage) { | |
461 if (!os::Linux::is_sig_ignored(SHUTDOWN1_SIGNAL)) { | |
462 sigaddset(&unblocked_sigs, SHUTDOWN1_SIGNAL); | |
463 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN1_SIGNAL); | |
464 } | |
465 if (!os::Linux::is_sig_ignored(SHUTDOWN2_SIGNAL)) { | |
466 sigaddset(&unblocked_sigs, SHUTDOWN2_SIGNAL); | |
467 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN2_SIGNAL); | |
468 } | |
469 if (!os::Linux::is_sig_ignored(SHUTDOWN3_SIGNAL)) { | |
470 sigaddset(&unblocked_sigs, SHUTDOWN3_SIGNAL); | |
471 sigaddset(&allowdebug_blocked_sigs, SHUTDOWN3_SIGNAL); | |
472 } | |
473 } | |
474 // Fill in signals that are blocked by all but the VM thread. | |
475 sigemptyset(&vm_sigs); | |
476 if (!ReduceSignalUsage) | |
477 sigaddset(&vm_sigs, BREAK_SIGNAL); | |
478 debug_only(signal_sets_initialized = true); | |
479 | |
480 } | |
481 | |
482 // These are signals that are unblocked while a thread is running Java. | |
483 // (For some reason, they get blocked by default.) | |
484 sigset_t* os::Linux::unblocked_signals() { | |
485 assert(signal_sets_initialized, "Not initialized"); | |
486 return &unblocked_sigs; | |
487 } | |
488 | |
489 // These are the signals that are blocked while a (non-VM) thread is | |
490 // running Java. Only the VM thread handles these signals. | |
491 sigset_t* os::Linux::vm_signals() { | |
492 assert(signal_sets_initialized, "Not initialized"); | |
493 return &vm_sigs; | |
494 } | |
495 | |
496 // These are signals that are blocked during cond_wait to allow debugger in | |
497 sigset_t* os::Linux::allowdebug_blocked_signals() { | |
498 assert(signal_sets_initialized, "Not initialized"); | |
499 return &allowdebug_blocked_sigs; | |
500 } | |
501 | |
502 void os::Linux::hotspot_sigmask(Thread* thread) { | |
503 | |
504 //Save caller's signal mask before setting VM signal mask | |
505 sigset_t caller_sigmask; | |
506 pthread_sigmask(SIG_BLOCK, NULL, &caller_sigmask); | |
507 | |
508 OSThread* osthread = thread->osthread(); | |
509 osthread->set_caller_sigmask(caller_sigmask); | |
510 | |
511 pthread_sigmask(SIG_UNBLOCK, os::Linux::unblocked_signals(), NULL); | |
512 | |
513 if (!ReduceSignalUsage) { | |
514 if (thread->is_VM_thread()) { | |
515 // Only the VM thread handles BREAK_SIGNAL ... | |
516 pthread_sigmask(SIG_UNBLOCK, vm_signals(), NULL); | |
517 } else { | |
518 // ... all other threads block BREAK_SIGNAL | |
519 pthread_sigmask(SIG_BLOCK, vm_signals(), NULL); | |
520 } | |
521 } | |
522 } | |
523 | |
524 ////////////////////////////////////////////////////////////////////////////// | |
525 // detecting pthread library | |
526 | |
527 void os::Linux::libpthread_init() { | |
528 // Save glibc and pthread version strings. Note that _CS_GNU_LIBC_VERSION | |
529 // and _CS_GNU_LIBPTHREAD_VERSION are supported in glibc >= 2.3.2. Use a | |
530 // generic name for earlier versions. | |
531 // Define macros here so we can build HotSpot on old systems. | |
532 # ifndef _CS_GNU_LIBC_VERSION | |
533 # define _CS_GNU_LIBC_VERSION 2 | |
534 # endif | |
535 # ifndef _CS_GNU_LIBPTHREAD_VERSION | |
536 # define _CS_GNU_LIBPTHREAD_VERSION 3 | |
537 # endif | |
538 | |
539 size_t n = confstr(_CS_GNU_LIBC_VERSION, NULL, 0); | |
540 if (n > 0) { | |
541 char *str = (char *)malloc(n); | |
542 confstr(_CS_GNU_LIBC_VERSION, str, n); | |
543 os::Linux::set_glibc_version(str); | |
544 } else { | |
545 // _CS_GNU_LIBC_VERSION is not supported, try gnu_get_libc_version() | |
546 static char _gnu_libc_version[32]; | |
547 jio_snprintf(_gnu_libc_version, sizeof(_gnu_libc_version), | |
548 "glibc %s %s", gnu_get_libc_version(), gnu_get_libc_release()); | |
549 os::Linux::set_glibc_version(_gnu_libc_version); | |
550 } | |
551 | |
552 n = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, 0); | |
553 if (n > 0) { | |
554 char *str = (char *)malloc(n); | |
555 confstr(_CS_GNU_LIBPTHREAD_VERSION, str, n); | |
556 // Vanilla RH-9 (glibc 2.3.2) has a bug that confstr() always tells | |
557 // us "NPTL-0.29" even we are running with LinuxThreads. Check if this | |
199
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
558 // is the case. LinuxThreads has a hard limit on max number of threads. |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
559 // So sysconf(_SC_THREAD_THREADS_MAX) will return a positive value. |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
560 // On the other hand, NPTL does not have such a limit, sysconf() |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
561 // will return -1 and errno is not changed. Check if it is really NPTL. |
0 | 562 if (strcmp(os::Linux::glibc_version(), "glibc 2.3.2") == 0 && |
199
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
563 strstr(str, "NPTL") && |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
564 sysconf(_SC_THREAD_THREADS_MAX) > 0) { |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
565 free(str); |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
566 os::Linux::set_libpthread_version("linuxthreads"); |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
567 } else { |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
568 os::Linux::set_libpthread_version(str); |
0 | 569 } |
570 } else { | |
199
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
571 // glibc before 2.3.2 only has LinuxThreads. |
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
572 os::Linux::set_libpthread_version("linuxthreads"); |
0 | 573 } |
574 | |
575 if (strstr(libpthread_version(), "NPTL")) { | |
576 os::Linux::set_is_NPTL(); | |
577 } else { | |
578 os::Linux::set_is_LinuxThreads(); | |
579 } | |
580 | |
581 // LinuxThreads have two flavors: floating-stack mode, which allows variable | |
582 // stack size; and fixed-stack mode. NPTL is always floating-stack. | |
583 if (os::Linux::is_NPTL() || os::Linux::supports_variable_stack_size()) { | |
584 os::Linux::set_is_floating_stack(); | |
585 } | |
586 } | |
587 | |
588 ///////////////////////////////////////////////////////////////////////////// | |
589 // thread stack | |
590 | |
591 // Force Linux kernel to expand current thread stack. If "bottom" is close | |
592 // to the stack guard, caller should block all signals. | |
593 // | |
594 // MAP_GROWSDOWN: | |
595 // A special mmap() flag that is used to implement thread stacks. It tells | |
596 // kernel that the memory region should extend downwards when needed. This | |
597 // allows early versions of LinuxThreads to only mmap the first few pages | |
598 // when creating a new thread. Linux kernel will automatically expand thread | |
599 // stack as needed (on page faults). | |
600 // | |
601 // However, because the memory region of a MAP_GROWSDOWN stack can grow on | |
602 // demand, if a page fault happens outside an already mapped MAP_GROWSDOWN | |
603 // region, it's hard to tell if the fault is due to a legitimate stack | |
604 // access or because of reading/writing non-exist memory (e.g. buffer | |
605 // overrun). As a rule, if the fault happens below current stack pointer, | |
606 // Linux kernel does not expand stack, instead a SIGSEGV is sent to the | |
607 // application (see Linux kernel fault.c). | |
608 // | |
609 // This Linux feature can cause SIGSEGV when VM bangs thread stack for | |
610 // stack overflow detection. | |
611 // | |
612 // Newer version of LinuxThreads (since glibc-2.2, or, RH-7.x) and NPTL do | |
613 // not use this flag. However, the stack of initial thread is not created | |
614 // by pthread, it is still MAP_GROWSDOWN. Also it's possible (though | |
615 // unlikely) that user code can create a thread with MAP_GROWSDOWN stack | |
616 // and then attach the thread to JVM. | |
617 // | |
618 // To get around the problem and allow stack banging on Linux, we need to | |
619 // manually expand thread stack after receiving the SIGSEGV. | |
620 // | |
621 // There are two ways to expand thread stack to address "bottom", we used | |
622 // both of them in JVM before 1.5: | |
623 // 1. adjust stack pointer first so that it is below "bottom", and then | |
624 // touch "bottom" | |
625 // 2. mmap() the page in question | |
626 // | |
627 // Now alternate signal stack is gone, it's harder to use 2. For instance, | |
628 // if current sp is already near the lower end of page 101, and we need to | |
629 // call mmap() to map page 100, it is possible that part of the mmap() frame | |
630 // will be placed in page 100. When page 100 is mapped, it is zero-filled. | |
631 // That will destroy the mmap() frame and cause VM to crash. | |
632 // | |
633 // The following code works by adjusting sp first, then accessing the "bottom" | |
634 // page to force a page fault. Linux kernel will then automatically expand the | |
635 // stack mapping. | |
636 // | |
637 // _expand_stack_to() assumes its frame size is less than page size, which | |
638 // should always be true if the function is not inlined. | |
639 | |
640 #if __GNUC__ < 3 // gcc 2.x does not support noinline attribute | |
641 #define NOINLINE | |
642 #else | |
643 #define NOINLINE __attribute__ ((noinline)) | |
644 #endif | |
645 | |
646 static void _expand_stack_to(address bottom) NOINLINE; | |
647 | |
648 static void _expand_stack_to(address bottom) { | |
649 address sp; | |
650 size_t size; | |
651 volatile char *p; | |
652 | |
653 // Adjust bottom to point to the largest address within the same page, it | |
654 // gives us a one-page buffer if alloca() allocates slightly more memory. | |
655 bottom = (address)align_size_down((uintptr_t)bottom, os::Linux::page_size()); | |
656 bottom += os::Linux::page_size() - 1; | |
657 | |
658 // sp might be slightly above current stack pointer; if that's the case, we | |
659 // will alloca() a little more space than necessary, which is OK. Don't use | |
660 // os::current_stack_pointer(), as its result can be slightly below current | |
661 // stack pointer, causing us to not alloca enough to reach "bottom". | |
662 sp = (address)&sp; | |
663 | |
664 if (sp > bottom) { | |
665 size = sp - bottom; | |
666 p = (volatile char *)alloca(size); | |
667 assert(p != NULL && p <= (volatile char *)bottom, "alloca problem?"); | |
668 p[0] = '\0'; | |
669 } | |
670 } | |
671 | |
672 bool os::Linux::manually_expand_stack(JavaThread * t, address addr) { | |
673 assert(t!=NULL, "just checking"); | |
674 assert(t->osthread()->expanding_stack(), "expand should be set"); | |
675 assert(t->stack_base() != NULL, "stack_base was not initialized"); | |
676 | |
677 if (addr < t->stack_base() && addr >= t->stack_yellow_zone_base()) { | |
678 sigset_t mask_all, old_sigset; | |
679 sigfillset(&mask_all); | |
680 pthread_sigmask(SIG_SETMASK, &mask_all, &old_sigset); | |
681 _expand_stack_to(addr); | |
682 pthread_sigmask(SIG_SETMASK, &old_sigset, NULL); | |
683 return true; | |
684 } | |
685 return false; | |
686 } | |
687 | |
688 ////////////////////////////////////////////////////////////////////////////// | |
689 // create new thread | |
690 | |
691 static address highest_vm_reserved_address(); | |
692 | |
693 // check if it's safe to start a new thread | |
694 static bool _thread_safety_check(Thread* thread) { | |
695 if (os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack()) { | |
696 // Fixed stack LinuxThreads (SuSE Linux/x86, and some versions of Redhat) | |
697 // Heap is mmap'ed at lower end of memory space. Thread stacks are | |
698 // allocated (MAP_FIXED) from high address space. Every thread stack | |
699 // occupies a fixed size slot (usually 2Mbytes, but user can change | |
700 // it to other values if they rebuild LinuxThreads). | |
701 // | |
702 // Problem with MAP_FIXED is that mmap() can still succeed even part of | |
703 // the memory region has already been mmap'ed. That means if we have too | |
704 // many threads and/or very large heap, eventually thread stack will | |
705 // collide with heap. | |
706 // | |
707 // Here we try to prevent heap/stack collision by comparing current | |
708 // stack bottom with the highest address that has been mmap'ed by JVM | |
709 // plus a safety margin for memory maps created by native code. | |
710 // | |
711 // This feature can be disabled by setting ThreadSafetyMargin to 0 | |
712 // | |
713 if (ThreadSafetyMargin > 0) { | |
714 address stack_bottom = os::current_stack_base() - os::current_stack_size(); | |
715 | |
716 // not safe if our stack extends below the safety margin | |
717 return stack_bottom - ThreadSafetyMargin >= highest_vm_reserved_address(); | |
718 } else { | |
719 return true; | |
720 } | |
721 } else { | |
722 // Floating stack LinuxThreads or NPTL: | |
723 // Unlike fixed stack LinuxThreads, thread stacks are not MAP_FIXED. When | |
724 // there's not enough space left, pthread_create() will fail. If we come | |
725 // here, that means enough space has been reserved for stack. | |
726 return true; | |
727 } | |
728 } | |
729 | |
730 // Thread start routine for all newly created threads | |
731 static void *java_start(Thread *thread) { | |
732 // Try to randomize the cache line index of hot stack frames. | |
733 // This helps when threads of the same stack traces evict each other's | |
734 // cache lines. The threads can be either from the same JVM instance, or | |
735 // from different JVM instances. The benefit is especially true for | |
736 // processors with hyperthreading technology. | |
737 static int counter = 0; | |
738 int pid = os::current_process_id(); | |
739 alloca(((pid ^ counter++) & 7) * 128); | |
740 | |
741 ThreadLocalStorage::set_thread(thread); | |
742 | |
743 OSThread* osthread = thread->osthread(); | |
744 Monitor* sync = osthread->startThread_lock(); | |
745 | |
746 // non floating stack LinuxThreads needs extra check, see above | |
747 if (!_thread_safety_check(thread)) { | |
748 // notify parent thread | |
749 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); | |
750 osthread->set_state(ZOMBIE); | |
751 sync->notify_all(); | |
752 return NULL; | |
753 } | |
754 | |
755 // thread_id is kernel thread id (similar to Solaris LWP id) | |
756 osthread->set_thread_id(os::Linux::gettid()); | |
757 | |
758 if (UseNUMA) { | |
759 int lgrp_id = os::numa_get_group_id(); | |
760 if (lgrp_id != -1) { | |
761 thread->set_lgrp_id(lgrp_id); | |
762 } | |
763 } | |
764 // initialize signal mask for this thread | |
765 os::Linux::hotspot_sigmask(thread); | |
766 | |
767 // initialize floating point control register | |
768 os::Linux::init_thread_fpu_state(); | |
769 | |
770 // handshaking with parent thread | |
771 { | |
772 MutexLockerEx ml(sync, Mutex::_no_safepoint_check_flag); | |
773 | |
774 // notify parent thread | |
775 osthread->set_state(INITIALIZED); | |
776 sync->notify_all(); | |
777 | |
778 // wait until os::start_thread() | |
779 while (osthread->get_state() == INITIALIZED) { | |
780 sync->wait(Mutex::_no_safepoint_check_flag); | |
781 } | |
782 } | |
783 | |
784 // call one more level start routine | |
785 thread->run(); | |
786 | |
787 return 0; | |
788 } | |
789 | |
790 bool os::create_thread(Thread* thread, ThreadType thr_type, size_t stack_size) { | |
791 assert(thread->osthread() == NULL, "caller responsible"); | |
792 | |
793 // Allocate the OSThread object | |
794 OSThread* osthread = new OSThread(NULL, NULL); | |
795 if (osthread == NULL) { | |
796 return false; | |
797 } | |
798 | |
799 // set the correct thread state | |
800 osthread->set_thread_type(thr_type); | |
801 | |
802 // Initial state is ALLOCATED but not INITIALIZED | |
803 osthread->set_state(ALLOCATED); | |
804 | |
805 thread->set_osthread(osthread); | |
806 | |
807 // init thread attributes | |
808 pthread_attr_t attr; | |
809 pthread_attr_init(&attr); | |
810 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); | |
811 | |
812 // stack size | |
813 if (os::Linux::supports_variable_stack_size()) { | |
814 // calculate stack size if it's not specified by caller | |
815 if (stack_size == 0) { | |
816 stack_size = os::Linux::default_stack_size(thr_type); | |
817 | |
818 switch (thr_type) { | |
819 case os::java_thread: | |
820 // Java threads use ThreadStackSize which default value can be changed with the flag -Xss | |
821 if (JavaThread::stack_size_at_create() > 0) stack_size = JavaThread::stack_size_at_create(); | |
822 break; | |
823 case os::compiler_thread: | |
824 if (CompilerThreadStackSize > 0) { | |
825 stack_size = (size_t)(CompilerThreadStackSize * K); | |
826 break; | |
827 } // else fall through: | |
828 // use VMThreadStackSize if CompilerThreadStackSize is not defined | |
829 case os::vm_thread: | |
830 case os::pgc_thread: | |
831 case os::cgc_thread: | |
832 case os::watcher_thread: | |
833 if (VMThreadStackSize > 0) stack_size = (size_t)(VMThreadStackSize * K); | |
834 break; | |
835 } | |
836 } | |
837 | |
838 stack_size = MAX2(stack_size, os::Linux::min_stack_allowed); | |
839 pthread_attr_setstacksize(&attr, stack_size); | |
840 } else { | |
841 // let pthread_create() pick the default value. | |
842 } | |
843 | |
844 // glibc guard page | |
845 pthread_attr_setguardsize(&attr, os::Linux::default_guard_size(thr_type)); | |
846 | |
847 ThreadState state; | |
848 | |
849 { | |
850 // Serialize thread creation if we are running with fixed stack LinuxThreads | |
851 bool lock = os::Linux::is_LinuxThreads() && !os::Linux::is_floating_stack(); | |
852 if (lock) { | |
853 os::Linux::createThread_lock()->lock_without_safepoint_check(); | |
854 } | |
855 | |
856 pthread_t tid; | |
857 int ret = pthread_create(&tid, &attr, (void* (*)(void*)) java_start, thread); | |
858 | |
859 pthread_attr_destroy(&attr); | |
860 | |
861 if (ret != 0) { | |
862 if (PrintMiscellaneous && (Verbose || WizardMode)) { | |
863 perror("pthread_create()"); | |
864 } | |
865 // Need to clean up stuff we've allocated so far | |
866 thread->set_osthread(NULL); | |
867 delete osthread; | |
868 if (lock) os::Linux::createThread_lock()->unlock(); | |
869 return false; | |
870 } | |
871 | |
872 // Store pthread info into the OSThread | |
873 osthread->set_pthread_id(tid); | |
874 | |
875 // Wait until child thread is either initialized or aborted | |
876 { | |
877 Monitor* sync_with_child = osthread->startThread_lock(); | |
878 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); | |
879 while ((state = osthread->get_state()) == ALLOCATED) { | |
880 sync_with_child->wait(Mutex::_no_safepoint_check_flag); | |
881 } | |
882 } | |
883 | |
884 if (lock) { | |
885 os::Linux::createThread_lock()->unlock(); | |
886 } | |
887 } | |
888 | |
889 // Aborted due to thread limit being reached | |
890 if (state == ZOMBIE) { | |
891 thread->set_osthread(NULL); | |
892 delete osthread; | |
893 return false; | |
894 } | |
895 | |
896 // The thread is returned suspended (in state INITIALIZED), | |
897 // and is started higher up in the call chain | |
898 assert(state == INITIALIZED, "race condition"); | |
899 return true; | |
900 } | |
901 | |
902 ///////////////////////////////////////////////////////////////////////////// | |
903 // attach existing thread | |
904 | |
905 // bootstrap the main thread | |
906 bool os::create_main_thread(JavaThread* thread) { | |
907 assert(os::Linux::_main_thread == pthread_self(), "should be called inside main thread"); | |
908 return create_attached_thread(thread); | |
909 } | |
910 | |
911 bool os::create_attached_thread(JavaThread* thread) { | |
912 #ifdef ASSERT | |
913 thread->verify_not_published(); | |
914 #endif | |
915 | |
916 // Allocate the OSThread object | |
917 OSThread* osthread = new OSThread(NULL, NULL); | |
918 | |
919 if (osthread == NULL) { | |
920 return false; | |
921 } | |
922 | |
923 // Store pthread info into the OSThread | |
924 osthread->set_thread_id(os::Linux::gettid()); | |
925 osthread->set_pthread_id(::pthread_self()); | |
926 | |
927 // initialize floating point control register | |
928 os::Linux::init_thread_fpu_state(); | |
929 | |
930 // Initial thread state is RUNNABLE | |
931 osthread->set_state(RUNNABLE); | |
932 | |
933 thread->set_osthread(osthread); | |
934 | |
935 if (UseNUMA) { | |
936 int lgrp_id = os::numa_get_group_id(); | |
937 if (lgrp_id != -1) { | |
938 thread->set_lgrp_id(lgrp_id); | |
939 } | |
940 } | |
941 | |
942 if (os::Linux::is_initial_thread()) { | |
943 // If current thread is initial thread, its stack is mapped on demand, | |
944 // see notes about MAP_GROWSDOWN. Here we try to force kernel to map | |
945 // the entire stack region to avoid SEGV in stack banging. | |
946 // It is also useful to get around the heap-stack-gap problem on SuSE | |
947 // kernel (see 4821821 for details). We first expand stack to the top | |
948 // of yellow zone, then enable stack yellow zone (order is significant, | |
949 // enabling yellow zone first will crash JVM on SuSE Linux), so there | |
950 // is no gap between the last two virtual memory regions. | |
951 | |
952 JavaThread *jt = (JavaThread *)thread; | |
953 address addr = jt->stack_yellow_zone_base(); | |
954 assert(addr != NULL, "initialization problem?"); | |
955 assert(jt->stack_available(addr) > 0, "stack guard should not be enabled"); | |
956 | |
957 osthread->set_expanding_stack(); | |
958 os::Linux::manually_expand_stack(jt, addr); | |
959 osthread->clear_expanding_stack(); | |
960 } | |
961 | |
962 // initialize signal mask for this thread | |
963 // and save the caller's signal mask | |
964 os::Linux::hotspot_sigmask(thread); | |
965 | |
966 return true; | |
967 } | |
968 | |
969 void os::pd_start_thread(Thread* thread) { | |
970 OSThread * osthread = thread->osthread(); | |
971 assert(osthread->get_state() != INITIALIZED, "just checking"); | |
972 Monitor* sync_with_child = osthread->startThread_lock(); | |
973 MutexLockerEx ml(sync_with_child, Mutex::_no_safepoint_check_flag); | |
974 sync_with_child->notify(); | |
975 } | |
976 | |
977 // Free Linux resources related to the OSThread | |
978 void os::free_thread(OSThread* osthread) { | |
979 assert(osthread != NULL, "osthread not set"); | |
980 | |
981 if (Thread::current()->osthread() == osthread) { | |
982 // Restore caller's signal mask | |
983 sigset_t sigmask = osthread->caller_sigmask(); | |
984 pthread_sigmask(SIG_SETMASK, &sigmask, NULL); | |
985 } | |
986 | |
987 delete osthread; | |
988 } | |
989 | |
990 ////////////////////////////////////////////////////////////////////////////// | |
991 // thread local storage | |
992 | |
993 int os::allocate_thread_local_storage() { | |
994 pthread_key_t key; | |
995 int rslt = pthread_key_create(&key, NULL); | |
996 assert(rslt == 0, "cannot allocate thread local storage"); | |
997 return (int)key; | |
998 } | |
999 | |
1000 // Note: This is currently not used by VM, as we don't destroy TLS key | |
1001 // on VM exit. | |
1002 void os::free_thread_local_storage(int index) { | |
1003 int rslt = pthread_key_delete((pthread_key_t)index); | |
1004 assert(rslt == 0, "invalid index"); | |
1005 } | |
1006 | |
1007 void os::thread_local_storage_at_put(int index, void* value) { | |
1008 int rslt = pthread_setspecific((pthread_key_t)index, value); | |
1009 assert(rslt == 0, "pthread_setspecific failed"); | |
1010 } | |
1011 | |
1012 extern "C" Thread* get_thread() { | |
1013 return ThreadLocalStorage::thread(); | |
1014 } | |
1015 | |
1016 ////////////////////////////////////////////////////////////////////////////// | |
1017 // initial thread | |
1018 | |
1019 // Check if current thread is the initial thread, similar to Solaris thr_main. | |
1020 bool os::Linux::is_initial_thread(void) { | |
1021 char dummy; | |
1022 // If called before init complete, thread stack bottom will be null. | |
1023 // Can be called if fatal error occurs before initialization. | |
1024 if (initial_thread_stack_bottom() == NULL) return false; | |
1025 assert(initial_thread_stack_bottom() != NULL && | |
1026 initial_thread_stack_size() != 0, | |
1027 "os::init did not locate initial thread's stack region"); | |
1028 if ((address)&dummy >= initial_thread_stack_bottom() && | |
1029 (address)&dummy < initial_thread_stack_bottom() + initial_thread_stack_size()) | |
1030 return true; | |
1031 else return false; | |
1032 } | |
1033 | |
1034 // Find the virtual memory area that contains addr | |
1035 static bool find_vma(address addr, address* vma_low, address* vma_high) { | |
1036 FILE *fp = fopen("/proc/self/maps", "r"); | |
1037 if (fp) { | |
1038 address low, high; | |
1039 while (!feof(fp)) { | |
1040 if (fscanf(fp, "%p-%p", &low, &high) == 2) { | |
1041 if (low <= addr && addr < high) { | |
1042 if (vma_low) *vma_low = low; | |
1043 if (vma_high) *vma_high = high; | |
1044 fclose (fp); | |
1045 return true; | |
1046 } | |
1047 } | |
1048 for (;;) { | |
1049 int ch = fgetc(fp); | |
1050 if (ch == EOF || ch == (int)'\n') break; | |
1051 } | |
1052 } | |
1053 fclose(fp); | |
1054 } | |
1055 return false; | |
1056 } | |
1057 | |
1058 // Locate initial thread stack. This special handling of initial thread stack | |
1059 // is needed because pthread_getattr_np() on most (all?) Linux distros returns | |
1060 // bogus value for initial thread. | |
1061 void os::Linux::capture_initial_stack(size_t max_size) { | |
1062 // stack size is the easy part, get it from RLIMIT_STACK | |
1063 size_t stack_size; | |
1064 struct rlimit rlim; | |
1065 getrlimit(RLIMIT_STACK, &rlim); | |
1066 stack_size = rlim.rlim_cur; | |
1067 | |
1068 // 6308388: a bug in ld.so will relocate its own .data section to the | |
1069 // lower end of primordial stack; reduce ulimit -s value a little bit | |
1070 // so we won't install guard page on ld.so's data section. | |
1071 stack_size -= 2 * page_size(); | |
1072 | |
1073 // 4441425: avoid crash with "unlimited" stack size on SuSE 7.1 or Redhat | |
1074 // 7.1, in both cases we will get 2G in return value. | |
1075 // 4466587: glibc 2.2.x compiled w/o "--enable-kernel=2.4.0" (RH 7.0, | |
1076 // SuSE 7.2, Debian) can not handle alternate signal stack correctly | |
1077 // for initial thread if its stack size exceeds 6M. Cap it at 2M, | |
1078 // in case other parts in glibc still assumes 2M max stack size. | |
1079 // FIXME: alt signal stack is gone, maybe we can relax this constraint? | |
1080 #ifndef IA64 | |
1081 if (stack_size > 2 * K * K) stack_size = 2 * K * K; | |
1082 #else | |
1083 // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small | |
1084 if (stack_size > 4 * K * K) stack_size = 4 * K * K; | |
1085 #endif | |
1086 | |
1087 // Try to figure out where the stack base (top) is. This is harder. | |
1088 // | |
1089 // When an application is started, glibc saves the initial stack pointer in | |
1090 // a global variable "__libc_stack_end", which is then used by system | |
1091 // libraries. __libc_stack_end should be pretty close to stack top. The | |
1092 // variable is available since the very early days. However, because it is | |
1093 // a private interface, it could disappear in the future. | |
1094 // | |
1095 // Linux kernel saves start_stack information in /proc/<pid>/stat. Similar | |
1096 // to __libc_stack_end, it is very close to stack top, but isn't the real | |
1097 // stack top. Note that /proc may not exist if VM is running as a chroot | |
1098 // program, so reading /proc/<pid>/stat could fail. Also the contents of | |
1099 // /proc/<pid>/stat could change in the future (though unlikely). | |
1100 // | |
1101 // We try __libc_stack_end first. If that doesn't work, look for | |
1102 // /proc/<pid>/stat. If neither of them works, we use current stack pointer | |
1103 // as a hint, which should work well in most cases. | |
1104 | |
1105 uintptr_t stack_start; | |
1106 | |
1107 // try __libc_stack_end first | |
1108 uintptr_t *p = (uintptr_t *)dlsym(RTLD_DEFAULT, "__libc_stack_end"); | |
1109 if (p && *p) { | |
1110 stack_start = *p; | |
1111 } else { | |
1112 // see if we can get the start_stack field from /proc/self/stat | |
1113 FILE *fp; | |
1114 int pid; | |
1115 char state; | |
1116 int ppid; | |
1117 int pgrp; | |
1118 int session; | |
1119 int nr; | |
1120 int tpgrp; | |
1121 unsigned long flags; | |
1122 unsigned long minflt; | |
1123 unsigned long cminflt; | |
1124 unsigned long majflt; | |
1125 unsigned long cmajflt; | |
1126 unsigned long utime; | |
1127 unsigned long stime; | |
1128 long cutime; | |
1129 long cstime; | |
1130 long prio; | |
1131 long nice; | |
1132 long junk; | |
1133 long it_real; | |
1134 uintptr_t start; | |
1135 uintptr_t vsize; | |
1136 uintptr_t rss; | |
1137 unsigned long rsslim; | |
1138 uintptr_t scodes; | |
1139 uintptr_t ecode; | |
1140 int i; | |
1141 | |
1142 // Figure what the primordial thread stack base is. Code is inspired | |
1143 // by email from Hans Boehm. /proc/self/stat begins with current pid, | |
1144 // followed by command name surrounded by parentheses, state, etc. | |
1145 char stat[2048]; | |
1146 int statlen; | |
1147 | |
1148 fp = fopen("/proc/self/stat", "r"); | |
1149 if (fp) { | |
1150 statlen = fread(stat, 1, 2047, fp); | |
1151 stat[statlen] = '\0'; | |
1152 fclose(fp); | |
1153 | |
1154 // Skip pid and the command string. Note that we could be dealing with | |
1155 // weird command names, e.g. user could decide to rename java launcher | |
1156 // to "java 1.4.2 :)", then the stat file would look like | |
1157 // 1234 (java 1.4.2 :)) R ... ... | |
1158 // We don't really need to know the command string, just find the last | |
1159 // occurrence of ")" and then start parsing from there. See bug 4726580. | |
1160 char * s = strrchr(stat, ')'); | |
1161 | |
1162 i = 0; | |
1163 if (s) { | |
1164 // Skip blank chars | |
1165 do s++; while (isspace(*s)); | |
1166 | |
1167 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 */ | |
1168 /* 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 */ | |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1169 i = sscanf(s, "%c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld " |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1170 UINTX_FORMAT UINTX_FORMAT UINTX_FORMAT |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1171 " %lu " |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1172 UINTX_FORMAT UINTX_FORMAT UINTX_FORMAT, |
0 | 1173 &state, /* 3 %c */ |
1174 &ppid, /* 4 %d */ | |
1175 &pgrp, /* 5 %d */ | |
1176 &session, /* 6 %d */ | |
1177 &nr, /* 7 %d */ | |
1178 &tpgrp, /* 8 %d */ | |
1179 &flags, /* 9 %lu */ | |
1180 &minflt, /* 10 %lu */ | |
1181 &cminflt, /* 11 %lu */ | |
1182 &majflt, /* 12 %lu */ | |
1183 &cmajflt, /* 13 %lu */ | |
1184 &utime, /* 14 %lu */ | |
1185 &stime, /* 15 %lu */ | |
1186 &cutime, /* 16 %ld */ | |
1187 &cstime, /* 17 %ld */ | |
1188 &prio, /* 18 %ld */ | |
1189 &nice, /* 19 %ld */ | |
1190 &junk, /* 20 %ld */ | |
1191 &it_real, /* 21 %ld */ | |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1192 &start, /* 22 UINTX_FORMAT */ |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1193 &vsize, /* 23 UINTX_FORMAT */ |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1194 &rss, /* 24 UINTX_FORMAT */ |
0 | 1195 &rsslim, /* 25 %lu */ |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1196 &scodes, /* 26 UINTX_FORMAT */ |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1197 &ecode, /* 27 UINTX_FORMAT */ |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
1198 &stack_start); /* 28 UINTX_FORMAT */ |
0 | 1199 } |
1200 | |
1201 if (i != 28 - 2) { | |
1202 assert(false, "Bad conversion from /proc/self/stat"); | |
1203 // product mode - assume we are the initial thread, good luck in the | |
1204 // embedded case. | |
1205 warning("Can't detect initial thread stack location - bad conversion"); | |
1206 stack_start = (uintptr_t) &rlim; | |
1207 } | |
1208 } else { | |
1209 // For some reason we can't open /proc/self/stat (for example, running on | |
1210 // FreeBSD with a Linux emulator, or inside chroot), this should work for | |
1211 // most cases, so don't abort: | |
1212 warning("Can't detect initial thread stack location - no /proc/self/stat"); | |
1213 stack_start = (uintptr_t) &rlim; | |
1214 } | |
1215 } | |
1216 | |
1217 // Now we have a pointer (stack_start) very close to the stack top, the | |
1218 // next thing to do is to figure out the exact location of stack top. We | |
1219 // can find out the virtual memory area that contains stack_start by | |
1220 // reading /proc/self/maps, it should be the last vma in /proc/self/maps, | |
1221 // and its upper limit is the real stack top. (again, this would fail if | |
1222 // running inside chroot, because /proc may not exist.) | |
1223 | |
1224 uintptr_t stack_top; | |
1225 address low, high; | |
1226 if (find_vma((address)stack_start, &low, &high)) { | |
1227 // success, "high" is the true stack top. (ignore "low", because initial | |
1228 // thread stack grows on demand, its real bottom is high - RLIMIT_STACK.) | |
1229 stack_top = (uintptr_t)high; | |
1230 } else { | |
1231 // failed, likely because /proc/self/maps does not exist | |
1232 warning("Can't detect initial thread stack location - find_vma failed"); | |
1233 // best effort: stack_start is normally within a few pages below the real | |
1234 // stack top, use it as stack top, and reduce stack size so we won't put | |
1235 // guard page outside stack. | |
1236 stack_top = stack_start; | |
1237 stack_size -= 16 * page_size(); | |
1238 } | |
1239 | |
1240 // stack_top could be partially down the page so align it | |
1241 stack_top = align_size_up(stack_top, page_size()); | |
1242 | |
1243 if (max_size && stack_size > max_size) { | |
1244 _initial_thread_stack_size = max_size; | |
1245 } else { | |
1246 _initial_thread_stack_size = stack_size; | |
1247 } | |
1248 | |
1249 _initial_thread_stack_size = align_size_down(_initial_thread_stack_size, page_size()); | |
1250 _initial_thread_stack_bottom = (address)stack_top - _initial_thread_stack_size; | |
1251 } | |
1252 | |
1253 //////////////////////////////////////////////////////////////////////////////// | |
1254 // time support | |
1255 | |
1256 // Time since start-up in seconds to a fine granularity. | |
1257 // Used by VMSelfDestructTimer and the MemProfiler. | |
1258 double os::elapsedTime() { | |
1259 | |
1260 return (double)(os::elapsed_counter()) * 0.000001; | |
1261 } | |
1262 | |
1263 jlong os::elapsed_counter() { | |
1264 timeval time; | |
1265 int status = gettimeofday(&time, NULL); | |
1266 return jlong(time.tv_sec) * 1000 * 1000 + jlong(time.tv_usec) - initial_time_count; | |
1267 } | |
1268 | |
1269 jlong os::elapsed_frequency() { | |
1270 return (1000 * 1000); | |
1271 } | |
1272 | |
342
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1273 // For now, we say that linux does not support vtime. I have no idea |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1274 // whether it can actually be made to (DLD, 9/13/05). |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1275 |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1276 bool os::supports_vtime() { return false; } |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1277 bool os::enable_vtime() { return false; } |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1278 bool os::vtime_enabled() { return false; } |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1279 double os::elapsedVTime() { |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1280 // better than nothing, but not much |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1281 return elapsedTime(); |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1282 } |
37f87013dfd8
6711316: Open source the Garbage-First garbage collector
ysr
parents:
141
diff
changeset
|
1283 |
61 | 1284 jlong os::javaTimeMillis() { |
0 | 1285 timeval time; |
1286 int status = gettimeofday(&time, NULL); | |
1287 assert(status != -1, "linux error"); | |
1288 return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); | |
1289 } | |
1290 | |
1291 #ifndef CLOCK_MONOTONIC | |
1292 #define CLOCK_MONOTONIC (1) | |
1293 #endif | |
1294 | |
1295 void os::Linux::clock_init() { | |
1296 // we do dlopen's in this particular order due to bug in linux | |
1297 // dynamical loader (see 6348968) leading to crash on exit | |
1298 void* handle = dlopen("librt.so.1", RTLD_LAZY); | |
1299 if (handle == NULL) { | |
1300 handle = dlopen("librt.so", RTLD_LAZY); | |
1301 } | |
1302 | |
1303 if (handle) { | |
1304 int (*clock_getres_func)(clockid_t, struct timespec*) = | |
1305 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_getres"); | |
1306 int (*clock_gettime_func)(clockid_t, struct timespec*) = | |
1307 (int(*)(clockid_t, struct timespec*))dlsym(handle, "clock_gettime"); | |
1308 if (clock_getres_func && clock_gettime_func) { | |
1309 // See if monotonic clock is supported by the kernel. Note that some | |
1310 // early implementations simply return kernel jiffies (updated every | |
1311 // 1/100 or 1/1000 second). It would be bad to use such a low res clock | |
1312 // for nano time (though the monotonic property is still nice to have). | |
1313 // It's fixed in newer kernels, however clock_getres() still returns | |
1314 // 1/HZ. We check if clock_getres() works, but will ignore its reported | |
1315 // resolution for now. Hopefully as people move to new kernels, this | |
1316 // won't be a problem. | |
1317 struct timespec res; | |
1318 struct timespec tp; | |
1319 if (clock_getres_func (CLOCK_MONOTONIC, &res) == 0 && | |
1320 clock_gettime_func(CLOCK_MONOTONIC, &tp) == 0) { | |
1321 // yes, monotonic clock is supported | |
1322 _clock_gettime = clock_gettime_func; | |
1323 } else { | |
1324 // close librt if there is no monotonic clock | |
1325 dlclose(handle); | |
1326 } | |
1327 } | |
1328 } | |
1329 } | |
1330 | |
1331 #ifndef SYS_clock_getres | |
1332 | |
1333 #if defined(IA32) || defined(AMD64) | |
1334 #define SYS_clock_getres IA32_ONLY(266) AMD64_ONLY(229) | |
1335 #else | |
1336 #error Value of SYS_clock_getres not known on this platform | |
1337 #endif | |
1338 | |
1339 #endif | |
1340 | |
1341 #define sys_clock_getres(x,y) ::syscall(SYS_clock_getres, x, y) | |
1342 | |
1343 void os::Linux::fast_thread_clock_init() { | |
1344 if (!UseLinuxPosixThreadCPUClocks) { | |
1345 return; | |
1346 } | |
1347 clockid_t clockid; | |
1348 struct timespec tp; | |
1349 int (*pthread_getcpuclockid_func)(pthread_t, clockid_t *) = | |
1350 (int(*)(pthread_t, clockid_t *)) dlsym(RTLD_DEFAULT, "pthread_getcpuclockid"); | |
1351 | |
1352 // Switch to using fast clocks for thread cpu time if | |
1353 // the sys_clock_getres() returns 0 error code. | |
1354 // Note, that some kernels may support the current thread | |
1355 // clock (CLOCK_THREAD_CPUTIME_ID) but not the clocks | |
1356 // returned by the pthread_getcpuclockid(). | |
1357 // If the fast Posix clocks are supported then the sys_clock_getres() | |
1358 // must return at least tp.tv_sec == 0 which means a resolution | |
1359 // better than 1 sec. This is extra check for reliability. | |
1360 | |
1361 if(pthread_getcpuclockid_func && | |
1362 pthread_getcpuclockid_func(_main_thread, &clockid) == 0 && | |
1363 sys_clock_getres(clockid, &tp) == 0 && tp.tv_sec == 0) { | |
1364 | |
1365 _supports_fast_thread_cpu_time = true; | |
1366 _pthread_getcpuclockid = pthread_getcpuclockid_func; | |
1367 } | |
1368 } | |
1369 | |
1370 jlong os::javaTimeNanos() { | |
1371 if (Linux::supports_monotonic_clock()) { | |
1372 struct timespec tp; | |
1373 int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp); | |
1374 assert(status == 0, "gettime error"); | |
1375 jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec); | |
1376 return result; | |
1377 } else { | |
1378 timeval time; | |
1379 int status = gettimeofday(&time, NULL); | |
1380 assert(status != -1, "linux error"); | |
1381 jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec); | |
1382 return 1000 * usecs; | |
1383 } | |
1384 } | |
1385 | |
1386 void os::javaTimeNanos_info(jvmtiTimerInfo *info_ptr) { | |
1387 if (Linux::supports_monotonic_clock()) { | |
1388 info_ptr->max_value = ALL_64_BITS; | |
1389 | |
1390 // CLOCK_MONOTONIC - amount of time since some arbitrary point in the past | |
1391 info_ptr->may_skip_backward = false; // not subject to resetting or drifting | |
1392 info_ptr->may_skip_forward = false; // not subject to resetting or drifting | |
1393 } else { | |
1394 // gettimeofday - based on time in seconds since the Epoch thus does not wrap | |
1395 info_ptr->max_value = ALL_64_BITS; | |
1396 | |
1397 // gettimeofday is a real time clock so it skips | |
1398 info_ptr->may_skip_backward = true; | |
1399 info_ptr->may_skip_forward = true; | |
1400 } | |
1401 | |
1402 info_ptr->kind = JVMTI_TIMER_ELAPSED; // elapsed not CPU time | |
1403 } | |
1404 | |
1405 // Return the real, user, and system times in seconds from an | |
1406 // arbitrary fixed point in the past. | |
1407 bool os::getTimesSecs(double* process_real_time, | |
1408 double* process_user_time, | |
1409 double* process_system_time) { | |
1410 struct tms ticks; | |
1411 clock_t real_ticks = times(&ticks); | |
1412 | |
1413 if (real_ticks == (clock_t) (-1)) { | |
1414 return false; | |
1415 } else { | |
1416 double ticks_per_second = (double) clock_tics_per_sec; | |
1417 *process_user_time = ((double) ticks.tms_utime) / ticks_per_second; | |
1418 *process_system_time = ((double) ticks.tms_stime) / ticks_per_second; | |
1419 *process_real_time = ((double) real_ticks) / ticks_per_second; | |
1420 | |
1421 return true; | |
1422 } | |
1423 } | |
1424 | |
1425 | |
1426 char * os::local_time_string(char *buf, size_t buflen) { | |
1427 struct tm t; | |
1428 time_t long_time; | |
1429 time(&long_time); | |
1430 localtime_r(&long_time, &t); | |
1431 jio_snprintf(buf, buflen, "%d-%02d-%02d %02d:%02d:%02d", | |
1432 t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, | |
1433 t.tm_hour, t.tm_min, t.tm_sec); | |
1434 return buf; | |
1435 } | |
1436 | |
548
773234c55e8c
6800586: -XX:+PrintGCDateStamps is using mt-unsafe localtime function
ysr
parents:
516
diff
changeset
|
1437 struct tm* os::localtime_pd(const time_t* clock, struct tm* res) { |
773234c55e8c
6800586: -XX:+PrintGCDateStamps is using mt-unsafe localtime function
ysr
parents:
516
diff
changeset
|
1438 return localtime_r(clock, res); |
773234c55e8c
6800586: -XX:+PrintGCDateStamps is using mt-unsafe localtime function
ysr
parents:
516
diff
changeset
|
1439 } |
773234c55e8c
6800586: -XX:+PrintGCDateStamps is using mt-unsafe localtime function
ysr
parents:
516
diff
changeset
|
1440 |
0 | 1441 //////////////////////////////////////////////////////////////////////////////// |
1442 // runtime exit support | |
1443 | |
1444 // Note: os::shutdown() might be called very early during initialization, or | |
1445 // called from signal handler. Before adding something to os::shutdown(), make | |
1446 // sure it is async-safe and can handle partially initialized VM. | |
1447 void os::shutdown() { | |
1448 | |
1449 // allow PerfMemory to attempt cleanup of any persistent resources | |
1450 perfMemory_exit(); | |
1451 | |
1452 // needs to remove object in file system | |
1453 AttachListener::abort(); | |
1454 | |
1455 // flush buffered output, finish log files | |
1456 ostream_abort(); | |
1457 | |
1458 // Check for abort hook | |
1459 abort_hook_t abort_hook = Arguments::abort_hook(); | |
1460 if (abort_hook != NULL) { | |
1461 abort_hook(); | |
1462 } | |
1463 | |
1464 } | |
1465 | |
1466 // Note: os::abort() might be called very early during initialization, or | |
1467 // called from signal handler. Before adding something to os::abort(), make | |
1468 // sure it is async-safe and can handle partially initialized VM. | |
1469 void os::abort(bool dump_core) { | |
1470 os::shutdown(); | |
1471 if (dump_core) { | |
1472 #ifndef PRODUCT | |
1473 fdStream out(defaultStream::output_fd()); | |
1474 out.print_raw("Current thread is "); | |
1475 char buf[16]; | |
1476 jio_snprintf(buf, sizeof(buf), UINTX_FORMAT, os::current_thread_id()); | |
1477 out.print_raw_cr(buf); | |
1478 out.print_raw_cr("Dumping core ..."); | |
1479 #endif | |
1480 ::abort(); // dump core | |
1481 } | |
1482 | |
1483 ::exit(1); | |
1484 } | |
1485 | |
1486 // Die immediately, no exit hook, no abort hook, no cleanup. | |
1487 void os::die() { | |
1488 // _exit() on LinuxThreads only kills current thread | |
1489 ::abort(); | |
1490 } | |
1491 | |
1492 // unused on linux for now. | |
1493 void os::set_error_file(const char *logfile) {} | |
1494 | |
1495 intx os::current_thread_id() { return (intx)pthread_self(); } | |
1496 int os::current_process_id() { | |
1497 | |
1498 // Under the old linux thread library, linux gives each thread | |
1499 // its own process id. Because of this each thread will return | |
1500 // a different pid if this method were to return the result | |
1501 // of getpid(2). Linux provides no api that returns the pid | |
1502 // of the launcher thread for the vm. This implementation | |
1503 // returns a unique pid, the pid of the launcher thread | |
1504 // that starts the vm 'process'. | |
1505 | |
1506 // Under the NPTL, getpid() returns the same pid as the | |
1507 // launcher thread rather than a unique pid per thread. | |
1508 // Use gettid() if you want the old pre NPTL behaviour. | |
1509 | |
1510 // if you are looking for the result of a call to getpid() that | |
1511 // returns a unique pid for the calling thread, then look at the | |
1512 // OSThread::thread_id() method in osThread_linux.hpp file | |
1513 | |
1514 return (int)(_initial_pid ? _initial_pid : getpid()); | |
1515 } | |
1516 | |
1517 // DLL functions | |
1518 | |
1519 const char* os::dll_file_extension() { return ".so"; } | |
1520 | |
1521 const char* os::get_temp_directory() { return "/tmp/"; } | |
1522 | |
691 | 1523 static bool file_exists(const char* filename) { |
1524 struct stat statbuf; | |
1525 if (filename == NULL || strlen(filename) == 0) { | |
1526 return false; | |
1527 } | |
1528 return os::stat(filename, &statbuf) == 0; | |
1529 } | |
1530 | |
1531 void os::dll_build_name(char* buffer, size_t buflen, | |
1532 const char* pname, const char* fname) { | |
1533 // Copied from libhpi | |
242 | 1534 const size_t pnamelen = pname ? strlen(pname) : 0; |
1535 | |
691 | 1536 // Quietly truncate on buffer overflow. Should be an error. |
242 | 1537 if (pnamelen + strlen(fname) + 10 > (size_t) buflen) { |
1538 *buffer = '\0'; | |
1539 return; | |
1540 } | |
1541 | |
1542 if (pnamelen == 0) { | |
691 | 1543 snprintf(buffer, buflen, "lib%s.so", fname); |
1544 } else if (strchr(pname, *os::path_separator()) != NULL) { | |
1545 int n; | |
1546 char** pelements = split_path(pname, &n); | |
1547 for (int i = 0 ; i < n ; i++) { | |
1548 // Really shouldn't be NULL, but check can't hurt | |
1549 if (pelements[i] == NULL || strlen(pelements[i]) == 0) { | |
1550 continue; // skip the empty path values | |
1551 } | |
1552 snprintf(buffer, buflen, "%s/lib%s.so", pelements[i], fname); | |
1553 if (file_exists(buffer)) { | |
1554 break; | |
1555 } | |
1556 } | |
1557 // release the storage | |
1558 for (int i = 0 ; i < n ; i++) { | |
1559 if (pelements[i] != NULL) { | |
1560 FREE_C_HEAP_ARRAY(char, pelements[i]); | |
1561 } | |
1562 } | |
1563 if (pelements != NULL) { | |
1564 FREE_C_HEAP_ARRAY(char*, pelements); | |
1565 } | |
242 | 1566 } else { |
691 | 1567 snprintf(buffer, buflen, "%s/lib%s.so", pname, fname); |
242 | 1568 } |
1569 } | |
1570 | |
0 | 1571 const char* os::get_current_directory(char *buf, int buflen) { |
1572 return getcwd(buf, buflen); | |
1573 } | |
1574 | |
1575 // check if addr is inside libjvm[_g].so | |
1576 bool os::address_is_in_vm(address addr) { | |
1577 static address libjvm_base_addr; | |
1578 Dl_info dlinfo; | |
1579 | |
1580 if (libjvm_base_addr == NULL) { | |
1581 dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo); | |
1582 libjvm_base_addr = (address)dlinfo.dli_fbase; | |
1583 assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); | |
1584 } | |
1585 | |
1586 if (dladdr((void *)addr, &dlinfo)) { | |
1587 if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; | |
1588 } | |
1589 | |
1590 return false; | |
1591 } | |
1592 | |
1593 bool os::dll_address_to_function_name(address addr, char *buf, | |
1594 int buflen, int *offset) { | |
1595 Dl_info dlinfo; | |
1596 | |
1597 if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) { | |
1598 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); | |
1599 if (offset) *offset = addr - (address)dlinfo.dli_saddr; | |
1600 return true; | |
1601 } else { | |
1602 if (buf) buf[0] = '\0'; | |
1603 if (offset) *offset = -1; | |
1604 return false; | |
1605 } | |
1606 } | |
1607 | |
1608 struct _address_to_library_name { | |
1609 address addr; // input : memory address | |
1610 size_t buflen; // size of fname | |
1611 char* fname; // output: library name | |
1612 address base; // library base addr | |
1613 }; | |
1614 | |
1615 static int address_to_library_name_callback(struct dl_phdr_info *info, | |
1616 size_t size, void *data) { | |
1617 int i; | |
1618 bool found = false; | |
1619 address libbase = NULL; | |
1620 struct _address_to_library_name * d = (struct _address_to_library_name *)data; | |
1621 | |
1622 // iterate through all loadable segments | |
1623 for (i = 0; i < info->dlpi_phnum; i++) { | |
1624 address segbase = (address)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); | |
1625 if (info->dlpi_phdr[i].p_type == PT_LOAD) { | |
1626 // base address of a library is the lowest address of its loaded | |
1627 // segments. | |
1628 if (libbase == NULL || libbase > segbase) { | |
1629 libbase = segbase; | |
1630 } | |
1631 // see if 'addr' is within current segment | |
1632 if (segbase <= d->addr && | |
1633 d->addr < segbase + info->dlpi_phdr[i].p_memsz) { | |
1634 found = true; | |
1635 } | |
1636 } | |
1637 } | |
1638 | |
1639 // dlpi_name is NULL or empty if the ELF file is executable, return 0 | |
1640 // so dll_address_to_library_name() can fall through to use dladdr() which | |
1641 // can figure out executable name from argv[0]. | |
1642 if (found && info->dlpi_name && info->dlpi_name[0]) { | |
1643 d->base = libbase; | |
1644 if (d->fname) { | |
1645 jio_snprintf(d->fname, d->buflen, "%s", info->dlpi_name); | |
1646 } | |
1647 return 1; | |
1648 } | |
1649 return 0; | |
1650 } | |
1651 | |
1652 bool os::dll_address_to_library_name(address addr, char* buf, | |
1653 int buflen, int* offset) { | |
1654 Dl_info dlinfo; | |
1655 struct _address_to_library_name data; | |
1656 | |
1657 // There is a bug in old glibc dladdr() implementation that it could resolve | |
1658 // to wrong library name if the .so file has a base address != NULL. Here | |
1659 // we iterate through the program headers of all loaded libraries to find | |
1660 // out which library 'addr' really belongs to. This workaround can be | |
1661 // removed once the minimum requirement for glibc is moved to 2.3.x. | |
1662 data.addr = addr; | |
1663 data.fname = buf; | |
1664 data.buflen = buflen; | |
1665 data.base = NULL; | |
1666 int rslt = dl_iterate_phdr(address_to_library_name_callback, (void *)&data); | |
1667 | |
1668 if (rslt) { | |
1669 // buf already contains library name | |
1670 if (offset) *offset = addr - data.base; | |
1671 return true; | |
1672 } else if (dladdr((void*)addr, &dlinfo)){ | |
1673 if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); | |
1674 if (offset) *offset = addr - (address)dlinfo.dli_fbase; | |
1675 return true; | |
1676 } else { | |
1677 if (buf) buf[0] = '\0'; | |
1678 if (offset) *offset = -1; | |
1679 return false; | |
1680 } | |
1681 } | |
1682 | |
1683 // Loads .dll/.so and | |
1684 // in case of error it checks if .dll/.so was built for the | |
1685 // same architecture as Hotspot is running on | |
1686 | |
1687 void * os::dll_load(const char *filename, char *ebuf, int ebuflen) | |
1688 { | |
1689 void * result= ::dlopen(filename, RTLD_LAZY); | |
1690 if (result != NULL) { | |
1691 // Successful loading | |
1692 return result; | |
1693 } | |
1694 | |
1695 Elf32_Ehdr elf_head; | |
1696 | |
1697 // Read system error message into ebuf | |
1698 // It may or may not be overwritten below | |
1699 ::strncpy(ebuf, ::dlerror(), ebuflen-1); | |
1700 ebuf[ebuflen-1]='\0'; | |
1701 int diag_msg_max_length=ebuflen-strlen(ebuf); | |
1702 char* diag_msg_buf=ebuf+strlen(ebuf); | |
1703 | |
1704 if (diag_msg_max_length==0) { | |
1705 // No more space in ebuf for additional diagnostics message | |
1706 return NULL; | |
1707 } | |
1708 | |
1709 | |
1710 int file_descriptor= ::open(filename, O_RDONLY | O_NONBLOCK); | |
1711 | |
1712 if (file_descriptor < 0) { | |
1713 // Can't open library, report dlerror() message | |
1714 return NULL; | |
1715 } | |
1716 | |
1717 bool failed_to_read_elf_head= | |
1718 (sizeof(elf_head)!= | |
1719 (::read(file_descriptor, &elf_head,sizeof(elf_head)))) ; | |
1720 | |
1721 ::close(file_descriptor); | |
1722 if (failed_to_read_elf_head) { | |
1723 // file i/o error - report dlerror() msg | |
1724 return NULL; | |
1725 } | |
1726 | |
1727 typedef struct { | |
1728 Elf32_Half code; // Actual value as defined in elf.h | |
1729 Elf32_Half compat_class; // Compatibility of archs at VM's sense | |
1730 char elf_class; // 32 or 64 bit | |
1731 char endianess; // MSB or LSB | |
1732 char* name; // String representation | |
1733 } arch_t; | |
1734 | |
1735 #ifndef EM_486 | |
1736 #define EM_486 6 /* Intel 80486 */ | |
1737 #endif | |
1738 | |
1739 static const arch_t arch_array[]={ | |
1740 {EM_386, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, | |
1741 {EM_486, EM_386, ELFCLASS32, ELFDATA2LSB, (char*)"IA 32"}, | |
1742 {EM_IA_64, EM_IA_64, ELFCLASS64, ELFDATA2LSB, (char*)"IA 64"}, | |
1743 {EM_X86_64, EM_X86_64, ELFCLASS64, ELFDATA2LSB, (char*)"AMD 64"}, | |
1744 {EM_SPARC, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, | |
1745 {EM_SPARC32PLUS, EM_SPARC, ELFCLASS32, ELFDATA2MSB, (char*)"Sparc 32"}, | |
1746 {EM_SPARCV9, EM_SPARCV9, ELFCLASS64, ELFDATA2MSB, (char*)"Sparc v9 64"}, | |
1747 {EM_PPC, EM_PPC, ELFCLASS32, ELFDATA2MSB, (char*)"Power PC 32"}, | |
1010 | 1748 {EM_PPC64, EM_PPC64, ELFCLASS64, ELFDATA2MSB, (char*)"Power PC 64"}, |
1749 {EM_ARM, EM_ARM, ELFCLASS32, ELFDATA2LSB, (char*)"ARM"}, | |
1750 {EM_S390, EM_S390, ELFCLASSNONE, ELFDATA2MSB, (char*)"IBM System/390"}, | |
1751 {EM_ALPHA, EM_ALPHA, ELFCLASS64, ELFDATA2LSB, (char*)"Alpha"}, | |
1752 {EM_MIPS_RS3_LE, EM_MIPS_RS3_LE, ELFCLASS32, ELFDATA2LSB, (char*)"MIPSel"}, | |
1753 {EM_MIPS, EM_MIPS, ELFCLASS32, ELFDATA2MSB, (char*)"MIPS"}, | |
1754 {EM_PARISC, EM_PARISC, ELFCLASS32, ELFDATA2MSB, (char*)"PARISC"}, | |
1755 {EM_68K, EM_68K, ELFCLASS32, ELFDATA2MSB, (char*)"M68k"} | |
0 | 1756 }; |
1757 | |
1758 #if (defined IA32) | |
1759 static Elf32_Half running_arch_code=EM_386; | |
1760 #elif (defined AMD64) | |
1761 static Elf32_Half running_arch_code=EM_X86_64; | |
1762 #elif (defined IA64) | |
1763 static Elf32_Half running_arch_code=EM_IA_64; | |
1764 #elif (defined __sparc) && (defined _LP64) | |
1765 static Elf32_Half running_arch_code=EM_SPARCV9; | |
1766 #elif (defined __sparc) && (!defined _LP64) | |
1767 static Elf32_Half running_arch_code=EM_SPARC; | |
1768 #elif (defined __powerpc64__) | |
1769 static Elf32_Half running_arch_code=EM_PPC64; | |
1770 #elif (defined __powerpc__) | |
1771 static Elf32_Half running_arch_code=EM_PPC; | |
1010 | 1772 #elif (defined ARM) |
1773 static Elf32_Half running_arch_code=EM_ARM; | |
1774 #elif (defined S390) | |
1775 static Elf32_Half running_arch_code=EM_S390; | |
1776 #elif (defined ALPHA) | |
1777 static Elf32_Half running_arch_code=EM_ALPHA; | |
1778 #elif (defined MIPSEL) | |
1779 static Elf32_Half running_arch_code=EM_MIPS_RS3_LE; | |
1780 #elif (defined PARISC) | |
1781 static Elf32_Half running_arch_code=EM_PARISC; | |
1782 #elif (defined MIPS) | |
1783 static Elf32_Half running_arch_code=EM_MIPS; | |
1784 #elif (defined M68K) | |
1785 static Elf32_Half running_arch_code=EM_68K; | |
0 | 1786 #else |
1787 #error Method os::dll_load requires that one of following is defined:\ | |
1010 | 1788 IA32, AMD64, IA64, __sparc, __powerpc__, ARM, S390, ALPHA, MIPS, MIPSEL, PARISC, M68K |
0 | 1789 #endif |
1790 | |
1791 // Identify compatability class for VM's architecture and library's architecture | |
1792 // Obtain string descriptions for architectures | |
1793 | |
1794 arch_t lib_arch={elf_head.e_machine,0,elf_head.e_ident[EI_CLASS], elf_head.e_ident[EI_DATA], NULL}; | |
1795 int running_arch_index=-1; | |
1796 | |
1797 for (unsigned int i=0 ; i < ARRAY_SIZE(arch_array) ; i++ ) { | |
1798 if (running_arch_code == arch_array[i].code) { | |
1799 running_arch_index = i; | |
1800 } | |
1801 if (lib_arch.code == arch_array[i].code) { | |
1802 lib_arch.compat_class = arch_array[i].compat_class; | |
1803 lib_arch.name = arch_array[i].name; | |
1804 } | |
1805 } | |
1806 | |
1807 assert(running_arch_index != -1, | |
1808 "Didn't find running architecture code (running_arch_code) in arch_array"); | |
1809 if (running_arch_index == -1) { | |
1810 // Even though running architecture detection failed | |
1811 // we may still continue with reporting dlerror() message | |
1812 return NULL; | |
1813 } | |
1814 | |
1815 if (lib_arch.endianess != arch_array[running_arch_index].endianess) { | |
1816 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: endianness mismatch)"); | |
1817 return NULL; | |
1818 } | |
1819 | |
1010 | 1820 #ifndef S390 |
0 | 1821 if (lib_arch.elf_class != arch_array[running_arch_index].elf_class) { |
1822 ::snprintf(diag_msg_buf, diag_msg_max_length-1," (Possible cause: architecture word width mismatch)"); | |
1823 return NULL; | |
1824 } | |
1010 | 1825 #endif // !S390 |
0 | 1826 |
1827 if (lib_arch.compat_class != arch_array[running_arch_index].compat_class) { | |
1828 if ( lib_arch.name!=NULL ) { | |
1829 ::snprintf(diag_msg_buf, diag_msg_max_length-1, | |
1830 " (Possible cause: can't load %s-bit .so on a %s-bit platform)", | |
1831 lib_arch.name, arch_array[running_arch_index].name); | |
1832 } else { | |
1833 ::snprintf(diag_msg_buf, diag_msg_max_length-1, | |
1834 " (Possible cause: can't load this .so (machine code=0x%x) on a %s-bit platform)", | |
1835 lib_arch.code, | |
1836 arch_array[running_arch_index].name); | |
1837 } | |
1838 } | |
1839 | |
1840 return NULL; | |
1841 } | |
1842 | |
242 | 1843 /* |
1844 * glibc-2.0 libdl is not MT safe. If you are building with any glibc, | |
1845 * chances are you might want to run the generated bits against glibc-2.0 | |
1846 * libdl.so, so always use locking for any version of glibc. | |
1847 */ | |
1848 void* os::dll_lookup(void* handle, const char* name) { | |
1849 pthread_mutex_lock(&dl_mutex); | |
1850 void* res = dlsym(handle, name); | |
1851 pthread_mutex_unlock(&dl_mutex); | |
1852 return res; | |
1853 } | |
0 | 1854 |
1855 | |
1856 bool _print_ascii_file(const char* filename, outputStream* st) { | |
1857 int fd = open(filename, O_RDONLY); | |
1858 if (fd == -1) { | |
1859 return false; | |
1860 } | |
1861 | |
1862 char buf[32]; | |
1863 int bytes; | |
1864 while ((bytes = read(fd, buf, sizeof(buf))) > 0) { | |
1865 st->print_raw(buf, bytes); | |
1866 } | |
1867 | |
1868 close(fd); | |
1869 | |
1870 return true; | |
1871 } | |
1872 | |
1873 void os::print_dll_info(outputStream *st) { | |
1874 st->print_cr("Dynamic libraries:"); | |
1875 | |
1876 char fname[32]; | |
1877 pid_t pid = os::Linux::gettid(); | |
1878 | |
1879 jio_snprintf(fname, sizeof(fname), "/proc/%d/maps", pid); | |
1880 | |
1881 if (!_print_ascii_file(fname, st)) { | |
1882 st->print("Can not get library information for pid = %d\n", pid); | |
1883 } | |
1884 } | |
1885 | |
1886 | |
1887 void os::print_os_info(outputStream* st) { | |
1888 st->print("OS:"); | |
1889 | |
1890 // Try to identify popular distros. | |
1891 // Most Linux distributions have /etc/XXX-release file, which contains | |
1892 // the OS version string. Some have more than one /etc/XXX-release file | |
1893 // (e.g. Mandrake has both /etc/mandrake-release and /etc/redhat-release.), | |
1894 // so the order is important. | |
1895 if (!_print_ascii_file("/etc/mandrake-release", st) && | |
1896 !_print_ascii_file("/etc/sun-release", st) && | |
1897 !_print_ascii_file("/etc/redhat-release", st) && | |
1898 !_print_ascii_file("/etc/SuSE-release", st) && | |
1899 !_print_ascii_file("/etc/turbolinux-release", st) && | |
1900 !_print_ascii_file("/etc/gentoo-release", st) && | |
1901 !_print_ascii_file("/etc/debian_version", st)) { | |
1902 st->print("Linux"); | |
1903 } | |
1904 st->cr(); | |
1905 | |
1906 // kernel | |
1907 st->print("uname:"); | |
1908 struct utsname name; | |
1909 uname(&name); | |
1910 st->print(name.sysname); st->print(" "); | |
1911 st->print(name.release); st->print(" "); | |
1912 st->print(name.version); st->print(" "); | |
1913 st->print(name.machine); | |
1914 st->cr(); | |
1915 | |
1916 // Print warning if unsafe chroot environment detected | |
1917 if (unsafe_chroot_detected) { | |
1918 st->print("WARNING!! "); | |
1919 st->print_cr(unstable_chroot_error); | |
1920 } | |
1921 | |
1922 // libc, pthread | |
1923 st->print("libc:"); | |
1924 st->print(os::Linux::glibc_version()); st->print(" "); | |
1925 st->print(os::Linux::libpthread_version()); st->print(" "); | |
1926 if (os::Linux::is_LinuxThreads()) { | |
1927 st->print("(%s stack)", os::Linux::is_floating_stack() ? "floating" : "fixed"); | |
1928 } | |
1929 st->cr(); | |
1930 | |
1931 // rlimit | |
1932 st->print("rlimit:"); | |
1933 struct rlimit rlim; | |
1934 | |
1935 st->print(" STACK "); | |
1936 getrlimit(RLIMIT_STACK, &rlim); | |
1937 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
1938 else st->print("%uk", rlim.rlim_cur >> 10); | |
1939 | |
1940 st->print(", CORE "); | |
1941 getrlimit(RLIMIT_CORE, &rlim); | |
1942 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
1943 else st->print("%uk", rlim.rlim_cur >> 10); | |
1944 | |
1945 st->print(", NPROC "); | |
1946 getrlimit(RLIMIT_NPROC, &rlim); | |
1947 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
1948 else st->print("%d", rlim.rlim_cur); | |
1949 | |
1950 st->print(", NOFILE "); | |
1951 getrlimit(RLIMIT_NOFILE, &rlim); | |
1952 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
1953 else st->print("%d", rlim.rlim_cur); | |
1954 | |
1955 st->print(", AS "); | |
1956 getrlimit(RLIMIT_AS, &rlim); | |
1957 if (rlim.rlim_cur == RLIM_INFINITY) st->print("infinity"); | |
1958 else st->print("%uk", rlim.rlim_cur >> 10); | |
1959 st->cr(); | |
1960 | |
1961 // load average | |
1962 st->print("load average:"); | |
1963 double loadavg[3]; | |
1964 os::loadavg(loadavg, 3); | |
1965 st->print("%0.02f %0.02f %0.02f", loadavg[0], loadavg[1], loadavg[2]); | |
1966 st->cr(); | |
1967 } | |
1968 | |
1969 void os::print_memory_info(outputStream* st) { | |
1970 | |
1971 st->print("Memory:"); | |
1972 st->print(" %dk page", os::vm_page_size()>>10); | |
1973 | |
1974 // values in struct sysinfo are "unsigned long" | |
1975 struct sysinfo si; | |
1976 sysinfo(&si); | |
1977 | |
1978 st->print(", physical " UINT64_FORMAT "k", | |
1979 os::physical_memory() >> 10); | |
1980 st->print("(" UINT64_FORMAT "k free)", | |
1981 os::available_memory() >> 10); | |
1982 st->print(", swap " UINT64_FORMAT "k", | |
1983 ((jlong)si.totalswap * si.mem_unit) >> 10); | |
1984 st->print("(" UINT64_FORMAT "k free)", | |
1985 ((jlong)si.freeswap * si.mem_unit) >> 10); | |
1986 st->cr(); | |
1987 } | |
1988 | |
1989 // Taken from /usr/include/bits/siginfo.h Supposed to be architecture specific | |
1990 // but they're the same for all the linux arch that we support | |
1991 // and they're the same for solaris but there's no common place to put this. | |
1992 const char *ill_names[] = { "ILL0", "ILL_ILLOPC", "ILL_ILLOPN", "ILL_ILLADR", | |
1993 "ILL_ILLTRP", "ILL_PRVOPC", "ILL_PRVREG", | |
1994 "ILL_COPROC", "ILL_BADSTK" }; | |
1995 | |
1996 const char *fpe_names[] = { "FPE0", "FPE_INTDIV", "FPE_INTOVF", "FPE_FLTDIV", | |
1997 "FPE_FLTOVF", "FPE_FLTUND", "FPE_FLTRES", | |
1998 "FPE_FLTINV", "FPE_FLTSUB", "FPE_FLTDEN" }; | |
1999 | |
2000 const char *segv_names[] = { "SEGV0", "SEGV_MAPERR", "SEGV_ACCERR" }; | |
2001 | |
2002 const char *bus_names[] = { "BUS0", "BUS_ADRALN", "BUS_ADRERR", "BUS_OBJERR" }; | |
2003 | |
2004 void os::print_siginfo(outputStream* st, void* siginfo) { | |
2005 st->print("siginfo:"); | |
2006 | |
2007 const int buflen = 100; | |
2008 char buf[buflen]; | |
2009 siginfo_t *si = (siginfo_t*)siginfo; | |
2010 st->print("si_signo=%s: ", os::exception_name(si->si_signo, buf, buflen)); | |
2011 if (si->si_errno != 0 && strerror_r(si->si_errno, buf, buflen) == 0) { | |
2012 st->print("si_errno=%s", buf); | |
2013 } else { | |
2014 st->print("si_errno=%d", si->si_errno); | |
2015 } | |
2016 const int c = si->si_code; | |
2017 assert(c > 0, "unexpected si_code"); | |
2018 switch (si->si_signo) { | |
2019 case SIGILL: | |
2020 st->print(", si_code=%d (%s)", c, c > 8 ? "" : ill_names[c]); | |
2021 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2022 break; | |
2023 case SIGFPE: | |
2024 st->print(", si_code=%d (%s)", c, c > 9 ? "" : fpe_names[c]); | |
2025 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2026 break; | |
2027 case SIGSEGV: | |
2028 st->print(", si_code=%d (%s)", c, c > 2 ? "" : segv_names[c]); | |
2029 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2030 break; | |
2031 case SIGBUS: | |
2032 st->print(", si_code=%d (%s)", c, c > 3 ? "" : bus_names[c]); | |
2033 st->print(", si_addr=" PTR_FORMAT, si->si_addr); | |
2034 break; | |
2035 default: | |
2036 st->print(", si_code=%d", si->si_code); | |
2037 // no si_addr | |
2038 } | |
2039 | |
2040 if ((si->si_signo == SIGBUS || si->si_signo == SIGSEGV) && | |
2041 UseSharedSpaces) { | |
2042 FileMapInfo* mapinfo = FileMapInfo::current_info(); | |
2043 if (mapinfo->is_in_shared_space(si->si_addr)) { | |
2044 st->print("\n\nError accessing class data sharing archive." \ | |
2045 " Mapped file inaccessible during execution, " \ | |
2046 " possible disk/network problem."); | |
2047 } | |
2048 } | |
2049 st->cr(); | |
2050 } | |
2051 | |
2052 | |
2053 static void print_signal_handler(outputStream* st, int sig, | |
2054 char* buf, size_t buflen); | |
2055 | |
2056 void os::print_signal_handlers(outputStream* st, char* buf, size_t buflen) { | |
2057 st->print_cr("Signal Handlers:"); | |
2058 print_signal_handler(st, SIGSEGV, buf, buflen); | |
2059 print_signal_handler(st, SIGBUS , buf, buflen); | |
2060 print_signal_handler(st, SIGFPE , buf, buflen); | |
2061 print_signal_handler(st, SIGPIPE, buf, buflen); | |
2062 print_signal_handler(st, SIGXFSZ, buf, buflen); | |
2063 print_signal_handler(st, SIGILL , buf, buflen); | |
2064 print_signal_handler(st, INTERRUPT_SIGNAL, buf, buflen); | |
2065 print_signal_handler(st, SR_signum, buf, buflen); | |
2066 print_signal_handler(st, SHUTDOWN1_SIGNAL, buf, buflen); | |
2067 print_signal_handler(st, SHUTDOWN2_SIGNAL , buf, buflen); | |
2068 print_signal_handler(st, SHUTDOWN3_SIGNAL , buf, buflen); | |
2069 print_signal_handler(st, BREAK_SIGNAL, buf, buflen); | |
2070 } | |
2071 | |
2072 static char saved_jvm_path[MAXPATHLEN] = {0}; | |
2073 | |
2074 // Find the full path to the current module, libjvm.so or libjvm_g.so | |
2075 void os::jvm_path(char *buf, jint len) { | |
2076 // Error checking. | |
2077 if (len < MAXPATHLEN) { | |
2078 assert(false, "must use a large-enough buffer"); | |
2079 buf[0] = '\0'; | |
2080 return; | |
2081 } | |
2082 // Lazy resolve the path to current module. | |
2083 if (saved_jvm_path[0] != 0) { | |
2084 strcpy(buf, saved_jvm_path); | |
2085 return; | |
2086 } | |
2087 | |
2088 char dli_fname[MAXPATHLEN]; | |
2089 bool ret = dll_address_to_library_name( | |
2090 CAST_FROM_FN_PTR(address, os::jvm_path), | |
2091 dli_fname, sizeof(dli_fname), NULL); | |
2092 assert(ret != 0, "cannot locate libjvm"); | |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
2093 if (realpath(dli_fname, buf) == NULL) |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
2094 return; |
0 | 2095 |
2096 if (strcmp(Arguments::sun_java_launcher(), "gamma") == 0) { | |
2097 // Support for the gamma launcher. Typical value for buf is | |
2098 // "<JAVA_HOME>/jre/lib/<arch>/<vmtype>/libjvm.so". If "/jre/lib/" appears at | |
2099 // the right place in the string, then assume we are installed in a JDK and | |
2100 // we're done. Otherwise, check for a JAVA_HOME environment variable and fix | |
2101 // up the path so it looks like libjvm.so is installed there (append a | |
2102 // fake suffix hotspot/libjvm.so). | |
2103 const char *p = buf + strlen(buf) - 1; | |
2104 for (int count = 0; p > buf && count < 5; ++count) { | |
2105 for (--p; p > buf && *p != '/'; --p) | |
2106 /* empty */ ; | |
2107 } | |
2108 | |
2109 if (strncmp(p, "/jre/lib/", 9) != 0) { | |
2110 // Look for JAVA_HOME in the environment. | |
2111 char* java_home_var = ::getenv("JAVA_HOME"); | |
2112 if (java_home_var != NULL && java_home_var[0] != 0) { | |
2113 // Check the current module name "libjvm.so" or "libjvm_g.so". | |
2114 p = strrchr(buf, '/'); | |
2115 assert(strstr(p, "/libjvm") == p, "invalid library name"); | |
2116 p = strstr(p, "_g") ? "_g" : ""; | |
2117 | |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
2118 if (realpath(java_home_var, buf) == NULL) |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
2119 return; |
0 | 2120 sprintf(buf + strlen(buf), "/jre/lib/%s", cpu_arch); |
2121 if (0 == access(buf, F_OK)) { | |
2122 // Use current module name "libjvm[_g].so" instead of | |
2123 // "libjvm"debug_only("_g")".so" since for fastdebug version | |
2124 // we should have "libjvm.so" but debug_only("_g") adds "_g"! | |
2125 // It is used when we are choosing the HPI library's name | |
2126 // "libhpi[_g].so" in hpi::initialize_get_interface(). | |
2127 sprintf(buf + strlen(buf), "/hotspot/libjvm%s.so", p); | |
2128 } else { | |
2129 // Go back to path of .so | |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
2130 if (realpath(dli_fname, buf) == NULL) |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
2131 return; |
0 | 2132 } |
2133 } | |
2134 } | |
2135 } | |
2136 | |
2137 strcpy(saved_jvm_path, buf); | |
2138 } | |
2139 | |
2140 void os::print_jni_name_prefix_on(outputStream* st, int args_size) { | |
2141 // no prefix required, not even "_" | |
2142 } | |
2143 | |
2144 void os::print_jni_name_suffix_on(outputStream* st, int args_size) { | |
2145 // no suffix required | |
2146 } | |
2147 | |
2148 //////////////////////////////////////////////////////////////////////////////// | |
2149 // sun.misc.Signal support | |
2150 | |
2151 static volatile jint sigint_count = 0; | |
2152 | |
2153 static void | |
2154 UserHandler(int sig, void *siginfo, void *context) { | |
2155 // 4511530 - sem_post is serialized and handled by the manager thread. When | |
2156 // the program is interrupted by Ctrl-C, SIGINT is sent to every thread. We | |
2157 // don't want to flood the manager thread with sem_post requests. | |
2158 if (sig == SIGINT && Atomic::add(1, &sigint_count) > 1) | |
2159 return; | |
2160 | |
2161 // Ctrl-C is pressed during error reporting, likely because the error | |
2162 // handler fails to abort. Let VM die immediately. | |
2163 if (sig == SIGINT && is_error_reported()) { | |
2164 os::die(); | |
2165 } | |
2166 | |
2167 os::signal_notify(sig); | |
2168 } | |
2169 | |
2170 void* os::user_handler() { | |
2171 return CAST_FROM_FN_PTR(void*, UserHandler); | |
2172 } | |
2173 | |
2174 extern "C" { | |
2175 typedef void (*sa_handler_t)(int); | |
2176 typedef void (*sa_sigaction_t)(int, siginfo_t *, void *); | |
2177 } | |
2178 | |
2179 void* os::signal(int signal_number, void* handler) { | |
2180 struct sigaction sigAct, oldSigAct; | |
2181 | |
2182 sigfillset(&(sigAct.sa_mask)); | |
2183 sigAct.sa_flags = SA_RESTART|SA_SIGINFO; | |
2184 sigAct.sa_handler = CAST_TO_FN_PTR(sa_handler_t, handler); | |
2185 | |
2186 if (sigaction(signal_number, &sigAct, &oldSigAct)) { | |
2187 // -1 means registration failed | |
2188 return (void *)-1; | |
2189 } | |
2190 | |
2191 return CAST_FROM_FN_PTR(void*, oldSigAct.sa_handler); | |
2192 } | |
2193 | |
2194 void os::signal_raise(int signal_number) { | |
2195 ::raise(signal_number); | |
2196 } | |
2197 | |
2198 /* | |
2199 * The following code is moved from os.cpp for making this | |
2200 * code platform specific, which it is by its very nature. | |
2201 */ | |
2202 | |
2203 // Will be modified when max signal is changed to be dynamic | |
2204 int os::sigexitnum_pd() { | |
2205 return NSIG; | |
2206 } | |
2207 | |
2208 // a counter for each possible signal value | |
2209 static volatile jint pending_signals[NSIG+1] = { 0 }; | |
2210 | |
2211 // Linux(POSIX) specific hand shaking semaphore. | |
2212 static sem_t sig_sem; | |
2213 | |
2214 void os::signal_init_pd() { | |
2215 // Initialize signal structures | |
2216 ::memset((void*)pending_signals, 0, sizeof(pending_signals)); | |
2217 | |
2218 // Initialize signal semaphore | |
2219 ::sem_init(&sig_sem, 0, 0); | |
2220 } | |
2221 | |
2222 void os::signal_notify(int sig) { | |
2223 Atomic::inc(&pending_signals[sig]); | |
2224 ::sem_post(&sig_sem); | |
2225 } | |
2226 | |
2227 static int check_pending_signals(bool wait) { | |
2228 Atomic::store(0, &sigint_count); | |
2229 for (;;) { | |
2230 for (int i = 0; i < NSIG + 1; i++) { | |
2231 jint n = pending_signals[i]; | |
2232 if (n > 0 && n == Atomic::cmpxchg(n - 1, &pending_signals[i], n)) { | |
2233 return i; | |
2234 } | |
2235 } | |
2236 if (!wait) { | |
2237 return -1; | |
2238 } | |
2239 JavaThread *thread = JavaThread::current(); | |
2240 ThreadBlockInVM tbivm(thread); | |
2241 | |
2242 bool threadIsSuspended; | |
2243 do { | |
2244 thread->set_suspend_equivalent(); | |
2245 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() | |
2246 ::sem_wait(&sig_sem); | |
2247 | |
2248 // were we externally suspended while we were waiting? | |
2249 threadIsSuspended = thread->handle_special_suspend_equivalent_condition(); | |
2250 if (threadIsSuspended) { | |
2251 // | |
2252 // The semaphore has been incremented, but while we were waiting | |
2253 // another thread suspended us. We don't want to continue running | |
2254 // while suspended because that would surprise the thread that | |
2255 // suspended us. | |
2256 // | |
2257 ::sem_post(&sig_sem); | |
2258 | |
2259 thread->java_suspend_self(); | |
2260 } | |
2261 } while (threadIsSuspended); | |
2262 } | |
2263 } | |
2264 | |
2265 int os::signal_lookup() { | |
2266 return check_pending_signals(false); | |
2267 } | |
2268 | |
2269 int os::signal_wait() { | |
2270 return check_pending_signals(true); | |
2271 } | |
2272 | |
2273 //////////////////////////////////////////////////////////////////////////////// | |
2274 // Virtual Memory | |
2275 | |
2276 int os::vm_page_size() { | |
2277 // Seems redundant as all get out | |
2278 assert(os::Linux::page_size() != -1, "must call os::init"); | |
2279 return os::Linux::page_size(); | |
2280 } | |
2281 | |
2282 // Solaris allocates memory by pages. | |
2283 int os::vm_allocation_granularity() { | |
2284 assert(os::Linux::page_size() != -1, "must call os::init"); | |
2285 return os::Linux::page_size(); | |
2286 } | |
2287 | |
2288 // Rationale behind this function: | |
2289 // current (Mon Apr 25 20:12:18 MSD 2005) oprofile drops samples without executable | |
2290 // mapping for address (see lookup_dcookie() in the kernel module), thus we cannot get | |
2291 // samples for JITted code. Here we create private executable mapping over the code cache | |
2292 // and then we can use standard (well, almost, as mapping can change) way to provide | |
2293 // info for the reporting script by storing timestamp and location of symbol | |
2294 void linux_wrap_code(char* base, size_t size) { | |
2295 static volatile jint cnt = 0; | |
2296 | |
2297 if (!UseOprofile) { | |
2298 return; | |
2299 } | |
2300 | |
2301 char buf[40]; | |
2302 int num = Atomic::add(1, &cnt); | |
2303 | |
2304 sprintf(buf, "/tmp/hs-vm-%d-%d", os::current_process_id(), num); | |
2305 unlink(buf); | |
2306 | |
2307 int fd = open(buf, O_CREAT | O_RDWR, S_IRWXU); | |
2308 | |
2309 if (fd != -1) { | |
2310 off_t rv = lseek(fd, size-2, SEEK_SET); | |
2311 if (rv != (off_t)-1) { | |
2312 if (write(fd, "", 1) == 1) { | |
2313 mmap(base, size, | |
2314 PROT_READ|PROT_WRITE|PROT_EXEC, | |
2315 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE, fd, 0); | |
2316 } | |
2317 } | |
2318 close(fd); | |
2319 unlink(buf); | |
2320 } | |
2321 } | |
2322 | |
2323 // NOTE: Linux kernel does not really reserve the pages for us. | |
2324 // All it does is to check if there are enough free pages | |
2325 // left at the time of mmap(). This could be a potential | |
2326 // problem. | |
656 | 2327 bool os::commit_memory(char* addr, size_t size, bool exec) { |
2328 int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE; | |
2329 uintptr_t res = (uintptr_t) ::mmap(addr, size, prot, | |
0 | 2330 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); |
2331 return res != (uintptr_t) MAP_FAILED; | |
2332 } | |
2333 | |
656 | 2334 bool os::commit_memory(char* addr, size_t size, size_t alignment_hint, |
2335 bool exec) { | |
2336 return commit_memory(addr, size, exec); | |
0 | 2337 } |
2338 | |
2339 void os::realign_memory(char *addr, size_t bytes, size_t alignment_hint) { } | |
141 | 2340 |
2341 void os::free_memory(char *addr, size_t bytes) { | |
761
622212a69394
6838842: NUMA allocator: Segfault during startup on Linux
iveresov
parents:
691
diff
changeset
|
2342 ::mmap(addr, bytes, PROT_READ | PROT_WRITE, |
622212a69394
6838842: NUMA allocator: Segfault during startup on Linux
iveresov
parents:
691
diff
changeset
|
2343 MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0); |
141 | 2344 } |
2345 | |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2346 void os::numa_make_global(char *addr, size_t bytes) { |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2347 Linux::numa_interleave_memory(addr, bytes); |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2348 } |
141 | 2349 |
2350 void os::numa_make_local(char *addr, size_t bytes, int lgrp_hint) { | |
2351 Linux::numa_tonode_memory(addr, bytes, lgrp_hint); | |
2352 } | |
2353 | |
2354 bool os::numa_topology_changed() { return false; } | |
2355 | |
2356 size_t os::numa_get_groups_num() { | |
2357 int max_node = Linux::numa_max_node(); | |
2358 return max_node > 0 ? max_node + 1 : 1; | |
2359 } | |
2360 | |
2361 int os::numa_get_group_id() { | |
2362 int cpu_id = Linux::sched_getcpu(); | |
2363 if (cpu_id != -1) { | |
2364 int lgrp_id = Linux::get_node_by_cpu(cpu_id); | |
2365 if (lgrp_id != -1) { | |
2366 return lgrp_id; | |
2367 } | |
0 | 2368 } |
2369 return 0; | |
2370 } | |
2371 | |
141 | 2372 size_t os::numa_get_leaf_groups(int *ids, size_t size) { |
2373 for (size_t i = 0; i < size; i++) { | |
2374 ids[i] = i; | |
2375 } | |
2376 return size; | |
2377 } | |
2378 | |
0 | 2379 bool os::get_page_info(char *start, page_info* info) { |
2380 return false; | |
2381 } | |
2382 | |
2383 char *os::scan_pages(char *start, char* end, page_info* page_expected, page_info* page_found) { | |
2384 return end; | |
2385 } | |
2386 | |
141 | 2387 extern "C" void numa_warn(int number, char *where, ...) { } |
2388 extern "C" void numa_error(char *where) { } | |
2389 | |
763
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2390 |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2391 // If we are running with libnuma version > 2, then we should |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2392 // be trying to use symbols with versions 1.1 |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2393 // If we are running with earlier version, which did not have symbol versions, |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2394 // we should use the base version. |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2395 void* os::Linux::libnuma_dlsym(void* handle, const char *name) { |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2396 void *f = dlvsym(handle, name, "libnuma_1.1"); |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2397 if (f == NULL) { |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2398 f = dlsym(handle, name); |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2399 } |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2400 return f; |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2401 } |
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2402 |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2403 bool os::Linux::libnuma_init() { |
141 | 2404 // sched_getcpu() should be in libc. |
2405 set_sched_getcpu(CAST_TO_FN_PTR(sched_getcpu_func_t, | |
2406 dlsym(RTLD_DEFAULT, "sched_getcpu"))); | |
2407 | |
2408 if (sched_getcpu() != -1) { // Does it work? | |
267
9d6a3a6891f8
6720130: NUMA allocator: The linux version should search for libnuma.so.1
iveresov
parents:
199
diff
changeset
|
2409 void *handle = dlopen("libnuma.so.1", RTLD_LAZY); |
141 | 2410 if (handle != NULL) { |
2411 set_numa_node_to_cpus(CAST_TO_FN_PTR(numa_node_to_cpus_func_t, | |
763
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2412 libnuma_dlsym(handle, "numa_node_to_cpus"))); |
141 | 2413 set_numa_max_node(CAST_TO_FN_PTR(numa_max_node_func_t, |
763
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2414 libnuma_dlsym(handle, "numa_max_node"))); |
141 | 2415 set_numa_available(CAST_TO_FN_PTR(numa_available_func_t, |
763
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2416 libnuma_dlsym(handle, "numa_available"))); |
141 | 2417 set_numa_tonode_memory(CAST_TO_FN_PTR(numa_tonode_memory_func_t, |
763
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2418 libnuma_dlsym(handle, "numa_tonode_memory"))); |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2419 set_numa_interleave_memory(CAST_TO_FN_PTR(numa_interleave_memory_func_t, |
763
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2420 libnuma_dlsym(handle, "numa_interleave_memory"))); |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2421 |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2422 |
141 | 2423 if (numa_available() != -1) { |
763
cf71f149d7ae
6840196: NUMA allocator: crash in fastdebug during startup on Linux
iveresov
parents:
761
diff
changeset
|
2424 set_numa_all_nodes((unsigned long*)libnuma_dlsym(handle, "numa_all_nodes")); |
141 | 2425 // Create a cpu -> node mapping |
2426 _cpu_to_node = new (ResourceObj::C_HEAP) GrowableArray<int>(0, true); | |
2427 rebuild_cpu_to_node_map(); | |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2428 return true; |
141 | 2429 } |
2430 } | |
2431 } | |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2432 return false; |
141 | 2433 } |
2434 | |
2435 // rebuild_cpu_to_node_map() constructs a table mapping cpud id to node id. | |
2436 // The table is later used in get_node_by_cpu(). | |
2437 void os::Linux::rebuild_cpu_to_node_map() { | |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2438 const size_t NCPUS = 32768; // Since the buffer size computation is very obscure |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2439 // in libnuma (possible values are starting from 16, |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2440 // and continuing up with every other power of 2, but less |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2441 // than the maximum number of CPUs supported by kernel), and |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2442 // is a subject to change (in libnuma version 2 the requirements |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2443 // are more reasonable) we'll just hardcode the number they use |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2444 // in the library. |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2445 const size_t BitsPerCLong = sizeof(long) * CHAR_BIT; |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2446 |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2447 size_t cpu_num = os::active_processor_count(); |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2448 size_t cpu_map_size = NCPUS / BitsPerCLong; |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2449 size_t cpu_map_valid_size = |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2450 MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size); |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2451 |
141 | 2452 cpu_to_node()->clear(); |
2453 cpu_to_node()->at_grow(cpu_num - 1); | |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2454 size_t node_num = numa_get_groups_num(); |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2455 |
141 | 2456 unsigned long *cpu_map = NEW_C_HEAP_ARRAY(unsigned long, cpu_map_size); |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2457 for (size_t i = 0; i < node_num; i++) { |
141 | 2458 if (numa_node_to_cpus(i, cpu_map, cpu_map_size * sizeof(unsigned long)) != -1) { |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2459 for (size_t j = 0; j < cpu_map_valid_size; j++) { |
141 | 2460 if (cpu_map[j] != 0) { |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2461 for (size_t k = 0; k < BitsPerCLong; k++) { |
141 | 2462 if (cpu_map[j] & (1UL << k)) { |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2463 cpu_to_node()->at_put(j * BitsPerCLong + k, i); |
141 | 2464 } |
2465 } | |
2466 } | |
2467 } | |
2468 } | |
2469 } | |
2470 FREE_C_HEAP_ARRAY(unsigned long, cpu_map); | |
2471 } | |
2472 | |
2473 int os::Linux::get_node_by_cpu(int cpu_id) { | |
2474 if (cpu_to_node() != NULL && cpu_id >= 0 && cpu_id < cpu_to_node()->length()) { | |
2475 return cpu_to_node()->at(cpu_id); | |
2476 } | |
2477 return -1; | |
2478 } | |
2479 | |
2480 GrowableArray<int>* os::Linux::_cpu_to_node; | |
2481 os::Linux::sched_getcpu_func_t os::Linux::_sched_getcpu; | |
2482 os::Linux::numa_node_to_cpus_func_t os::Linux::_numa_node_to_cpus; | |
2483 os::Linux::numa_max_node_func_t os::Linux::_numa_max_node; | |
2484 os::Linux::numa_available_func_t os::Linux::_numa_available; | |
2485 os::Linux::numa_tonode_memory_func_t os::Linux::_numa_tonode_memory; | |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2486 os::Linux::numa_interleave_memory_func_t os::Linux::_numa_interleave_memory; |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
2487 unsigned long* os::Linux::_numa_all_nodes; |
141 | 2488 |
0 | 2489 bool os::uncommit_memory(char* addr, size_t size) { |
656 | 2490 return ::mmap(addr, size, PROT_NONE, |
0 | 2491 MAP_PRIVATE|MAP_FIXED|MAP_NORESERVE|MAP_ANONYMOUS, -1, 0) |
2492 != MAP_FAILED; | |
2493 } | |
2494 | |
2495 static address _highest_vm_reserved_address = NULL; | |
2496 | |
2497 // If 'fixed' is true, anon_mmap() will attempt to reserve anonymous memory | |
2498 // at 'requested_addr'. If there are existing memory mappings at the same | |
2499 // location, however, they will be overwritten. If 'fixed' is false, | |
2500 // 'requested_addr' is only treated as a hint, the return value may or | |
2501 // may not start from the requested address. Unlike Linux mmap(), this | |
2502 // function returns NULL to indicate failure. | |
2503 static char* anon_mmap(char* requested_addr, size_t bytes, bool fixed) { | |
2504 char * addr; | |
2505 int flags; | |
2506 | |
2507 flags = MAP_PRIVATE | MAP_NORESERVE | MAP_ANONYMOUS; | |
2508 if (fixed) { | |
2509 assert((uintptr_t)requested_addr % os::Linux::page_size() == 0, "unaligned address"); | |
2510 flags |= MAP_FIXED; | |
2511 } | |
2512 | |
656 | 2513 // Map uncommitted pages PROT_READ and PROT_WRITE, change access |
2514 // to PROT_EXEC if executable when we commit the page. | |
2515 addr = (char*)::mmap(requested_addr, bytes, PROT_READ|PROT_WRITE, | |
0 | 2516 flags, -1, 0); |
2517 | |
2518 if (addr != MAP_FAILED) { | |
2519 // anon_mmap() should only get called during VM initialization, | |
2520 // don't need lock (actually we can skip locking even it can be called | |
2521 // from multiple threads, because _highest_vm_reserved_address is just a | |
2522 // hint about the upper limit of non-stack memory regions.) | |
2523 if ((address)addr + bytes > _highest_vm_reserved_address) { | |
2524 _highest_vm_reserved_address = (address)addr + bytes; | |
2525 } | |
2526 } | |
2527 | |
2528 return addr == MAP_FAILED ? NULL : addr; | |
2529 } | |
2530 | |
2531 // Don't update _highest_vm_reserved_address, because there might be memory | |
2532 // regions above addr + size. If so, releasing a memory region only creates | |
2533 // a hole in the address space, it doesn't help prevent heap-stack collision. | |
2534 // | |
2535 static int anon_munmap(char * addr, size_t size) { | |
2536 return ::munmap(addr, size) == 0; | |
2537 } | |
2538 | |
2539 char* os::reserve_memory(size_t bytes, char* requested_addr, | |
2540 size_t alignment_hint) { | |
2541 return anon_mmap(requested_addr, bytes, (requested_addr != NULL)); | |
2542 } | |
2543 | |
2544 bool os::release_memory(char* addr, size_t size) { | |
2545 return anon_munmap(addr, size); | |
2546 } | |
2547 | |
2548 static address highest_vm_reserved_address() { | |
2549 return _highest_vm_reserved_address; | |
2550 } | |
2551 | |
2552 static bool linux_mprotect(char* addr, size_t size, int prot) { | |
2553 // Linux wants the mprotect address argument to be page aligned. | |
2554 char* bottom = (char*)align_size_down((intptr_t)addr, os::Linux::page_size()); | |
2555 | |
2556 // According to SUSv3, mprotect() should only be used with mappings | |
2557 // established by mmap(), and mmap() always maps whole pages. Unaligned | |
2558 // 'addr' likely indicates problem in the VM (e.g. trying to change | |
2559 // protection of malloc'ed or statically allocated memory). Check the | |
2560 // caller if you hit this assert. | |
2561 assert(addr == bottom, "sanity check"); | |
2562 | |
2563 size = align_size_up(pointer_delta(addr, bottom, 1) + size, os::Linux::page_size()); | |
2564 return ::mprotect(bottom, size, prot) == 0; | |
2565 } | |
2566 | |
237
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2567 // Set protections specified |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2568 bool os::protect_memory(char* addr, size_t bytes, ProtType prot, |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2569 bool is_committed) { |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2570 unsigned int p = 0; |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2571 switch (prot) { |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2572 case MEM_PROT_NONE: p = PROT_NONE; break; |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2573 case MEM_PROT_READ: p = PROT_READ; break; |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2574 case MEM_PROT_RW: p = PROT_READ|PROT_WRITE; break; |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2575 case MEM_PROT_RWX: p = PROT_READ|PROT_WRITE|PROT_EXEC; break; |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2576 default: |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2577 ShouldNotReachHere(); |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2578 } |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2579 // is_committed is unused. |
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
2580 return linux_mprotect(addr, bytes, p); |
0 | 2581 } |
2582 | |
2583 bool os::guard_memory(char* addr, size_t size) { | |
2584 return linux_mprotect(addr, size, PROT_NONE); | |
2585 } | |
2586 | |
2587 bool os::unguard_memory(char* addr, size_t size) { | |
477
24fda36852ce
6727377: VM stack guard pages on Windows should PAGE_READWRITE not PAGE_EXECUTE_READWRITE
coleenp
parents:
462
diff
changeset
|
2588 return linux_mprotect(addr, size, PROT_READ|PROT_WRITE); |
0 | 2589 } |
2590 | |
2591 // Large page support | |
2592 | |
2593 static size_t _large_page_size = 0; | |
2594 | |
2595 bool os::large_page_init() { | |
2596 if (!UseLargePages) return false; | |
2597 | |
2598 if (LargePageSizeInBytes) { | |
2599 _large_page_size = LargePageSizeInBytes; | |
2600 } else { | |
2601 // large_page_size on Linux is used to round up heap size. x86 uses either | |
2602 // 2M or 4M page, depending on whether PAE (Physical Address Extensions) | |
2603 // mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. IA64 can use | |
2604 // page as large as 256M. | |
2605 // | |
2606 // Here we try to figure out page size by parsing /proc/meminfo and looking | |
2607 // for a line with the following format: | |
2608 // Hugepagesize: 2048 kB | |
2609 // | |
2610 // If we can't determine the value (e.g. /proc is not mounted, or the text | |
2611 // format has been changed), we'll use the largest page size supported by | |
2612 // the processor. | |
2613 | |
1010 | 2614 #ifndef ZERO |
0 | 2615 _large_page_size = IA32_ONLY(4 * M) AMD64_ONLY(2 * M) IA64_ONLY(256 * M) SPARC_ONLY(4 * M); |
1010 | 2616 #endif // ZERO |
0 | 2617 |
2618 FILE *fp = fopen("/proc/meminfo", "r"); | |
2619 if (fp) { | |
2620 while (!feof(fp)) { | |
2621 int x = 0; | |
2622 char buf[16]; | |
2623 if (fscanf(fp, "Hugepagesize: %d", &x) == 1) { | |
2624 if (x && fgets(buf, sizeof(buf), fp) && strcmp(buf, " kB\n") == 0) { | |
2625 _large_page_size = x * K; | |
2626 break; | |
2627 } | |
2628 } else { | |
2629 // skip to next line | |
2630 for (;;) { | |
2631 int ch = fgetc(fp); | |
2632 if (ch == EOF || ch == (int)'\n') break; | |
2633 } | |
2634 } | |
2635 } | |
2636 fclose(fp); | |
2637 } | |
2638 } | |
2639 | |
2640 const size_t default_page_size = (size_t)Linux::page_size(); | |
2641 if (_large_page_size > default_page_size) { | |
2642 _page_sizes[0] = _large_page_size; | |
2643 _page_sizes[1] = default_page_size; | |
2644 _page_sizes[2] = 0; | |
2645 } | |
2646 | |
2647 // Large page support is available on 2.6 or newer kernel, some vendors | |
2648 // (e.g. Redhat) have backported it to their 2.4 based distributions. | |
2649 // We optimistically assume the support is available. If later it turns out | |
2650 // not true, VM will automatically switch to use regular page size. | |
2651 return true; | |
2652 } | |
2653 | |
2654 #ifndef SHM_HUGETLB | |
2655 #define SHM_HUGETLB 04000 | |
2656 #endif | |
2657 | |
656 | 2658 char* os::reserve_memory_special(size_t bytes, char* req_addr, bool exec) { |
2659 // "exec" is passed in but not used. Creating the shared image for | |
2660 // the code cache doesn't have an SHM_X executable permission to check. | |
0 | 2661 assert(UseLargePages, "only for large pages"); |
2662 | |
2663 key_t key = IPC_PRIVATE; | |
2664 char *addr; | |
2665 | |
2666 bool warn_on_failure = UseLargePages && | |
2667 (!FLAG_IS_DEFAULT(UseLargePages) || | |
2668 !FLAG_IS_DEFAULT(LargePageSizeInBytes) | |
2669 ); | |
2670 char msg[128]; | |
2671 | |
2672 // Create a large shared memory region to attach to based on size. | |
2673 // Currently, size is the total size of the heap | |
2674 int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W); | |
2675 if (shmid == -1) { | |
2676 // Possible reasons for shmget failure: | |
2677 // 1. shmmax is too small for Java heap. | |
2678 // > check shmmax value: cat /proc/sys/kernel/shmmax | |
2679 // > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax | |
2680 // 2. not enough large page memory. | |
2681 // > check available large pages: cat /proc/meminfo | |
2682 // > increase amount of large pages: | |
2683 // echo new_value > /proc/sys/vm/nr_hugepages | |
2684 // Note 1: different Linux may use different name for this property, | |
2685 // e.g. on Redhat AS-3 it is "hugetlb_pool". | |
2686 // Note 2: it's possible there's enough physical memory available but | |
2687 // they are so fragmented after a long run that they can't | |
2688 // coalesce into large pages. Try to reserve large pages when | |
2689 // the system is still "fresh". | |
2690 if (warn_on_failure) { | |
2691 jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno); | |
2692 warning(msg); | |
2693 } | |
2694 return NULL; | |
2695 } | |
2696 | |
2697 // attach to the region | |
2698 addr = (char*)shmat(shmid, NULL, 0); | |
2699 int err = errno; | |
2700 | |
2701 // Remove shmid. If shmat() is successful, the actual shared memory segment | |
2702 // will be deleted when it's detached by shmdt() or when the process | |
2703 // terminates. If shmat() is not successful this will remove the shared | |
2704 // segment immediately. | |
2705 shmctl(shmid, IPC_RMID, NULL); | |
2706 | |
2707 if ((intptr_t)addr == -1) { | |
2708 if (warn_on_failure) { | |
2709 jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err); | |
2710 warning(msg); | |
2711 } | |
2712 return NULL; | |
2713 } | |
2714 | |
2715 return addr; | |
2716 } | |
2717 | |
2718 bool os::release_memory_special(char* base, size_t bytes) { | |
2719 // detaching the SHM segment will also delete it, see reserve_memory_special() | |
2720 int rslt = shmdt(base); | |
2721 return rslt == 0; | |
2722 } | |
2723 | |
2724 size_t os::large_page_size() { | |
2725 return _large_page_size; | |
2726 } | |
2727 | |
2728 // Linux does not support anonymous mmap with large page memory. The only way | |
2729 // to reserve large page memory without file backing is through SysV shared | |
2730 // memory API. The entire memory region is committed and pinned upfront. | |
2731 // Hopefully this will change in the future... | |
2732 bool os::can_commit_large_page_memory() { | |
2733 return false; | |
2734 } | |
2735 | |
79
82db0859acbe
6642862: Code cache allocation fails with large pages after 6588638
jcoomes
parents:
62
diff
changeset
|
2736 bool os::can_execute_large_page_memory() { |
82db0859acbe
6642862: Code cache allocation fails with large pages after 6588638
jcoomes
parents:
62
diff
changeset
|
2737 return false; |
82db0859acbe
6642862: Code cache allocation fails with large pages after 6588638
jcoomes
parents:
62
diff
changeset
|
2738 } |
82db0859acbe
6642862: Code cache allocation fails with large pages after 6588638
jcoomes
parents:
62
diff
changeset
|
2739 |
0 | 2740 // Reserve memory at an arbitrary address, only if that area is |
2741 // available (and not reserved for something else). | |
2742 | |
2743 char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) { | |
2744 const int max_tries = 10; | |
2745 char* base[max_tries]; | |
2746 size_t size[max_tries]; | |
2747 const size_t gap = 0x000000; | |
2748 | |
2749 // Assert only that the size is a multiple of the page size, since | |
2750 // that's all that mmap requires, and since that's all we really know | |
2751 // about at this low abstraction level. If we need higher alignment, | |
2752 // we can either pass an alignment to this method or verify alignment | |
2753 // in one of the methods further up the call chain. See bug 5044738. | |
2754 assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); | |
2755 | |
2756 // Repeatedly allocate blocks until the block is allocated at the | |
2757 // right spot. Give up after max_tries. Note that reserve_memory() will | |
2758 // automatically update _highest_vm_reserved_address if the call is | |
2759 // successful. The variable tracks the highest memory address every reserved | |
2760 // by JVM. It is used to detect heap-stack collision if running with | |
2761 // fixed-stack LinuxThreads. Because here we may attempt to reserve more | |
2762 // space than needed, it could confuse the collision detecting code. To | |
2763 // solve the problem, save current _highest_vm_reserved_address and | |
2764 // calculate the correct value before return. | |
2765 address old_highest = _highest_vm_reserved_address; | |
2766 | |
2767 // Linux mmap allows caller to pass an address as hint; give it a try first, | |
2768 // if kernel honors the hint then we can return immediately. | |
2769 char * addr = anon_mmap(requested_addr, bytes, false); | |
2770 if (addr == requested_addr) { | |
2771 return requested_addr; | |
2772 } | |
2773 | |
2774 if (addr != NULL) { | |
2775 // mmap() is successful but it fails to reserve at the requested address | |
2776 anon_munmap(addr, bytes); | |
2777 } | |
2778 | |
2779 int i; | |
2780 for (i = 0; i < max_tries; ++i) { | |
2781 base[i] = reserve_memory(bytes); | |
2782 | |
2783 if (base[i] != NULL) { | |
2784 // Is this the block we wanted? | |
2785 if (base[i] == requested_addr) { | |
2786 size[i] = bytes; | |
2787 break; | |
2788 } | |
2789 | |
2790 // Does this overlap the block we wanted? Give back the overlapped | |
2791 // parts and try again. | |
2792 | |
2793 size_t top_overlap = requested_addr + (bytes + gap) - base[i]; | |
2794 if (top_overlap >= 0 && top_overlap < bytes) { | |
2795 unmap_memory(base[i], top_overlap); | |
2796 base[i] += top_overlap; | |
2797 size[i] = bytes - top_overlap; | |
2798 } else { | |
2799 size_t bottom_overlap = base[i] + bytes - requested_addr; | |
2800 if (bottom_overlap >= 0 && bottom_overlap < bytes) { | |
2801 unmap_memory(requested_addr, bottom_overlap); | |
2802 size[i] = bytes - bottom_overlap; | |
2803 } else { | |
2804 size[i] = bytes; | |
2805 } | |
2806 } | |
2807 } | |
2808 } | |
2809 | |
2810 // Give back the unused reserved pieces. | |
2811 | |
2812 for (int j = 0; j < i; ++j) { | |
2813 if (base[j] != NULL) { | |
2814 unmap_memory(base[j], size[j]); | |
2815 } | |
2816 } | |
2817 | |
2818 if (i < max_tries) { | |
2819 _highest_vm_reserved_address = MAX2(old_highest, (address)requested_addr + bytes); | |
2820 return requested_addr; | |
2821 } else { | |
2822 _highest_vm_reserved_address = old_highest; | |
2823 return NULL; | |
2824 } | |
2825 } | |
2826 | |
2827 size_t os::read(int fd, void *buf, unsigned int nBytes) { | |
2828 return ::read(fd, buf, nBytes); | |
2829 } | |
2830 | |
2831 // TODO-FIXME: reconcile Solaris' os::sleep with the linux variation. | |
2832 // Solaris uses poll(), linux uses park(). | |
2833 // Poll() is likely a better choice, assuming that Thread.interrupt() | |
2834 // generates a SIGUSRx signal. Note that SIGUSR1 can interfere with | |
2835 // SIGSEGV, see 4355769. | |
2836 | |
2837 const int NANOSECS_PER_MILLISECS = 1000000; | |
2838 | |
2839 int os::sleep(Thread* thread, jlong millis, bool interruptible) { | |
2840 assert(thread == Thread::current(), "thread consistency check"); | |
2841 | |
2842 ParkEvent * const slp = thread->_SleepEvent ; | |
2843 slp->reset() ; | |
2844 OrderAccess::fence() ; | |
2845 | |
2846 if (interruptible) { | |
2847 jlong prevtime = javaTimeNanos(); | |
2848 | |
2849 for (;;) { | |
2850 if (os::is_interrupted(thread, true)) { | |
2851 return OS_INTRPT; | |
2852 } | |
2853 | |
2854 jlong newtime = javaTimeNanos(); | |
2855 | |
2856 if (newtime - prevtime < 0) { | |
2857 // time moving backwards, should only happen if no monotonic clock | |
2858 // not a guarantee() because JVM should not abort on kernel/glibc bugs | |
2859 assert(!Linux::supports_monotonic_clock(), "time moving backwards"); | |
2860 } else { | |
2861 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISECS; | |
2862 } | |
2863 | |
2864 if(millis <= 0) { | |
2865 return OS_OK; | |
2866 } | |
2867 | |
2868 prevtime = newtime; | |
2869 | |
2870 { | |
2871 assert(thread->is_Java_thread(), "sanity check"); | |
2872 JavaThread *jt = (JavaThread *) thread; | |
2873 ThreadBlockInVM tbivm(jt); | |
2874 OSThreadWaitState osts(jt->osthread(), false /* not Object.wait() */); | |
2875 | |
2876 jt->set_suspend_equivalent(); | |
2877 // cleared by handle_special_suspend_equivalent_condition() or | |
2878 // java_suspend_self() via check_and_wait_while_suspended() | |
2879 | |
2880 slp->park(millis); | |
2881 | |
2882 // were we externally suspended while we were waiting? | |
2883 jt->check_and_wait_while_suspended(); | |
2884 } | |
2885 } | |
2886 } else { | |
2887 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); | |
2888 jlong prevtime = javaTimeNanos(); | |
2889 | |
2890 for (;;) { | |
2891 // It'd be nice to avoid the back-to-back javaTimeNanos() calls on | |
2892 // the 1st iteration ... | |
2893 jlong newtime = javaTimeNanos(); | |
2894 | |
2895 if (newtime - prevtime < 0) { | |
2896 // time moving backwards, should only happen if no monotonic clock | |
2897 // not a guarantee() because JVM should not abort on kernel/glibc bugs | |
2898 assert(!Linux::supports_monotonic_clock(), "time moving backwards"); | |
2899 } else { | |
2900 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISECS; | |
2901 } | |
2902 | |
2903 if(millis <= 0) break ; | |
2904 | |
2905 prevtime = newtime; | |
2906 slp->park(millis); | |
2907 } | |
2908 return OS_OK ; | |
2909 } | |
2910 } | |
2911 | |
2912 int os::naked_sleep() { | |
2913 // %% make the sleep time an integer flag. for now use 1 millisec. | |
2914 return os::sleep(Thread::current(), 1, false); | |
2915 } | |
2916 | |
2917 // Sleep forever; naked call to OS-specific sleep; use with CAUTION | |
2918 void os::infinite_sleep() { | |
2919 while (true) { // sleep forever ... | |
2920 ::sleep(100); // ... 100 seconds at a time | |
2921 } | |
2922 } | |
2923 | |
2924 // Used to convert frequent JVM_Yield() to nops | |
2925 bool os::dont_yield() { | |
2926 return DontYieldALot; | |
2927 } | |
2928 | |
2929 void os::yield() { | |
2930 sched_yield(); | |
2931 } | |
2932 | |
2933 os::YieldResult os::NakedYield() { sched_yield(); return os::YIELD_UNKNOWN ;} | |
2934 | |
2935 void os::yield_all(int attempts) { | |
2936 // Yields to all threads, including threads with lower priorities | |
2937 // Threads on Linux are all with same priority. The Solaris style | |
2938 // os::yield_all() with nanosleep(1ms) is not necessary. | |
2939 sched_yield(); | |
2940 } | |
2941 | |
2942 // Called from the tight loops to possibly influence time-sharing heuristics | |
2943 void os::loop_breaker(int attempts) { | |
2944 os::yield_all(attempts); | |
2945 } | |
2946 | |
2947 //////////////////////////////////////////////////////////////////////////////// | |
2948 // thread priority support | |
2949 | |
2950 // Note: Normal Linux applications are run with SCHED_OTHER policy. SCHED_OTHER | |
2951 // only supports dynamic priority, static priority must be zero. For real-time | |
2952 // applications, Linux supports SCHED_RR which allows static priority (1-99). | |
2953 // However, for large multi-threaded applications, SCHED_RR is not only slower | |
2954 // than SCHED_OTHER, but also very unstable (my volano tests hang hard 4 out | |
2955 // of 5 runs - Sep 2005). | |
2956 // | |
2957 // The following code actually changes the niceness of kernel-thread/LWP. It | |
2958 // has an assumption that setpriority() only modifies one kernel-thread/LWP, | |
2959 // not the entire user process, and user level threads are 1:1 mapped to kernel | |
2960 // threads. It has always been the case, but could change in the future. For | |
2961 // this reason, the code should not be used as default (ThreadPriorityPolicy=0). | |
2962 // It is only used when ThreadPriorityPolicy=1 and requires root privilege. | |
2963 | |
2964 int os::java_to_os_priority[MaxPriority + 1] = { | |
2965 19, // 0 Entry should never be used | |
2966 | |
2967 4, // 1 MinPriority | |
2968 3, // 2 | |
2969 2, // 3 | |
2970 | |
2971 1, // 4 | |
2972 0, // 5 NormPriority | |
2973 -1, // 6 | |
2974 | |
2975 -2, // 7 | |
2976 -3, // 8 | |
2977 -4, // 9 NearMaxPriority | |
2978 | |
2979 -5 // 10 MaxPriority | |
2980 }; | |
2981 | |
2982 static int prio_init() { | |
2983 if (ThreadPriorityPolicy == 1) { | |
2984 // Only root can raise thread priority. Don't allow ThreadPriorityPolicy=1 | |
2985 // if effective uid is not root. Perhaps, a more elegant way of doing | |
2986 // this is to test CAP_SYS_NICE capability, but that will require libcap.so | |
2987 if (geteuid() != 0) { | |
2988 if (!FLAG_IS_DEFAULT(ThreadPriorityPolicy)) { | |
2989 warning("-XX:ThreadPriorityPolicy requires root privilege on Linux"); | |
2990 } | |
2991 ThreadPriorityPolicy = 0; | |
2992 } | |
2993 } | |
2994 return 0; | |
2995 } | |
2996 | |
2997 OSReturn os::set_native_priority(Thread* thread, int newpri) { | |
2998 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) return OS_OK; | |
2999 | |
3000 int ret = setpriority(PRIO_PROCESS, thread->osthread()->thread_id(), newpri); | |
3001 return (ret == 0) ? OS_OK : OS_ERR; | |
3002 } | |
3003 | |
3004 OSReturn os::get_native_priority(const Thread* const thread, int *priority_ptr) { | |
3005 if ( !UseThreadPriorities || ThreadPriorityPolicy == 0 ) { | |
3006 *priority_ptr = java_to_os_priority[NormPriority]; | |
3007 return OS_OK; | |
3008 } | |
3009 | |
3010 errno = 0; | |
3011 *priority_ptr = getpriority(PRIO_PROCESS, thread->osthread()->thread_id()); | |
3012 return (*priority_ptr != -1 || errno == 0 ? OS_OK : OS_ERR); | |
3013 } | |
3014 | |
3015 // Hint to the underlying OS that a task switch would not be good. | |
3016 // Void return because it's a hint and can fail. | |
3017 void os::hint_no_preempt() {} | |
3018 | |
3019 //////////////////////////////////////////////////////////////////////////////// | |
3020 // suspend/resume support | |
3021 | |
3022 // the low-level signal-based suspend/resume support is a remnant from the | |
3023 // old VM-suspension that used to be for java-suspension, safepoints etc, | |
3024 // within hotspot. Now there is a single use-case for this: | |
3025 // - calling get_thread_pc() on the VMThread by the flat-profiler task | |
3026 // that runs in the watcher thread. | |
3027 // The remaining code is greatly simplified from the more general suspension | |
3028 // code that used to be used. | |
3029 // | |
3030 // The protocol is quite simple: | |
3031 // - suspend: | |
3032 // - sends a signal to the target thread | |
3033 // - polls the suspend state of the osthread using a yield loop | |
3034 // - target thread signal handler (SR_handler) sets suspend state | |
3035 // and blocks in sigsuspend until continued | |
3036 // - resume: | |
3037 // - sets target osthread state to continue | |
3038 // - sends signal to end the sigsuspend loop in the SR_handler | |
3039 // | |
3040 // Note that the SR_lock plays no role in this suspend/resume protocol. | |
3041 // | |
3042 | |
3043 static void resume_clear_context(OSThread *osthread) { | |
3044 osthread->set_ucontext(NULL); | |
3045 osthread->set_siginfo(NULL); | |
3046 | |
3047 // notify the suspend action is completed, we have now resumed | |
3048 osthread->sr.clear_suspended(); | |
3049 } | |
3050 | |
3051 static void suspend_save_context(OSThread *osthread, siginfo_t* siginfo, ucontext_t* context) { | |
3052 osthread->set_ucontext(context); | |
3053 osthread->set_siginfo(siginfo); | |
3054 } | |
3055 | |
3056 // | |
3057 // Handler function invoked when a thread's execution is suspended or | |
3058 // resumed. We have to be careful that only async-safe functions are | |
3059 // called here (Note: most pthread functions are not async safe and | |
3060 // should be avoided.) | |
3061 // | |
3062 // Note: sigwait() is a more natural fit than sigsuspend() from an | |
3063 // interface point of view, but sigwait() prevents the signal hander | |
3064 // from being run. libpthread would get very confused by not having | |
3065 // its signal handlers run and prevents sigwait()'s use with the | |
3066 // mutex granting granting signal. | |
3067 // | |
3068 // Currently only ever called on the VMThread | |
3069 // | |
3070 static void SR_handler(int sig, siginfo_t* siginfo, ucontext_t* context) { | |
3071 // Save and restore errno to avoid confusing native code with EINTR | |
3072 // after sigsuspend. | |
3073 int old_errno = errno; | |
3074 | |
3075 Thread* thread = Thread::current(); | |
3076 OSThread* osthread = thread->osthread(); | |
3077 assert(thread->is_VM_thread(), "Must be VMThread"); | |
3078 // read current suspend action | |
3079 int action = osthread->sr.suspend_action(); | |
3080 if (action == SR_SUSPEND) { | |
3081 suspend_save_context(osthread, siginfo, context); | |
3082 | |
3083 // Notify the suspend action is about to be completed. do_suspend() | |
3084 // waits until SR_SUSPENDED is set and then returns. We will wait | |
3085 // here for a resume signal and that completes the suspend-other | |
3086 // action. do_suspend/do_resume is always called as a pair from | |
3087 // the same thread - so there are no races | |
3088 | |
3089 // notify the caller | |
3090 osthread->sr.set_suspended(); | |
3091 | |
3092 sigset_t suspend_set; // signals for sigsuspend() | |
3093 | |
3094 // get current set of blocked signals and unblock resume signal | |
3095 pthread_sigmask(SIG_BLOCK, NULL, &suspend_set); | |
3096 sigdelset(&suspend_set, SR_signum); | |
3097 | |
3098 // wait here until we are resumed | |
3099 do { | |
3100 sigsuspend(&suspend_set); | |
3101 // ignore all returns until we get a resume signal | |
3102 } while (osthread->sr.suspend_action() != SR_CONTINUE); | |
3103 | |
3104 resume_clear_context(osthread); | |
3105 | |
3106 } else { | |
3107 assert(action == SR_CONTINUE, "unexpected sr action"); | |
3108 // nothing special to do - just leave the handler | |
3109 } | |
3110 | |
3111 errno = old_errno; | |
3112 } | |
3113 | |
3114 | |
3115 static int SR_initialize() { | |
3116 struct sigaction act; | |
3117 char *s; | |
3118 /* Get signal number to use for suspend/resume */ | |
3119 if ((s = ::getenv("_JAVA_SR_SIGNUM")) != 0) { | |
3120 int sig = ::strtol(s, 0, 10); | |
3121 if (sig > 0 || sig < _NSIG) { | |
3122 SR_signum = sig; | |
3123 } | |
3124 } | |
3125 | |
3126 assert(SR_signum > SIGSEGV && SR_signum > SIGBUS, | |
3127 "SR_signum must be greater than max(SIGSEGV, SIGBUS), see 4355769"); | |
3128 | |
3129 sigemptyset(&SR_sigset); | |
3130 sigaddset(&SR_sigset, SR_signum); | |
3131 | |
3132 /* Set up signal handler for suspend/resume */ | |
3133 act.sa_flags = SA_RESTART|SA_SIGINFO; | |
3134 act.sa_handler = (void (*)(int)) SR_handler; | |
3135 | |
3136 // SR_signum is blocked by default. | |
3137 // 4528190 - We also need to block pthread restart signal (32 on all | |
3138 // supported Linux platforms). Note that LinuxThreads need to block | |
3139 // this signal for all threads to work properly. So we don't have | |
3140 // to use hard-coded signal number when setting up the mask. | |
3141 pthread_sigmask(SIG_BLOCK, NULL, &act.sa_mask); | |
3142 | |
3143 if (sigaction(SR_signum, &act, 0) == -1) { | |
3144 return -1; | |
3145 } | |
3146 | |
3147 // Save signal flag | |
3148 os::Linux::set_our_sigflags(SR_signum, act.sa_flags); | |
3149 return 0; | |
3150 } | |
3151 | |
3152 static int SR_finalize() { | |
3153 return 0; | |
3154 } | |
3155 | |
3156 | |
3157 // returns true on success and false on error - really an error is fatal | |
3158 // but this seems the normal response to library errors | |
3159 static bool do_suspend(OSThread* osthread) { | |
3160 // mark as suspended and send signal | |
3161 osthread->sr.set_suspend_action(SR_SUSPEND); | |
3162 int status = pthread_kill(osthread->pthread_id(), SR_signum); | |
3163 assert_status(status == 0, status, "pthread_kill"); | |
3164 | |
3165 // check status and wait until notified of suspension | |
3166 if (status == 0) { | |
3167 for (int i = 0; !osthread->sr.is_suspended(); i++) { | |
3168 os::yield_all(i); | |
3169 } | |
3170 osthread->sr.set_suspend_action(SR_NONE); | |
3171 return true; | |
3172 } | |
3173 else { | |
3174 osthread->sr.set_suspend_action(SR_NONE); | |
3175 return false; | |
3176 } | |
3177 } | |
3178 | |
3179 static void do_resume(OSThread* osthread) { | |
3180 assert(osthread->sr.is_suspended(), "thread should be suspended"); | |
3181 osthread->sr.set_suspend_action(SR_CONTINUE); | |
3182 | |
3183 int status = pthread_kill(osthread->pthread_id(), SR_signum); | |
3184 assert_status(status == 0, status, "pthread_kill"); | |
3185 // check status and wait unit notified of resumption | |
3186 if (status == 0) { | |
3187 for (int i = 0; osthread->sr.is_suspended(); i++) { | |
3188 os::yield_all(i); | |
3189 } | |
3190 } | |
3191 osthread->sr.set_suspend_action(SR_NONE); | |
3192 } | |
3193 | |
3194 //////////////////////////////////////////////////////////////////////////////// | |
3195 // interrupt support | |
3196 | |
3197 void os::interrupt(Thread* thread) { | |
3198 assert(Thread::current() == thread || Threads_lock->owned_by_self(), | |
3199 "possibility of dangling Thread pointer"); | |
3200 | |
3201 OSThread* osthread = thread->osthread(); | |
3202 | |
3203 if (!osthread->interrupted()) { | |
3204 osthread->set_interrupted(true); | |
3205 // More than one thread can get here with the same value of osthread, | |
3206 // resulting in multiple notifications. We do, however, want the store | |
3207 // to interrupted() to be visible to other threads before we execute unpark(). | |
3208 OrderAccess::fence(); | |
3209 ParkEvent * const slp = thread->_SleepEvent ; | |
3210 if (slp != NULL) slp->unpark() ; | |
3211 } | |
3212 | |
3213 // For JSR166. Unpark even if interrupt status already was set | |
3214 if (thread->is_Java_thread()) | |
3215 ((JavaThread*)thread)->parker()->unpark(); | |
3216 | |
3217 ParkEvent * ev = thread->_ParkEvent ; | |
3218 if (ev != NULL) ev->unpark() ; | |
3219 | |
3220 } | |
3221 | |
3222 bool os::is_interrupted(Thread* thread, bool clear_interrupted) { | |
3223 assert(Thread::current() == thread || Threads_lock->owned_by_self(), | |
3224 "possibility of dangling Thread pointer"); | |
3225 | |
3226 OSThread* osthread = thread->osthread(); | |
3227 | |
3228 bool interrupted = osthread->interrupted(); | |
3229 | |
3230 if (interrupted && clear_interrupted) { | |
3231 osthread->set_interrupted(false); | |
3232 // consider thread->_SleepEvent->reset() ... optional optimization | |
3233 } | |
3234 | |
3235 return interrupted; | |
3236 } | |
3237 | |
3238 /////////////////////////////////////////////////////////////////////////////////// | |
3239 // signal handling (except suspend/resume) | |
3240 | |
3241 // This routine may be used by user applications as a "hook" to catch signals. | |
3242 // The user-defined signal handler must pass unrecognized signals to this | |
3243 // routine, and if it returns true (non-zero), then the signal handler must | |
3244 // return immediately. If the flag "abort_if_unrecognized" is true, then this | |
3245 // routine will never retun false (zero), but instead will execute a VM panic | |
3246 // routine kill the process. | |
3247 // | |
3248 // If this routine returns false, it is OK to call it again. This allows | |
3249 // the user-defined signal handler to perform checks either before or after | |
3250 // the VM performs its own checks. Naturally, the user code would be making | |
3251 // a serious error if it tried to handle an exception (such as a null check | |
3252 // or breakpoint) that the VM was generating for its own correct operation. | |
3253 // | |
3254 // This routine may recognize any of the following kinds of signals: | |
3255 // SIGBUS, SIGSEGV, SIGILL, SIGFPE, SIGQUIT, SIGPIPE, SIGXFSZ, SIGUSR1. | |
3256 // It should be consulted by handlers for any of those signals. | |
3257 // | |
3258 // The caller of this routine must pass in the three arguments supplied | |
3259 // to the function referred to in the "sa_sigaction" (not the "sa_handler") | |
3260 // field of the structure passed to sigaction(). This routine assumes that | |
3261 // the sa_flags field passed to sigaction() includes SA_SIGINFO and SA_RESTART. | |
3262 // | |
3263 // Note that the VM will print warnings if it detects conflicting signal | |
3264 // handlers, unless invoked with the option "-XX:+AllowUserSignalHandlers". | |
3265 // | |
3266 extern "C" int | |
3267 JVM_handle_linux_signal(int signo, siginfo_t* siginfo, | |
3268 void* ucontext, int abort_if_unrecognized); | |
3269 | |
3270 void signalHandler(int sig, siginfo_t* info, void* uc) { | |
3271 assert(info != NULL && uc != NULL, "it must be old kernel"); | |
3272 JVM_handle_linux_signal(sig, info, uc, true); | |
3273 } | |
3274 | |
3275 | |
3276 // This boolean allows users to forward their own non-matching signals | |
3277 // to JVM_handle_linux_signal, harmlessly. | |
3278 bool os::Linux::signal_handlers_are_installed = false; | |
3279 | |
3280 // For signal-chaining | |
3281 struct sigaction os::Linux::sigact[MAXSIGNUM]; | |
3282 unsigned int os::Linux::sigs = 0; | |
3283 bool os::Linux::libjsig_is_loaded = false; | |
3284 typedef struct sigaction *(*get_signal_t)(int); | |
3285 get_signal_t os::Linux::get_signal_action = NULL; | |
3286 | |
3287 struct sigaction* os::Linux::get_chained_signal_action(int sig) { | |
3288 struct sigaction *actp = NULL; | |
3289 | |
3290 if (libjsig_is_loaded) { | |
3291 // Retrieve the old signal handler from libjsig | |
3292 actp = (*get_signal_action)(sig); | |
3293 } | |
3294 if (actp == NULL) { | |
3295 // Retrieve the preinstalled signal handler from jvm | |
3296 actp = get_preinstalled_handler(sig); | |
3297 } | |
3298 | |
3299 return actp; | |
3300 } | |
3301 | |
3302 static bool call_chained_handler(struct sigaction *actp, int sig, | |
3303 siginfo_t *siginfo, void *context) { | |
3304 // Call the old signal handler | |
3305 if (actp->sa_handler == SIG_DFL) { | |
3306 // It's more reasonable to let jvm treat it as an unexpected exception | |
3307 // instead of taking the default action. | |
3308 return false; | |
3309 } else if (actp->sa_handler != SIG_IGN) { | |
3310 if ((actp->sa_flags & SA_NODEFER) == 0) { | |
3311 // automaticlly block the signal | |
3312 sigaddset(&(actp->sa_mask), sig); | |
3313 } | |
3314 | |
3315 sa_handler_t hand; | |
3316 sa_sigaction_t sa; | |
3317 bool siginfo_flag_set = (actp->sa_flags & SA_SIGINFO) != 0; | |
3318 // retrieve the chained handler | |
3319 if (siginfo_flag_set) { | |
3320 sa = actp->sa_sigaction; | |
3321 } else { | |
3322 hand = actp->sa_handler; | |
3323 } | |
3324 | |
3325 if ((actp->sa_flags & SA_RESETHAND) != 0) { | |
3326 actp->sa_handler = SIG_DFL; | |
3327 } | |
3328 | |
3329 // try to honor the signal mask | |
3330 sigset_t oset; | |
3331 pthread_sigmask(SIG_SETMASK, &(actp->sa_mask), &oset); | |
3332 | |
3333 // call into the chained handler | |
3334 if (siginfo_flag_set) { | |
3335 (*sa)(sig, siginfo, context); | |
3336 } else { | |
3337 (*hand)(sig); | |
3338 } | |
3339 | |
3340 // restore the signal mask | |
3341 pthread_sigmask(SIG_SETMASK, &oset, 0); | |
3342 } | |
3343 // Tell jvm's signal handler the signal is taken care of. | |
3344 return true; | |
3345 } | |
3346 | |
3347 bool os::Linux::chained_handler(int sig, siginfo_t* siginfo, void* context) { | |
3348 bool chained = false; | |
3349 // signal-chaining | |
3350 if (UseSignalChaining) { | |
3351 struct sigaction *actp = get_chained_signal_action(sig); | |
3352 if (actp != NULL) { | |
3353 chained = call_chained_handler(actp, sig, siginfo, context); | |
3354 } | |
3355 } | |
3356 return chained; | |
3357 } | |
3358 | |
3359 struct sigaction* os::Linux::get_preinstalled_handler(int sig) { | |
3360 if ((( (unsigned int)1 << sig ) & sigs) != 0) { | |
3361 return &sigact[sig]; | |
3362 } | |
3363 return NULL; | |
3364 } | |
3365 | |
3366 void os::Linux::save_preinstalled_handler(int sig, struct sigaction& oldAct) { | |
3367 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
3368 sigact[sig] = oldAct; | |
3369 sigs |= (unsigned int)1 << sig; | |
3370 } | |
3371 | |
3372 // for diagnostic | |
3373 int os::Linux::sigflags[MAXSIGNUM]; | |
3374 | |
3375 int os::Linux::get_our_sigflags(int sig) { | |
3376 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
3377 return sigflags[sig]; | |
3378 } | |
3379 | |
3380 void os::Linux::set_our_sigflags(int sig, int flags) { | |
3381 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
3382 sigflags[sig] = flags; | |
3383 } | |
3384 | |
3385 void os::Linux::set_signal_handler(int sig, bool set_installed) { | |
3386 // Check for overwrite. | |
3387 struct sigaction oldAct; | |
3388 sigaction(sig, (struct sigaction*)NULL, &oldAct); | |
3389 | |
3390 void* oldhand = oldAct.sa_sigaction | |
3391 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) | |
3392 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); | |
3393 if (oldhand != CAST_FROM_FN_PTR(void*, SIG_DFL) && | |
3394 oldhand != CAST_FROM_FN_PTR(void*, SIG_IGN) && | |
3395 oldhand != CAST_FROM_FN_PTR(void*, (sa_sigaction_t)signalHandler)) { | |
3396 if (AllowUserSignalHandlers || !set_installed) { | |
3397 // Do not overwrite; user takes responsibility to forward to us. | |
3398 return; | |
3399 } else if (UseSignalChaining) { | |
3400 // save the old handler in jvm | |
3401 save_preinstalled_handler(sig, oldAct); | |
3402 // libjsig also interposes the sigaction() call below and saves the | |
3403 // old sigaction on it own. | |
3404 } else { | |
3405 fatal2("Encountered unexpected pre-existing sigaction handler %#lx for signal %d.", (long)oldhand, sig); | |
3406 } | |
3407 } | |
3408 | |
3409 struct sigaction sigAct; | |
3410 sigfillset(&(sigAct.sa_mask)); | |
3411 sigAct.sa_handler = SIG_DFL; | |
3412 if (!set_installed) { | |
3413 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; | |
3414 } else { | |
3415 sigAct.sa_sigaction = signalHandler; | |
3416 sigAct.sa_flags = SA_SIGINFO|SA_RESTART; | |
3417 } | |
3418 // Save flags, which are set by ours | |
3419 assert(sig > 0 && sig < MAXSIGNUM, "vm signal out of expected range"); | |
3420 sigflags[sig] = sigAct.sa_flags; | |
3421 | |
3422 int ret = sigaction(sig, &sigAct, &oldAct); | |
3423 assert(ret == 0, "check"); | |
3424 | |
3425 void* oldhand2 = oldAct.sa_sigaction | |
3426 ? CAST_FROM_FN_PTR(void*, oldAct.sa_sigaction) | |
3427 : CAST_FROM_FN_PTR(void*, oldAct.sa_handler); | |
3428 assert(oldhand2 == oldhand, "no concurrent signal handler installation"); | |
3429 } | |
3430 | |
3431 // install signal handlers for signals that HotSpot needs to | |
3432 // handle in order to support Java-level exception handling. | |
3433 | |
3434 void os::Linux::install_signal_handlers() { | |
3435 if (!signal_handlers_are_installed) { | |
3436 signal_handlers_are_installed = true; | |
3437 | |
3438 // signal-chaining | |
3439 typedef void (*signal_setting_t)(); | |
3440 signal_setting_t begin_signal_setting = NULL; | |
3441 signal_setting_t end_signal_setting = NULL; | |
3442 begin_signal_setting = CAST_TO_FN_PTR(signal_setting_t, | |
3443 dlsym(RTLD_DEFAULT, "JVM_begin_signal_setting")); | |
3444 if (begin_signal_setting != NULL) { | |
3445 end_signal_setting = CAST_TO_FN_PTR(signal_setting_t, | |
3446 dlsym(RTLD_DEFAULT, "JVM_end_signal_setting")); | |
3447 get_signal_action = CAST_TO_FN_PTR(get_signal_t, | |
3448 dlsym(RTLD_DEFAULT, "JVM_get_signal_action")); | |
3449 libjsig_is_loaded = true; | |
3450 assert(UseSignalChaining, "should enable signal-chaining"); | |
3451 } | |
3452 if (libjsig_is_loaded) { | |
3453 // Tell libjsig jvm is setting signal handlers | |
3454 (*begin_signal_setting)(); | |
3455 } | |
3456 | |
3457 set_signal_handler(SIGSEGV, true); | |
3458 set_signal_handler(SIGPIPE, true); | |
3459 set_signal_handler(SIGBUS, true); | |
3460 set_signal_handler(SIGILL, true); | |
3461 set_signal_handler(SIGFPE, true); | |
3462 set_signal_handler(SIGXFSZ, true); | |
3463 | |
3464 if (libjsig_is_loaded) { | |
3465 // Tell libjsig jvm finishes setting signal handlers | |
3466 (*end_signal_setting)(); | |
3467 } | |
3468 | |
3469 // We don't activate signal checker if libjsig is in place, we trust ourselves | |
3470 // and if UserSignalHandler is installed all bets are off | |
3471 if (CheckJNICalls) { | |
3472 if (libjsig_is_loaded) { | |
3473 tty->print_cr("Info: libjsig is activated, all active signal checking is disabled"); | |
3474 check_signals = false; | |
3475 } | |
3476 if (AllowUserSignalHandlers) { | |
3477 tty->print_cr("Info: AllowUserSignalHandlers is activated, all active signal checking is disabled"); | |
3478 check_signals = false; | |
3479 } | |
3480 } | |
3481 } | |
3482 } | |
3483 | |
3484 // This is the fastest way to get thread cpu time on Linux. | |
3485 // Returns cpu time (user+sys) for any thread, not only for current. | |
3486 // POSIX compliant clocks are implemented in the kernels 2.6.16+. | |
3487 // It might work on 2.6.10+ with a special kernel/glibc patch. | |
3488 // For reference, please, see IEEE Std 1003.1-2004: | |
3489 // http://www.unix.org/single_unix_specification | |
3490 | |
3491 jlong os::Linux::fast_thread_cpu_time(clockid_t clockid) { | |
3492 struct timespec tp; | |
3493 int rc = os::Linux::clock_gettime(clockid, &tp); | |
3494 assert(rc == 0, "clock_gettime is expected to return 0 code"); | |
3495 | |
3496 return (tp.tv_sec * SEC_IN_NANOSECS) + tp.tv_nsec; | |
3497 } | |
3498 | |
3499 ///// | |
3500 // glibc on Linux platform uses non-documented flag | |
3501 // to indicate, that some special sort of signal | |
3502 // trampoline is used. | |
3503 // We will never set this flag, and we should | |
3504 // ignore this flag in our diagnostic | |
3505 #ifdef SIGNIFICANT_SIGNAL_MASK | |
3506 #undef SIGNIFICANT_SIGNAL_MASK | |
3507 #endif | |
3508 #define SIGNIFICANT_SIGNAL_MASK (~0x04000000) | |
3509 | |
3510 static const char* get_signal_handler_name(address handler, | |
3511 char* buf, int buflen) { | |
3512 int offset; | |
3513 bool found = os::dll_address_to_library_name(handler, buf, buflen, &offset); | |
3514 if (found) { | |
3515 // skip directory names | |
3516 const char *p1, *p2; | |
3517 p1 = buf; | |
3518 size_t len = strlen(os::file_separator()); | |
3519 while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len; | |
3520 jio_snprintf(buf, buflen, "%s+0x%x", p1, offset); | |
3521 } else { | |
3522 jio_snprintf(buf, buflen, PTR_FORMAT, handler); | |
3523 } | |
3524 return buf; | |
3525 } | |
3526 | |
3527 static void print_signal_handler(outputStream* st, int sig, | |
3528 char* buf, size_t buflen) { | |
3529 struct sigaction sa; | |
3530 | |
3531 sigaction(sig, NULL, &sa); | |
3532 | |
3533 // See comment for SIGNIFICANT_SIGNAL_MASK define | |
3534 sa.sa_flags &= SIGNIFICANT_SIGNAL_MASK; | |
3535 | |
3536 st->print("%s: ", os::exception_name(sig, buf, buflen)); | |
3537 | |
3538 address handler = (sa.sa_flags & SA_SIGINFO) | |
3539 ? CAST_FROM_FN_PTR(address, sa.sa_sigaction) | |
3540 : CAST_FROM_FN_PTR(address, sa.sa_handler); | |
3541 | |
3542 if (handler == CAST_FROM_FN_PTR(address, SIG_DFL)) { | |
3543 st->print("SIG_DFL"); | |
3544 } else if (handler == CAST_FROM_FN_PTR(address, SIG_IGN)) { | |
3545 st->print("SIG_IGN"); | |
3546 } else { | |
3547 st->print("[%s]", get_signal_handler_name(handler, buf, buflen)); | |
3548 } | |
3549 | |
3550 st->print(", sa_mask[0]=" PTR32_FORMAT, *(uint32_t*)&sa.sa_mask); | |
3551 | |
3552 address rh = VMError::get_resetted_sighandler(sig); | |
3553 // May be, handler was resetted by VMError? | |
3554 if(rh != NULL) { | |
3555 handler = rh; | |
3556 sa.sa_flags = VMError::get_resetted_sigflags(sig) & SIGNIFICANT_SIGNAL_MASK; | |
3557 } | |
3558 | |
3559 st->print(", sa_flags=" PTR32_FORMAT, sa.sa_flags); | |
3560 | |
3561 // Check: is it our handler? | |
3562 if(handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler) || | |
3563 handler == CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler)) { | |
3564 // It is our signal handler | |
3565 // check for flags, reset system-used one! | |
3566 if((int)sa.sa_flags != os::Linux::get_our_sigflags(sig)) { | |
3567 st->print( | |
3568 ", flags was changed from " PTR32_FORMAT ", consider using jsig library", | |
3569 os::Linux::get_our_sigflags(sig)); | |
3570 } | |
3571 } | |
3572 st->cr(); | |
3573 } | |
3574 | |
3575 | |
3576 #define DO_SIGNAL_CHECK(sig) \ | |
3577 if (!sigismember(&check_signal_done, sig)) \ | |
3578 os::Linux::check_signal_handler(sig) | |
3579 | |
3580 // This method is a periodic task to check for misbehaving JNI applications | |
3581 // under CheckJNI, we can add any periodic checks here | |
3582 | |
3583 void os::run_periodic_checks() { | |
3584 | |
3585 if (check_signals == false) return; | |
3586 | |
3587 // SEGV and BUS if overridden could potentially prevent | |
3588 // generation of hs*.log in the event of a crash, debugging | |
3589 // such a case can be very challenging, so we absolutely | |
3590 // check the following for a good measure: | |
3591 DO_SIGNAL_CHECK(SIGSEGV); | |
3592 DO_SIGNAL_CHECK(SIGILL); | |
3593 DO_SIGNAL_CHECK(SIGFPE); | |
3594 DO_SIGNAL_CHECK(SIGBUS); | |
3595 DO_SIGNAL_CHECK(SIGPIPE); | |
3596 DO_SIGNAL_CHECK(SIGXFSZ); | |
3597 | |
3598 | |
3599 // ReduceSignalUsage allows the user to override these handlers | |
3600 // see comments at the very top and jvm_solaris.h | |
3601 if (!ReduceSignalUsage) { | |
3602 DO_SIGNAL_CHECK(SHUTDOWN1_SIGNAL); | |
3603 DO_SIGNAL_CHECK(SHUTDOWN2_SIGNAL); | |
3604 DO_SIGNAL_CHECK(SHUTDOWN3_SIGNAL); | |
3605 DO_SIGNAL_CHECK(BREAK_SIGNAL); | |
3606 } | |
3607 | |
3608 DO_SIGNAL_CHECK(SR_signum); | |
3609 DO_SIGNAL_CHECK(INTERRUPT_SIGNAL); | |
3610 } | |
3611 | |
3612 typedef int (*os_sigaction_t)(int, const struct sigaction *, struct sigaction *); | |
3613 | |
3614 static os_sigaction_t os_sigaction = NULL; | |
3615 | |
3616 void os::Linux::check_signal_handler(int sig) { | |
3617 char buf[O_BUFLEN]; | |
3618 address jvmHandler = NULL; | |
3619 | |
3620 | |
3621 struct sigaction act; | |
3622 if (os_sigaction == NULL) { | |
3623 // only trust the default sigaction, in case it has been interposed | |
3624 os_sigaction = (os_sigaction_t)dlsym(RTLD_DEFAULT, "sigaction"); | |
3625 if (os_sigaction == NULL) return; | |
3626 } | |
3627 | |
3628 os_sigaction(sig, (struct sigaction*)NULL, &act); | |
3629 | |
3630 | |
3631 act.sa_flags &= SIGNIFICANT_SIGNAL_MASK; | |
3632 | |
3633 address thisHandler = (act.sa_flags & SA_SIGINFO) | |
3634 ? CAST_FROM_FN_PTR(address, act.sa_sigaction) | |
3635 : CAST_FROM_FN_PTR(address, act.sa_handler) ; | |
3636 | |
3637 | |
3638 switch(sig) { | |
3639 case SIGSEGV: | |
3640 case SIGBUS: | |
3641 case SIGFPE: | |
3642 case SIGPIPE: | |
3643 case SIGILL: | |
3644 case SIGXFSZ: | |
3645 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)signalHandler); | |
3646 break; | |
3647 | |
3648 case SHUTDOWN1_SIGNAL: | |
3649 case SHUTDOWN2_SIGNAL: | |
3650 case SHUTDOWN3_SIGNAL: | |
3651 case BREAK_SIGNAL: | |
3652 jvmHandler = (address)user_handler(); | |
3653 break; | |
3654 | |
3655 case INTERRUPT_SIGNAL: | |
3656 jvmHandler = CAST_FROM_FN_PTR(address, SIG_DFL); | |
3657 break; | |
3658 | |
3659 default: | |
3660 if (sig == SR_signum) { | |
3661 jvmHandler = CAST_FROM_FN_PTR(address, (sa_sigaction_t)SR_handler); | |
3662 } else { | |
3663 return; | |
3664 } | |
3665 break; | |
3666 } | |
3667 | |
3668 if (thisHandler != jvmHandler) { | |
3669 tty->print("Warning: %s handler ", exception_name(sig, buf, O_BUFLEN)); | |
3670 tty->print("expected:%s", get_signal_handler_name(jvmHandler, buf, O_BUFLEN)); | |
3671 tty->print_cr(" found:%s", get_signal_handler_name(thisHandler, buf, O_BUFLEN)); | |
3672 // No need to check this sig any longer | |
3673 sigaddset(&check_signal_done, sig); | |
3674 } else if(os::Linux::get_our_sigflags(sig) != 0 && (int)act.sa_flags != os::Linux::get_our_sigflags(sig)) { | |
3675 tty->print("Warning: %s handler flags ", exception_name(sig, buf, O_BUFLEN)); | |
3676 tty->print("expected:" PTR32_FORMAT, os::Linux::get_our_sigflags(sig)); | |
3677 tty->print_cr(" found:" PTR32_FORMAT, act.sa_flags); | |
3678 // No need to check this sig any longer | |
3679 sigaddset(&check_signal_done, sig); | |
3680 } | |
3681 | |
3682 // Dump all the signal | |
3683 if (sigismember(&check_signal_done, sig)) { | |
3684 print_signal_handlers(tty, buf, O_BUFLEN); | |
3685 } | |
3686 } | |
3687 | |
3688 extern void report_error(char* file_name, int line_no, char* title, char* format, ...); | |
3689 | |
3690 extern bool signal_name(int signo, char* buf, size_t len); | |
3691 | |
3692 const char* os::exception_name(int exception_code, char* buf, size_t size) { | |
3693 if (0 < exception_code && exception_code <= SIGRTMAX) { | |
3694 // signal | |
3695 if (!signal_name(exception_code, buf, size)) { | |
3696 jio_snprintf(buf, size, "SIG%d", exception_code); | |
3697 } | |
3698 return buf; | |
3699 } else { | |
3700 return NULL; | |
3701 } | |
3702 } | |
3703 | |
3704 // this is called _before_ the most of global arguments have been parsed | |
3705 void os::init(void) { | |
3706 char dummy; /* used to get a guess on initial stack address */ | |
3707 // first_hrtime = gethrtime(); | |
3708 | |
3709 // With LinuxThreads the JavaMain thread pid (primordial thread) | |
3710 // is different than the pid of the java launcher thread. | |
3711 // So, on Linux, the launcher thread pid is passed to the VM | |
3712 // via the sun.java.launcher.pid property. | |
3713 // Use this property instead of getpid() if it was correctly passed. | |
3714 // See bug 6351349. | |
3715 pid_t java_launcher_pid = (pid_t) Arguments::sun_java_launcher_pid(); | |
3716 | |
3717 _initial_pid = (java_launcher_pid > 0) ? java_launcher_pid : getpid(); | |
3718 | |
3719 clock_tics_per_sec = sysconf(_SC_CLK_TCK); | |
3720 | |
3721 init_random(1234567); | |
3722 | |
3723 ThreadCritical::initialize(); | |
3724 | |
3725 Linux::set_page_size(sysconf(_SC_PAGESIZE)); | |
3726 if (Linux::page_size() == -1) { | |
3727 fatal1("os_linux.cpp: os::init: sysconf failed (%s)", strerror(errno)); | |
3728 } | |
3729 init_page_sizes((size_t) Linux::page_size()); | |
3730 | |
3731 Linux::initialize_system_info(); | |
3732 | |
3733 // main_thread points to the aboriginal thread | |
3734 Linux::_main_thread = pthread_self(); | |
3735 | |
3736 Linux::clock_init(); | |
3737 initial_time_count = os::elapsed_counter(); | |
242 | 3738 pthread_mutex_init(&dl_mutex, NULL); |
0 | 3739 } |
3740 | |
3741 // To install functions for atexit system call | |
3742 extern "C" { | |
3743 static void perfMemory_exit_helper() { | |
3744 perfMemory_exit(); | |
3745 } | |
3746 } | |
3747 | |
3748 // this is called _after_ the global arguments have been parsed | |
3749 jint os::init_2(void) | |
3750 { | |
3751 Linux::fast_thread_clock_init(); | |
3752 | |
3753 // Allocate a single page and mark it as readable for safepoint polling | |
3754 address polling_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); | |
3755 guarantee( polling_page != MAP_FAILED, "os::init_2: failed to allocate polling page" ); | |
3756 | |
3757 os::set_polling_page( polling_page ); | |
3758 | |
3759 #ifndef PRODUCT | |
3760 if(Verbose && PrintMiscellaneous) | |
3761 tty->print("[SafePoint Polling address: " INTPTR_FORMAT "]\n", (intptr_t)polling_page); | |
3762 #endif | |
3763 | |
3764 if (!UseMembar) { | |
3765 address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); | |
3766 guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page"); | |
3767 os::set_memory_serialize_page( mem_serialize_page ); | |
3768 | |
3769 #ifndef PRODUCT | |
3770 if(Verbose && PrintMiscellaneous) | |
3771 tty->print("[Memory Serialize Page address: " INTPTR_FORMAT "]\n", (intptr_t)mem_serialize_page); | |
3772 #endif | |
3773 } | |
3774 | |
3775 FLAG_SET_DEFAULT(UseLargePages, os::large_page_init()); | |
3776 | |
3777 // initialize suspend/resume support - must do this before signal_sets_init() | |
3778 if (SR_initialize() != 0) { | |
3779 perror("SR_initialize failed"); | |
3780 return JNI_ERR; | |
3781 } | |
3782 | |
3783 Linux::signal_sets_init(); | |
3784 Linux::install_signal_handlers(); | |
3785 | |
3786 size_t threadStackSizeInBytes = ThreadStackSize * K; | |
3787 if (threadStackSizeInBytes != 0 && | |
3788 threadStackSizeInBytes < Linux::min_stack_allowed) { | |
3789 tty->print_cr("\nThe stack size specified is too small, " | |
3790 "Specify at least %dk", | |
3791 Linux::min_stack_allowed / K); | |
3792 return JNI_ERR; | |
3793 } | |
3794 | |
3795 // Make the stack size a multiple of the page size so that | |
3796 // the yellow/red zones can be guarded. | |
3797 JavaThread::set_stack_size_at_create(round_to(threadStackSizeInBytes, | |
3798 vm_page_size())); | |
3799 | |
3800 Linux::capture_initial_stack(JavaThread::stack_size_at_create()); | |
3801 | |
3802 Linux::libpthread_init(); | |
3803 if (PrintMiscellaneous && (Verbose || WizardMode)) { | |
3804 tty->print_cr("[HotSpot is running with %s, %s(%s)]\n", | |
3805 Linux::glibc_version(), Linux::libpthread_version(), | |
3806 Linux::is_floating_stack() ? "floating stack" : "fixed stack"); | |
3807 } | |
3808 | |
141 | 3809 if (UseNUMA) { |
462
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3810 if (!Linux::libnuma_init()) { |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3811 UseNUMA = false; |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3812 } else { |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3813 if ((Linux::numa_max_node() < 1)) { |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3814 // There's only one node(they start from 0), disable NUMA. |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3815 UseNUMA = false; |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3816 } |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3817 } |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3818 if (!UseNUMA && ForceNUMA) { |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3819 UseNUMA = true; |
85f1b9537f70
6779436: NUMA allocator: libnuma expects certain size of the buffer in numa_node_to_cpus()
iveresov
parents:
356
diff
changeset
|
3820 } |
141 | 3821 } |
3822 | |
0 | 3823 if (MaxFDLimit) { |
3824 // set the number of file descriptors to max. print out error | |
3825 // if getrlimit/setrlimit fails but continue regardless. | |
3826 struct rlimit nbr_files; | |
3827 int status = getrlimit(RLIMIT_NOFILE, &nbr_files); | |
3828 if (status != 0) { | |
3829 if (PrintMiscellaneous && (Verbose || WizardMode)) | |
3830 perror("os::init_2 getrlimit failed"); | |
3831 } else { | |
3832 nbr_files.rlim_cur = nbr_files.rlim_max; | |
3833 status = setrlimit(RLIMIT_NOFILE, &nbr_files); | |
3834 if (status != 0) { | |
3835 if (PrintMiscellaneous && (Verbose || WizardMode)) | |
3836 perror("os::init_2 setrlimit failed"); | |
3837 } | |
3838 } | |
3839 } | |
3840 | |
3841 // Initialize lock used to serialize thread creation (see os::create_thread) | |
3842 Linux::set_createThread_lock(new Mutex(Mutex::leaf, "createThread_lock", false)); | |
3843 | |
3844 // Initialize HPI. | |
3845 jint hpi_result = hpi::initialize(); | |
3846 if (hpi_result != JNI_OK) { | |
3847 tty->print_cr("There was an error trying to initialize the HPI library."); | |
3848 return hpi_result; | |
3849 } | |
3850 | |
3851 // at-exit methods are called in the reverse order of their registration. | |
3852 // atexit functions are called on return from main or as a result of a | |
3853 // call to exit(3C). There can be only 32 of these functions registered | |
3854 // and atexit() does not set errno. | |
3855 | |
3856 if (PerfAllowAtExitRegistration) { | |
3857 // only register atexit functions if PerfAllowAtExitRegistration is set. | |
3858 // atexit functions can be delayed until process exit time, which | |
3859 // can be problematic for embedded VM situations. Embedded VMs should | |
3860 // call DestroyJavaVM() to assure that VM resources are released. | |
3861 | |
3862 // note: perfMemory_exit_helper atexit function may be removed in | |
3863 // the future if the appropriate cleanup code can be added to the | |
3864 // VM_Exit VMOperation's doit method. | |
3865 if (atexit(perfMemory_exit_helper) != 0) { | |
3866 warning("os::init2 atexit(perfMemory_exit_helper) failed"); | |
3867 } | |
3868 } | |
3869 | |
3870 // initialize thread priority policy | |
3871 prio_init(); | |
3872 | |
3873 return JNI_OK; | |
3874 } | |
3875 | |
3876 // Mark the polling page as unreadable | |
3877 void os::make_polling_page_unreadable(void) { | |
3878 if( !guard_memory((char*)_polling_page, Linux::page_size()) ) | |
3879 fatal("Could not disable polling page"); | |
3880 }; | |
3881 | |
3882 // Mark the polling page as readable | |
3883 void os::make_polling_page_readable(void) { | |
237
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
3884 if( !linux_mprotect((char *)_polling_page, Linux::page_size(), PROT_READ)) { |
0 | 3885 fatal("Could not enable polling page"); |
237
1fdb98a17101
6716785: implicit null checks not triggering with CompressedOops
coleenp
parents:
235
diff
changeset
|
3886 } |
0 | 3887 }; |
3888 | |
3889 int os::active_processor_count() { | |
3890 // Linux doesn't yet have a (official) notion of processor sets, | |
3891 // so just return the number of online processors. | |
3892 int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN); | |
3893 assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check"); | |
3894 return online_cpus; | |
3895 } | |
3896 | |
3897 bool os::distribute_processes(uint length, uint* distribution) { | |
3898 // Not yet implemented. | |
3899 return false; | |
3900 } | |
3901 | |
3902 bool os::bind_to_processor(uint processor_id) { | |
3903 // Not yet implemented. | |
3904 return false; | |
3905 } | |
3906 | |
3907 /// | |
3908 | |
3909 // Suspends the target using the signal mechanism and then grabs the PC before | |
3910 // resuming the target. Used by the flat-profiler only | |
3911 ExtendedPC os::get_thread_pc(Thread* thread) { | |
3912 // Make sure that it is called by the watcher for the VMThread | |
3913 assert(Thread::current()->is_Watcher_thread(), "Must be watcher"); | |
3914 assert(thread->is_VM_thread(), "Can only be called for VMThread"); | |
3915 | |
3916 ExtendedPC epc; | |
3917 | |
3918 OSThread* osthread = thread->osthread(); | |
3919 if (do_suspend(osthread)) { | |
3920 if (osthread->ucontext() != NULL) { | |
3921 epc = os::Linux::ucontext_get_pc(osthread->ucontext()); | |
3922 } else { | |
3923 // NULL context is unexpected, double-check this is the VMThread | |
3924 guarantee(thread->is_VM_thread(), "can only be called for VMThread"); | |
3925 } | |
3926 do_resume(osthread); | |
3927 } | |
3928 // failure means pthread_kill failed for some reason - arguably this is | |
3929 // a fatal problem, but such problems are ignored elsewhere | |
3930 | |
3931 return epc; | |
3932 } | |
3933 | |
3934 int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, const struct timespec *_abstime) | |
3935 { | |
3936 if (is_NPTL()) { | |
3937 return pthread_cond_timedwait(_cond, _mutex, _abstime); | |
3938 } else { | |
3939 #ifndef IA64 | |
3940 // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control | |
3941 // word back to default 64bit precision if condvar is signaled. Java | |
3942 // wants 53bit precision. Save and restore current value. | |
3943 int fpu = get_fpu_control_word(); | |
3944 #endif // IA64 | |
3945 int status = pthread_cond_timedwait(_cond, _mutex, _abstime); | |
3946 #ifndef IA64 | |
3947 set_fpu_control_word(fpu); | |
3948 #endif // IA64 | |
3949 return status; | |
3950 } | |
3951 } | |
3952 | |
3953 //////////////////////////////////////////////////////////////////////////////// | |
3954 // debug support | |
3955 | |
3956 #ifndef PRODUCT | |
3957 static address same_page(address x, address y) { | |
3958 int page_bits = -os::vm_page_size(); | |
3959 if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) | |
3960 return x; | |
3961 else if (x > y) | |
3962 return (address)(intptr_t(y) | ~page_bits) + 1; | |
3963 else | |
3964 return (address)(intptr_t(y) & page_bits); | |
3965 } | |
3966 | |
3967 bool os::find(address addr) { | |
3968 Dl_info dlinfo; | |
3969 memset(&dlinfo, 0, sizeof(dlinfo)); | |
3970 if (dladdr(addr, &dlinfo)) { | |
3971 tty->print(PTR_FORMAT ": ", addr); | |
3972 if (dlinfo.dli_sname != NULL) { | |
3973 tty->print("%s+%#x", dlinfo.dli_sname, | |
3974 addr - (intptr_t)dlinfo.dli_saddr); | |
3975 } else if (dlinfo.dli_fname) { | |
3976 tty->print("<offset %#x>", addr - (intptr_t)dlinfo.dli_fbase); | |
3977 } else { | |
3978 tty->print("<absolute address>"); | |
3979 } | |
3980 if (dlinfo.dli_fname) { | |
3981 tty->print(" in %s", dlinfo.dli_fname); | |
3982 } | |
3983 if (dlinfo.dli_fbase) { | |
3984 tty->print(" at " PTR_FORMAT, dlinfo.dli_fbase); | |
3985 } | |
3986 tty->cr(); | |
3987 | |
3988 if (Verbose) { | |
3989 // decode some bytes around the PC | |
3990 address begin = same_page(addr-40, addr); | |
3991 address end = same_page(addr+40, addr); | |
3992 address lowest = (address) dlinfo.dli_sname; | |
3993 if (!lowest) lowest = (address) dlinfo.dli_fbase; | |
3994 if (begin < lowest) begin = lowest; | |
3995 Dl_info dlinfo2; | |
3996 if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr | |
3997 && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) | |
3998 end = (address) dlinfo2.dli_saddr; | |
3999 Disassembler::decode(begin, end); | |
4000 } | |
4001 return true; | |
4002 } | |
4003 return false; | |
4004 } | |
4005 | |
4006 #endif | |
4007 | |
4008 //////////////////////////////////////////////////////////////////////////////// | |
4009 // misc | |
4010 | |
4011 // This does not do anything on Linux. This is basically a hook for being | |
4012 // able to use structured exception handling (thread-local exception filters) | |
4013 // on, e.g., Win32. | |
4014 void | |
4015 os::os_exception_wrapper(java_call_t f, JavaValue* value, methodHandle* method, | |
4016 JavaCallArguments* args, Thread* thread) { | |
4017 f(value, method, args, thread); | |
4018 } | |
4019 | |
4020 void os::print_statistics() { | |
4021 } | |
4022 | |
4023 int os::message_box(const char* title, const char* message) { | |
4024 int i; | |
4025 fdStream err(defaultStream::error_fd()); | |
4026 for (i = 0; i < 78; i++) err.print_raw("="); | |
4027 err.cr(); | |
4028 err.print_raw_cr(title); | |
4029 for (i = 0; i < 78; i++) err.print_raw("-"); | |
4030 err.cr(); | |
4031 err.print_raw_cr(message); | |
4032 for (i = 0; i < 78; i++) err.print_raw("="); | |
4033 err.cr(); | |
4034 | |
4035 char buf[16]; | |
4036 // Prevent process from exiting upon "read error" without consuming all CPU | |
4037 while (::read(0, buf, sizeof(buf)) <= 0) { ::sleep(100); } | |
4038 | |
4039 return buf[0] == 'y' || buf[0] == 'Y'; | |
4040 } | |
4041 | |
4042 int os::stat(const char *path, struct stat *sbuf) { | |
4043 char pathbuf[MAX_PATH]; | |
4044 if (strlen(path) > MAX_PATH - 1) { | |
4045 errno = ENAMETOOLONG; | |
4046 return -1; | |
4047 } | |
4048 hpi::native_path(strcpy(pathbuf, path)); | |
4049 return ::stat(pathbuf, sbuf); | |
4050 } | |
4051 | |
4052 bool os::check_heap(bool force) { | |
4053 return true; | |
4054 } | |
4055 | |
4056 int local_vsnprintf(char* buf, size_t count, const char* format, va_list args) { | |
4057 return ::vsnprintf(buf, count, format, args); | |
4058 } | |
4059 | |
4060 // Is a (classpath) directory empty? | |
4061 bool os::dir_is_empty(const char* path) { | |
4062 DIR *dir = NULL; | |
4063 struct dirent *ptr; | |
4064 | |
4065 dir = opendir(path); | |
4066 if (dir == NULL) return true; | |
4067 | |
4068 /* Scan the directory */ | |
4069 bool result = true; | |
4070 char buf[sizeof(struct dirent) + MAX_PATH]; | |
4071 while (result && (ptr = ::readdir(dir)) != NULL) { | |
4072 if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) { | |
4073 result = false; | |
4074 } | |
4075 } | |
4076 closedir(dir); | |
4077 return result; | |
4078 } | |
4079 | |
4080 // create binary file, rewriting existing file if required | |
4081 int os::create_binary_file(const char* path, bool rewrite_existing) { | |
4082 int oflags = O_WRONLY | O_CREAT; | |
4083 if (!rewrite_existing) { | |
4084 oflags |= O_EXCL; | |
4085 } | |
4086 return ::open64(path, oflags, S_IREAD | S_IWRITE); | |
4087 } | |
4088 | |
4089 // return current position of file pointer | |
4090 jlong os::current_file_offset(int fd) { | |
4091 return (jlong)::lseek64(fd, (off64_t)0, SEEK_CUR); | |
4092 } | |
4093 | |
4094 // move file pointer to the specified offset | |
4095 jlong os::seek_to_file_offset(int fd, jlong offset) { | |
4096 return (jlong)::lseek64(fd, (off64_t)offset, SEEK_SET); | |
4097 } | |
4098 | |
4099 // Map a block of memory. | |
4100 char* os::map_memory(int fd, const char* file_name, size_t file_offset, | |
4101 char *addr, size_t bytes, bool read_only, | |
4102 bool allow_exec) { | |
4103 int prot; | |
4104 int flags; | |
4105 | |
4106 if (read_only) { | |
4107 prot = PROT_READ; | |
4108 flags = MAP_SHARED; | |
4109 } else { | |
4110 prot = PROT_READ | PROT_WRITE; | |
4111 flags = MAP_PRIVATE; | |
4112 } | |
4113 | |
4114 if (allow_exec) { | |
4115 prot |= PROT_EXEC; | |
4116 } | |
4117 | |
4118 if (addr != NULL) { | |
4119 flags |= MAP_FIXED; | |
4120 } | |
4121 | |
4122 char* mapped_address = (char*)mmap(addr, (size_t)bytes, prot, flags, | |
4123 fd, file_offset); | |
4124 if (mapped_address == MAP_FAILED) { | |
4125 return NULL; | |
4126 } | |
4127 return mapped_address; | |
4128 } | |
4129 | |
4130 | |
4131 // Remap a block of memory. | |
4132 char* os::remap_memory(int fd, const char* file_name, size_t file_offset, | |
4133 char *addr, size_t bytes, bool read_only, | |
4134 bool allow_exec) { | |
4135 // same as map_memory() on this OS | |
4136 return os::map_memory(fd, file_name, file_offset, addr, bytes, read_only, | |
4137 allow_exec); | |
4138 } | |
4139 | |
4140 | |
4141 // Unmap a block of memory. | |
4142 bool os::unmap_memory(char* addr, size_t bytes) { | |
4143 return munmap(addr, bytes) == 0; | |
4144 } | |
4145 | |
4146 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time); | |
4147 | |
4148 static clockid_t thread_cpu_clockid(Thread* thread) { | |
4149 pthread_t tid = thread->osthread()->pthread_id(); | |
4150 clockid_t clockid; | |
4151 | |
4152 // Get thread clockid | |
4153 int rc = os::Linux::pthread_getcpuclockid(tid, &clockid); | |
4154 assert(rc == 0, "pthread_getcpuclockid is expected to return 0 code"); | |
4155 return clockid; | |
4156 } | |
4157 | |
4158 // current_thread_cpu_time(bool) and thread_cpu_time(Thread*, bool) | |
4159 // are used by JVM M&M and JVMTI to get user+sys or user CPU time | |
4160 // of a thread. | |
4161 // | |
4162 // current_thread_cpu_time() and thread_cpu_time(Thread*) returns | |
4163 // the fast estimate available on the platform. | |
4164 | |
4165 jlong os::current_thread_cpu_time() { | |
4166 if (os::Linux::supports_fast_thread_cpu_time()) { | |
4167 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); | |
4168 } else { | |
4169 // return user + sys since the cost is the same | |
4170 return slow_thread_cpu_time(Thread::current(), true /* user + sys */); | |
4171 } | |
4172 } | |
4173 | |
4174 jlong os::thread_cpu_time(Thread* thread) { | |
4175 // consistent with what current_thread_cpu_time() returns | |
4176 if (os::Linux::supports_fast_thread_cpu_time()) { | |
4177 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); | |
4178 } else { | |
4179 return slow_thread_cpu_time(thread, true /* user + sys */); | |
4180 } | |
4181 } | |
4182 | |
4183 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) { | |
4184 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { | |
4185 return os::Linux::fast_thread_cpu_time(CLOCK_THREAD_CPUTIME_ID); | |
4186 } else { | |
4187 return slow_thread_cpu_time(Thread::current(), user_sys_cpu_time); | |
4188 } | |
4189 } | |
4190 | |
4191 jlong os::thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { | |
4192 if (user_sys_cpu_time && os::Linux::supports_fast_thread_cpu_time()) { | |
4193 return os::Linux::fast_thread_cpu_time(thread_cpu_clockid(thread)); | |
4194 } else { | |
4195 return slow_thread_cpu_time(thread, user_sys_cpu_time); | |
4196 } | |
4197 } | |
4198 | |
4199 // | |
4200 // -1 on error. | |
4201 // | |
4202 | |
4203 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) { | |
4204 static bool proc_pid_cpu_avail = true; | |
4205 static bool proc_task_unchecked = true; | |
4206 static const char *proc_stat_path = "/proc/%d/stat"; | |
4207 pid_t tid = thread->osthread()->thread_id(); | |
4208 int i; | |
4209 char *s; | |
4210 char stat[2048]; | |
4211 int statlen; | |
4212 char proc_name[64]; | |
4213 int count; | |
4214 long sys_time, user_time; | |
4215 char string[64]; | |
4216 int idummy; | |
4217 long ldummy; | |
4218 FILE *fp; | |
4219 | |
4220 // We first try accessing /proc/<pid>/cpu since this is faster to | |
4221 // process. If this file is not present (linux kernels 2.5 and above) | |
4222 // then we open /proc/<pid>/stat. | |
4223 if ( proc_pid_cpu_avail ) { | |
4224 sprintf(proc_name, "/proc/%d/cpu", tid); | |
4225 fp = fopen(proc_name, "r"); | |
4226 if ( fp != NULL ) { | |
4227 count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time); | |
4228 fclose(fp); | |
4229 if ( count != 3 ) return -1; | |
4230 | |
4231 if (user_sys_cpu_time) { | |
4232 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); | |
4233 } else { | |
4234 return (jlong)user_time * (1000000000 / clock_tics_per_sec); | |
4235 } | |
4236 } | |
4237 else proc_pid_cpu_avail = false; | |
4238 } | |
4239 | |
4240 // The /proc/<tid>/stat aggregates per-process usage on | |
4241 // new Linux kernels 2.6+ where NPTL is supported. | |
4242 // The /proc/self/task/<tid>/stat still has the per-thread usage. | |
4243 // See bug 6328462. | |
4244 // There can be no directory /proc/self/task on kernels 2.4 with NPTL | |
4245 // and possibly in some other cases, so we check its availability. | |
4246 if (proc_task_unchecked && os::Linux::is_NPTL()) { | |
4247 // This is executed only once | |
4248 proc_task_unchecked = false; | |
4249 fp = fopen("/proc/self/task", "r"); | |
4250 if (fp != NULL) { | |
4251 proc_stat_path = "/proc/self/task/%d/stat"; | |
4252 fclose(fp); | |
4253 } | |
4254 } | |
4255 | |
4256 sprintf(proc_name, proc_stat_path, tid); | |
4257 fp = fopen(proc_name, "r"); | |
4258 if ( fp == NULL ) return -1; | |
4259 statlen = fread(stat, 1, 2047, fp); | |
4260 stat[statlen] = '\0'; | |
4261 fclose(fp); | |
4262 | |
4263 // Skip pid and the command string. Note that we could be dealing with | |
4264 // weird command names, e.g. user could decide to rename java launcher | |
4265 // to "java 1.4.2 :)", then the stat file would look like | |
4266 // 1234 (java 1.4.2 :)) R ... ... | |
4267 // We don't really need to know the command string, just find the last | |
4268 // occurrence of ")" and then start parsing from there. See bug 4726580. | |
4269 s = strrchr(stat, ')'); | |
4270 i = 0; | |
4271 if (s == NULL ) return -1; | |
4272 | |
4273 // Skip blank chars | |
4274 do s++; while (isspace(*s)); | |
4275 | |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
4276 count = sscanf(s,"%*c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu", |
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
4277 &idummy, &idummy, &idummy, &idummy, &idummy, |
0 | 4278 &ldummy, &ldummy, &ldummy, &ldummy, &ldummy, |
4279 &user_time, &sys_time); | |
513
2328d1d3f8cf
6781583: Hotspot build fails on linux 64 bit platform with gcc 4.3.2
xlu
parents:
477
diff
changeset
|
4280 if ( count != 12 ) return -1; |
0 | 4281 if (user_sys_cpu_time) { |
4282 return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec); | |
4283 } else { | |
4284 return (jlong)user_time * (1000000000 / clock_tics_per_sec); | |
4285 } | |
4286 } | |
4287 | |
4288 void os::current_thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { | |
4289 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits | |
4290 info_ptr->may_skip_backward = false; // elapsed time not wall time | |
4291 info_ptr->may_skip_forward = false; // elapsed time not wall time | |
4292 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned | |
4293 } | |
4294 | |
4295 void os::thread_cpu_time_info(jvmtiTimerInfo *info_ptr) { | |
4296 info_ptr->max_value = ALL_64_BITS; // will not wrap in less than 64 bits | |
4297 info_ptr->may_skip_backward = false; // elapsed time not wall time | |
4298 info_ptr->may_skip_forward = false; // elapsed time not wall time | |
4299 info_ptr->kind = JVMTI_TIMER_TOTAL_CPU; // user+system time is returned | |
4300 } | |
4301 | |
4302 bool os::is_thread_cpu_time_supported() { | |
4303 return true; | |
4304 } | |
4305 | |
4306 // System loadavg support. Returns -1 if load average cannot be obtained. | |
4307 // Linux doesn't yet have a (official) notion of processor sets, | |
4308 // so just return the system wide load average. | |
4309 int os::loadavg(double loadavg[], int nelem) { | |
4310 return ::getloadavg(loadavg, nelem); | |
4311 } | |
4312 | |
4313 void os::pause() { | |
4314 char filename[MAX_PATH]; | |
4315 if (PauseAtStartupFile && PauseAtStartupFile[0]) { | |
4316 jio_snprintf(filename, MAX_PATH, PauseAtStartupFile); | |
4317 } else { | |
4318 jio_snprintf(filename, MAX_PATH, "./vm.paused.%d", current_process_id()); | |
4319 } | |
4320 | |
4321 int fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); | |
4322 if (fd != -1) { | |
4323 struct stat buf; | |
4324 close(fd); | |
4325 while (::stat(filename, &buf) == 0) { | |
4326 (void)::poll(NULL, 0, 100); | |
4327 } | |
4328 } else { | |
4329 jio_fprintf(stderr, | |
4330 "Could not open pause file '%s', continuing immediately.\n", filename); | |
4331 } | |
4332 } | |
4333 | |
4334 extern "C" { | |
4335 | |
4336 /** | |
4337 * NOTE: the following code is to keep the green threads code | |
4338 * in the libjava.so happy. Once the green threads is removed, | |
4339 * these code will no longer be needed. | |
4340 */ | |
4341 int | |
4342 jdk_waitpid(pid_t pid, int* status, int options) { | |
4343 return waitpid(pid, status, options); | |
4344 } | |
4345 | |
4346 int | |
4347 fork1() { | |
4348 return fork(); | |
4349 } | |
4350 | |
4351 int | |
4352 jdk_sem_init(sem_t *sem, int pshared, unsigned int value) { | |
4353 return sem_init(sem, pshared, value); | |
4354 } | |
4355 | |
4356 int | |
4357 jdk_sem_post(sem_t *sem) { | |
4358 return sem_post(sem); | |
4359 } | |
4360 | |
4361 int | |
4362 jdk_sem_wait(sem_t *sem) { | |
4363 return sem_wait(sem); | |
4364 } | |
4365 | |
4366 int | |
4367 jdk_pthread_sigmask(int how , const sigset_t* newmask, sigset_t* oldmask) { | |
4368 return pthread_sigmask(how , newmask, oldmask); | |
4369 } | |
4370 | |
4371 } | |
4372 | |
4373 // Refer to the comments in os_solaris.cpp park-unpark. | |
4374 // | |
4375 // Beware -- Some versions of NPTL embody a flaw where pthread_cond_timedwait() can | |
4376 // hang indefinitely. For instance NPTL 0.60 on 2.4.21-4ELsmp is vulnerable. | |
4377 // For specifics regarding the bug see GLIBC BUGID 261237 : | |
4378 // http://www.mail-archive.com/debian-glibc@lists.debian.org/msg10837.html. | |
4379 // Briefly, pthread_cond_timedwait() calls with an expiry time that's not in the future | |
4380 // will either hang or corrupt the condvar, resulting in subsequent hangs if the condvar | |
4381 // is used. (The simple C test-case provided in the GLIBC bug report manifests the | |
4382 // hang). The JVM is vulernable via sleep(), Object.wait(timo), LockSupport.parkNanos() | |
4383 // and monitorenter when we're using 1-0 locking. All those operations may result in | |
4384 // calls to pthread_cond_timedwait(). Using LD_ASSUME_KERNEL to use an older version | |
4385 // of libpthread avoids the problem, but isn't practical. | |
4386 // | |
4387 // Possible remedies: | |
4388 // | |
4389 // 1. Establish a minimum relative wait time. 50 to 100 msecs seems to work. | |
4390 // This is palliative and probabilistic, however. If the thread is preempted | |
4391 // between the call to compute_abstime() and pthread_cond_timedwait(), more | |
4392 // than the minimum period may have passed, and the abstime may be stale (in the | |
4393 // past) resultin in a hang. Using this technique reduces the odds of a hang | |
4394 // but the JVM is still vulnerable, particularly on heavily loaded systems. | |
4395 // | |
4396 // 2. Modify park-unpark to use per-thread (per ParkEvent) pipe-pairs instead | |
4397 // of the usual flag-condvar-mutex idiom. The write side of the pipe is set | |
4398 // NDELAY. unpark() reduces to write(), park() reduces to read() and park(timo) | |
4399 // reduces to poll()+read(). This works well, but consumes 2 FDs per extant | |
4400 // thread. | |
4401 // | |
4402 // 3. Embargo pthread_cond_timedwait() and implement a native "chron" thread | |
4403 // that manages timeouts. We'd emulate pthread_cond_timedwait() by enqueuing | |
4404 // a timeout request to the chron thread and then blocking via pthread_cond_wait(). | |
4405 // This also works well. In fact it avoids kernel-level scalability impediments | |
4406 // on certain platforms that don't handle lots of active pthread_cond_timedwait() | |
4407 // timers in a graceful fashion. | |
4408 // | |
4409 // 4. When the abstime value is in the past it appears that control returns | |
4410 // correctly from pthread_cond_timedwait(), but the condvar is left corrupt. | |
4411 // Subsequent timedwait/wait calls may hang indefinitely. Given that, we | |
4412 // can avoid the problem by reinitializing the condvar -- by cond_destroy() | |
4413 // followed by cond_init() -- after all calls to pthread_cond_timedwait(). | |
4414 // It may be possible to avoid reinitialization by checking the return | |
4415 // value from pthread_cond_timedwait(). In addition to reinitializing the | |
4416 // condvar we must establish the invariant that cond_signal() is only called | |
4417 // within critical sections protected by the adjunct mutex. This prevents | |
4418 // cond_signal() from "seeing" a condvar that's in the midst of being | |
4419 // reinitialized or that is corrupt. Sadly, this invariant obviates the | |
4420 // desirable signal-after-unlock optimization that avoids futile context switching. | |
4421 // | |
4422 // I'm also concerned that some versions of NTPL might allocate an auxilliary | |
4423 // structure when a condvar is used or initialized. cond_destroy() would | |
4424 // release the helper structure. Our reinitialize-after-timedwait fix | |
4425 // put excessive stress on malloc/free and locks protecting the c-heap. | |
4426 // | |
4427 // We currently use (4). See the WorkAroundNTPLTimedWaitHang flag. | |
4428 // It may be possible to refine (4) by checking the kernel and NTPL verisons | |
4429 // and only enabling the work-around for vulnerable environments. | |
4430 | |
4431 // utility to compute the abstime argument to timedwait: | |
4432 // millis is the relative timeout time | |
4433 // abstime will be the absolute timeout time | |
4434 // TODO: replace compute_abstime() with unpackTime() | |
4435 | |
4436 static struct timespec* compute_abstime(timespec* abstime, jlong millis) { | |
4437 if (millis < 0) millis = 0; | |
4438 struct timeval now; | |
4439 int status = gettimeofday(&now, NULL); | |
4440 assert(status == 0, "gettimeofday"); | |
4441 jlong seconds = millis / 1000; | |
4442 millis %= 1000; | |
4443 if (seconds > 50000000) { // see man cond_timedwait(3T) | |
4444 seconds = 50000000; | |
4445 } | |
4446 abstime->tv_sec = now.tv_sec + seconds; | |
4447 long usec = now.tv_usec + millis * 1000; | |
4448 if (usec >= 1000000) { | |
4449 abstime->tv_sec += 1; | |
4450 usec -= 1000000; | |
4451 } | |
4452 abstime->tv_nsec = usec * 1000; | |
4453 return abstime; | |
4454 } | |
4455 | |
4456 | |
4457 // Test-and-clear _Event, always leaves _Event set to 0, returns immediately. | |
4458 // Conceptually TryPark() should be equivalent to park(0). | |
4459 | |
4460 int os::PlatformEvent::TryPark() { | |
4461 for (;;) { | |
4462 const int v = _Event ; | |
4463 guarantee ((v == 0) || (v == 1), "invariant") ; | |
4464 if (Atomic::cmpxchg (0, &_Event, v) == v) return v ; | |
4465 } | |
4466 } | |
4467 | |
4468 void os::PlatformEvent::park() { // AKA "down()" | |
4469 // Invariant: Only the thread associated with the Event/PlatformEvent | |
4470 // may call park(). | |
4471 // TODO: assert that _Assoc != NULL or _Assoc == Self | |
4472 int v ; | |
4473 for (;;) { | |
4474 v = _Event ; | |
4475 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; | |
4476 } | |
4477 guarantee (v >= 0, "invariant") ; | |
4478 if (v == 0) { | |
4479 // Do this the hard way by blocking ... | |
4480 int status = pthread_mutex_lock(_mutex); | |
4481 assert_status(status == 0, status, "mutex_lock"); | |
4482 guarantee (_nParked == 0, "invariant") ; | |
4483 ++ _nParked ; | |
4484 while (_Event < 0) { | |
4485 status = pthread_cond_wait(_cond, _mutex); | |
4486 // for some reason, under 2.7 lwp_cond_wait() may return ETIME ... | |
4487 // Treat this the same as if the wait was interrupted | |
4488 if (status == ETIME) { status = EINTR; } | |
4489 assert_status(status == 0 || status == EINTR, status, "cond_wait"); | |
4490 } | |
4491 -- _nParked ; | |
4492 | |
4493 // In theory we could move the ST of 0 into _Event past the unlock(), | |
4494 // but then we'd need a MEMBAR after the ST. | |
4495 _Event = 0 ; | |
4496 status = pthread_mutex_unlock(_mutex); | |
4497 assert_status(status == 0, status, "mutex_unlock"); | |
4498 } | |
4499 guarantee (_Event >= 0, "invariant") ; | |
4500 } | |
4501 | |
4502 int os::PlatformEvent::park(jlong millis) { | |
4503 guarantee (_nParked == 0, "invariant") ; | |
4504 | |
4505 int v ; | |
4506 for (;;) { | |
4507 v = _Event ; | |
4508 if (Atomic::cmpxchg (v-1, &_Event, v) == v) break ; | |
4509 } | |
4510 guarantee (v >= 0, "invariant") ; | |
4511 if (v != 0) return OS_OK ; | |
4512 | |
4513 // We do this the hard way, by blocking the thread. | |
4514 // Consider enforcing a minimum timeout value. | |
4515 struct timespec abst; | |
4516 compute_abstime(&abst, millis); | |
4517 | |
4518 int ret = OS_TIMEOUT; | |
4519 int status = pthread_mutex_lock(_mutex); | |
4520 assert_status(status == 0, status, "mutex_lock"); | |
4521 guarantee (_nParked == 0, "invariant") ; | |
4522 ++_nParked ; | |
4523 | |
4524 // Object.wait(timo) will return because of | |
4525 // (a) notification | |
4526 // (b) timeout | |
4527 // (c) thread.interrupt | |
4528 // | |
4529 // Thread.interrupt and object.notify{All} both call Event::set. | |
4530 // That is, we treat thread.interrupt as a special case of notification. | |
4531 // The underlying Solaris implementation, cond_timedwait, admits | |
4532 // spurious/premature wakeups, but the JLS/JVM spec prevents the | |
4533 // JVM from making those visible to Java code. As such, we must | |
4534 // filter out spurious wakeups. We assume all ETIME returns are valid. | |
4535 // | |
4536 // TODO: properly differentiate simultaneous notify+interrupt. | |
4537 // In that case, we should propagate the notify to another waiter. | |
4538 | |
4539 while (_Event < 0) { | |
4540 status = os::Linux::safe_cond_timedwait(_cond, _mutex, &abst); | |
4541 if (status != 0 && WorkAroundNPTLTimedWaitHang) { | |
4542 pthread_cond_destroy (_cond); | |
4543 pthread_cond_init (_cond, NULL) ; | |
4544 } | |
4545 assert_status(status == 0 || status == EINTR || | |
4546 status == ETIME || status == ETIMEDOUT, | |
4547 status, "cond_timedwait"); | |
4548 if (!FilterSpuriousWakeups) break ; // previous semantics | |
4549 if (status == ETIME || status == ETIMEDOUT) break ; | |
4550 // We consume and ignore EINTR and spurious wakeups. | |
4551 } | |
4552 --_nParked ; | |
4553 if (_Event >= 0) { | |
4554 ret = OS_OK; | |
4555 } | |
4556 _Event = 0 ; | |
4557 status = pthread_mutex_unlock(_mutex); | |
4558 assert_status(status == 0, status, "mutex_unlock"); | |
4559 assert (_nParked == 0, "invariant") ; | |
4560 return ret; | |
4561 } | |
4562 | |
4563 void os::PlatformEvent::unpark() { | |
4564 int v, AnyWaiters ; | |
4565 for (;;) { | |
4566 v = _Event ; | |
4567 if (v > 0) { | |
4568 // The LD of _Event could have reordered or be satisfied | |
4569 // by a read-aside from this processor's write buffer. | |
4570 // To avoid problems execute a barrier and then | |
4571 // ratify the value. | |
4572 OrderAccess::fence() ; | |
4573 if (_Event == v) return ; | |
4574 continue ; | |
4575 } | |
4576 if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ; | |
4577 } | |
4578 if (v < 0) { | |
4579 // Wait for the thread associated with the event to vacate | |
4580 int status = pthread_mutex_lock(_mutex); | |
4581 assert_status(status == 0, status, "mutex_lock"); | |
4582 AnyWaiters = _nParked ; | |
4583 assert (AnyWaiters == 0 || AnyWaiters == 1, "invariant") ; | |
4584 if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) { | |
4585 AnyWaiters = 0 ; | |
4586 pthread_cond_signal (_cond); | |
4587 } | |
4588 status = pthread_mutex_unlock(_mutex); | |
4589 assert_status(status == 0, status, "mutex_unlock"); | |
4590 if (AnyWaiters != 0) { | |
4591 status = pthread_cond_signal(_cond); | |
4592 assert_status(status == 0, status, "cond_signal"); | |
4593 } | |
4594 } | |
4595 | |
4596 // Note that we signal() _after dropping the lock for "immortal" Events. | |
4597 // This is safe and avoids a common class of futile wakeups. In rare | |
4598 // circumstances this can cause a thread to return prematurely from | |
4599 // cond_{timed}wait() but the spurious wakeup is benign and the victim will | |
4600 // simply re-test the condition and re-park itself. | |
4601 } | |
4602 | |
4603 | |
4604 // JSR166 | |
4605 // ------------------------------------------------------- | |
4606 | |
4607 /* | |
4608 * The solaris and linux implementations of park/unpark are fairly | |
4609 * conservative for now, but can be improved. They currently use a | |
4610 * mutex/condvar pair, plus a a count. | |
4611 * Park decrements count if > 0, else does a condvar wait. Unpark | |
4612 * sets count to 1 and signals condvar. Only one thread ever waits | |
4613 * on the condvar. Contention seen when trying to park implies that someone | |
4614 * is unparking you, so don't wait. And spurious returns are fine, so there | |
4615 * is no need to track notifications. | |
4616 */ | |
4617 | |
4618 | |
4619 #define NANOSECS_PER_SEC 1000000000 | |
4620 #define NANOSECS_PER_MILLISEC 1000000 | |
4621 #define MAX_SECS 100000000 | |
4622 /* | |
4623 * This code is common to linux and solaris and will be moved to a | |
4624 * common place in dolphin. | |
4625 * | |
4626 * The passed in time value is either a relative time in nanoseconds | |
4627 * or an absolute time in milliseconds. Either way it has to be unpacked | |
4628 * into suitable seconds and nanoseconds components and stored in the | |
4629 * given timespec structure. | |
4630 * Given time is a 64-bit value and the time_t used in the timespec is only | |
4631 * a signed-32-bit value (except on 64-bit Linux) we have to watch for | |
4632 * overflow if times way in the future are given. Further on Solaris versions | |
4633 * prior to 10 there is a restriction (see cond_timedwait) that the specified | |
4634 * number of seconds, in abstime, is less than current_time + 100,000,000. | |
4635 * As it will be 28 years before "now + 100000000" will overflow we can | |
4636 * ignore overflow and just impose a hard-limit on seconds using the value | |
4637 * of "now + 100,000,000". This places a limit on the timeout of about 3.17 | |
4638 * years from "now". | |
4639 */ | |
4640 | |
4641 static void unpackTime(timespec* absTime, bool isAbsolute, jlong time) { | |
4642 assert (time > 0, "convertTime"); | |
4643 | |
4644 struct timeval now; | |
4645 int status = gettimeofday(&now, NULL); | |
4646 assert(status == 0, "gettimeofday"); | |
4647 | |
4648 time_t max_secs = now.tv_sec + MAX_SECS; | |
4649 | |
4650 if (isAbsolute) { | |
4651 jlong secs = time / 1000; | |
4652 if (secs > max_secs) { | |
4653 absTime->tv_sec = max_secs; | |
4654 } | |
4655 else { | |
4656 absTime->tv_sec = secs; | |
4657 } | |
4658 absTime->tv_nsec = (time % 1000) * NANOSECS_PER_MILLISEC; | |
4659 } | |
4660 else { | |
4661 jlong secs = time / NANOSECS_PER_SEC; | |
4662 if (secs >= MAX_SECS) { | |
4663 absTime->tv_sec = max_secs; | |
4664 absTime->tv_nsec = 0; | |
4665 } | |
4666 else { | |
4667 absTime->tv_sec = now.tv_sec + secs; | |
4668 absTime->tv_nsec = (time % NANOSECS_PER_SEC) + now.tv_usec*1000; | |
4669 if (absTime->tv_nsec >= NANOSECS_PER_SEC) { | |
4670 absTime->tv_nsec -= NANOSECS_PER_SEC; | |
4671 ++absTime->tv_sec; // note: this must be <= max_secs | |
4672 } | |
4673 } | |
4674 } | |
4675 assert(absTime->tv_sec >= 0, "tv_sec < 0"); | |
4676 assert(absTime->tv_sec <= max_secs, "tv_sec > max_secs"); | |
4677 assert(absTime->tv_nsec >= 0, "tv_nsec < 0"); | |
4678 assert(absTime->tv_nsec < NANOSECS_PER_SEC, "tv_nsec >= nanos_per_sec"); | |
4679 } | |
4680 | |
4681 void Parker::park(bool isAbsolute, jlong time) { | |
4682 // Optional fast-path check: | |
4683 // Return immediately if a permit is available. | |
4684 if (_counter > 0) { | |
4685 _counter = 0 ; | |
1117
95e9083cf4a7
6822370: ReentrantReadWriteLock: threads hung when there are no threads holding onto the lock (Netra x4450)
dholmes
parents:
1010
diff
changeset
|
4686 OrderAccess::fence(); |
0 | 4687 return ; |
4688 } | |
4689 | |
4690 Thread* thread = Thread::current(); | |
4691 assert(thread->is_Java_thread(), "Must be JavaThread"); | |
4692 JavaThread *jt = (JavaThread *)thread; | |
4693 | |
4694 // Optional optimization -- avoid state transitions if there's an interrupt pending. | |
4695 // Check interrupt before trying to wait | |
4696 if (Thread::is_interrupted(thread, false)) { | |
4697 return; | |
4698 } | |
4699 | |
4700 // Next, demultiplex/decode time arguments | |
4701 timespec absTime; | |
4702 if (time < 0) { // don't wait at all | |
4703 return; | |
4704 } | |
4705 if (time > 0) { | |
4706 unpackTime(&absTime, isAbsolute, time); | |
4707 } | |
4708 | |
4709 | |
4710 // Enter safepoint region | |
4711 // Beware of deadlocks such as 6317397. | |
4712 // The per-thread Parker:: mutex is a classic leaf-lock. | |
4713 // In particular a thread must never block on the Threads_lock while | |
4714 // holding the Parker:: mutex. If safepoints are pending both the | |
4715 // the ThreadBlockInVM() CTOR and DTOR may grab Threads_lock. | |
4716 ThreadBlockInVM tbivm(jt); | |
4717 | |
4718 // Don't wait if cannot get lock since interference arises from | |
4719 // unblocking. Also. check interrupt before trying wait | |
4720 if (Thread::is_interrupted(thread, false) || pthread_mutex_trylock(_mutex) != 0) { | |
4721 return; | |
4722 } | |
4723 | |
4724 int status ; | |
4725 if (_counter > 0) { // no wait needed | |
4726 _counter = 0; | |
4727 status = pthread_mutex_unlock(_mutex); | |
4728 assert (status == 0, "invariant") ; | |
1117
95e9083cf4a7
6822370: ReentrantReadWriteLock: threads hung when there are no threads holding onto the lock (Netra x4450)
dholmes
parents:
1010
diff
changeset
|
4729 OrderAccess::fence(); |
0 | 4730 return; |
4731 } | |
4732 | |
4733 #ifdef ASSERT | |
4734 // Don't catch signals while blocked; let the running threads have the signals. | |
4735 // (This allows a debugger to break into the running thread.) | |
4736 sigset_t oldsigs; | |
4737 sigset_t* allowdebug_blocked = os::Linux::allowdebug_blocked_signals(); | |
4738 pthread_sigmask(SIG_BLOCK, allowdebug_blocked, &oldsigs); | |
4739 #endif | |
4740 | |
4741 OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */); | |
4742 jt->set_suspend_equivalent(); | |
4743 // cleared by handle_special_suspend_equivalent_condition() or java_suspend_self() | |
4744 | |
4745 if (time == 0) { | |
4746 status = pthread_cond_wait (_cond, _mutex) ; | |
4747 } else { | |
4748 status = os::Linux::safe_cond_timedwait (_cond, _mutex, &absTime) ; | |
4749 if (status != 0 && WorkAroundNPTLTimedWaitHang) { | |
4750 pthread_cond_destroy (_cond) ; | |
4751 pthread_cond_init (_cond, NULL); | |
4752 } | |
4753 } | |
4754 assert_status(status == 0 || status == EINTR || | |
4755 status == ETIME || status == ETIMEDOUT, | |
4756 status, "cond_timedwait"); | |
4757 | |
4758 #ifdef ASSERT | |
4759 pthread_sigmask(SIG_SETMASK, &oldsigs, NULL); | |
4760 #endif | |
4761 | |
4762 _counter = 0 ; | |
4763 status = pthread_mutex_unlock(_mutex) ; | |
4764 assert_status(status == 0, status, "invariant") ; | |
4765 // If externally suspended while waiting, re-suspend | |
4766 if (jt->handle_special_suspend_equivalent_condition()) { | |
4767 jt->java_suspend_self(); | |
4768 } | |
4769 | |
1117
95e9083cf4a7
6822370: ReentrantReadWriteLock: threads hung when there are no threads holding onto the lock (Netra x4450)
dholmes
parents:
1010
diff
changeset
|
4770 OrderAccess::fence(); |
0 | 4771 } |
4772 | |
4773 void Parker::unpark() { | |
4774 int s, status ; | |
4775 status = pthread_mutex_lock(_mutex); | |
4776 assert (status == 0, "invariant") ; | |
4777 s = _counter; | |
4778 _counter = 1; | |
4779 if (s < 1) { | |
4780 if (WorkAroundNPTLTimedWaitHang) { | |
4781 status = pthread_cond_signal (_cond) ; | |
4782 assert (status == 0, "invariant") ; | |
4783 status = pthread_mutex_unlock(_mutex); | |
4784 assert (status == 0, "invariant") ; | |
4785 } else { | |
4786 status = pthread_mutex_unlock(_mutex); | |
4787 assert (status == 0, "invariant") ; | |
4788 status = pthread_cond_signal (_cond) ; | |
4789 assert (status == 0, "invariant") ; | |
4790 } | |
4791 } else { | |
4792 pthread_mutex_unlock(_mutex); | |
4793 assert (status == 0, "invariant") ; | |
4794 } | |
4795 } | |
4796 | |
4797 | |
4798 extern char** environ; | |
4799 | |
4800 #ifndef __NR_fork | |
4801 #define __NR_fork IA32_ONLY(2) IA64_ONLY(not defined) AMD64_ONLY(57) | |
4802 #endif | |
4803 | |
4804 #ifndef __NR_execve | |
4805 #define __NR_execve IA32_ONLY(11) IA64_ONLY(1033) AMD64_ONLY(59) | |
4806 #endif | |
4807 | |
4808 // Run the specified command in a separate process. Return its exit value, | |
4809 // or -1 on failure (e.g. can't fork a new process). | |
4810 // Unlike system(), this function can be called from signal handler. It | |
4811 // doesn't block SIGINT et al. | |
4812 int os::fork_and_exec(char* cmd) { | |
199
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
4813 const char * argv[4] = {"sh", "-c", cmd, NULL}; |
0 | 4814 |
4815 // fork() in LinuxThreads/NPTL is not async-safe. It needs to run | |
4816 // pthread_atfork handlers and reset pthread library. All we need is a | |
4817 // separate process to execve. Make a direct syscall to fork process. | |
4818 // On IA64 there's no fork syscall, we have to use fork() and hope for | |
4819 // the best... | |
4820 pid_t pid = NOT_IA64(syscall(__NR_fork);) | |
4821 IA64_ONLY(fork();) | |
4822 | |
4823 if (pid < 0) { | |
4824 // fork failed | |
4825 return -1; | |
4826 | |
4827 } else if (pid == 0) { | |
4828 // child process | |
4829 | |
4830 // execve() in LinuxThreads will call pthread_kill_other_threads_np() | |
4831 // first to kill every thread on the thread list. Because this list is | |
4832 // not reset by fork() (see notes above), execve() will instead kill | |
4833 // every thread in the parent process. We know this is the only thread | |
4834 // in the new process, so make a system call directly. | |
4835 // IA64 should use normal execve() from glibc to match the glibc fork() | |
4836 // above. | |
4837 NOT_IA64(syscall(__NR_execve, "/bin/sh", argv, environ);) | |
199
f139919897d2
6681796: hotspot build failure on gcc 4.2.x (ubuntu 8.04) w/ openjdk 6
xlu
parents:
141
diff
changeset
|
4838 IA64_ONLY(execve("/bin/sh", (char* const*)argv, environ);) |
0 | 4839 |
4840 // execve failed | |
4841 _exit(-1); | |
4842 | |
4843 } else { | |
4844 // copied from J2SE ..._waitForProcessExit() in UNIXProcess_md.c; we don't | |
4845 // care about the actual exit code, for now. | |
4846 | |
4847 int status; | |
4848 | |
4849 // Wait for the child process to exit. This returns immediately if | |
4850 // the child has already exited. */ | |
4851 while (waitpid(pid, &status, 0) < 0) { | |
4852 switch (errno) { | |
4853 case ECHILD: return 0; | |
4854 case EINTR: break; | |
4855 default: return -1; | |
4856 } | |
4857 } | |
4858 | |
4859 if (WIFEXITED(status)) { | |
4860 // The child exited normally; get its exit code. | |
4861 return WEXITSTATUS(status); | |
4862 } else if (WIFSIGNALED(status)) { | |
4863 // The child exited because of a signal | |
4864 // The best value to return is 0x80 + signal number, | |
4865 // because that is what all Unix shells do, and because | |
4866 // it allows callers to distinguish between process exit and | |
4867 // process death by signal. | |
4868 return 0x80 + WTERMSIG(status); | |
4869 } else { | |
4870 // Unknown exit code; pass it through | |
4871 return status; | |
4872 } | |
4873 } | |
4874 } |