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