3 * Copyright 2008-2011 Novell Inc
4 * Copyright 2011 Xamarin Inc
5 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
9 #include "utils/mono-proclib.h"
10 #include "utils/mono-time.h"
19 #ifdef HAVE_SCHED_GETAFFINITY
23 #if defined(_POSIX_VERSION)
24 #ifdef HAVE_SYS_ERRNO_H
25 #include <sys/errno.h>
27 #include <sys/param.h>
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
32 #ifdef HAVE_SYS_SYSCTL_H
33 #include <sys/sysctl.h>
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
39 #if defined(__HAIKU__)
40 #include <os/kernel/OS.h>
42 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
44 #if defined(__APPLE__)
45 #include <mach/mach.h>
47 #ifdef HAVE_SYS_USER_H
50 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
51 # define kinfo_starttime_member kp_proc.p_starttime
52 # define kinfo_pid_member kp_proc.p_pid
53 # define kinfo_name_member kp_proc.p_comm
54 #elif defined(__NetBSD__)
55 # define kinfo_starttime_member p_ustart_sec
56 # define kinfo_pid_member p_pid
57 # define kinfo_name_member p_comm
58 #elif defined(__OpenBSD__)
59 // Can not figure out how to get the proc's start time on OpenBSD
60 # undef kinfo_starttime_member
61 # define kinfo_pid_member p_pid
62 # define kinfo_name_member p_comm
64 #define kinfo_starttime_member ki_start
65 #define kinfo_pid_member ki_pid
66 #define kinfo_name_member ki_comm
71 #ifdef HAVE_SCHED_GETAFFINITY
72 # ifndef GLIBC_HAS_CPU_COUNT
74 CPU_COUNT(cpu_set_t
*set
)
78 for (int i
= 0; i
< CPU_SETSIZE
; i
++)
79 if (CPU_ISSET(i
, set
))
88 * \param size a pointer to a location where the size of the returned array is stored
89 * \returns an array of pid values for the processes currently running on the system.
90 * The size of the array is stored in \p size.
93 mono_process_list (int *size
)
99 size_t data_len
= sizeof (struct kinfo_proc2
) * 400;
100 struct kinfo_proc2
*processes
= g_malloc (data_len
);
103 size_t data_len
= sizeof (struct kinfo_proc
) * 16;
104 struct kinfo_proc
*processes
;
106 #endif /* KERN_PROC2 */
117 mib
[1] = KERN_PROC2
;
118 mib
[2] = KERN_PROC_ALL
;
120 mib
[4] = sizeof(struct kinfo_proc2
);
121 mib
[5] = 400; /* XXX */
123 res
= sysctl (mib
, 6, processes
, &data_len
, NULL
, 0);
133 mib
[2] = KERN_PROC_ALL
;
136 res
= sysctl (mib
, 3, NULL
, &data_len
, NULL
, 0);
139 processes
= (struct kinfo_proc
*) g_malloc (data_len
);
140 res
= sysctl (mib
, 3, processes
, &data_len
, NULL
, 0);
150 #endif /* KERN_PROC2 */
153 res
= data_len
/sizeof (struct kinfo_proc2
);
155 res
= data_len
/sizeof (struct kinfo_proc
);
156 #endif /* KERN_PROC2 */
157 buf
= (void **) g_realloc (buf
, res
* sizeof (void*));
158 for (i
= 0; i
< res
; ++i
)
159 buf
[i
] = GINT_TO_POINTER (processes
[i
].kinfo_pid_member
);
164 #elif defined(__HAIKU__)
170 get_system_info(&si
);
171 void **buf
= g_calloc(si
.used_teams
, sizeof(void*));
173 while (get_next_team_info(&cookie
, &ti
) == B_OK
&& i
< si
.used_teams
) {
174 buf
[i
++] = GINT_TO_POINTER (ti
.team
);
184 GDir
*dir
= g_dir_open ("/proc/", 0, NULL
);
190 while ((name
= g_dir_read_name (dir
))) {
193 pid
= strtol (name
, &nend
, 10);
194 if (pid
<= 0 || nend
== name
|| *nend
)
201 buf
= (void **)g_realloc (buf
, count
* sizeof (void*));
203 buf
[i
++] = GINT_TO_POINTER (pid
);
212 static G_GNUC_UNUSED
char*
213 get_pid_status_item_buf (int pid
, const char *item
, char *rbuf
, int blen
, MonoProcessError
*error
)
218 size_t len
= strlen (item
);
220 g_snprintf (buf
, sizeof (buf
), "/proc/%d/status", pid
);
221 f
= fopen (buf
, "r");
224 *error
= MONO_PROCESS_ERROR_NOT_FOUND
;
227 while ((s
= fgets (buf
, sizeof (buf
), f
))) {
230 if (strncmp (buf
, item
, len
))
233 while (g_ascii_isspace (*s
)) s
++;
236 while (g_ascii_isspace (*s
)) s
++;
239 memcpy (rbuf
, s
, MIN (len
, blen
));
240 rbuf
[MIN (len
, blen
) - 1] = 0;
242 *error
= MONO_PROCESS_ERROR_NONE
;
247 *error
= MONO_PROCESS_ERROR_OTHER
;
254 #define KINFO_PROC struct kinfo_proc2
256 #define KINFO_PROC struct kinfo_proc
260 sysctl_kinfo_proc (gpointer pid
, KINFO_PROC
* processi
)
263 size_t data_len
= sizeof (KINFO_PROC
);
268 mib
[1] = KERN_PROC2
;
269 mib
[2] = KERN_PROC_PID
;
270 mib
[3] = GPOINTER_TO_UINT (pid
);
271 mib
[4] = sizeof(KINFO_PROC
);
272 mib
[5] = 400; /* XXX */
274 res
= sysctl (mib
, 6, processi
, &data_len
, NULL
, 0);
279 mib
[2] = KERN_PROC_PID
;
280 mib
[3] = GPOINTER_TO_UINT (pid
);
282 res
= sysctl (mib
, 4, processi
, &data_len
, NULL
, 0);
283 #endif /* KERN_PROC2 */
285 if (res
< 0 || data_len
!= sizeof (KINFO_PROC
))
290 #endif /* USE_SYSCTL */
293 * mono_process_get_name:
294 * \param pid pid of the process
295 * \param buf byte buffer where to store the name of the prcoess
296 * \param len size of the buffer \p buf
297 * \returns the name of the process identified by \p pid, storing it
298 * inside \p buf for a maximum of len bytes (including the terminating 0).
301 mono_process_get_name (gpointer pid
, char *buf
, int len
)
306 memset (buf
, 0, len
);
308 if (sysctl_kinfo_proc (pid
, &processi
))
309 memcpy (buf
, processi
.kinfo_name_member
, len
- 1);
317 sprintf (fname
, "/proc/%d/cmdline", GPOINTER_TO_INT (pid
));
319 file
= fopen (fname
, "r");
322 r
= fread (buf
, 1, len
- 1, file
);
325 p
= strrchr (buf
, '/');
329 return get_pid_status_item_buf (GPOINTER_TO_INT (pid
), "Name", buf
, len
, NULL
);
336 mono_process_get_times (gpointer pid
, gint64
*start_time
, gint64
*user_time
, gint64
*kernel_time
)
339 *user_time
= mono_process_get_data (pid
, MONO_PROCESS_USER_TIME
);
342 *kernel_time
= mono_process_get_data (pid
, MONO_PROCESS_SYSTEM_TIME
);
347 #if USE_SYSCTL && defined(kinfo_starttime_member)
351 if (sysctl_kinfo_proc (pid
, &processi
)) {
352 #if defined(__NetBSD__)
354 tv
.tv_sec
= processi
.kinfo_starttime_member
;
355 tv
.tv_usec
= processi
.p_ustart_usec
;
356 *start_time
= mono_100ns_datetime_from_timeval(tv
);
358 *start_time
= mono_100ns_datetime_from_timeval (processi
.kinfo_starttime_member
);
364 if (*start_time
== 0) {
365 static guint64 boot_time
= 0;
367 boot_time
= mono_100ns_datetime () - mono_msec_boottime () * 10000;
369 *start_time
= boot_time
+ mono_process_get_data (pid
, MONO_PROCESS_ELAPSED
);
375 * /proc/pid/stat format:
377 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
378 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize
379 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
380 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
383 #define RET_ERROR(err) do { \
384 if (error) *error = (err); \
389 get_process_stat_item (int pid
, int pos
, int sum
, MonoProcessError
*error
)
391 #if defined(__APPLE__)
392 double process_user_time
= 0, process_system_time
= 0;//, process_percent = 0;
394 struct task_basic_info t_info
;
395 mach_msg_type_number_t t_info_count
= TASK_BASIC_INFO_COUNT
, th_count
;
396 thread_array_t th_array
;
400 if (pid
== getpid ()) {
401 /* task_for_pid () doesn't work on ios, even for the current process */
402 task
= mach_task_self ();
405 ret
= task_for_pid (mach_task_self (), pid
, &task
);
406 } while (ret
== KERN_ABORTED
);
408 if (ret
!= KERN_SUCCESS
)
409 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND
);
413 ret
= task_info (task
, TASK_BASIC_INFO
, (task_info_t
)&t_info
, &t_info_count
);
414 } while (ret
== KERN_ABORTED
);
416 if (ret
!= KERN_SUCCESS
) {
417 if (pid
!= getpid ())
418 mach_port_deallocate (mach_task_self (), task
);
419 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
423 ret
= task_threads (task
, &th_array
, &th_count
);
424 } while (ret
== KERN_ABORTED
);
426 if (ret
!= KERN_SUCCESS
) {
427 if (pid
!= getpid ())
428 mach_port_deallocate (mach_task_self (), task
);
429 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
432 for (i
= 0; i
< th_count
; i
++) {
433 double thread_user_time
, thread_system_time
;//, thread_percent;
435 struct thread_basic_info th_info
;
436 mach_msg_type_number_t th_info_count
= THREAD_BASIC_INFO_COUNT
;
438 ret
= thread_info(th_array
[i
], THREAD_BASIC_INFO
, (thread_info_t
)&th_info
, &th_info_count
);
439 } while (ret
== KERN_ABORTED
);
441 if (ret
== KERN_SUCCESS
) {
442 thread_user_time
= th_info
.user_time
.seconds
+ th_info
.user_time
.microseconds
/ 1e6
;
443 thread_system_time
= th_info
.system_time
.seconds
+ th_info
.system_time
.microseconds
/ 1e6
;
444 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
446 process_user_time
+= thread_user_time
;
447 process_system_time
+= thread_system_time
;
448 //process_percent += th_percent;
452 for (i
= 0; i
< th_count
; i
++)
453 mach_port_deallocate(task
, th_array
[i
]);
455 if (pid
!= getpid ())
456 mach_port_deallocate (mach_task_self (), task
);
458 process_user_time
+= t_info
.user_time
.seconds
+ t_info
.user_time
.microseconds
/ 1e6
;
459 process_system_time
+= t_info
.system_time
.seconds
+ t_info
.system_time
.microseconds
/ 1e6
;
461 if (pos
== 10 && sum
== TRUE
)
462 return (gint64
)((process_user_time
+ process_system_time
) * 10000000);
464 return (gint64
)(process_user_time
* 10000000);
466 return (gint64
)(process_system_time
* 10000000);
477 g_snprintf (buf
, sizeof (buf
), "/proc/%d/stat", pid
);
478 f
= fopen (buf
, "r");
480 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND
);
481 len
= fread (buf
, 1, sizeof (buf
), f
);
484 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
485 s
= strchr (buf
, ')');
487 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
489 while (g_ascii_isspace (*s
)) s
++;
491 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
492 /* skip the status char */
493 while (*s
&& !g_ascii_isspace (*s
)) s
++;
495 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
496 for (i
= 0; i
< pos
; ++i
) {
497 while (g_ascii_isspace (*s
)) s
++;
499 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
500 while (*s
&& !g_ascii_isspace (*s
)) s
++;
502 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
504 /* we are finally at the needed item */
505 value
= strtoul (s
, &end
, 0);
506 /* add also the following value */
508 while (g_ascii_isspace (*s
)) s
++;
510 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
511 value
+= strtoul (s
, &end
, 0);
514 *error
= MONO_PROCESS_ERROR_NONE
;
522 static int user_hz
= 0;
524 #if defined (_SC_CLK_TCK) && defined (HAVE_SYSCONF)
525 user_hz
= sysconf (_SC_CLK_TCK
);
534 get_process_stat_time (int pid
, int pos
, int sum
, MonoProcessError
*error
)
536 gint64 val
= get_process_stat_item (pid
, pos
, sum
, error
);
537 #if defined(__APPLE__)
540 /* return 100ns ticks */
541 return (val
* 10000000) / get_user_hz ();
546 get_pid_status_item (int pid
, const char *item
, MonoProcessError
*error
, int multiplier
)
548 #if defined(__APPLE__)
549 // ignore the multiplier
553 task_vm_info_data_t t_info
;
554 mach_msg_type_number_t info_count
= TASK_VM_INFO_COUNT
;
555 kern_return_t mach_ret
;
557 if (pid
== getpid ()) {
558 /* task_for_pid () doesn't work on ios, even for the current process */
559 task
= mach_task_self ();
562 mach_ret
= task_for_pid (mach_task_self (), pid
, &task
);
563 } while (mach_ret
== KERN_ABORTED
);
565 if (mach_ret
!= KERN_SUCCESS
)
566 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND
);
570 mach_ret
= task_info (task
, TASK_VM_INFO
, (task_info_t
)&t_info
, &info_count
);
571 } while (mach_ret
== KERN_ABORTED
);
573 if (mach_ret
!= KERN_SUCCESS
) {
574 if (pid
!= getpid ())
575 mach_port_deallocate (mach_task_self (), task
);
576 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
579 if(strcmp (item
, "VmData") == 0)
580 ret
= t_info
.internal
+ t_info
.compressed
;
581 else if (strcmp (item
, "VmRSS") == 0)
582 ret
= t_info
.resident_size
;
583 else if(strcmp (item
, "VmHWM") == 0)
584 ret
= t_info
.resident_size_peak
;
585 else if (strcmp (item
, "VmSize") == 0 || strcmp (item
, "VmPeak") == 0)
586 ret
= t_info
.virtual_size
;
587 else if (strcmp (item
, "Threads") == 0) {
588 struct task_basic_info t_info
;
589 mach_msg_type_number_t th_count
= TASK_BASIC_INFO_COUNT
;
591 mach_ret
= task_info (task
, TASK_BASIC_INFO
, (task_info_t
)&t_info
, &th_count
);
592 } while (mach_ret
== KERN_ABORTED
);
594 if (mach_ret
!= KERN_SUCCESS
) {
595 if (pid
!= getpid ())
596 mach_port_deallocate (mach_task_self (), task
);
597 RET_ERROR (MONO_PROCESS_ERROR_OTHER
);
600 } else if (strcmp (item
, "VmSwap") == 0)
601 ret
= t_info
.compressed
;
605 if (pid
!= getpid ())
606 mach_port_deallocate (mach_task_self (), task
);
613 s
= get_pid_status_item_buf (pid
, item
, buf
, sizeof (buf
), error
);
615 return ((gint64
) atol (s
)) * multiplier
;
621 * mono_process_get_data:
622 * \param pid pid of the process
623 * \param data description of data to return
624 * \returns a data item of a process like user time, memory use etc,
625 * according to the \p data argumet.
628 mono_process_get_data_with_error (gpointer pid
, MonoProcessData data
, MonoProcessError
*error
)
631 int rpid
= GPOINTER_TO_INT (pid
);
634 *error
= MONO_PROCESS_ERROR_OTHER
;
637 case MONO_PROCESS_NUM_THREADS
:
638 return get_pid_status_item (rpid
, "Threads", error
, 1);
639 case MONO_PROCESS_USER_TIME
:
640 return get_process_stat_time (rpid
, 10, FALSE
, error
);
641 case MONO_PROCESS_SYSTEM_TIME
:
642 return get_process_stat_time (rpid
, 11, FALSE
, error
);
643 case MONO_PROCESS_TOTAL_TIME
:
644 return get_process_stat_time (rpid
, 10, TRUE
, error
);
645 case MONO_PROCESS_WORKING_SET
:
646 return get_pid_status_item (rpid
, "VmRSS", error
, 1024);
647 case MONO_PROCESS_WORKING_SET_PEAK
:
648 val
= get_pid_status_item (rpid
, "VmHWM", error
, 1024);
650 val
= get_pid_status_item (rpid
, "VmRSS", error
, 1024);
652 case MONO_PROCESS_PRIVATE_BYTES
:
653 return get_pid_status_item (rpid
, "VmData", error
, 1024);
654 case MONO_PROCESS_VIRTUAL_BYTES
:
655 return get_pid_status_item (rpid
, "VmSize", error
, 1024);
656 case MONO_PROCESS_VIRTUAL_BYTES_PEAK
:
657 val
= get_pid_status_item (rpid
, "VmPeak", error
, 1024);
659 val
= get_pid_status_item (rpid
, "VmSize", error
, 1024);
661 case MONO_PROCESS_FAULTS
:
662 return get_process_stat_item (rpid
, 6, TRUE
, error
);
663 case MONO_PROCESS_ELAPSED
:
664 return get_process_stat_time (rpid
, 18, FALSE
, error
);
665 case MONO_PROCESS_PPID
:
666 return get_process_stat_time (rpid
, 0, FALSE
, error
);
667 case MONO_PROCESS_PAGED_BYTES
:
668 return get_pid_status_item (rpid
, "VmSwap", error
, 1024);
671 case MONO_PROCESS_END
:
678 mono_process_get_data (gpointer pid
, MonoProcessData data
)
680 MonoProcessError error
;
681 return mono_process_get_data_with_error (pid
, data
, &error
);
686 mono_process_current_pid ()
688 #if defined(HAVE_UNISTD_H)
689 return (int) getpid ();
694 #endif /* !HOST_WIN32 */
698 * \returns the number of processors on the system.
702 mono_cpu_count (void)
705 /* Android tries really hard to save power by powering off CPUs on SMP phones which
706 * means the normal way to query cpu count returns a wrong value with userspace API.
707 * Instead we use /sys entries to query the actual hardware CPU count.
710 char buffer
[8] = {'\0'};
711 int present
= open ("/sys/devices/system/cpu/present", O_RDONLY
);
712 /* Format of the /sys entry is a cpulist of indexes which in the case
713 * of present is always of the form "0-(n-1)" when there is more than
714 * 1 core, n being the number of CPU cores in the system. Otherwise
715 * the value is simply 0
717 if (present
!= -1 && read (present
, (char*)buffer
, sizeof (buffer
)) > 3)
718 count
= strtol (((char*)buffer
) + 2, NULL
, 10);
725 #if defined(HOST_ARM) || defined (HOST_ARM64)
728 * Recap from Alexander Köplinger <alex.koeplinger@outlook.com>:
730 * When we merged the change from PR #2722, we started seeing random failures on ARM in
731 * the MonoTests.System.Threading.ThreadPoolTests.SetAndGetMaxThreads and
732 * MonoTests.System.Threading.ManualResetEventSlimTests.Constructor_Defaults tests. Both
733 * of those tests are dealing with Environment.ProcessorCount to verify some implementation
736 * It turns out that on the Jetson TK1 board we use on public Jenkins and on ARM kernels
737 * in general, the value returned by sched_getaffinity (or _SC_NPROCESSORS_ONLN) doesn't
738 * contain CPUs/cores that are powered off for power saving reasons. This is contrary to
739 * what happens on x86, where even cores in deep-sleep state are returned [1], [2]. This
740 * means that we would get a processor count of 1 at one point in time and a higher value
741 * when load increases later on as the system wakes CPUs.
743 * Various runtime pieces like the threadpool and also user code however relies on the
744 * value returned by Environment.ProcessorCount e.g. for deciding how many parallel tasks
745 * to start, thereby limiting the performance when that code thinks we only have one CPU.
747 * Talking to a few people, this was the reason why we changed to _SC_NPROCESSORS_CONF in
748 * mono#1688 and why we added a special case for Android in mono@de3addc to get the "real"
749 * number of processors in the system.
751 * Because of those issues Android/Dalvik also switched from _ONLN to _SC_NPROCESSORS_CONF
752 * for the Java API Runtime.availableProcessors() too [3], citing:
753 * > Traditionally this returned the number currently online, but many mobile devices are
754 * able to take unused cores offline to save power, so releases newer than Android 4.2 (Jelly
755 * Bean) return the maximum number of cores that could be made available if there were no
756 * power or heat constraints.
758 * The problem with sticking to _SC_NPROCESSORS_CONF however is that it breaks down in
759 * constrained environments like Docker or with an explicit CPU affinity set by the Linux
760 * `taskset` command, They'd get a higher CPU count than can be used, start more threads etc.
761 * which results in unnecessary context switches and overloaded systems. That's why we need
762 * to respect sched_getaffinity.
764 * So while in an ideal world we would be able to rely on sched_getaffinity/_SC_NPROCESSORS_ONLN
765 * to return the number of theoretically available CPUs regardless of power saving measures
766 * everywhere, we can't do this on ARM.
768 * I think the pragmatic solution is the following:
769 * * use sched_getaffinity (+ fallback to _SC_NPROCESSORS_ONLN in case of error) on x86. This
770 * ensures we're inline with what OpenJDK [4] and CoreCLR [5] do
771 * * use _SC_NPROCESSORS_CONF exclusively on ARM (I think we could eventually even get rid of
772 * the HOST_ANDROID special case)
776 * [1] https://sourceware.org/ml/libc-alpha/2013-07/msg00383.html
777 * [2] https://lists.01.org/pipermail/powertop/2012-September/000433.html
778 * [3] https://android.googlesource.com/platform/libcore/+/750dc634e56c58d1d04f6a138734ac2b772900b5%5E1..750dc634e56c58d1d04f6a138734ac2b772900b5/
779 * [4] https://bugs.openjdk.java.net/browse/JDK-6515172
780 * [5] https://github.com/dotnet/coreclr/blob/7058273693db2555f127ce16e6b0c5b40fb04867/src/pal/src/misc/sysinfo.cpp#L148
783 #if defined (_SC_NPROCESSORS_CONF) && defined (HAVE_SYSCONF)
785 int count
= sysconf (_SC_NPROCESSORS_CONF
);
793 #ifdef HAVE_SCHED_GETAFFINITY
796 if (sched_getaffinity (mono_process_current_pid (), sizeof (set
), &set
) == 0)
797 return CPU_COUNT (&set
);
800 #if defined (_SC_NPROCESSORS_ONLN) && defined (HAVE_SYSCONF)
802 int count
= sysconf (_SC_NPROCESSORS_ONLN
);
808 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
814 size_t len
= sizeof (int);
817 if (sysctl (mib
, 2, &count
, &len
, NULL
, 0) == 0)
824 #endif /* !HOST_WIN32 */
827 get_cpu_times (int cpu_id
, gint64
*user
, gint64
*systemt
, gint64
*irq
, gint64
*sirq
, gint64
*idle
)
831 int uhz
= get_user_hz ();
832 guint64 user_ticks
= 0, nice_ticks
= 0, system_ticks
= 0, idle_ticks
= 0, irq_ticks
= 0, sirq_ticks
= 0;
833 FILE *f
= fopen ("/proc/stat", "r");
837 uhz
*= mono_cpu_count ();
838 while ((s
= fgets (buf
, sizeof (buf
), f
))) {
840 if (cpu_id
< 0 && strncmp (s
, "cpu", 3) == 0 && g_ascii_isspace (s
[3])) {
842 } else if (cpu_id
>= 0 && strncmp (s
, "cpu", 3) == 0 && strtol (s
+ 3, &data
, 10) == cpu_id
) {
850 user_ticks
= strtoull (data
, &data
, 10);
851 nice_ticks
= strtoull (data
, &data
, 10);
852 system_ticks
= strtoull (data
, &data
, 10);
853 idle_ticks
= strtoull (data
, &data
, 10);
854 /* iowait_ticks = strtoull (data, &data, 10); */
855 irq_ticks
= strtoull (data
, &data
, 10);
856 sirq_ticks
= strtoull (data
, &data
, 10);
862 *user
= (user_ticks
+ nice_ticks
) * 10000000 / uhz
;
864 *systemt
= (system_ticks
) * 10000000 / uhz
;
866 *irq
= (irq_ticks
) * 10000000 / uhz
;
868 *sirq
= (sirq_ticks
) * 10000000 / uhz
;
870 *idle
= (idle_ticks
) * 10000000 / uhz
;
875 * \param cpu_id processor number or -1 to get a summary of all the processors
876 * \param data type of data to retrieve
877 * Get data about a processor on the system, like time spent in user space or idle time.
880 mono_cpu_get_data (int cpu_id
, MonoCpuData data
, MonoProcessError
*error
)
885 *error
= MONO_PROCESS_ERROR_NONE
;
887 case MONO_CPU_USER_TIME
:
888 get_cpu_times (cpu_id
, &value
, NULL
, NULL
, NULL
, NULL
);
890 case MONO_CPU_PRIV_TIME
:
891 get_cpu_times (cpu_id
, NULL
, &value
, NULL
, NULL
, NULL
);
893 case MONO_CPU_INTR_TIME
:
894 get_cpu_times (cpu_id
, NULL
, NULL
, &value
, NULL
, NULL
);
896 case MONO_CPU_DCP_TIME
:
897 get_cpu_times (cpu_id
, NULL
, NULL
, NULL
, &value
, NULL
);
899 case MONO_CPU_IDLE_TIME
:
900 get_cpu_times (cpu_id
, NULL
, NULL
, NULL
, NULL
, &value
);
911 mono_atexit (void (*func
)(void))
914 /* Some versions of android libc doesn't define atexit () */
917 return atexit (func
);
922 * This function returns the cpu usage in percentage,
923 * normalized on the number of cores.
925 * Warning : the percentage returned can be > 100%. This
926 * might happens on systems like Android which, for
927 * battery and performance reasons, shut down cores and
928 * lie about the number of active cores.
932 mono_cpu_usage (MonoCpuUsageState
*prev
)
934 gint32 cpu_usage
= 0;
935 #ifdef HAVE_GETRUSAGE
936 gint64 cpu_total_time
;
937 gint64 cpu_busy_time
;
938 struct rusage resource_usage
;
943 if (getrusage (RUSAGE_SELF
, &resource_usage
) == -1) {
944 g_error ("getrusage() failed, errno is %d (%s)\n", errno
, strerror (errno
));
948 current_time
= mono_100ns_ticks ();
949 kernel_time
= resource_usage
.ru_stime
.tv_sec
* 1000 * 1000 * 10 + resource_usage
.ru_stime
.tv_usec
* 10;
950 user_time
= resource_usage
.ru_utime
.tv_sec
* 1000 * 1000 * 10 + resource_usage
.ru_utime
.tv_usec
* 10;
952 cpu_busy_time
= (user_time
- (prev
? prev
->user_time
: 0)) + (kernel_time
- (prev
? prev
->kernel_time
: 0));
953 cpu_total_time
= (current_time
- (prev
? prev
->current_time
: 0)) * mono_cpu_count ();
956 prev
->kernel_time
= kernel_time
;
957 prev
->user_time
= user_time
;
958 prev
->current_time
= current_time
;
961 if (cpu_total_time
> 0 && cpu_busy_time
> 0)
962 cpu_usage
= (gint32
)(cpu_busy_time
* 100 / cpu_total_time
);
966 #endif /* !HOST_WIN32 */