5c5635d23049515499a05009d212f0517db40b41
[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
26 void
27 initCapability( Capability *cap )
28 {
29     cap->f.stgChk0         = (F_)__stg_chk_0;
30     cap->f.stgChk1         = (F_)__stg_chk_1;
31     cap->f.stgGCEnter1     = (F_)__stg_gc_enter_1;
32     cap->f.stgUpdatePAP    = (F_)__stg_update_PAP;
33 }
34
35 /* Free capability list.
36  * Locks required: sched_mutex.
37  */
38 #if defined(SMP)
39 static Capability *free_capabilities; /* Available capabilities for running threads */
40
41
42 void grabCapability(Capability** cap)
43 {
44   *cap = free_capabilities;
45   free_capabilities = (*cap)->link;
46   rts_n_free_capabilities--;
47 }
48
49 void releaseCapability(Capability** cap)
50 {
51   (*cap)->link = free_capabilities;
52   free_capabilities = *cap;
53   rts_n_free_capabilities++;
54   return;
55 }
56
57 /* Allocate 'n' capabilities */
58 void
59 initCapabilities(nat n)
60 {
61   nat i;
62   Capability *cap, *prev;
63   cap  = NULL;
64   prev = NULL;
65   for (i = 0; i < n; i++) {
66     cap = stgMallocBytes(sizeof(Capability), "initCapabilities");
67     initCapability(cap);
68     cap->link = prev;
69     prev = cap;
70   }
71   free_capabilities = cap;
72   rts_n_free_capabilities = n;
73   IF_DEBUG(scheduler,fprintf(stderr,"scheduler: Allocated %d capabilities\n", n_free_capabilities););
74 }
75 #endif /* SMP */
76