2008-10-31 Gonzalo Paniagua Javier <gonzalo@novell.com>
[mono.git] / mono / metadata / mono-perfcounters.c
1 /*
2  * mono-perfcounters.c
3  *
4  * Performance counters support.
5  *
6  * Author: Paolo Molaro (lupus@ximian.com)
7  *
8  * (C) 2008 Novell, Inc
9  */
10
11 #include "config.h"
12 #include <time.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #ifdef HAVE_SYS_TIME_H
16 #include <sys/time.h>
17 #endif
18 #include "metadata/mono-perfcounters.h"
19 #include "metadata/appdomain.h"
20 /* for mono_stats */
21 #include "metadata/class-internals.h"
22 #include "utils/mono-time.h"
23 #include "utils/mono-mmap.h"
24 #include "utils/mono-proclib.h"
25 #include <mono/io-layer/io-layer.h>
26
27 /* map of CounterSample.cs */
28 struct _MonoCounterSample {
29         gint64 rawValue;
30         gint64 baseValue;
31         gint64 counterFrequency;
32         gint64 systemFrequency;
33         gint64 timeStamp;
34         gint64 timeStamp100nSec;
35         gint64 counterTimeStamp;
36         int counterType;
37 };
38
39 /* map of PerformanceCounterType.cs */
40 enum {
41         NumberOfItemsHEX32=0x00000000,
42         NumberOfItemsHEX64=0x00000100,
43         NumberOfItems32=0x00010000,
44         NumberOfItems64=0x00010100,
45         CounterDelta32=0x00400400,
46         CounterDelta64=0x00400500,
47         SampleCounter=0x00410400,
48         CountPerTimeInterval32=0x00450400,
49         CountPerTimeInterval64=0x00450500,
50         RateOfCountsPerSecond32=0x10410400,
51         RateOfCountsPerSecond64=0x10410500,
52         RawFraction=0x20020400,
53         CounterTimer=0x20410500,
54         Timer100Ns=0x20510500,
55         SampleFraction=0x20C20400,
56         CounterTimerInverse=0x21410500,
57         Timer100NsInverse=0x21510500,
58         CounterMultiTimer=0x22410500,
59         CounterMultiTimer100Ns=0x22510500,
60         CounterMultiTimerInverse=0x23410500,
61         CounterMultiTimer100NsInverse=0x23510500,
62         AverageTimer32=0x30020400,
63         ElapsedTime=0x30240500,
64         AverageCount64=0x40020500,
65         SampleBase=0x40030401,
66         AverageBase=0x40030402,
67         RawBase=0x40030403,
68         CounterMultiBase=0x42030500
69 };
70
71 /* maps a small integer type to the counter types above */
72 static const int
73 simple_type_to_type [] = {
74         NumberOfItemsHEX32, NumberOfItemsHEX64,
75         NumberOfItems32, NumberOfItems64,
76         CounterDelta32, CounterDelta64,
77         SampleCounter, CountPerTimeInterval32,
78         CountPerTimeInterval64, RateOfCountsPerSecond32,
79         RateOfCountsPerSecond64, RawFraction,
80         CounterTimer, Timer100Ns,
81         SampleFraction, CounterTimerInverse,
82         Timer100NsInverse, CounterMultiTimer,
83         CounterMultiTimer100Ns, CounterMultiTimerInverse,
84         CounterMultiTimer100NsInverse, AverageTimer32,
85         ElapsedTime, AverageCount64,
86         SampleBase, AverageBase,
87         RawBase, CounterMultiBase
88 };
89
90 enum {
91         SingleInstance,
92         MultiInstance,
93         CatTypeUnknown = -1
94 };
95
96 enum {
97         ProcessInstance,
98         ThreadInstance,
99         CPUInstance,
100         MonoInstance,
101         CustomInstance
102 };
103
104 #define PERFCTR_CAT(id,name,help,type,inst,first_counter) CATEGORY_ ## id,
105 #define PERFCTR_COUNTER(id,name,help,type,field)
106 enum {
107 #include "mono-perfcounters-def.h"
108         NUM_CATEGORIES
109 };
110
111 #undef PERFCTR_CAT
112 #undef PERFCTR_COUNTER
113 #define PERFCTR_CAT(id,name,help,type,inst,first_counter) CATEGORY_START_ ## id = -1,
114 #define PERFCTR_COUNTER(id,name,help,type,field) COUNTER_ ## id,
115 /* each counter is assigned an id starting from 0 inside the category */
116 enum {
117 #include "mono-perfcounters-def.h"
118         END_COUNTERS
119 };
120
121 #undef PERFCTR_CAT
122 #undef PERFCTR_COUNTER
123 #define PERFCTR_CAT(id,name,help,type,inst,first_counter)
124 #define PERFCTR_COUNTER(id,name,help,type,field) CCOUNTER_ ## id,
125 /* this is used just to count the number of counters */
126 enum {
127 #include "mono-perfcounters-def.h"
128         NUM_COUNTERS
129 };
130
131 static CRITICAL_SECTION perfctr_mutex;
132 #define perfctr_lock() EnterCriticalSection (&perfctr_mutex)
133 #define perfctr_unlock() LeaveCriticalSection (&perfctr_mutex)
134
135 typedef struct {
136         char reserved [16];
137         int size;
138         unsigned short counters_start;
139         unsigned short counters_size;
140         unsigned short data_start;
141         MonoPerfCounters counters;
142         char data [1];
143 } MonoSharedArea;
144
145 /*
146   binary format of custom counters in shared memory, starting from MonoSharedArea* + data_start;
147   basic stanza:
148   struct stanza_header {
149         byte stanza_type; // FTYPE_*
150         byte other_info;
151         ushort stanza_length; // includeas header
152         ... data ...
153   }
154
155 // strings are utf8
156 // perfcat and perfinstance are 4-bytes aligned
157 struct perfcat {
158         byte typeidx;
159         byte categorytype;
160         ushort length; // includes the counters
161         ushort num_counters;
162         ushort counters_data_size;
163         int num_instances;
164         char name[]; // null terminated
165         char help[]; // null terminated
166         // perfcounters follow
167         {
168                 byte countertype;
169                 char name[]; // null terminated
170                 char help[]; // null terminated
171         }
172         0-byte
173 };
174
175 struct perfinstance {
176         byte typeidx;
177         byte data_offset; // offset of counters from beginning of struct
178         ushort length;
179         uint category_offset; // offset of category in the shared area
180         char name[]; // null terminated
181         // data follows: this is always 8-byte aligned
182 };
183
184 */
185
186 enum {
187         FTYPE_CATEGORY = 'C',
188         FTYPE_DELETED = 'D',
189         FTYPE_PREDEF_INSTANCE = 'P', // an instance of a predef counter
190         FTYPE_INSTANCE = 'I',
191         FTYPE_DIRTY = 'd',
192         FTYPE_END = 0
193 };
194
195 typedef struct {
196         unsigned char ftype;
197         unsigned char extra;
198         unsigned short size;
199 } SharedHeader;
200
201 typedef struct {
202         SharedHeader header;
203         unsigned short num_counters;
204         unsigned short counters_data_size;
205         int num_instances;
206         /* variable length data follows */
207         char name [1];
208 } SharedCategory;
209
210 typedef struct {
211         SharedHeader header;
212         unsigned int category_offset;
213         /* variable length data follows */
214         char name [1];
215 } SharedInstance;
216
217 typedef struct {
218         unsigned char type;
219         /* variable length data follows */
220         char name [1];
221 } SharedCounter;
222
223 typedef struct {
224         const char *name;
225         const char *help;
226         unsigned char id;
227         signed int type : 2;
228         unsigned int instance_type : 6;
229         short first_counter;
230 } CategoryDesc;
231
232 typedef struct {
233         const char *name;
234         const char *help;
235         short id;
236         unsigned short offset; // offset inside MonoPerfCounters
237         int type;
238 } CounterDesc;
239
240 #undef PERFCTR_CAT
241 #undef PERFCTR_COUNTER
242 #define PERFCTR_CAT(id,name,help,type,inst,first_counter) {name, help, CATEGORY_ ## id, type, inst ## Instance, CCOUNTER_ ## first_counter},
243 #define PERFCTR_COUNTER(id,name,help,type,field)
244 static const CategoryDesc
245 predef_categories [] = {
246 #include "mono-perfcounters-def.h"
247         {NULL, NULL, NUM_CATEGORIES, -1, 0, NUM_COUNTERS}
248 };
249
250 #undef PERFCTR_CAT
251 #undef PERFCTR_COUNTER
252 #define PERFCTR_CAT(id,name,help,type,inst,first_counter)
253 #define PERFCTR_COUNTER(id,name,help,type,field) {name, help, COUNTER_ ## id, G_STRUCT_OFFSET (MonoPerfCounters, field), type},
254 static const CounterDesc
255 predef_counters [] = {
256 #include "mono-perfcounters-def.h"
257         {NULL, NULL, -1, 0, 0}
258 };
259
260 /*
261  * We have several different classes of counters:
262  * *) system counters
263  * *) runtime counters
264  * *) remote counters
265  * *) user-defined counters
266  * *) windows counters (the implementation on windows will use this)
267  *
268  * To easily handle the differences we create a vtable for each class that contains the
269  * function pointers with the actual implementation to access the counters.
270  */
271 typedef struct _ImplVtable ImplVtable;
272
273 typedef MonoBoolean (*SampleFunc) (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample* sample);
274 typedef gint64 (*UpdateFunc) (ImplVtable *vtable, MonoBoolean do_incr, gint64 value);
275 typedef void (*CleanupFunc) (ImplVtable *vtable);
276
277 struct _ImplVtable {
278         void *arg;
279         SampleFunc sample;
280         UpdateFunc update;
281         CleanupFunc cleanup;
282 };
283
284 typedef struct {
285         ImplVtable vtable;
286         MonoPerfCounters *counters;
287         int pid;
288 } PredefVtable;
289
290 static ImplVtable*
291 create_vtable (void *arg, SampleFunc sample, UpdateFunc update)
292 {
293         ImplVtable *vtable = g_new0 (ImplVtable, 1);
294         vtable->arg = arg;
295         vtable->sample = sample;
296         vtable->update = update;
297         return vtable;
298 }
299
300 MonoPerfCounters *mono_perfcounters = NULL;
301 static MonoSharedArea *shared_area = NULL;
302
303 typedef struct {
304         void *sarea;
305         int refcount;
306 } ExternalSArea;
307
308 /* maps a pid to a ExternalSArea pointer */
309 static GHashTable *pid_to_shared_area = NULL;
310
311 static MonoSharedArea *
312 load_sarea_for_pid (int pid)
313 {
314         ExternalSArea *data;
315         MonoSharedArea *area = NULL;
316
317         perfctr_lock ();
318         if (pid_to_shared_area == NULL)
319                 pid_to_shared_area = g_hash_table_new (NULL, NULL);
320         data = g_hash_table_lookup (pid_to_shared_area, GINT_TO_POINTER (pid));
321         if (!data) {
322                 area = mono_shared_area_for_pid (GINT_TO_POINTER (pid));
323                 if (area) {
324                         data = g_new (ExternalSArea, 1);
325                         data->sarea = area;
326                         data->refcount = 1;
327                         g_hash_table_insert (pid_to_shared_area, GINT_TO_POINTER (pid), data);
328                 }
329         } else {
330                 area = data->sarea;
331                 data->refcount ++;
332         }
333         perfctr_unlock ();
334         return area;
335 }
336
337 static void
338 predef_cleanup (ImplVtable *vtable)
339 {
340         PredefVtable *vt = (PredefVtable*)vtable;
341         ExternalSArea *data;
342         perfctr_lock ();
343         if (!pid_to_shared_area) {
344                 perfctr_unlock ();
345                 return;
346         }
347         data = g_hash_table_lookup (pid_to_shared_area, GINT_TO_POINTER (vt->pid));
348         if (data) {
349                 data->refcount--;
350                 if (!data->refcount) {
351                         g_hash_table_remove (pid_to_shared_area, GINT_TO_POINTER (vt->pid));
352                         mono_shared_area_unload (data->sarea);
353                         g_free (data);
354                 }
355         }
356         perfctr_unlock ();
357 }
358
359 void
360 mono_perfcounters_init (void)
361 {
362         int d_offset = G_STRUCT_OFFSET (MonoSharedArea, data);
363         d_offset += 7;
364         d_offset &= ~7;
365
366         InitializeCriticalSection (&perfctr_mutex);
367
368         shared_area = mono_shared_area ();
369         shared_area->counters_start = G_STRUCT_OFFSET (MonoSharedArea, counters);
370         shared_area->counters_size = sizeof (MonoPerfCounters);
371         shared_area->data_start = d_offset;
372         shared_area->size = 4096;
373         mono_perfcounters = &shared_area->counters;
374 }
375
376 static int
377 perfctr_type_compress (int type)
378 {
379         int i;
380         for (i = 0; i < G_N_ELEMENTS (simple_type_to_type); ++i) {
381                 if (simple_type_to_type [i] == type)
382                         return i;
383         }
384         /* NumberOfItems32 */
385         return 2;
386 }
387
388 static unsigned char*
389 shared_data_find_room (int size)
390 {
391         unsigned char *p = (unsigned char *)shared_area + shared_area->data_start;
392         unsigned char *end = (unsigned char *)shared_area + shared_area->size;
393
394         size += 3;
395         size &= ~3;
396         while (p < end) {
397                 unsigned short *next;
398                 if (*p == FTYPE_END) {
399                         if (size < (end - p))
400                                 return p;
401                         return NULL;
402                 }
403                 if (p + 4 > end)
404                         return NULL;
405                 next = (unsigned short*)(p + 2);
406                 if (*p == FTYPE_DELETED) {
407                         /* we reuse only if it's the same size */
408                         if (*next == size) {
409                                 return p;
410                         }
411                 }
412                 p += *next;
413         }
414         return NULL;
415 }
416
417 typedef gboolean (*SharedFunc) (SharedHeader *header, void *data);
418
419 static void
420 foreach_shared_item (SharedFunc func, void *data)
421 {
422         unsigned char *p = (unsigned char *)shared_area + shared_area->data_start;
423         unsigned char *end = (unsigned char *)shared_area + shared_area->size;
424
425         while (p < end) {
426                 unsigned short *next;
427                 if (p + 4 > end)
428                         return;
429                 next = (unsigned short*)(p + 2);
430                 if (!func ((SharedHeader*)p, data))
431                         return;
432                 if (*p == FTYPE_END)
433                         return;
434                 p += *next;
435         }
436 }
437
438 static int
439 mono_string_compare_ascii (MonoString *str, const char *ascii_str)
440 {
441         /* FIXME: make this case insensitive */
442         guint16 *strc = mono_string_chars (str);
443         while (*strc == *ascii_str++) {
444                 if (*strc == 0)
445                         return 0;
446                 strc++;
447         }
448         return *strc - *(const unsigned char *)(ascii_str - 1);
449 }
450
451 typedef struct {
452         MonoString *name;
453         SharedCategory *cat;
454 } CatSearch;
455
456 static gboolean
457 category_search (SharedHeader *header, void *data)
458 {
459         CatSearch *search = data;
460         if (header->ftype == FTYPE_CATEGORY) {
461                 SharedCategory *cat = (SharedCategory*)header;
462                 if (mono_string_compare_ascii (search->name, cat->name) == 0) {
463                         search->cat = cat;
464                         return FALSE;
465                 }
466         }
467         return TRUE;
468 }
469
470 static SharedCategory*
471 find_custom_category (MonoString *name)
472 {
473         CatSearch search;
474         search.name = name;
475         search.cat = NULL;
476         foreach_shared_item (category_search, &search);
477         return search.cat;
478 }
479
480 static gboolean
481 category_collect (SharedHeader *header, void *data)
482 {
483         GSList **list = data;
484         if (header->ftype == FTYPE_CATEGORY) {
485                 *list = g_slist_prepend (*list, header);
486         }
487         return TRUE;
488 }
489
490 static GSList*
491 get_custom_categories (void) {
492         GSList *list = NULL;
493         foreach_shared_item (category_collect, &list);
494         return list;
495 }
496
497 static char*
498 custom_category_counters (SharedCategory* cat)
499 {
500         char *p = cat->name + strlen (cat->name) + 1;
501         p += strlen (p) + 1; /* skip category help */
502         return p;
503 }
504
505 static SharedCounter*
506 find_custom_counter (SharedCategory* cat, MonoString *name)
507 {
508         int i;
509         char *p = custom_category_counters (cat);
510         for (i = 0; i < cat->num_counters; ++i) {
511                 SharedCounter *counter = (SharedCounter*)p;
512                 if (mono_string_compare_ascii (name, counter->name) == 0)
513                         return counter;
514                 p += 1 + strlen (p + 1) + 1; /* skip counter type and name */
515                 p += strlen (p) + 1; /* skip counter help */
516         }
517         return NULL;
518 }
519
520 static char*
521 custom_category_help (SharedCategory* cat)
522 {
523         return cat->name + strlen (cat->name) + 1;
524 }
525
526 static const CounterDesc*
527 get_counter_in_category (const CategoryDesc *desc, MonoString *counter)
528 {
529         const CounterDesc *cdesc = &predef_counters [desc->first_counter];
530         const CounterDesc *end = &predef_counters [desc [1].first_counter];
531         for (; cdesc < end; ++cdesc) {
532                 if (mono_string_compare_ascii (counter, cdesc->name) == 0)
533                         return cdesc;
534         }
535         return NULL;
536 }
537
538 /* fill the info in sample (except the raw value) */
539 static void
540 fill_sample (MonoCounterSample *sample)
541 {
542         sample->timeStamp = mono_100ns_ticks ();
543         sample->timeStamp100nSec = sample->timeStamp;
544         sample->counterTimeStamp = sample->timeStamp;
545         sample->counterFrequency = 10000000;
546         sample->systemFrequency = 10000000;
547         // the real basevalue needs to be get from a different counter...
548         sample->baseValue = 0;
549 }
550
551 static int
552 id_from_string (MonoString *instance, gboolean is_process)
553 {
554         int id = -1;
555         if (mono_string_length (instance)) {
556                 char *id_str = mono_string_to_utf8 (instance);
557                 char *end;
558                 id = strtol (id_str, &end, 0);
559                 if (end == id_str && !is_process)
560                         id = -1;
561                 g_free (id_str);
562         }
563         return id;
564 }
565
566 static MonoBoolean
567 get_cpu_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
568 {
569         MonoProcessError error;
570         int id = GPOINTER_TO_INT (vtable->arg);
571         int pid = id >> 5;
572         id &= 0x1f;
573         if (!only_value) {
574                 fill_sample (sample);
575                 sample->baseValue = 1;
576         }
577         sample->counterType = predef_counters [predef_categories [CATEGORY_CPU].first_counter + id].type;
578         switch (id) {
579         case COUNTER_CPU_USER_TIME:
580                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_USER_TIME, &error);
581                 return TRUE;
582         case COUNTER_CPU_PRIV_TIME:
583                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_PRIV_TIME, &error);
584                 return TRUE;
585         case COUNTER_CPU_INTR_TIME:
586                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_INTR_TIME, &error);
587                 return TRUE;
588         case COUNTER_CPU_DCP_TIME:
589                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_DCP_TIME, &error);
590                 return TRUE;
591         case COUNTER_CPU_PROC_TIME:
592                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_IDLE_TIME, &error);
593                 return TRUE;
594         }
595         return FALSE;
596 }
597
598 static void*
599 cpu_get_impl (MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
600 {
601         int id = id_from_string (instance, FALSE) << 5;
602         const CounterDesc *cdesc;
603         *custom = FALSE;
604         /* increase the shift above and the mask also in the implementation functions */
605         //g_assert (32 > desc [1].first_counter - desc->first_counter);
606         if ((cdesc = get_counter_in_category (&predef_categories [CATEGORY_CPU], counter))) {
607                 *type = cdesc->type;
608                 return create_vtable (GINT_TO_POINTER (id | cdesc->id), get_cpu_counter, NULL);
609         }
610         return NULL;
611 }
612
613 static MonoBoolean
614 get_process_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
615 {
616         int id = GPOINTER_TO_INT (vtable->arg);
617         int pid = id >> 5;
618         if (pid < 0)
619                 return FALSE;
620         id &= 0x1f;
621         if (!only_value) {
622                 fill_sample (sample);
623                 sample->baseValue = 1;
624         }
625         sample->counterType = predef_counters [predef_categories [CATEGORY_PROC].first_counter + id].type;
626         switch (id) {
627         case COUNTER_PROC_USER_TIME:
628                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_USER_TIME);
629                 return TRUE;
630         case COUNTER_PROC_PRIV_TIME:
631                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_SYSTEM_TIME);
632                 return TRUE;
633         case COUNTER_PROC_PROC_TIME:
634                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_TOTAL_TIME);
635                 return TRUE;
636         case COUNTER_PROC_THREADS:
637                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_NUM_THREADS);
638                 return TRUE;
639         case COUNTER_PROC_VBYTES:
640                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_VIRTUAL_BYTES);
641                 return TRUE;
642         case COUNTER_PROC_WSET:
643                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_WORKING_SET);
644                 return TRUE;
645         case COUNTER_PROC_PBYTES:
646                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_PRIVATE_BYTES);
647                 return TRUE;
648         }
649         return FALSE;
650 }
651
652 static void*
653 process_get_impl (MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
654 {
655         int id = id_from_string (instance, TRUE) << 5;
656         const CounterDesc *cdesc;
657         *custom = FALSE;
658         /* increase the shift above and the mask also in the implementation functions */
659         //g_assert (32 > desc [1].first_counter - desc->first_counter);
660         if ((cdesc = get_counter_in_category (&predef_categories [CATEGORY_PROC], counter))) {
661                 *type = cdesc->type;
662                 return create_vtable (GINT_TO_POINTER (id | cdesc->id), get_process_counter, NULL);
663         }
664         return NULL;
665 }
666
667 static MonoBoolean
668 mono_mem_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
669 {
670         int id = GPOINTER_TO_INT (vtable->arg);
671         if (!only_value) {
672                 fill_sample (sample);
673                 sample->baseValue = 1;
674         }
675         sample->counterType = predef_counters [predef_categories [CATEGORY_MONO_MEM].first_counter + id].type;
676         switch (id) {
677         case COUNTER_MEM_NUM_OBJECTS:
678                 sample->rawValue = mono_stats.new_object_count;
679                 return TRUE;
680         }
681         return FALSE;
682 }
683
684 static void*
685 mono_mem_get_impl (MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
686 {
687         const CounterDesc *cdesc;
688         *custom = FALSE;
689         if ((cdesc = get_counter_in_category (&predef_categories [CATEGORY_MONO_MEM], counter))) {
690                 *type = cdesc->type;
691                 return create_vtable (GINT_TO_POINTER (cdesc->id), mono_mem_counter, NULL);
692         }
693         return NULL;
694 }
695
696 static MonoBoolean
697 predef_readonly_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
698 {
699         PredefVtable *vt = (PredefVtable *)vtable;
700         const CounterDesc *desc;
701         int cat_id = GPOINTER_TO_INT (vtable->arg);
702         int id = cat_id >> 16;
703         cat_id &= 0xffff;
704         if (!only_value) {
705                 fill_sample (sample);
706                 sample->baseValue = 1;
707         }
708         desc = &predef_counters [predef_categories [cat_id].first_counter + id];
709         sample->counterType = desc->type;
710         /* FIXME: check that the offset fits inside imported counters */
711         /*g_print ("loading %s at %d\n", desc->name, desc->offset);*/
712         sample->rawValue = *(guint32*)((char*)vt->counters + desc->offset);
713         return TRUE;
714 }
715
716 static ImplVtable*
717 predef_vtable (void *arg, MonoString *instance)
718 {
719         MonoSharedArea *area;
720         PredefVtable *vtable;
721         char *pids = mono_string_to_utf8 (instance);
722         int pid;
723
724         pid = atoi (pids);
725         g_free (pids);
726         area = load_sarea_for_pid (pid);
727         if (!area)
728                 return NULL;
729
730         vtable = g_new (PredefVtable, 1);
731         vtable->vtable.arg = arg;
732         vtable->vtable.sample = predef_readonly_counter;
733         vtable->vtable.cleanup = predef_cleanup;
734         vtable->counters = (MonoPerfCounters*)((char*)area + area->counters_start);
735         vtable->pid = pid;
736
737         return (ImplVtable*)vtable;
738 }
739
740 /* consider storing the pointer directly in vtable->arg, so the runtime overhead is lower:
741  * this needs some way to set sample->counterType as well, though.
742  */
743 static MonoBoolean
744 predef_writable_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
745 {
746         int cat_id = GPOINTER_TO_INT (vtable->arg);
747         int id = cat_id >> 16;
748         cat_id &= 0xffff;
749         if (!only_value) {
750                 fill_sample (sample);
751                 sample->baseValue = 1;
752         }
753         sample->counterType = predef_counters [predef_categories [cat_id].first_counter + id].type;
754         switch (cat_id) {
755         case CATEGORY_ASPNET:
756                 switch (id) {
757                 case COUNTER_ASPNET_REQ_Q:
758                         sample->rawValue = mono_perfcounters->aspnet_requests_queued;
759                         return TRUE;
760                 }
761                 break;
762         }
763         return FALSE;
764 }
765
766 static gint64
767 predef_writable_update (ImplVtable *vtable, MonoBoolean do_incr, gint64 value)
768 {
769         guint32 *ptr = NULL;
770         int cat_id = GPOINTER_TO_INT (vtable->arg);
771         int id = cat_id >> 16;
772         cat_id &= 0xffff;
773         switch (cat_id) {
774         case CATEGORY_ASPNET:
775                 switch (id) {
776                 case COUNTER_ASPNET_REQ_Q: ptr = &mono_perfcounters->aspnet_requests_queued; break;
777                 }
778                 break;
779         }
780         if (ptr) {
781                 if (do_incr) {
782                         /* FIXME: we need to do this atomically */
783                         *ptr += value;
784                         return *ptr;
785                 }
786                 /* this can be non-atomic */
787                 *ptr = value;
788                 return value;
789         }
790         return 0;
791 }
792
793 static void*
794 predef_writable_get_impl (int cat, MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
795 {
796         const CounterDesc *cdesc;
797         *custom = TRUE;
798         if ((cdesc = get_counter_in_category (&predef_categories [cat], counter))) {
799                 *type = cdesc->type;
800                 if (instance == NULL || mono_string_compare_ascii (instance, "") == 0)
801                         return create_vtable (GINT_TO_POINTER ((cdesc->id << 16) | cat), predef_writable_counter, predef_writable_update);
802                 else
803                         return predef_vtable (GINT_TO_POINTER ((cdesc->id << 16) | cat), instance);
804         }
805         return NULL;
806 }
807
808 static MonoBoolean
809 custom_writable_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
810 {
811         SharedCounter *scounter = vtable->arg;
812         if (!only_value) {
813                 fill_sample (sample);
814                 sample->baseValue = 1;
815         }
816         sample->counterType = simple_type_to_type [scounter->type];
817         /* FIXME */
818         sample->rawValue = 0;
819         return TRUE;
820 }
821
822 static gint64
823 custom_writable_update (ImplVtable *vtable, MonoBoolean do_incr, gint64 value)
824 {
825         /* FIXME */
826         guint32 *ptr = NULL;
827         if (ptr) {
828                 if (do_incr) {
829                         /* FIXME: we need to do this atomically */
830                         *ptr += value;
831                         return *ptr;
832                 }
833                 /* this can be non-atomic */
834                 *ptr = value;
835                 return value;
836         }
837         return 0;
838 }
839
840 static void*
841 custom_get_impl (SharedCategory *cat, MonoString* counter, MonoString* instance, int *type)
842 {
843         SharedCounter *scounter;
844
845         scounter = find_custom_counter (cat, counter);
846         if (!scounter)
847                 return NULL;
848         *type = simple_type_to_type [scounter->type];
849         /* FIXME: use instance */
850         return create_vtable (scounter, custom_writable_counter, custom_writable_update);
851 }
852
853 static const CategoryDesc*
854 find_category (MonoString *category)
855 {
856         int i;
857         for (i = 0; i < NUM_CATEGORIES; ++i) {
858                 if (mono_string_compare_ascii (category, predef_categories [i].name) == 0)
859                         return &predef_categories [i];
860         }
861         return NULL;
862 }
863
864 void*
865 mono_perfcounter_get_impl (MonoString* category, MonoString* counter, MonoString* instance,
866                 MonoString* machine, int *type, MonoBoolean *custom)
867 {
868         const CategoryDesc *cdesc;
869         /* no support for counters on other machines */
870         if (mono_string_compare_ascii (machine, "."))
871                 return NULL;
872         cdesc = find_category (category);
873         if (!cdesc) {
874                 SharedCategory *scat = find_custom_category (category);
875                 if (!scat)
876                         return NULL;
877                 *custom = TRUE;
878                 return custom_get_impl (scat, counter, instance, type);
879         }
880         switch (cdesc->id) {
881         case CATEGORY_CPU:
882                 return cpu_get_impl (counter, instance, type, custom);
883         case CATEGORY_PROC:
884                 return process_get_impl (counter, instance, type, custom);
885         case CATEGORY_MONO_MEM:
886                 return mono_mem_get_impl (counter, instance, type, custom);
887         case CATEGORY_JIT:
888         case CATEGORY_EXC:
889         case CATEGORY_GC:
890         case CATEGORY_REMOTING:
891         case CATEGORY_LOADING:
892         case CATEGORY_THREAD:
893         case CATEGORY_INTEROP:
894         case CATEGORY_SECURITY:
895         case CATEGORY_ASPNET:
896                 return predef_writable_get_impl (cdesc->id, counter, instance, type, custom);
897         }
898         return NULL;
899 }
900
901 MonoBoolean
902 mono_perfcounter_get_sample (void *impl, MonoBoolean only_value, MonoCounterSample *sample)
903 {
904         ImplVtable *vtable = impl;
905         if (vtable && vtable->sample)
906                 return vtable->sample (vtable, only_value, sample);
907         return FALSE;
908 }
909
910 gint64
911 mono_perfcounter_update_value (void *impl, MonoBoolean do_incr, gint64 value)
912 {
913         ImplVtable *vtable = impl;
914         if (vtable && vtable->update)
915                 return vtable->update (vtable, do_incr, value);
916         return 0;
917 }
918
919 void
920 mono_perfcounter_free_data (void *impl)
921 {
922         ImplVtable *vtable = impl;
923         if (vtable && vtable->cleanup)
924                 vtable->cleanup (vtable);
925         g_free (impl);
926 }
927
928 /* Category icalls */
929 MonoBoolean
930 mono_perfcounter_category_del (MonoString *name)
931 {
932         const CategoryDesc *cdesc;
933         SharedCategory *cat;
934         cdesc = find_category (name);
935         /* can't delete a predefined category */
936         if (cdesc)
937                 return FALSE;
938         perfctr_lock ();
939         cat = find_custom_category (name);
940         /* FIXME: check the semantics, if deleting a category means also deleting the instances */
941         if (!cat || cat->num_instances) {
942                 perfctr_unlock ();
943                 return FALSE;
944         }
945         cat->header.ftype = FTYPE_DELETED;
946         perfctr_unlock ();
947         return TRUE;
948 }
949
950 MonoString*
951 mono_perfcounter_category_help (MonoString *category, MonoString *machine)
952 {
953         const CategoryDesc *cdesc;
954         /* no support for counters on other machines */
955         if (mono_string_compare_ascii (machine, "."))
956                 return NULL;
957         cdesc = find_category (category);
958         if (!cdesc) {
959                 SharedCategory *scat = find_custom_category (category);
960                 if (!scat)
961                         return NULL;
962                 return mono_string_new (mono_domain_get (), custom_category_help (scat));
963         }
964         return mono_string_new (mono_domain_get (), cdesc->help);
965 }
966
967 /*
968  * Check if the category named @category exists on @machine. If @counter is not NULL, return
969  * TRUE only if a counter with that name exists in the category.
970  */
971 MonoBoolean
972 mono_perfcounter_category_exists (MonoString *counter, MonoString *category, MonoString *machine)
973 {
974         const CategoryDesc *cdesc;
975         /* no support for counters on other machines */
976         if (mono_string_compare_ascii (machine, "."))
977                 return FALSE;
978         cdesc = find_category (category);
979         if (!cdesc) {
980                 SharedCategory *scat = find_custom_category (category);
981                 if (!scat)
982                         return FALSE;
983                 /* counter is allowed to be null */
984                 if (!counter)
985                         return TRUE;
986                 /* search through the custom category */
987                 return find_custom_counter (scat, counter) != NULL;
988         }
989         /* counter is allowed to be null */
990         if (!counter)
991                 return TRUE;
992         if (get_counter_in_category (cdesc, counter))
993                 return TRUE;
994         return FALSE;
995 }
996
997 /* C map of the type with the same name */
998 typedef struct {
999         MonoObject object;
1000         MonoString *help;
1001         MonoString *name;
1002         int type;
1003 } CounterCreationData;
1004
1005 /*
1006  * Since we'll keep a copy of the category per-process, we should also make sure
1007  * categories with the same name are compatible.
1008  */
1009 MonoBoolean
1010 mono_perfcounter_create (MonoString *category, MonoString *help, int type, MonoArray *items)
1011 {
1012         int result = FALSE;
1013         int i, size;
1014         int num_counters = mono_array_length (items);
1015         int counters_data_size;
1016         char *name = mono_string_to_utf8 (category);
1017         char *chelp = mono_string_to_utf8 (help);
1018         char **counter_info;
1019         unsigned char *ptr;
1020         char *p;
1021         SharedCategory *cat;
1022
1023         counter_info = g_new0 (char*, num_counters * 2);
1024         /* calculate the size we need structure size + name/help + 2 0 string terminators */
1025         size = G_STRUCT_OFFSET (SharedCategory, name) + strlen (name) + strlen (chelp) + 2;
1026         for (i = 0; i < num_counters; ++i) {
1027                 CounterCreationData *data = mono_array_get (items, CounterCreationData*, i);
1028                 counter_info [i * 2] = mono_string_to_utf8 (data->name);
1029                 counter_info [i * 2 + 1] = mono_string_to_utf8 (data->help);
1030                 size += 3; /* type and two 0 string terminators */
1031         }
1032         for (i = 0; i < num_counters * 2; ++i) {
1033                 if (!counter_info [i])
1034                         goto failure;
1035                 size += strlen (counter_info [i]);
1036         }
1037         counters_data_size = num_counters * 8; /* optimize for size later */
1038         if (size > 65535)
1039                 goto failure;
1040         perfctr_lock ();
1041         ptr = shared_data_find_room (size);
1042         if (!ptr) {
1043                 perfctr_unlock ();
1044                 goto failure;
1045         }
1046         cat = (SharedCategory*)ptr;
1047         cat->header.extra = type;
1048         cat->header.size = size;
1049         cat->num_counters = num_counters;
1050         cat->counters_data_size = counters_data_size;
1051         /* now copy the vaiable data */
1052         p = cat->name;
1053         strcpy (p, name);
1054         p += strlen (name) + 1;
1055         strcpy (p, chelp);
1056         p += strlen (chelp) + 1;
1057         for (i = 0; i < num_counters; ++i) {
1058                 CounterCreationData *data = mono_array_get (items, CounterCreationData*, i);
1059                 *p++ = perfctr_type_compress (data->type);
1060                 strcpy (p, counter_info [i * 2]);
1061                 p += strlen (counter_info [i * 2]) + 1;
1062                 strcpy (p, counter_info [i * 2 + 1]);
1063                 p += strlen (counter_info [i * 2 + 1]) + 1;
1064         }
1065         cat->header.ftype = FTYPE_CATEGORY;
1066
1067         perfctr_unlock ();
1068         result = TRUE;
1069 failure:
1070         for (i = 0; i < num_counters * 2; ++i) {
1071                 g_free (counter_info [i]);
1072         }
1073         g_free (counter_info);
1074         g_free (name);
1075         g_free (chelp);
1076         return result;
1077 }
1078
1079 int
1080 mono_perfcounter_instance_exists (MonoString *instance, MonoString *category, MonoString *machine)
1081 {
1082         const CategoryDesc *cdesc;
1083         /* no support for counters on other machines */
1084         if (mono_string_compare_ascii (machine, "."))
1085                 return FALSE;
1086         cdesc = find_category (category);
1087         if (!cdesc)
1088                 return FALSE;
1089         return FALSE;
1090 }
1091
1092 MonoArray*
1093 mono_perfcounter_category_names (MonoString *machine)
1094 {
1095         int i;
1096         MonoArray *res;
1097         MonoDomain *domain = mono_domain_get ();
1098         GSList *custom_categories, *tmp;
1099         /* no support for counters on other machines */
1100         if (mono_string_compare_ascii (machine, "."))
1101                 return mono_array_new (domain, mono_get_string_class (), 0);
1102         perfctr_lock ();
1103         custom_categories = get_custom_categories ();
1104         res = mono_array_new (domain, mono_get_string_class (), NUM_CATEGORIES + g_slist_length (custom_categories));
1105         for (i = 0; i < NUM_CATEGORIES; ++i) {
1106                 const CategoryDesc *cdesc = &predef_categories [i];
1107                 mono_array_setref (res, i, mono_string_new (domain, cdesc->name));
1108         }
1109         for (tmp = custom_categories; tmp; tmp = tmp->next) {
1110                 SharedCategory *scat = tmp->data;
1111                 mono_array_setref (res, i, mono_string_new (domain, scat->name));
1112                 i++;
1113         }
1114         perfctr_unlock ();
1115         g_slist_free (custom_categories);
1116         return res;
1117 }
1118
1119 MonoArray*
1120 mono_perfcounter_counter_names (MonoString *category, MonoString *machine)
1121 {
1122         int i;
1123         SharedCategory *scat;
1124         const CategoryDesc *cdesc;
1125         MonoArray *res;
1126         MonoDomain *domain = mono_domain_get ();
1127         /* no support for counters on other machines */
1128         if (mono_string_compare_ascii (machine, "."))
1129                 return mono_array_new (domain, mono_get_string_class (), 0);
1130         cdesc = find_category (category);
1131         if (cdesc) {
1132                 res = mono_array_new (domain, mono_get_string_class (), cdesc [1].first_counter - cdesc->first_counter);
1133                 for (i = cdesc->first_counter; i < cdesc [1].first_counter; ++i) {
1134                         const CounterDesc *desc = &predef_counters [i];
1135                         mono_array_setref (res, i - cdesc->first_counter, mono_string_new (domain, desc->name));
1136                 }
1137                 return res;
1138         }
1139         perfctr_lock ();
1140         scat = find_custom_category (category);
1141         if (scat) {
1142                 char *p = custom_category_counters (scat);
1143                 int i;
1144                 res = mono_array_new (domain, mono_get_string_class (), scat->num_counters);
1145                 for (i = 0; i < scat->num_counters; ++i) {
1146                         mono_array_setref (res, i, mono_string_new (domain, p + 1));
1147                         p += 1 + strlen (p + 1) + 1; /* skip counter type and name */
1148                         p += strlen (p) + 1; /* skip counter help */
1149                 }
1150                 perfctr_unlock ();
1151                 return res;
1152         }
1153         perfctr_unlock ();
1154         return mono_array_new (domain, mono_get_string_class (), 0);
1155 }
1156
1157 static MonoArray*
1158 get_string_array (void **array, int count, gboolean is_process)
1159 {
1160         int i;
1161         MonoDomain *domain = mono_domain_get ();
1162         MonoArray * res = mono_array_new (mono_domain_get (), mono_get_string_class (), count);
1163         for (i = 0; i < count; ++i) {
1164                 char buf [128];
1165                 char *p;
1166                 if (is_process) {
1167                         char *pname = mono_process_get_name (array [i], buf, sizeof (buf));
1168                         p = g_strdup_printf ("%d/%s", GPOINTER_TO_INT (array [i]), pname);
1169                 } else {
1170                         sprintf (buf, "%d", GPOINTER_TO_INT (array [i]));
1171                         p = buf;
1172                 }
1173                 mono_array_setref (res, i, mono_string_new (domain, p));
1174                 if (p != buf)
1175                         g_free (p);
1176         }
1177         return res;
1178 }
1179
1180 static MonoArray*
1181 get_mono_instances (void)
1182 {
1183         int count = 64;
1184         int res;
1185         void **buf = NULL;
1186         MonoArray *array;
1187         do {
1188                 count *= 2;
1189                 g_free (buf);
1190                 buf = g_new (void*, count);
1191                 res = mono_shared_area_instances (buf, count);
1192         } while (res == count);
1193         array = get_string_array (buf, res, TRUE);
1194         g_free (buf);
1195         return array;
1196 }
1197
1198 static MonoArray*
1199 get_cpu_instances (void)
1200 {
1201         void **buf = NULL;
1202         int i, count;
1203         MonoArray *array;
1204         count = mono_cpu_count ();
1205         buf = g_new (void*, count);
1206         for (i = 0; i < count; ++i)
1207                 buf [i] = GINT_TO_POINTER (i);
1208         array = get_string_array (buf, count, FALSE);
1209         g_free (buf);
1210         return array;
1211 }
1212
1213 static MonoArray*
1214 get_processes_instances (void)
1215 {
1216         MonoArray *array;
1217         int count = 0;
1218         void **buf = mono_process_list (&count);
1219         if (!buf)
1220                 return get_string_array (NULL, 0, FALSE);
1221         array = get_string_array (buf, count, TRUE);
1222         g_free (buf);
1223         return array;
1224 }
1225
1226 MonoArray*
1227 mono_perfcounter_instance_names (MonoString *category, MonoString *machine)
1228 {
1229         const CategoryDesc* cat;
1230         if (mono_string_compare_ascii (machine, "."))
1231                 return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
1232         cat = find_category (category);
1233         if (!cat)
1234                 return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
1235         switch (cat->instance_type) {
1236         case MonoInstance:
1237                 return get_mono_instances ();
1238         case CPUInstance:
1239                 return get_cpu_instances ();
1240         case ProcessInstance:
1241                 return get_processes_instances ();
1242         case CustomInstance:
1243         case ThreadInstance:
1244         default:
1245                 return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
1246         }
1247 }
1248