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