Merge pull request #4630 from BrzVlad/feature-valloc-limit
[mono-project.git] / mono / utils / mono-proclib.c
blobf733896a6d73ae9a4997347724b5790488230aa4
1 /**
2 * \file
3 * Copyright 2008-2011 Novell Inc
4 * Copyright 2011 Xamarin Inc
5 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
6 */
8 #include "config.h"
9 #include "utils/mono-proclib.h"
10 #include "utils/mono-time.h"
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <fcntl.h>
16 #ifdef HAVE_UNISTD_H
17 #include <unistd.h>
18 #endif
19 #ifdef HAVE_SCHED_GETAFFINITY
20 #include <sched.h>
21 #endif
23 #if defined(_POSIX_VERSION)
24 #ifdef HAVE_SYS_ERRNO_H
25 #include <sys/errno.h>
26 #endif
27 #include <sys/param.h>
28 #include <errno.h>
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
32 #ifdef HAVE_SYS_SYSCTL_H
33 #include <sys/sysctl.h>
34 #endif
35 #include <sys/resource.h>
36 #endif
37 #if defined(__HAIKU__)
38 #include <os/kernel/OS.h>
39 #endif
40 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
41 #include <sys/proc.h>
42 #if defined(__APPLE__)
43 #include <mach/mach.h>
44 #endif
45 #ifdef HAVE_SYS_USER_H
46 #include <sys/user.h>
47 #endif
48 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
49 # define kinfo_starttime_member kp_proc.p_starttime
50 # define kinfo_pid_member kp_proc.p_pid
51 # define kinfo_name_member kp_proc.p_comm
52 #elif defined(__NetBSD__)
53 # define kinfo_starttime_member p_ustart_sec
54 # define kinfo_pid_member p_pid
55 # define kinfo_name_member p_comm
56 #elif defined(__OpenBSD__)
57 // Can not figure out how to get the proc's start time on OpenBSD
58 # undef kinfo_starttime_member
59 # define kinfo_pid_member p_pid
60 # define kinfo_name_member p_comm
61 #else
62 #define kinfo_starttime_member ki_start
63 #define kinfo_pid_member ki_pid
64 #define kinfo_name_member ki_comm
65 #endif
66 #define USE_SYSCTL 1
67 #endif
69 #ifdef HAVE_SCHED_GETAFFINITY
70 # ifndef GLIBC_HAS_CPU_COUNT
71 static int
72 CPU_COUNT(cpu_set_t *set)
74 int i, count = 0;
76 for (int i = 0; i < CPU_SETSIZE; i++)
77 if (CPU_ISSET(i, set))
78 count++;
79 return count;
81 # endif
82 #endif
84 /**
85 * mono_process_list:
86 * \param size a pointer to a location where the size of the returned array is stored
87 * \returns an array of pid values for the processes currently running on the system.
88 * The size of the array is stored in \p size.
90 gpointer*
91 mono_process_list (int *size)
93 #if USE_SYSCTL
94 int res, i;
95 #ifdef KERN_PROC2
96 int mib [6];
97 size_t data_len = sizeof (struct kinfo_proc2) * 400;
98 struct kinfo_proc2 *processes = g_malloc (data_len);
99 #else
100 int mib [4];
101 size_t data_len = sizeof (struct kinfo_proc) * 16;
102 struct kinfo_proc *processes;
103 int limit = 8;
104 #endif /* KERN_PROC2 */
105 void **buf = NULL;
107 if (size)
108 *size = 0;
110 #ifdef KERN_PROC2
111 if (!processes)
112 return NULL;
114 mib [0] = CTL_KERN;
115 mib [1] = KERN_PROC2;
116 mib [2] = KERN_PROC_ALL;
117 mib [3] = 0;
118 mib [4] = sizeof(struct kinfo_proc2);
119 mib [5] = 400; /* XXX */
121 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
122 if (res < 0) {
123 g_free (processes);
124 return NULL;
126 #else
127 processes = NULL;
128 while (limit) {
129 mib [0] = CTL_KERN;
130 mib [1] = KERN_PROC;
131 mib [2] = KERN_PROC_ALL;
132 mib [3] = 0;
134 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
135 if (res)
136 return NULL;
137 processes = (struct kinfo_proc *) g_malloc (data_len);
138 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
139 if (res < 0) {
140 g_free (processes);
141 if (errno != ENOMEM)
142 return NULL;
143 limit --;
144 } else {
145 break;
148 #endif /* KERN_PROC2 */
150 #ifdef KERN_PROC2
151 res = data_len/sizeof (struct kinfo_proc2);
152 #else
153 res = data_len/sizeof (struct kinfo_proc);
154 #endif /* KERN_PROC2 */
155 buf = (void **) g_realloc (buf, res * sizeof (void*));
156 for (i = 0; i < res; ++i)
157 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
158 g_free (processes);
159 if (size)
160 *size = res;
161 return buf;
162 #elif defined(__HAIKU__)
163 int32 cookie = 0;
164 int32 i = 0;
165 team_info ti;
166 system_info si;
168 get_system_info(&si);
169 void **buf = g_calloc(si.used_teams, sizeof(void*));
171 while (get_next_team_info(&cookie, &ti) == B_OK && i < si.used_teams) {
172 buf[i++] = GINT_TO_POINTER (ti.team);
174 *size = i;
176 return buf;
177 #else
178 const char *name;
179 void **buf = NULL;
180 int count = 0;
181 int i = 0;
182 GDir *dir = g_dir_open ("/proc/", 0, NULL);
183 if (!dir) {
184 if (size)
185 *size = 0;
186 return NULL;
188 while ((name = g_dir_read_name (dir))) {
189 int pid;
190 char *nend;
191 pid = strtol (name, &nend, 10);
192 if (pid <= 0 || nend == name || *nend)
193 continue;
194 if (i >= count) {
195 if (!count)
196 count = 16;
197 else
198 count *= 2;
199 buf = (void **)g_realloc (buf, count * sizeof (void*));
201 buf [i++] = GINT_TO_POINTER (pid);
203 g_dir_close (dir);
204 if (size)
205 *size = i;
206 return buf;
207 #endif
210 static G_GNUC_UNUSED char*
211 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
213 char buf [256];
214 char *s;
215 FILE *f;
216 size_t len = strlen (item);
218 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
219 f = fopen (buf, "r");
220 if (!f) {
221 if (error)
222 *error = MONO_PROCESS_ERROR_NOT_FOUND;
223 return NULL;
225 while ((s = fgets (buf, sizeof (buf), f))) {
226 if (*item != *buf)
227 continue;
228 if (strncmp (buf, item, len))
229 continue;
230 s = buf + len;
231 while (g_ascii_isspace (*s)) s++;
232 if (*s++ != ':')
233 continue;
234 while (g_ascii_isspace (*s)) s++;
235 fclose (f);
236 len = strlen (s);
237 memcpy (rbuf, s, MIN (len, blen));
238 rbuf [MIN (len, blen) - 1] = 0;
239 if (error)
240 *error = MONO_PROCESS_ERROR_NONE;
241 return rbuf;
243 fclose (f);
244 if (error)
245 *error = MONO_PROCESS_ERROR_OTHER;
246 return NULL;
249 #if USE_SYSCTL
251 #ifdef KERN_PROC2
252 #define KINFO_PROC struct kinfo_proc2
253 #else
254 #define KINFO_PROC struct kinfo_proc
255 #endif
257 static gboolean
258 sysctl_kinfo_proc (gpointer pid, KINFO_PROC* processi)
260 int res;
261 size_t data_len = sizeof (KINFO_PROC);
263 #ifdef KERN_PROC2
264 int mib [6];
265 mib [0] = CTL_KERN;
266 mib [1] = KERN_PROC2;
267 mib [2] = KERN_PROC_PID;
268 mib [3] = GPOINTER_TO_UINT (pid);
269 mib [4] = sizeof(KINFO_PROC);
270 mib [5] = 400; /* XXX */
272 res = sysctl (mib, 6, processi, &data_len, NULL, 0);
273 #else
274 int mib [4];
275 mib [0] = CTL_KERN;
276 mib [1] = KERN_PROC;
277 mib [2] = KERN_PROC_PID;
278 mib [3] = GPOINTER_TO_UINT (pid);
280 res = sysctl (mib, 4, processi, &data_len, NULL, 0);
281 #endif /* KERN_PROC2 */
283 if (res < 0 || data_len != sizeof (KINFO_PROC))
284 return FALSE;
286 return TRUE;
288 #endif /* USE_SYSCTL */
291 * mono_process_get_name:
292 * \param pid pid of the process
293 * \param buf byte buffer where to store the name of the prcoess
294 * \param len size of the buffer \p buf
295 * \returns the name of the process identified by \p pid, storing it
296 * inside \p buf for a maximum of len bytes (including the terminating 0).
298 char*
299 mono_process_get_name (gpointer pid, char *buf, int len)
301 #if USE_SYSCTL
302 KINFO_PROC processi;
304 memset (buf, 0, len);
306 if (sysctl_kinfo_proc (pid, &processi))
307 memcpy (buf, processi.kinfo_name_member, len - 1);
309 return buf;
310 #else
311 char fname [128];
312 FILE *file;
313 char *p;
314 size_t r;
315 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
316 buf [0] = 0;
317 file = fopen (fname, "r");
318 if (!file)
319 return buf;
320 r = fread (buf, 1, len - 1, file);
321 fclose (file);
322 buf [r] = 0;
323 p = strrchr (buf, '/');
324 if (p)
325 return p + 1;
326 if (r == 0) {
327 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
329 return buf;
330 #endif
333 void
334 mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time)
336 if (user_time)
337 *user_time = mono_process_get_data (pid, MONO_PROCESS_USER_TIME);
339 if (kernel_time)
340 *kernel_time = mono_process_get_data (pid, MONO_PROCESS_SYSTEM_TIME);
342 if (start_time) {
343 *start_time = 0;
345 #if USE_SYSCTL && defined(kinfo_starttime_member)
347 KINFO_PROC processi;
349 if (sysctl_kinfo_proc (pid, &processi)) {
350 #if defined(__NetBSD__)
351 struct timeval tv;
352 tv.tv_sec = processi.kinfo_starttime_member;
353 tv.tv_usec = processi.p_ustart_usec;
354 *start_time = mono_100ns_datetime_from_timeval(tv);
355 #else
356 *start_time = mono_100ns_datetime_from_timeval (processi.kinfo_starttime_member);
357 #endif
360 #endif
362 if (*start_time == 0) {
363 static guint64 boot_time = 0;
364 if (!boot_time)
365 boot_time = mono_100ns_datetime () - mono_msec_boottime () * 10000;
367 *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED);
373 * /proc/pid/stat format:
374 * pid (cmdname) S
375 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
376 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize
377 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
378 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
381 #define RET_ERROR(err) do { \
382 if (error) *error = (err); \
383 return 0; \
384 } while (0)
386 static gint64
387 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
389 #if defined(__APPLE__)
390 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
391 task_t task;
392 struct task_basic_info t_info;
393 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
394 thread_array_t th_array;
395 size_t i;
396 kern_return_t ret;
398 if (pid == getpid ()) {
399 /* task_for_pid () doesn't work on ios, even for the current process */
400 task = mach_task_self ();
401 } else {
402 do {
403 ret = task_for_pid (mach_task_self (), pid, &task);
404 } while (ret == KERN_ABORTED);
406 if (ret != KERN_SUCCESS)
407 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
410 do {
411 ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
412 } while (ret == KERN_ABORTED);
414 if (ret != KERN_SUCCESS) {
415 if (pid != getpid ())
416 mach_port_deallocate (mach_task_self (), task);
417 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
420 do {
421 ret = task_threads (task, &th_array, &th_count);
422 } while (ret == KERN_ABORTED);
424 if (ret != KERN_SUCCESS) {
425 if (pid != getpid ())
426 mach_port_deallocate (mach_task_self (), task);
427 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
430 for (i = 0; i < th_count; i++) {
431 double thread_user_time, thread_system_time;//, thread_percent;
433 struct thread_basic_info th_info;
434 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
435 do {
436 ret = thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count);
437 } while (ret == KERN_ABORTED);
439 if (ret == KERN_SUCCESS) {
440 thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
441 thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
442 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
444 process_user_time += thread_user_time;
445 process_system_time += thread_system_time;
446 //process_percent += th_percent;
450 for (i = 0; i < th_count; i++)
451 mach_port_deallocate(task, th_array[i]);
453 if (pid != getpid ())
454 mach_port_deallocate (mach_task_self (), task);
456 process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
457 process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
459 if (pos == 10 && sum == TRUE)
460 return (gint64)((process_user_time + process_system_time) * 10000000);
461 else if (pos == 10)
462 return (gint64)(process_user_time * 10000000);
463 else if (pos == 11)
464 return (gint64)(process_system_time * 10000000);
466 return 0;
467 #else
468 char buf [512];
469 char *s, *end;
470 FILE *f;
471 size_t len;
472 int i;
473 gint64 value;
475 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
476 f = fopen (buf, "r");
477 if (!f)
478 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
479 len = fread (buf, 1, sizeof (buf), f);
480 fclose (f);
481 if (len <= 0)
482 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
483 s = strchr (buf, ')');
484 if (!s)
485 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
486 s++;
487 while (g_ascii_isspace (*s)) s++;
488 if (!*s)
489 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
490 /* skip the status char */
491 while (*s && !g_ascii_isspace (*s)) s++;
492 if (!*s)
493 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
494 for (i = 0; i < pos; ++i) {
495 while (g_ascii_isspace (*s)) s++;
496 if (!*s)
497 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
498 while (*s && !g_ascii_isspace (*s)) s++;
499 if (!*s)
500 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
502 /* we are finally at the needed item */
503 value = strtoul (s, &end, 0);
504 /* add also the following value */
505 if (sum) {
506 while (g_ascii_isspace (*s)) s++;
507 if (!*s)
508 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
509 value += strtoul (s, &end, 0);
511 if (error)
512 *error = MONO_PROCESS_ERROR_NONE;
513 return value;
514 #endif
517 static int
518 get_user_hz (void)
520 static int user_hz = 0;
521 if (user_hz == 0) {
522 #ifdef _SC_CLK_TCK
523 user_hz = sysconf (_SC_CLK_TCK);
524 #endif
525 if (user_hz == 0)
526 user_hz = 100;
528 return user_hz;
531 static gint64
532 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
534 gint64 val = get_process_stat_item (pid, pos, sum, error);
535 #if defined(__APPLE__)
536 return val;
537 #else
538 /* return 100ns ticks */
539 return (val * 10000000) / get_user_hz ();
540 #endif
543 static gint64
544 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
546 #if defined(__APPLE__)
547 // ignore the multiplier
549 gint64 ret;
550 task_t task;
551 struct task_basic_info t_info;
552 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
553 kern_return_t mach_ret;
555 if (pid == getpid ()) {
556 /* task_for_pid () doesn't work on ios, even for the current process */
557 task = mach_task_self ();
558 } else {
559 do {
560 mach_ret = task_for_pid (mach_task_self (), pid, &task);
561 } while (mach_ret == KERN_ABORTED);
563 if (mach_ret != KERN_SUCCESS)
564 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
567 do {
568 mach_ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count);
569 } while (mach_ret == KERN_ABORTED);
571 if (mach_ret != KERN_SUCCESS) {
572 if (pid != getpid ())
573 mach_port_deallocate (mach_task_self (), task);
574 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
577 if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
578 ret = t_info.resident_size;
579 else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
580 ret = t_info.virtual_size;
581 else if (strcmp (item, "Threads") == 0)
582 ret = th_count;
583 else
584 ret = 0;
586 if (pid != getpid ())
587 mach_port_deallocate (mach_task_self (), task);
589 return ret;
590 #else
591 char buf [64];
592 char *s;
594 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
595 if (s)
596 return ((gint64) atol (s)) * multiplier;
597 return 0;
598 #endif
602 * mono_process_get_data:
603 * \param pid pid of the process
604 * \param data description of data to return
605 * \returns a data item of a process like user time, memory use etc,
606 * according to the \p data argumet.
608 gint64
609 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
611 gint64 val;
612 int rpid = GPOINTER_TO_INT (pid);
614 if (error)
615 *error = MONO_PROCESS_ERROR_OTHER;
617 switch (data) {
618 case MONO_PROCESS_NUM_THREADS:
619 return get_pid_status_item (rpid, "Threads", error, 1);
620 case MONO_PROCESS_USER_TIME:
621 return get_process_stat_time (rpid, 10, FALSE, error);
622 case MONO_PROCESS_SYSTEM_TIME:
623 return get_process_stat_time (rpid, 11, FALSE, error);
624 case MONO_PROCESS_TOTAL_TIME:
625 return get_process_stat_time (rpid, 10, TRUE, error);
626 case MONO_PROCESS_WORKING_SET:
627 return get_pid_status_item (rpid, "VmRSS", error, 1024);
628 case MONO_PROCESS_WORKING_SET_PEAK:
629 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
630 if (val == 0)
631 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
632 return val;
633 case MONO_PROCESS_PRIVATE_BYTES:
634 return get_pid_status_item (rpid, "VmData", error, 1024);
635 case MONO_PROCESS_VIRTUAL_BYTES:
636 return get_pid_status_item (rpid, "VmSize", error, 1024);
637 case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
638 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
639 if (val == 0)
640 val = get_pid_status_item (rpid, "VmSize", error, 1024);
641 return val;
642 case MONO_PROCESS_FAULTS:
643 return get_process_stat_item (rpid, 6, TRUE, error);
644 case MONO_PROCESS_ELAPSED:
645 return get_process_stat_time (rpid, 18, FALSE, error);
646 case MONO_PROCESS_PPID:
647 return get_process_stat_time (rpid, 0, FALSE, error);
648 case MONO_PROCESS_PAGED_BYTES:
649 return get_pid_status_item (rpid, "VmSwap", error, 1024);
651 /* Nothing yet */
652 case MONO_PROCESS_END:
653 return 0;
655 return 0;
658 gint64
659 mono_process_get_data (gpointer pid, MonoProcessData data)
661 MonoProcessError error;
662 return mono_process_get_data_with_error (pid, data, &error);
665 #ifndef HOST_WIN32
667 mono_process_current_pid ()
669 #if defined(HAVE_UNISTD_H)
670 return (int) getpid ();
671 #else
672 #error getpid
673 #endif
675 #endif /* !HOST_WIN32 */
678 * mono_cpu_count:
679 * \returns the number of processors on the system.
681 #ifndef HOST_WIN32
683 mono_cpu_count (void)
685 #ifdef PLATFORM_ANDROID
686 /* Android tries really hard to save power by powering off CPUs on SMP phones which
687 * means the normal way to query cpu count returns a wrong value with userspace API.
688 * Instead we use /sys entries to query the actual hardware CPU count.
690 int count = 0;
691 char buffer[8] = {'\0'};
692 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
693 /* Format of the /sys entry is a cpulist of indexes which in the case
694 * of present is always of the form "0-(n-1)" when there is more than
695 * 1 core, n being the number of CPU cores in the system. Otherwise
696 * the value is simply 0
698 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
699 count = strtol (((char*)buffer) + 2, NULL, 10);
700 if (present != -1)
701 close (present);
702 if (count > 0)
703 return count + 1;
704 #endif
706 #if defined(HOST_ARM) || defined (HOST_ARM64)
709 * Recap from Alexander Köplinger <alex.koeplinger@outlook.com>:
711 * When we merged the change from PR #2722, we started seeing random failures on ARM in
712 * the MonoTests.System.Threading.ThreadPoolTests.SetAndGetMaxThreads and
713 * MonoTests.System.Threading.ManualResetEventSlimTests.Constructor_Defaults tests. Both
714 * of those tests are dealing with Environment.ProcessorCount to verify some implementation
715 * details.
717 * It turns out that on the Jetson TK1 board we use on public Jenkins and on ARM kernels
718 * in general, the value returned by sched_getaffinity (or _SC_NPROCESSORS_ONLN) doesn't
719 * contain CPUs/cores that are powered off for power saving reasons. This is contrary to
720 * what happens on x86, where even cores in deep-sleep state are returned [1], [2]. This
721 * means that we would get a processor count of 1 at one point in time and a higher value
722 * when load increases later on as the system wakes CPUs.
724 * Various runtime pieces like the threadpool and also user code however relies on the
725 * value returned by Environment.ProcessorCount e.g. for deciding how many parallel tasks
726 * to start, thereby limiting the performance when that code thinks we only have one CPU.
728 * Talking to a few people, this was the reason why we changed to _SC_NPROCESSORS_CONF in
729 * mono#1688 and why we added a special case for Android in mono@de3addc to get the "real"
730 * number of processors in the system.
732 * Because of those issues Android/Dalvik also switched from _ONLN to _SC_NPROCESSORS_CONF
733 * for the Java API Runtime.availableProcessors() too [3], citing:
734 * > Traditionally this returned the number currently online, but many mobile devices are
735 * able to take unused cores offline to save power, so releases newer than Android 4.2 (Jelly
736 * Bean) return the maximum number of cores that could be made available if there were no
737 * power or heat constraints.
739 * The problem with sticking to _SC_NPROCESSORS_CONF however is that it breaks down in
740 * constrained environments like Docker or with an explicit CPU affinity set by the Linux
741 * `taskset` command, They'd get a higher CPU count than can be used, start more threads etc.
742 * which results in unnecessary context switches and overloaded systems. That's why we need
743 * to respect sched_getaffinity.
745 * So while in an ideal world we would be able to rely on sched_getaffinity/_SC_NPROCESSORS_ONLN
746 * to return the number of theoretically available CPUs regardless of power saving measures
747 * everywhere, we can't do this on ARM.
749 * I think the pragmatic solution is the following:
750 * * use sched_getaffinity (+ fallback to _SC_NPROCESSORS_ONLN in case of error) on x86. This
751 * ensures we're inline with what OpenJDK [4] and CoreCLR [5] do
752 * * use _SC_NPROCESSORS_CONF exclusively on ARM (I think we could eventually even get rid of
753 * the PLATFORM_ANDROID special case)
755 * Helpful links:
757 * [1] https://sourceware.org/ml/libc-alpha/2013-07/msg00383.html
758 * [2] https://lists.01.org/pipermail/powertop/2012-September/000433.html
759 * [3] https://android.googlesource.com/platform/libcore/+/750dc634e56c58d1d04f6a138734ac2b772900b5%5E1..750dc634e56c58d1d04f6a138734ac2b772900b5/
760 * [4] https://bugs.openjdk.java.net/browse/JDK-6515172
761 * [5] https://github.com/dotnet/coreclr/blob/7058273693db2555f127ce16e6b0c5b40fb04867/src/pal/src/misc/sysinfo.cpp#L148
764 #ifdef _SC_NPROCESSORS_CONF
766 int count = sysconf (_SC_NPROCESSORS_CONF);
767 if (count > 0)
768 return count;
770 #endif
772 #else
774 #ifdef HAVE_SCHED_GETAFFINITY
776 cpu_set_t set;
777 if (sched_getaffinity (mono_process_current_pid (), sizeof (set), &set) == 0)
778 return CPU_COUNT (&set);
780 #endif
781 #ifdef _SC_NPROCESSORS_ONLN
783 int count = sysconf (_SC_NPROCESSORS_ONLN);
784 if (count > 0)
785 return count;
787 #endif
789 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
791 #ifdef USE_SYSCTL
793 int count;
794 int mib [2];
795 size_t len = sizeof (int);
796 mib [0] = CTL_HW;
797 mib [1] = HW_NCPU;
798 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
799 return count;
801 #endif
802 /* FIXME: warn */
803 return 1;
805 #endif /* !HOST_WIN32 */
807 static void
808 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
810 char buf [256];
811 char *s;
812 int hz = get_user_hz ();
813 guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
814 FILE *f = fopen ("/proc/stat", "r");
815 if (!f)
816 return;
817 if (cpu_id < 0)
818 hz *= mono_cpu_count ();
819 while ((s = fgets (buf, sizeof (buf), f))) {
820 char *data = NULL;
821 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
822 data = s + 4;
823 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
824 if (data == s + 3)
825 continue;
826 data++;
827 } else {
828 continue;
831 user_ticks = strtoull (data, &data, 10);
832 nice_ticks = strtoull (data, &data, 10);
833 system_ticks = strtoull (data, &data, 10);
834 idle_ticks = strtoull (data, &data, 10);
835 /* iowait_ticks = strtoull (data, &data, 10); */
836 irq_ticks = strtoull (data, &data, 10);
837 sirq_ticks = strtoull (data, &data, 10);
838 break;
840 fclose (f);
842 if (user)
843 *user = (user_ticks + nice_ticks) * 10000000 / hz;
844 if (systemt)
845 *systemt = (system_ticks) * 10000000 / hz;
846 if (irq)
847 *irq = (irq_ticks) * 10000000 / hz;
848 if (sirq)
849 *sirq = (sirq_ticks) * 10000000 / hz;
850 if (idle)
851 *idle = (idle_ticks) * 10000000 / hz;
855 * mono_cpu_get_data:
856 * \param cpu_id processor number or -1 to get a summary of all the processors
857 * \param data type of data to retrieve
858 * Get data about a processor on the system, like time spent in user space or idle time.
860 gint64
861 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
863 gint64 value = 0;
865 if (error)
866 *error = MONO_PROCESS_ERROR_NONE;
867 switch (data) {
868 case MONO_CPU_USER_TIME:
869 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
870 break;
871 case MONO_CPU_PRIV_TIME:
872 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
873 break;
874 case MONO_CPU_INTR_TIME:
875 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
876 break;
877 case MONO_CPU_DCP_TIME:
878 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
879 break;
880 case MONO_CPU_IDLE_TIME:
881 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
882 break;
884 case MONO_CPU_END:
885 /* Nothing yet */
886 return 0;
888 return value;
892 mono_atexit (void (*func)(void))
894 #ifdef PLATFORM_ANDROID
895 /* Some versions of android libc doesn't define atexit () */
896 return 0;
897 #else
898 return atexit (func);
899 #endif
903 * This function returns the cpu usage in percentage,
904 * normalized on the number of cores.
906 * Warning : the percentage returned can be > 100%. This
907 * might happens on systems like Android which, for
908 * battery and performance reasons, shut down cores and
909 * lie about the number of active cores.
911 #ifndef HOST_WIN32
912 gint32
913 mono_cpu_usage (MonoCpuUsageState *prev)
915 gint32 cpu_usage = 0;
916 gint64 cpu_total_time;
917 gint64 cpu_busy_time;
918 struct rusage resource_usage;
919 gint64 current_time;
920 gint64 kernel_time;
921 gint64 user_time;
923 if (getrusage (RUSAGE_SELF, &resource_usage) == -1) {
924 g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno));
925 return -1;
928 current_time = mono_100ns_ticks ();
929 kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10;
930 user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10;
932 cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0));
933 cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count ();
935 if (prev) {
936 prev->kernel_time = kernel_time;
937 prev->user_time = user_time;
938 prev->current_time = current_time;
941 if (cpu_total_time > 0 && cpu_busy_time > 0)
942 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
944 return cpu_usage;
946 #endif /* !HOST_WIN32 */