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