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