First set of licensing changes
[mono.git] / mono / utils / mono-counters.c
1 /*
2  * Copyright 2006-2010 Novell
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 <stdlib.h>
8 #include <glib.h>
9 #include "config.h"
10 #include "mono-counters.h"
11 #include "mono-proclib.h"
12 #include "mono-os-mutex.h"
13
14 #ifdef HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17
18 struct _MonoCounter {
19         MonoCounter *next;
20         const char *name;
21         void *addr;
22         int type;
23         size_t size;
24 };
25
26 static MonoCounter *counters = NULL;
27 static mono_mutex_t counters_mutex;
28
29 static volatile gboolean initialized = FALSE;
30
31 static int valid_mask = 0;
32 static int set_mask = 0;
33
34 static GSList *register_callbacks = NULL;
35
36 static void initialize_system_counters (void);
37
38 /**
39  * mono_counter_get_variance:
40  * @counter: counter to get the variance
41  *
42  * Variance specifies how the counter value is expected to behave between any two samplings.
43  *
44  * Returns: the monotonicity of the counter.
45  */
46 int
47 mono_counter_get_variance (MonoCounter *counter)
48 {
49         return counter->type & MONO_COUNTER_VARIANCE_MASK;
50 }
51
52 /**
53  * mono_counter_get_unit:
54  * @counter: counter to get the unit
55  *
56  * The unit gives a high level view of the unit that the counter is measuring.
57  *
58  * Returns: the unit of the counter.
59  */
60 int
61 mono_counter_get_unit (MonoCounter *counter)
62 {
63         return counter->type & MONO_COUNTER_UNIT_MASK;
64 }
65
66 /**
67  * mono_counter_get_section:
68  * @counter: counter to get the section
69  *
70  * Sections are the unit of organization between all counters.
71  *
72  * Returns: the section of the counter.
73  */
74
75 int
76 mono_counter_get_section (MonoCounter *counter)
77 {
78         return counter->type & MONO_COUNTER_SECTION_MASK;
79 }
80
81 /**
82  * mono_counter_get_type:
83  * @counter: counter to get the type
84  *
85  * Returns the type used to strong the value of the counter.
86  *
87  * Returns:the type of the counter.
88  */
89 int
90 mono_counter_get_type (MonoCounter *counter)
91 {
92         return counter->type & MONO_COUNTER_TYPE_MASK;
93 }
94
95 /**
96  * mono_counter_get_name:
97  * @counter: counter to get the name
98  *
99  * Returns the counter name. The string should not be freed.
100  *
101  * Returns the name of the counter.
102  */
103
104 const char*
105 mono_counter_get_name (MonoCounter *counter)
106 {
107         return counter->name;
108 }
109
110 /**
111  * mono_counter_get_size:
112  * @counter: counter to get the max size of the counter
113  *
114  * Use the returned size to create the buffer used with mono_counters_sample
115  *
116  * Returns: the max size of the counter data.
117  */
118 size_t
119 mono_counter_get_size (MonoCounter *counter)
120 {
121         return counter->size;
122 }
123
124 /**
125  * mono_counters_enable:
126  * @section_mask: a mask listing the sections that will be displayed
127  *
128  * This is used to track which counters will be displayed.
129  */
130 void
131 mono_counters_enable (int section_mask)
132 {
133         valid_mask = section_mask & MONO_COUNTER_SECTION_MASK;
134 }
135
136 void
137 mono_counters_init (void)
138 {
139         if (initialized)
140                 return;
141
142         mono_os_mutex_init (&counters_mutex);
143
144         initialize_system_counters ();
145
146         initialized = TRUE;
147 }
148
149 static void
150 register_internal (const char *name, int type, void *addr, int size)
151 {
152         MonoCounter *counter;
153         GSList *register_callback;
154
155         g_assert (size >= 0);
156         if ((type & MONO_COUNTER_VARIANCE_MASK) == 0)
157                 type |= MONO_COUNTER_MONOTONIC;
158
159         mono_os_mutex_lock (&counters_mutex);
160
161         for (counter = counters; counter; counter = counter->next) {
162                 if (counter->addr == addr) {
163                         g_warning ("you are registering twice the same counter address");
164                         mono_os_mutex_unlock (&counters_mutex);
165                         return;
166                 }
167         }
168
169         counter = (MonoCounter *) malloc (sizeof (MonoCounter));
170         if (!counter) {
171                 mono_os_mutex_unlock (&counters_mutex);
172                 return;
173         }
174         counter->name = g_strdup (name);
175         counter->type = type;
176         counter->addr = addr;
177         counter->next = NULL;
178         counter->size = size;
179
180         set_mask |= type;
181
182         /* Append */
183         if (counters) {
184                 MonoCounter *item = counters;
185                 while (item->next)
186                         item = item->next;
187                 item->next = counter;
188         } else {
189                 counters = counter;
190         }
191
192         for (register_callback = register_callbacks; register_callback; register_callback = register_callback->next)
193                 ((MonoCounterRegisterCallback)register_callback->data) (counter);
194
195         mono_os_mutex_unlock (&counters_mutex);
196 }
197
198 /**
199  * mono_counters_register:
200  * @name: The name for this counters.
201  * @type: One of the possible MONO_COUNTER types, or MONO_COUNTER_CALLBACK for a function pointer.
202  * @addr: The address to register.
203  *
204  * Register addr as the address of a counter of type type.
205  * Note that @name must be a valid string at all times until
206  * mono_counters_dump () is called.
207  *
208  * This function should not be used with counter types that require an explicit size such as string
209  * as the counter size will be set to zero making them effectively useless.
210  *
211  *
212  * It may be a function pointer if MONO_COUNTER_CALLBACK is specified:
213  * the function should return the value and take no arguments.
214  */
215 void 
216 mono_counters_register (const char* name, int type, void *addr)
217 {
218         int size;
219         switch (type & MONO_COUNTER_TYPE_MASK) {
220         case MONO_COUNTER_INT:
221                 size = sizeof (int);
222                 break;
223         case MONO_COUNTER_UINT:
224                 size = sizeof (guint);
225                 break;
226         case MONO_COUNTER_LONG:
227         case MONO_COUNTER_TIME_INTERVAL:
228                 size = sizeof (gint64);
229                 break;
230         case MONO_COUNTER_ULONG:
231                 size = sizeof (guint64);
232                 break;
233         case MONO_COUNTER_WORD:
234                 size = sizeof (gssize);
235                 break;
236         case MONO_COUNTER_DOUBLE:
237                 size = sizeof (double);
238                 break;
239         case MONO_COUNTER_STRING:
240                 size = 0;
241                 break;
242         default:
243                 g_assert_not_reached ();
244         }
245
246         if (!initialized)
247                 g_debug ("counters not enabled");
248         else
249                 register_internal (name, type, addr, size);
250 }
251
252 /**
253  * mono_counters_register_with_size:
254  * @name: The name for this counters.
255  * @type: One of the possible MONO_COUNTER types, or MONO_COUNTER_CALLBACK for a function pointer.
256  * @addr: The address to register.
257  * @size: Max size of the counter data.
258  *
259  * Register addr as the address of a counter of type @type.
260  * Note that @name must be a valid string at all times until
261  * mono_counters_dump () is called.
262  *
263  * It may be a function pointer if MONO_COUNTER_CALLBACK is specified:
264  * the function should return the value and take no arguments.
265  *
266  * The value of @size is ignored for types with fixed size such as int and long.
267  *
268  * Use @size for types that can have dynamic size such as string.
269  *
270  * If @size is negative, it's silently converted to zero.
271  */
272 void
273 mono_counters_register_with_size (const char *name, int type, void *addr, int size)
274 {
275         if (!initialized)
276                 g_debug ("counters not enabled");
277         else
278                 register_internal (name, type, addr, size);
279 }
280
281 /**
282  * mono_counters_on_register
283  * @callback : function to callback when a counter is registered
284  *
285  * Add a callback that is going to be called when a counter is registered
286  */
287 void
288 mono_counters_on_register (MonoCounterRegisterCallback callback)
289 {
290         if (!initialized) {
291                 g_debug ("counters not enabled");
292                 return;
293         }
294
295         mono_os_mutex_lock (&counters_mutex);
296         register_callbacks = g_slist_append (register_callbacks, (gpointer) callback);
297         mono_os_mutex_unlock (&counters_mutex);
298 }
299
300 typedef int (*IntFunc) (void);
301 typedef guint (*UIntFunc) (void);
302 typedef gint64 (*LongFunc) (void);
303 typedef guint64 (*ULongFunc) (void);
304 typedef gssize (*PtrFunc) (void);
305 typedef double (*DoubleFunc) (void);
306 typedef char* (*StrFunc) (void);
307
308 static gint64
309 user_time (void)
310 {
311         return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_USER_TIME);
312 }
313
314 static gint64
315 system_time (void)
316 {
317         return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_SYSTEM_TIME);
318 }
319
320 static gint64
321 total_time (void)
322 {
323         return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_TOTAL_TIME);
324 }
325
326 static gint64
327 working_set (void)
328 {
329         return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_WORKING_SET);
330 }
331
332 static gint64
333 private_bytes (void)
334 {
335         return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_PRIVATE_BYTES);
336 }
337
338 static gint64
339 virtual_bytes (void)
340 {
341         return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_VIRTUAL_BYTES);
342 }
343
344 static gint64
345 page_faults (void)
346 {
347         return mono_process_get_data (GINT_TO_POINTER (mono_process_current_pid ()), MONO_PROCESS_FAULTS);
348 }
349
350 static double
351 cpu_load (int kind)
352 {
353 #if defined(TARGET_WIN32)
354 #elif defined(TARGET_MACH)
355         double load [3];
356         if (getloadavg (load, 3) > 0)
357                 return load [kind];
358 #else
359         char buffer[512], *b;
360         int len, i;
361         FILE *f = fopen ("/proc/loadavg", "r");
362         if (f) {
363                 len = fread (buffer, 1, sizeof (buffer) - 1, f);
364                 fclose (f);
365                 if (len > 0) {
366                         buffer [len < 511 ? len : 511] = 0;
367                         b = buffer;
368                         for (i = 0; i < 3; i++) {
369                                 if (kind == i)
370                                         return strtod (b, NULL);
371                                 if (i < 2) {
372                                         b = strchr (b, ' ');
373                                         if (!b)
374                                                 return 0;
375                                         b += 1;
376                                 }
377                         }
378                 }
379         }
380 #endif
381         return 0;
382 }
383
384 static double
385 cpu_load_1min (void)
386 {
387         return cpu_load (0);
388 }
389
390 static double
391 cpu_load_5min (void)
392 {
393         return cpu_load (1);
394 }
395
396 static double
397 cpu_load_15min (void)
398 {
399         return cpu_load (2);
400 }
401
402 #define SYSCOUNTER_TIME (MONO_COUNTER_SYSTEM | MONO_COUNTER_LONG | MONO_COUNTER_TIME | MONO_COUNTER_MONOTONIC | MONO_COUNTER_CALLBACK)
403 #define SYSCOUNTER_BYTES (MONO_COUNTER_SYSTEM | MONO_COUNTER_LONG | MONO_COUNTER_BYTES | MONO_COUNTER_VARIABLE | MONO_COUNTER_CALLBACK)
404 #define SYSCOUNTER_COUNT (MONO_COUNTER_SYSTEM | MONO_COUNTER_LONG | MONO_COUNTER_COUNT | MONO_COUNTER_MONOTONIC | MONO_COUNTER_CALLBACK)
405 #define SYSCOUNTER_LOAD (MONO_COUNTER_SYSTEM | MONO_COUNTER_DOUBLE | MONO_COUNTER_PERCENTAGE | MONO_COUNTER_VARIABLE | MONO_COUNTER_CALLBACK)
406
407 static void
408 initialize_system_counters (void)
409 {
410         register_internal ("User Time", SYSCOUNTER_TIME, (gpointer) &user_time, sizeof (gint64));
411         register_internal ("System Time", SYSCOUNTER_TIME, (gpointer) &system_time, sizeof (gint64));
412         register_internal ("Total Time", SYSCOUNTER_TIME, (gpointer) &total_time, sizeof (gint64));
413         register_internal ("Working Set", SYSCOUNTER_BYTES, (gpointer) &working_set, sizeof (gint64));
414         register_internal ("Private Bytes", SYSCOUNTER_BYTES, (gpointer) &private_bytes, sizeof (gint64));
415         register_internal ("Virtual Bytes", SYSCOUNTER_BYTES, (gpointer) &virtual_bytes, sizeof (gint64));
416         register_internal ("Page Faults", SYSCOUNTER_COUNT, (gpointer) &page_faults, sizeof (gint64));
417         register_internal ("CPU Load Average - 1min", SYSCOUNTER_LOAD, (gpointer) &cpu_load_1min, sizeof (double));
418         register_internal ("CPU Load Average - 5min", SYSCOUNTER_LOAD, (gpointer) &cpu_load_5min, sizeof (double));
419         register_internal ("CPU Load Average - 15min", SYSCOUNTER_LOAD, (gpointer) &cpu_load_15min, sizeof (double));
420 }
421
422 /**
423  * mono_counters_foreach:
424  * @cb: The callback that will be called for each counter.
425  * @user_data: Value passed as second argument of the callback.
426  *
427  * Iterate over all counters and call @cb for each one of them. Stop iterating if
428  * the callback returns FALSE.
429  *
430  */
431 void
432 mono_counters_foreach (CountersEnumCallback cb, gpointer user_data)
433 {
434         MonoCounter *counter;
435
436         if (!initialized) {
437                 g_debug ("counters not enabled");
438                 return;
439         }
440
441         mono_os_mutex_lock (&counters_mutex);
442
443         for (counter = counters; counter; counter = counter->next) {
444                 if (!cb (counter, user_data)) {
445                         mono_os_mutex_unlock (&counters_mutex);
446                         return;
447                 }
448         }
449
450         mono_os_mutex_unlock (&counters_mutex);
451 }
452
453 #define COPY_COUNTER(type,functype) do {        \
454                 size = sizeof (type);   \
455                 if (buffer_size < size) \
456                         size = -1;      \
457                 else                    \
458                         *(type*)buffer = cb ? ((functype)counter->addr) () : *(type*)counter->addr; \
459         } while (0);
460
461 /* lockless */
462 static int
463 sample_internal (MonoCounter *counter, void *buffer, int buffer_size)
464 {
465         int cb = counter->type & MONO_COUNTER_CALLBACK;
466         int size = -1;
467
468         char *strval;
469
470         switch (mono_counter_get_type (counter)) {
471         case MONO_COUNTER_INT:
472                 COPY_COUNTER (int, IntFunc);
473                 break;
474         case MONO_COUNTER_UINT:
475                 COPY_COUNTER (guint, UIntFunc);
476                 break;
477         case MONO_COUNTER_LONG:
478         case MONO_COUNTER_TIME_INTERVAL:
479                 COPY_COUNTER (gint64, LongFunc);
480                 break;
481         case MONO_COUNTER_ULONG:
482                 COPY_COUNTER (guint64, ULongFunc);
483                 break;
484         case MONO_COUNTER_WORD:
485                 COPY_COUNTER (gssize, PtrFunc);
486                 break;
487         case MONO_COUNTER_DOUBLE:
488                 COPY_COUNTER (double, DoubleFunc);
489                 break;
490         case MONO_COUNTER_STRING:
491                 if (buffer_size < counter->size) {
492                         size = -1;
493                 } else if (counter->size == 0) {
494                         size = 0;
495                 } else {
496                         strval = cb ? ((StrFunc)counter->addr) () : (char*)counter->addr;
497                         if (!strval) {
498                                 size = 0;
499                         } else {
500                                 size = counter->size;
501                                 strncpy ((char *) buffer, strval, size - 1);
502                                 ((char*)buffer)[size - 1] = '\0';
503                         }
504                 }
505         }
506
507         return size;
508 }
509
510 int
511 mono_counters_sample (MonoCounter *counter, void *buffer, int buffer_size)
512 {
513         if (!initialized) {
514                 g_debug ("counters not enabled");
515                 return -1;
516         }
517
518         return sample_internal (counter, buffer, buffer_size);
519 }
520
521 #define ENTRY_FMT "%-36s: "
522 static void
523 dump_counter (MonoCounter *counter, FILE *outfile) {
524         void *buffer = g_malloc0 (counter->size);
525         int size = sample_internal (counter, buffer, counter->size);
526
527         switch (counter->type & MONO_COUNTER_TYPE_MASK) {
528         case MONO_COUNTER_INT:
529                 fprintf (outfile, ENTRY_FMT "%d\n", counter->name, *(int*)buffer);
530                 break;
531         case MONO_COUNTER_UINT:
532                 fprintf (outfile, ENTRY_FMT "%u\n", counter->name, *(guint*)buffer);
533                 break;
534         case MONO_COUNTER_LONG:
535                 if ((counter->type & MONO_COUNTER_UNIT_MASK) == MONO_COUNTER_TIME)
536                         fprintf (outfile, ENTRY_FMT "%.2f ms\n", counter->name, (double)(*(gint64*)buffer) / 10000.0);
537                 else
538                         fprintf (outfile, ENTRY_FMT "%lld\n", counter->name, *(long long *)buffer);
539                 break;
540         case MONO_COUNTER_ULONG:
541                 if ((counter->type & MONO_COUNTER_UNIT_MASK) == MONO_COUNTER_TIME)
542                         fprintf (outfile, ENTRY_FMT "%.2f ms\n", counter->name, (double)(*(guint64*)buffer) / 10000.0);
543                 else
544                         fprintf (outfile, ENTRY_FMT "%llu\n", counter->name, *(unsigned long long *)buffer);
545                 break;
546         case MONO_COUNTER_WORD:
547                 fprintf (outfile, ENTRY_FMT "%zd\n", counter->name, *(gssize*)buffer);
548                 break;
549         case MONO_COUNTER_DOUBLE:
550                 fprintf (outfile, ENTRY_FMT "%.4f\n", counter->name, *(double*)buffer);
551                 break;
552         case MONO_COUNTER_STRING:
553                 fprintf (outfile, ENTRY_FMT "%s\n", counter->name, (size == 0) ? "(null)" : (char*)buffer);
554                 break;
555         case MONO_COUNTER_TIME_INTERVAL:
556                 fprintf (outfile, ENTRY_FMT "%.2f ms\n", counter->name, (double)(*(gint64*)buffer) / 1000.0);
557                 break;
558         }
559
560         g_free (buffer);
561 }
562
563 static const char
564 section_names [][10] = {
565         "JIT",
566         "GC",
567         "Metadata",
568         "Generics",
569         "Security",
570         "Runtime",
571         "System",
572 };
573
574 static void
575 mono_counters_dump_section (int section, int variance, FILE *outfile)
576 {
577         MonoCounter *counter = counters;
578         while (counter) {
579                 if ((counter->type & section) && (mono_counter_get_variance (counter) & variance))
580                         dump_counter (counter, outfile);
581                 counter = counter->next;
582         }
583 }
584
585 /**
586  * mono_counters_dump:
587  * @section_mask: The sections to dump counters for
588  * @outfile: a FILE to dump the results to
589  *
590  * Displays the counts of all the enabled counters registered. 
591  * To filter by variance, you can OR one or more variance with the specific section you want.
592  * Use MONO_COUNTER_SECTION_MASK to dump all categories of a specific variance.
593  */
594 void
595 mono_counters_dump (int section_mask, FILE *outfile)
596 {
597         int i, j;
598         int variance;
599         section_mask &= valid_mask;
600
601         if (!initialized)
602                 return;
603
604         mono_os_mutex_lock (&counters_mutex);
605
606         if (!counters) {
607                 mono_os_mutex_unlock (&counters_mutex);
608                 return;
609         }
610
611         variance = section_mask & MONO_COUNTER_VARIANCE_MASK;
612
613         /* If no variance mask is supplied, we default to all kinds. */
614         if (!variance)
615                 variance = MONO_COUNTER_VARIANCE_MASK;
616         section_mask &= ~MONO_COUNTER_VARIANCE_MASK;
617
618         for (j = 0, i = MONO_COUNTER_JIT; i < MONO_COUNTER_LAST_SECTION; j++, i <<= 1) {
619                 if ((section_mask & i) && (set_mask & i)) {
620                         fprintf (outfile, "\n%s statistics\n", section_names [j]);
621                         mono_counters_dump_section (i, variance, outfile);
622                 }
623         }
624
625         fflush (outfile);
626         mono_os_mutex_unlock (&counters_mutex);
627 }
628
629 /**
630  * mono_counters_cleanup:
631  *
632  * Perform any needed cleanup at process exit.
633  */
634 void
635 mono_counters_cleanup (void)
636 {
637         MonoCounter *counter;
638
639         if (!initialized)
640                 return;
641
642         mono_os_mutex_lock (&counters_mutex);
643
644         counter = counters;
645         counters = NULL;
646         while (counter) {
647                 MonoCounter *tmp = counter;
648                 counter = counter->next;
649                 free ((void*)tmp->name);
650                 free (tmp);
651         }
652
653         mono_os_mutex_unlock (&counters_mutex);
654 }
655
656 static MonoResourceCallback limit_reached = NULL;
657 static uintptr_t resource_limits [MONO_RESOURCE_COUNT * 2];
658
659 /**
660  * mono_runtime_resource_check_limit:
661  * @resource_type: one of the #MonoResourceType enum values
662  * @value: the current value of the resource usage
663  *
664  * Check if a runtime resource limit has been reached. This function
665  * is intended to be used by the runtime only.
666  */
667 void
668 mono_runtime_resource_check_limit (int resource_type, uintptr_t value)
669 {
670         if (!limit_reached)
671                 return;
672         /* check the hard limit first */
673         if (value > resource_limits [resource_type * 2 + 1]) {
674                 limit_reached (resource_type, value, 0);
675                 return;
676         }
677         if (value > resource_limits [resource_type * 2])
678                 limit_reached (resource_type, value, 1);
679 }
680
681 /**
682  * mono_runtime_resource_limit:
683  * @resource_type: one of the #MonoResourceType enum values
684  * @soft_limit: the soft limit value
685  * @hard_limit: the hard limit value
686  *
687  * This function sets the soft and hard limit for runtime resources. When the limit
688  * is reached, a user-specified callback is called. The callback runs in a restricted
689  * environment, in which the world coult be stopped, so it can't take locks, perform
690  * allocations etc. The callback may be called multiple times once a limit has been reached
691  * if action is not taken to decrease the resource use.
692  *
693  * Returns: 0 on error or a positive integer otherwise.
694  */
695 int
696 mono_runtime_resource_limit (int resource_type, uintptr_t soft_limit, uintptr_t hard_limit)
697 {
698         if (resource_type >= MONO_RESOURCE_COUNT || resource_type < 0)
699                 return 0;
700         if (soft_limit > hard_limit)
701                 return 0;
702         resource_limits [resource_type * 2] = soft_limit;
703         resource_limits [resource_type * 2 + 1] = hard_limit;
704         return 1;
705 }
706
707 /**
708  * mono_runtime_resource_set_callback:
709  * @callback: a function pointer
710  * 
711  * Set the callback to be invoked when a resource limit is reached.
712  * The callback will receive the resource type, the resource amount in resource-specific
713  * units and a flag indicating whether the soft or hard limit was reached.
714  */
715 void
716 mono_runtime_resource_set_callback (MonoResourceCallback callback)
717 {
718         limit_reached = callback;
719 }
720
721