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