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