71b348488fad56bb081215798903c3d0087a3f2e
[ghc-hetmet.git] / rts / eventlog / EventLog.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2008-2009
4  *
5  * Support for fast binary event logging.
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #include "Rts.h"
11
12 #ifdef TRACING
13
14 #include "Trace.h"
15 #include "Capability.h"
16 #include "RtsUtils.h"
17 #include "Stats.h"
18 #include "EventLog.h"
19
20 #include <string.h>
21 #include <stdio.h>
22 #ifdef HAVE_SYS_TYPES_H
23 #include <sys/types.h>
24 #endif
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28
29 // PID of the process that writes to event_log_filename (#4512)
30 static pid_t event_log_pid = -1;
31
32 static char *event_log_filename = NULL;
33
34 // File for logging events
35 FILE *event_log_file = NULL;
36
37 #define EVENT_LOG_SIZE 2 * (1024 * 1024) // 2MB
38
39 static int flushCount;
40
41 // Struct for record keeping of buffer to store event types and events.
42 typedef struct _EventsBuf {
43   StgInt8 *begin;
44   StgInt8 *pos;
45   StgInt8 *marker;
46   StgWord64 size;
47   EventCapNo capno; // which capability this buffer belongs to, or -1
48 } EventsBuf;
49
50 EventsBuf *capEventBuf; // one EventsBuf for each Capability
51
52 EventsBuf eventBuf; // an EventsBuf not associated with any Capability
53 #ifdef THREADED_RTS
54 Mutex eventBufMutex; // protected by this mutex
55 #endif
56
57 char *EventDesc[] = {
58   [EVENT_CREATE_THREAD]       = "Create thread",
59   [EVENT_RUN_THREAD]          = "Run thread",
60   [EVENT_STOP_THREAD]         = "Stop thread",
61   [EVENT_THREAD_RUNNABLE]     = "Thread runnable",
62   [EVENT_MIGRATE_THREAD]      = "Migrate thread",
63   [EVENT_RUN_SPARK]           = "Run spark",
64   [EVENT_STEAL_SPARK]         = "Steal spark",
65   [EVENT_SHUTDOWN]            = "Shutdown",
66   [EVENT_THREAD_WAKEUP]       = "Wakeup thread",
67   [EVENT_GC_START]            = "Starting GC",
68   [EVENT_GC_END]              = "Finished GC",
69   [EVENT_REQUEST_SEQ_GC]      = "Request sequential GC",
70   [EVENT_REQUEST_PAR_GC]      = "Request parallel GC",
71   [EVENT_CREATE_SPARK_THREAD] = "Create spark thread",
72   [EVENT_LOG_MSG]             = "Log message",
73   [EVENT_USER_MSG]            = "User message",
74   [EVENT_STARTUP]             = "Startup",
75   [EVENT_GC_IDLE]             = "GC idle",
76   [EVENT_GC_WORK]             = "GC working",
77   [EVENT_GC_DONE]             = "GC done",
78   [EVENT_BLOCK_MARKER]        = "Block marker"
79 };
80
81 // Event type. 
82
83 typedef struct _EventType {
84   EventTypeNum etNum;  // Event Type number.
85   nat   size;     // size of the payload in bytes
86   char *desc;     // Description
87 } EventType;
88
89 EventType eventTypes[NUM_EVENT_TAGS];
90
91 static void initEventsBuf(EventsBuf* eb, StgWord64 size, EventCapNo capno);
92 static void resetEventsBuf(EventsBuf* eb);
93 static void printAndClearEventBuf (EventsBuf *eventsBuf);
94
95 static void postEventType(EventsBuf *eb, EventType *et);
96
97 static void postLogMsg(EventsBuf *eb, EventTypeNum type, char *msg, va_list ap);
98
99 static void postBlockMarker(EventsBuf *eb);
100 static void closeBlockMarker(EventsBuf *ebuf);
101
102 static StgBool hasRoomForEvent(EventsBuf *eb, EventTypeNum eNum);
103 static StgBool hasRoomForVariableEvent(EventsBuf *eb, nat payload_bytes);
104
105 static inline void postWord8(EventsBuf *eb, StgWord8 i)
106 {
107     *(eb->pos++) = i; 
108 }
109
110 static inline void postWord16(EventsBuf *eb, StgWord16 i)
111 {
112     postWord8(eb, (StgWord8)(i >> 8));
113     postWord8(eb, (StgWord8)i);
114 }
115
116 static inline void postWord32(EventsBuf *eb, StgWord32 i)
117 {
118     postWord16(eb, (StgWord16)(i >> 16));
119     postWord16(eb, (StgWord16)i);
120 }
121
122 static inline void postWord64(EventsBuf *eb, StgWord64 i)
123 {
124     postWord32(eb, (StgWord32)(i >> 32));
125     postWord32(eb, (StgWord32)i);
126 }
127
128 static inline void postBuf(EventsBuf *eb, StgWord8 *buf, nat size)
129 {
130     memcpy(eb->pos, buf, size);
131     eb->pos += size;
132 }
133
134 static inline StgWord64 time_ns(void)
135 { return stat_getElapsedTime() * (1000000000LL/TICKS_PER_SECOND); }
136
137 static inline void postEventTypeNum(EventsBuf *eb, EventTypeNum etNum)
138 { postWord16(eb, etNum); }
139
140 static inline void postTimestamp(EventsBuf *eb)
141 { postWord64(eb, time_ns()); }
142
143 static inline void postThreadID(EventsBuf *eb, EventThreadID id)
144 { postWord32(eb,id); }
145
146 static inline void postCapNo(EventsBuf *eb, EventCapNo no)
147 { postWord16(eb,no); }
148
149 static inline void postPayloadSize(EventsBuf *eb, EventPayloadSize size)
150 { postWord16(eb,size); }
151
152 static inline void postEventHeader(EventsBuf *eb, EventTypeNum type)
153 {
154     postEventTypeNum(eb, type);
155     postTimestamp(eb);
156 }    
157
158 static inline void postInt8(EventsBuf *eb, StgInt8 i)
159 { postWord8(eb, (StgWord8)i); }
160
161 static inline void postInt16(EventsBuf *eb, StgInt16 i)
162 { postWord16(eb, (StgWord16)i); }
163
164 static inline void postInt32(EventsBuf *eb, StgInt32 i)
165 { postWord32(eb, (StgWord32)i); }
166
167 static inline void postInt64(EventsBuf *eb, StgInt64 i)
168 { postWord64(eb, (StgWord64)i); }
169
170
171 void
172 initEventLogging(void)
173 {
174     StgWord8 t, c;
175     nat n_caps;
176
177     event_log_filename = stgMallocBytes(strlen(prog_name) + 10,
178                                         "initEventLogging");
179
180     if (sizeof(EventDesc) / sizeof(char*) != NUM_EVENT_TAGS) {
181         barf("EventDesc array has the wrong number of elements");
182     }
183
184     if (event_log_pid == -1) { // #4512
185         // Single process
186         sprintf(event_log_filename, "%s.eventlog", prog_name);
187         event_log_pid = getpid();
188     } else {
189         // Forked process, eventlog already started by the parent
190         // before fork
191         event_log_pid = getpid();
192         sprintf(event_log_filename, "%s.%d.eventlog", prog_name, event_log_pid);
193     }
194
195     /* Open event log file for writing. */
196     if ((event_log_file = fopen(event_log_filename, "wb")) == NULL) {
197         sysErrorBelch("initEventLogging: can't open %s", event_log_filename);
198         stg_exit(EXIT_FAILURE);    
199     }
200
201     /* 
202      * Allocate buffer(s) to store events.
203      * Create buffer large enough for the header begin marker, all event
204      * types, and header end marker to prevent checking if buffer has room
205      * for each of these steps, and remove the need to flush the buffer to
206      * disk during initialization.
207      *
208      * Use a single buffer to store the header with event types, then flush 
209      * the buffer so all buffers are empty for writing events.
210      */
211 #ifdef THREADED_RTS
212     // XXX n_capabilities hasn't been initislised yet
213     n_caps = RtsFlags.ParFlags.nNodes;
214 #else
215     n_caps = 1;
216 #endif
217     capEventBuf = stgMallocBytes(n_caps * sizeof(EventsBuf),"initEventLogging");
218
219     for (c = 0; c < n_caps; ++c) {
220         // Init buffer for events.
221         initEventsBuf(&capEventBuf[c], EVENT_LOG_SIZE, c);
222     }
223     initEventsBuf(&eventBuf, EVENT_LOG_SIZE, (EventCapNo)(-1));
224
225     // Write in buffer: the header begin marker.
226     postInt32(&eventBuf, EVENT_HEADER_BEGIN);
227
228     // Mark beginning of event types in the header.
229     postInt32(&eventBuf, EVENT_HET_BEGIN);
230     for (t = 0; t < NUM_EVENT_TAGS; ++t) {
231
232         eventTypes[t].etNum = t;
233         eventTypes[t].desc = EventDesc[t];
234
235         switch (t) {
236         case EVENT_CREATE_THREAD:   // (cap, thread)
237         case EVENT_RUN_THREAD:      // (cap, thread)
238         case EVENT_THREAD_RUNNABLE: // (cap, thread)
239         case EVENT_RUN_SPARK:       // (cap, thread)
240         case EVENT_CREATE_SPARK_THREAD: // (cap, spark_thread)
241             eventTypes[t].size = sizeof(EventThreadID);
242             break;
243
244         case EVENT_MIGRATE_THREAD:  // (cap, thread, new_cap)
245         case EVENT_STEAL_SPARK:     // (cap, thread, victim_cap)
246         case EVENT_THREAD_WAKEUP:   // (cap, thread, other_cap)
247             eventTypes[t].size =
248                 sizeof(EventThreadID) + sizeof(EventCapNo);
249             break;
250
251         case EVENT_STOP_THREAD:     // (cap, thread, status)
252             eventTypes[t].size =
253                 sizeof(EventThreadID) + sizeof(StgWord16);
254             break;
255
256         case EVENT_STARTUP:         // (cap count)
257             eventTypes[t].size = sizeof(EventCapNo);
258             break;
259
260         case EVENT_SHUTDOWN:        // (cap)
261         case EVENT_REQUEST_SEQ_GC:  // (cap)
262         case EVENT_REQUEST_PAR_GC:  // (cap)
263         case EVENT_GC_START:        // (cap)
264         case EVENT_GC_END:          // (cap)
265         case EVENT_GC_IDLE:
266         case EVENT_GC_WORK:
267         case EVENT_GC_DONE:
268             eventTypes[t].size = 0;
269             break;
270
271         case EVENT_LOG_MSG:          // (msg)
272         case EVENT_USER_MSG:         // (msg)
273             eventTypes[t].size = 0xffff;
274             break;
275
276         case EVENT_BLOCK_MARKER:
277             eventTypes[t].size = sizeof(StgWord32) + sizeof(EventTimestamp) + 
278                 sizeof(EventCapNo);
279             break;
280
281         default:
282             continue; /* ignore deprecated events */
283         }
284
285         // Write in buffer: the start event type.
286         postEventType(&eventBuf, &eventTypes[t]);
287     }
288
289     // Mark end of event types in the header.
290     postInt32(&eventBuf, EVENT_HET_END);
291     
292     // Write in buffer: the header end marker.
293     postInt32(&eventBuf, EVENT_HEADER_END);
294     
295     // Prepare event buffer for events (data).
296     postInt32(&eventBuf, EVENT_DATA_BEGIN);
297     
298     // Post a STARTUP event with the number of capabilities
299     postEventHeader(&eventBuf, EVENT_STARTUP);
300     postCapNo(&eventBuf, n_caps);
301
302     // Flush capEventBuf with header.
303     /*
304      * Flush header and data begin marker to the file, thus preparing the
305      * file to have events written to it.
306      */
307     printAndClearEventBuf(&eventBuf);
308
309     for (c = 0; c < n_caps; ++c) {
310         postBlockMarker(&capEventBuf[c]);
311     }
312
313 #ifdef THREADED_RTS
314     initMutex(&eventBufMutex);
315 #endif
316 }
317
318 void
319 endEventLogging(void)
320 {
321     nat c;
322
323     // Flush all events remaining in the buffers.
324     for (c = 0; c < n_capabilities; ++c) {
325         printAndClearEventBuf(&capEventBuf[c]);
326     }
327     printAndClearEventBuf(&eventBuf);
328     resetEventsBuf(&eventBuf); // we don't want the block marker
329
330     // Mark end of events (data).
331     postEventTypeNum(&eventBuf, EVENT_DATA_END);
332
333     // Flush the end of data marker.
334     printAndClearEventBuf(&eventBuf);
335
336     if (event_log_file != NULL) {
337         fclose(event_log_file);
338     }
339 }
340
341 void 
342 freeEventLogging(void)
343 {
344     StgWord8 c;
345     
346     // Free events buffer.
347     for (c = 0; c < n_capabilities; ++c) {
348         if (capEventBuf[c].begin != NULL) 
349             stgFree(capEventBuf[c].begin);
350     }
351     if (capEventBuf != NULL)  {
352         stgFree(capEventBuf);
353     }
354     if (event_log_filename != NULL) {
355         stgFree(event_log_filename);
356     }
357 }
358
359 void 
360 flushEventLog(void)
361 {
362     if (event_log_file != NULL) {
363         fflush(event_log_file);
364     }
365 }
366
367 void 
368 abortEventLogging(void)
369 {
370     freeEventLogging();
371     if (event_log_file != NULL) {
372         fclose(event_log_file);
373     }
374 }
375 /*
376  * Post an event message to the capability's eventlog buffer.
377  * If the buffer is full, prints out the buffer and clears it.
378  */
379 void
380 postSchedEvent (Capability *cap, 
381                 EventTypeNum tag, 
382                 StgThreadID thread, 
383                 StgWord64 other)
384 {
385     EventsBuf *eb;
386
387     eb = &capEventBuf[cap->no];
388
389     if (!hasRoomForEvent(eb, tag)) {
390         // Flush event buffer to make room for new event.
391         printAndClearEventBuf(eb);
392     }
393     
394     postEventHeader(eb, tag);
395
396     switch (tag) {
397     case EVENT_CREATE_THREAD:   // (cap, thread)
398     case EVENT_RUN_THREAD:      // (cap, thread)
399     case EVENT_THREAD_RUNNABLE: // (cap, thread)
400     case EVENT_RUN_SPARK:       // (cap, thread)
401     {
402         postThreadID(eb,thread);
403         break;
404     }
405
406     case EVENT_CREATE_SPARK_THREAD: // (cap, spark_thread)
407     {
408         postThreadID(eb,other /* spark_thread */);
409         break;
410     }
411
412     case EVENT_MIGRATE_THREAD:  // (cap, thread, new_cap)
413     case EVENT_STEAL_SPARK:     // (cap, thread, victim_cap)
414     case EVENT_THREAD_WAKEUP:   // (cap, thread, other_cap)
415     {
416         postThreadID(eb,thread);
417         postCapNo(eb,other /* new_cap | victim_cap | other_cap */);
418         break;
419    }
420
421     case EVENT_STOP_THREAD:     // (cap, thread, status)
422     {
423         postThreadID(eb,thread);
424         postWord16(eb,other /* status */);
425         break;
426     }
427
428     case EVENT_SHUTDOWN:        // (cap)
429     case EVENT_REQUEST_SEQ_GC:  // (cap)
430     case EVENT_REQUEST_PAR_GC:  // (cap)
431     case EVENT_GC_START:        // (cap)
432     case EVENT_GC_END:          // (cap)
433     {
434         break;
435     }
436
437     default:
438         barf("postEvent: unknown event tag %d", tag);
439     }
440 }
441
442 void
443 postEvent (Capability *cap, EventTypeNum tag)
444 {
445     EventsBuf *eb;
446
447     eb = &capEventBuf[cap->no];
448
449     if (!hasRoomForEvent(eb, tag)) {
450         // Flush event buffer to make room for new event.
451         printAndClearEventBuf(eb);
452     }
453
454     postEventHeader(eb, tag);
455 }
456
457 #define BUF 512
458
459 void postLogMsg(EventsBuf *eb, EventTypeNum type, char *msg, va_list ap)
460 {
461     char buf[BUF];
462     nat size;
463
464     size = vsnprintf(buf,BUF,msg,ap);
465     if (size > BUF) {
466         buf[BUF-1] = '\0';
467         size = BUF;
468     }
469
470     if (!hasRoomForVariableEvent(eb, size)) {
471         // Flush event buffer to make room for new event.
472         printAndClearEventBuf(eb);
473     }
474
475     postEventHeader(eb, type);
476     postPayloadSize(eb, size);
477     postBuf(eb,(StgWord8*)buf,size);
478 }
479
480 void postMsg(char *msg, va_list ap)
481 {
482     ACQUIRE_LOCK(&eventBufMutex);
483     postLogMsg(&eventBuf, EVENT_LOG_MSG, msg, ap);
484     RELEASE_LOCK(&eventBufMutex);
485 }
486
487 void postCapMsg(Capability *cap, char *msg, va_list ap)
488 {
489     postLogMsg(&capEventBuf[cap->no], EVENT_LOG_MSG, msg, ap);
490 }
491
492 void postUserMsg(Capability *cap, char *msg, va_list ap)
493 {
494     postLogMsg(&capEventBuf[cap->no], EVENT_USER_MSG, msg, ap);
495 }    
496
497 void closeBlockMarker (EventsBuf *ebuf)
498 {
499     StgInt8* save_pos;
500
501     if (ebuf->marker)
502     {
503         // (type:16, time:64, size:32, end_time:64)
504
505         save_pos = ebuf->pos;
506         ebuf->pos = ebuf->marker + sizeof(EventTypeNum) +
507                     sizeof(EventTimestamp);
508         postWord32(ebuf, save_pos - ebuf->marker);
509         postTimestamp(ebuf);
510         ebuf->pos = save_pos;
511         ebuf->marker = NULL;
512     }
513 }
514
515
516 void postBlockMarker (EventsBuf *eb)
517 {
518     if (!hasRoomForEvent(eb, EVENT_BLOCK_MARKER)) {
519         printAndClearEventBuf(eb);
520     }
521
522     closeBlockMarker(eb);
523
524     eb->marker = eb->pos;
525     postEventHeader(eb, EVENT_BLOCK_MARKER);
526     postWord32(eb,0); // these get filled in later by closeBlockMarker();
527     postWord64(eb,0);
528     postCapNo(eb, eb->capno);
529 }
530
531 void printAndClearEventBuf (EventsBuf *ebuf)
532 {
533     StgWord64 numBytes = 0, written = 0;
534
535     closeBlockMarker(ebuf);
536
537     if (ebuf->begin != NULL && ebuf->pos != ebuf->begin)
538     {
539         numBytes = ebuf->pos - ebuf->begin;
540         
541         written = fwrite(ebuf->begin, 1, numBytes, event_log_file);
542         if (written != numBytes) {
543             debugBelch(
544                 "printAndClearEventLog: fwrite() failed, written=%" FMT_Word64
545                 " doesn't match numBytes=%" FMT_Word64, written, numBytes);
546             return;
547         }
548         
549         resetEventsBuf(ebuf);
550         flushCount++;
551
552         postBlockMarker(ebuf);
553     }
554 }
555
556 void initEventsBuf(EventsBuf* eb, StgWord64 size, EventCapNo capno)
557 {
558     eb->begin = eb->pos = stgMallocBytes(size, "initEventsBuf");
559     eb->size = size;
560     eb->marker = NULL;
561     eb->capno = capno;
562 }
563
564 void resetEventsBuf(EventsBuf* eb)
565 {
566     eb->pos = eb->begin;
567     eb->marker = NULL;
568 }
569
570 StgBool hasRoomForEvent(EventsBuf *eb, EventTypeNum eNum)
571 {
572   nat size;
573
574   size = sizeof(EventTypeNum) + sizeof(EventTimestamp) + eventTypes[eNum].size;
575
576   if (eb->pos + size > eb->begin + eb->size) {
577       return 0; // Not enough space.
578   } else  {
579       return 1; // Buf has enough space for the event.
580   }
581 }
582
583 StgBool hasRoomForVariableEvent(EventsBuf *eb, nat payload_bytes)
584 {
585   nat size;
586
587   size = sizeof(EventTypeNum) + sizeof(EventTimestamp) +
588       sizeof(EventPayloadSize) + payload_bytes;
589
590   if (eb->pos + size > eb->begin + eb->size) {
591       return 0; // Not enough space.
592   } else  {
593       return 1; // Buf has enough space for the event.
594   }
595 }    
596
597 void postEventType(EventsBuf *eb, EventType *et)
598 {
599     StgWord8 d;
600     nat desclen;
601
602     postInt32(eb, EVENT_ET_BEGIN);
603     postEventTypeNum(eb, et->etNum);
604     postWord16(eb, (StgWord16)et->size);
605     desclen = strlen(et->desc);
606     postWord32(eb, desclen);
607     for (d = 0; d < desclen; ++d) {
608         postInt8(eb, (StgInt8)et->desc[d]);
609     }
610     postWord32(eb, 0); // no extensions yet
611     postInt32(eb, EVENT_ET_END);
612 }
613
614 #endif /* TRACING */