78c10bfe5659a19b81f3aed5525ab5248966659d
[ghc-hetmet.git] / ghc / rts / Capability.c
1 /* ---------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 2001
4  *
5  * Capabilities
6  *
7  * The notion of a capability is used when operating in multi-threaded
8  * environments (which the SMP and Threads builds of the RTS do), to
9  * hold all the state an OS thread/task needs to run Haskell code:
10  * its STG registers, a pointer to its  TSO, a nursery etc. During
11  * STG execution, a pointer to the capabilitity is kept in a 
12  * register (BaseReg).
13  *
14  * Only in an SMP build will there be multiple capabilities, the threaded
15  * RTS and other non-threaded builds, there is one global capability,
16  * namely MainRegTable.
17  *
18  * 
19  * --------------------------------------------------------------------------*/
20 #include "PosixSource.h"
21 #include "Rts.h"
22 #include "RtsUtils.h"
23 #include "Capability.h"
24
25 #if !defined(SMP)
26 Capability MainCapability;     /* for non-SMP, we have one global capability */
27 #endif
28
29 static
30 void
31 initCapability( Capability *cap )
32 {
33     cap->f.stgChk0         = (F_)__stg_chk_0;
34     cap->f.stgChk1         = (F_)__stg_chk_1;
35     cap->f.stgGCEnter1     = (F_)__stg_gc_enter_1;
36     cap->f.stgUpdatePAP    = (F_)__stg_update_PAP;
37 }
38
39 #ifdef SMP
40 static void initCapabilities_(nat n);
41 #endif
42
43 /* 
44  */
45 void
46 initCapabilities()
47 {
48 #if defined(SMP)
49   initCapabilities_(RtsFlags.ParFlags.nNodes);
50 #else
51   initCapability(&MainCapability);
52 #endif
53
54   return;
55 }
56
57 /* Free capability list.
58  * Locks required: sched_mutex.
59  */
60 #if defined(SMP)
61 static Capability *free_capabilities; /* Available capabilities for running threads */
62 #endif
63
64 void grabCapability(Capability** cap)
65 {
66 #if !defined(SMP)
67   *cap = &MainCapability;
68 #else
69   *cap = free_capabilities;
70   free_capabilities = (*cap)->link;
71   rts_n_free_capabilities--;
72 #endif
73 }
74
75 void releaseCapability(Capability* cap)
76 {
77 #if defined(SMP)
78   cap->link = free_capabilities;
79   free_capabilities = cap;
80   rts_n_free_capabilities++;
81 #endif
82   return;
83 }
84
85 #if defined(SMP)
86 /* Allocate 'n' capabilities */
87 static void
88 initCapabilities_(nat n)
89 {
90   nat i;
91   Capability *cap, *prev;
92   cap  = NULL;
93   prev = NULL;
94   for (i = 0; i < n; i++) {
95     cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
96     initCapability(cap);
97     cap->link = prev;
98     prev = cap;
99   }
100   free_capabilities = cap;
101   rts_n_free_capabilities = n;
102   IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););
103 }
104 #endif /* SMP */
105