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