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