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