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