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