Addition of PAPI to RTS
[ghc-hetmet.git] / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2002
4  *
5  * Main function for a standalone Haskell program.
6  *
7  * ---------------------------------------------------------------------------*/
8
9 // PAPI uses caddr_t, which is not POSIX
10 // #include "PosixSource.h"
11
12 #include "Rts.h"
13 #include "RtsAPI.h"
14 #include "RtsUtils.h"
15 #include "RtsFlags.h"  
16 #include "OSThreads.h"
17 #include "Schedule.h"   /* initScheduler */
18 #include "Stats.h"      /* initStats */
19 #include "STM.h"        /* initSTM */
20 #include "Signals.h"
21 #include "RtsSignals.h"
22 #include "Timer.h"      /* startTimer, stopTimer */
23 #include "Weak.h"
24 #include "Ticky.h"
25 #include "StgRun.h"
26 #include "Prelude.h"            /* fixupRTStoPreludeRefs */
27 #include "HsFFI.h"
28 #include "Linker.h"
29 #include "ThreadLabels.h"
30 #include "BlockAlloc.h"
31 #include "Trace.h"
32 #include "RtsTypeable.h"
33 #include "Stable.h"
34 #include "Hpc.h"
35
36 #if defined(RTS_GTK_FRONTPANEL)
37 #include "FrontPanel.h"
38 #endif
39
40 #if defined(PROFILING) || defined(DEBUG)
41 # include "Profiling.h"
42 # include "ProfHeap.h"
43 # include "RetainerProfile.h"
44 #endif
45
46 #if defined(GRAN)
47 # include "GranSimRts.h"
48 #endif
49
50 #if defined(GRAN) || defined(PAR)
51 # include "ParallelRts.h"
52 #endif
53
54 #if defined(PAR)
55 # include "Parallel.h"
56 # include "LLC.h"
57 #endif
58
59 #if defined(mingw32_HOST_OS)
60 #include "win32/AsyncIO.h"
61 #endif
62
63 #include <stdlib.h>
64
65 #ifdef HAVE_TERMIOS_H
66 #include <termios.h>
67 #endif
68 #ifdef HAVE_SIGNAL_H
69 #include <signal.h>
70 #endif
71
72 #if USE_PAPI
73 #include "Papi.h"
74 #endif
75
76 // Count of how many outstanding hs_init()s there have been.
77 static int hs_init_count = 0;
78
79 // Here we save the terminal settings on the standard file
80 // descriptors, if we need to change them (eg. to support NoBuffering
81 // input).
82 static void *saved_termios[3] = {NULL,NULL,NULL};
83
84 void*
85 __hscore_get_saved_termios(int fd)
86 {
87   return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
88     saved_termios[fd] : NULL;
89 }
90
91 void
92 __hscore_set_saved_termios(int fd, void* ts)
93 {
94   if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
95     saved_termios[fd] = ts;
96   }
97 }
98
99 /* -----------------------------------------------------------------------------
100    Initialise floating point unit on x86 (currently disabled. why?)
101    (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
102    -------------------------------------------------------------------------- */
103
104 #define X86_INIT_FPU 0
105
106 #if X86_INIT_FPU
107 static void
108 x86_init_fpu ( void )
109 {
110   __volatile unsigned short int fpu_cw;
111
112   // Grab the control word
113   __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
114
115 #if 0
116   printf("fpu_cw: %x\n", fpu_cw);
117 #endif
118
119   // Set bits 8-9 to 10 (64-bit precision).
120   fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
121
122   // Store the new control word back
123   __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
124 }
125 #endif
126
127 /* -----------------------------------------------------------------------------
128    Starting up the RTS
129    -------------------------------------------------------------------------- */
130
131 void
132 hs_init(int *argc, char **argv[])
133 {
134     hs_init_count++;
135     if (hs_init_count > 1) {
136         // second and subsequent inits are ignored
137         return;
138     }
139
140     /* The very first thing we do is grab the start time...just in case we're
141      * collecting timing statistics.
142      */
143     stat_startInit();
144
145 #ifdef PAR
146     /*
147      * The parallel system needs to be initialised and synchronised before
148      * the program is run.  
149      */ 
150     startupParallelSystem(argv);
151      
152     if (*argv[0] == '-') { /* Strip off mainPE flag argument */
153       argv++; 
154       argc--;                   
155     }
156
157     argv[1] = argv[0];   /* ignore the nPEs argument */
158     argv++; argc--;
159 #endif
160
161     /* Initialise the performance tracking library */
162 #ifdef USE_PAPI
163     /* Must fix to abort gracefully */
164     if(PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
165       exit(1);
166 #ifdef THREADED_RTS
167     {
168         int err;
169         if ((err = PAPI_thread_init(osThreadId)) < 0) {
170             barf("PAPI_thread_init: %d",err);
171         }
172     }
173 #endif
174 #endif
175
176     /* Set the RTS flags to default values. */
177
178     initRtsFlagsDefaults();
179
180     /* Call the user hook to reset defaults, if present */
181     defaultsHook();
182
183     /* Parse the flags, separating the RTS flags from the programs args */
184     if (argc != NULL && argv != NULL) {
185         setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
186         setProgArgv(*argc,*argv);
187     }
188
189     /* initTracing must be after setupRtsFlags() */
190     initTracing();
191
192 #if defined(PAR)
193     /* NB: this really must be done after processing the RTS flags */
194     IF_PAR_DEBUG(verbose,
195                  debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
196     synchroniseSystem();             // calls initParallelSystem etc
197 #endif  /* PAR */
198
199     /* Perform initialisation of adjustor thunk layer. */
200     initAdjustor();
201
202     /* initialise scheduler data structures (needs to be done before
203      * initStorage()).
204      */
205     initScheduler();
206
207 #if defined(GRAN)
208     /* And start GranSim profiling if required: */
209     if (RtsFlags.GranFlags.GranSimStats.Full)
210       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
211 #elif defined(PAR)
212     /* And start GUM profiling if required: */
213     if (RtsFlags.ParFlags.ParStats.Full)
214       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
215 #endif  /* PAR || GRAN */
216
217     /* initialize the storage manager */
218     initStorage();
219
220     /* initialise the stable pointer table */
221     initStablePtrTable();
222
223     /* initialise the shared Typeable store */
224     initTypeableStore();
225
226 #if defined(DEBUG)
227     /* initialise thread label table (tso->char*) */
228     initThreadLabelTable();
229 #endif
230
231 #if defined(PROFILING) || defined(DEBUG)
232     initProfiling1();
233 #endif
234
235     /* start the virtual timer 'subsystem'. */
236     startTimer();
237
238     /* Initialise the stats department */
239     initStats();
240
241 #if defined(RTS_USER_SIGNALS)
242     /* Initialise the user signal handler set */
243     initUserSignals();
244     /* Set up handler to run on SIGINT, etc. */
245     initDefaultHandlers();
246 #endif
247  
248 #if defined(mingw32_HOST_OS)
249     startupAsyncIO();
250 #endif
251
252 #ifdef RTS_GTK_FRONTPANEL
253     if (RtsFlags.GcFlags.frontpanel) {
254         initFrontPanel();
255     }
256 #endif
257
258 #if X86_INIT_FPU
259     x86_init_fpu();
260 #endif
261
262 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
263     ioManagerStart();
264 #endif
265
266     /* Record initialization times */
267     stat_endInit();
268 }
269
270 // Compatibility interface
271 void
272 startupHaskell(int argc, char *argv[], void (*init_root)(void))
273 {
274     hs_init(&argc, &argv);
275     if(init_root)
276         hs_add_root(init_root);
277 }
278
279
280 /* -----------------------------------------------------------------------------
281    Per-module initialisation
282
283    This process traverses all the compiled modules in the program
284    starting with "Main", and performing per-module initialisation for
285    each one.
286
287    So far, two things happen at initialisation time:
288
289       - we register stable names for each foreign-exported function
290         in that module.  This prevents foreign-exported entities, and
291         things they depend on, from being garbage collected.
292
293       - we supply a unique integer to each statically declared cost
294         centre and cost centre stack in the program.
295
296    The code generator inserts a small function "__stginit_<module>" in each
297    module and calls the registration functions in each of the modules it
298    imports.
299
300    The init* functions are compiled in the same way as STG code,
301    i.e. without normal C call/return conventions.  Hence we must use
302    StgRun to call this stuff.
303    -------------------------------------------------------------------------- */
304
305 /* The init functions use an explicit stack... 
306  */
307 #define INIT_STACK_BLOCKS  4
308 static F_ *init_stack = NULL;
309
310 void
311 hs_add_root(void (*init_root)(void))
312 {
313     bdescr *bd;
314     nat init_sp;
315     Capability *cap = &MainCapability;
316
317     if (hs_init_count <= 0) {
318         barf("hs_add_root() must be called after hs_init()");
319     }
320
321     /* The initialisation stack grows downward, with sp pointing 
322        to the last occupied word */
323     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
324     bd = allocGroup_lock(INIT_STACK_BLOCKS);
325     init_stack = (F_ *)bd->start;
326     init_stack[--init_sp] = (F_)stg_init_finish;
327     if (init_root != NULL) {
328         init_stack[--init_sp] = (F_)init_root;
329     }
330     
331     cap->r.rSp = (P_)(init_stack + init_sp);
332     StgRun((StgFunPtr)stg_init, &cap->r);
333
334     freeGroup_lock(bd);
335
336     startupHpc();
337
338 #if defined(PROFILING) || defined(DEBUG)
339     // This must be done after module initialisation.
340     // ToDo: make this work in the presence of multiple hs_add_root()s.
341     initProfiling2();
342 #endif
343 }
344
345 /* -----------------------------------------------------------------------------
346    Shutting down the RTS
347    -------------------------------------------------------------------------- */
348
349 void
350 hs_exit(void)
351 {
352     if (hs_init_count <= 0) {
353         errorBelch("warning: too many hs_exit()s");
354         return;
355     }
356     hs_init_count--;
357     if (hs_init_count > 0) {
358         // ignore until it's the last one
359         return;
360     }
361
362     /* start timing the shutdown */
363     stat_startExit();
364     
365 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
366     ioManagerDie();
367 #endif
368
369     /* stop all running tasks */
370     exitScheduler();
371     
372 #if defined(GRAN)
373     /* end_gr_simulation prints global stats if requested -- HWL */
374     if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
375         end_gr_simulation();
376 #endif
377     
378     /* stop the ticker */
379     stopTimer();
380     
381     /* reset the standard file descriptors to blocking mode */
382     resetNonBlockingFd(0);
383     resetNonBlockingFd(1);
384     resetNonBlockingFd(2);
385
386 #if HAVE_TERMIOS_H
387     // Reset the terminal settings on the standard file descriptors,
388     // if we changed them.  See System.Posix.Internals.tcSetAttr for
389     // more details, including the reason we termporarily disable
390     // SIGTTOU here.
391     { 
392         int fd;
393         sigset_t sigset, old_sigset;
394         sigemptyset(&sigset);
395         sigaddset(&sigset, SIGTTOU);
396         sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
397         for (fd = 0; fd <= 2; fd++) {
398             struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
399             if (ts != NULL) {
400                 tcsetattr(fd,TCSANOW,ts);
401             }
402         }
403         sigprocmask(SIG_SETMASK, &old_sigset, NULL);
404     }
405 #endif
406
407 #if defined(PAR)
408     /* controlled exit; good thread! */
409     shutdownParallelSystem(0);
410     
411     /* global statistics in parallel system */
412     PAR_TICKY_PAR_END();
413 #endif
414
415     /* stop timing the shutdown, we're about to print stats */
416     stat_endExit();
417     
418     /* shutdown the hpc support (if needed) */
419     exitHpc();
420
421     // clean up things from the storage manager's point of view.
422     // also outputs the stats (+RTS -s) info.
423     exitStorage();
424     
425     /* free shared Typeable store */
426     exitTypeableStore();
427
428     /* initialise the stable pointer table */
429     exitStablePtrTable();
430
431     /* free hash table storage */
432     exitHashTable();
433
434 #ifdef RTS_GTK_FRONTPANEL
435     if (RtsFlags.GcFlags.frontpanel) {
436         stopFrontPanel();
437     }
438 #endif
439
440 #if defined(PROFILING) 
441     reportCCSProfiling();
442 #endif
443
444 #if defined(PROFILING) || defined(DEBUG)
445     endProfiling();
446 #endif
447
448 #ifdef PROFILING
449     // Originally, this was in report_ccs_profiling().  Now, retainer
450     // profiling might tack some extra stuff on to the end of this file
451     // during endProfiling().
452     fclose(prof_file);
453 #endif
454
455 #if defined(TICKY_TICKY)
456     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
457 #endif
458
459 #if defined(mingw32_HOST_OS)
460     shutdownAsyncIO();
461 #endif
462
463     // Finally, free all our storage.
464     freeStorage();
465 }
466
467 // Compatibility interfaces
468 void
469 shutdownHaskell(void)
470 {
471     hs_exit();
472 }
473
474 void
475 shutdownHaskellAndExit(int n)
476 {
477     if (hs_init_count == 1) {
478         OnExitHook();
479         hs_exit();
480 #if defined(PAR)
481         /* really exit (stg_exit() would call shutdownParallelSystem() again) */
482         exit(n);
483 #else
484         stg_exit(n);
485 #endif
486     }
487 }
488
489 /* 
490  * called from STG-land to exit the program
491  */
492
493 #ifdef PAR
494 static int exit_started=rtsFalse;
495 #endif
496
497 void (*exitFn)(int) = 0;
498
499 void  
500 stg_exit(int n)
501
502 #ifdef PAR
503   /* HACK: avoid a loop when exiting due to a stupid error */
504   if (exit_started) 
505     return;
506   exit_started=rtsTrue;
507
508   IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
509   shutdownParallelSystem(n);
510 #endif
511   if (exitFn)
512     (*exitFn)(n);
513   exit(n);
514 }