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