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