OSDN Git Service

* a-calend-mingw.adb: Add call to OS_Primitives.Initialize;
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-taskin.ads
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                  GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS                --
4 --                                                                          --
5 --                        S Y S T E M . T A S K I N G                       --
6 --                                                                          --
7 --                                  S p e c                                 --
8 --                                                                          --
9 --          Copyright (C) 1992-2005, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNARL is free software; you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNARL; see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- As a special exception,  if other files  instantiate  generics from this --
23 -- unit, or you link  this unit with other files  to produce an executable, --
24 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
25 -- covered  by the  GNU  General  Public  License.  This exception does not --
26 -- however invalidate  any other reasons why  the executable file  might be --
27 -- covered by the  GNU Public License.                                      --
28 --                                                                          --
29 -- GNARL was developed by the GNARL team at Florida State University.       --
30 -- Extensive contributions were provided by Ada Core Technologies, Inc.     --
31 --                                                                          --
32 ------------------------------------------------------------------------------
33
34 --  This package provides necessary type definitions for compiler interface
35
36 --  Note: the compiler generates direct calls to this interface, via Rtsfind.
37 --  Any changes to this interface may require corresponding compiler changes.
38
39 with Ada.Exceptions;
40 --  Used for:  Exception_Id
41
42 with System.Parameters;
43 --  used for Size_Type
44
45 with System.Task_Info;
46 --  used for Task_Info_Type
47
48 with System.Soft_Links;
49 --  used for TSD
50
51 with System.Task_Primitives;
52 --  used for Private_Data
53
54 with Unchecked_Conversion;
55
56 package System.Tasking is
57    pragma Preelaborate;
58
59    -------------------
60    -- Locking Rules --
61    -------------------
62
63    --  The following rules must be followed at all times, to prevent
64    --  deadlock and generally ensure correct operation of locking.
65
66    --  Never lock a lock unless abort is deferred
67
68    --  Never undefer abort while holding a lock
69
70    --  Overlapping critical sections must be properly nested, and locks must
71    --  be released in LIFO order. e.g., the following is not allowed:
72
73    --         Lock (X);
74    --         ...
75    --         Lock (Y);
76    --         ...
77    --         Unlock (X);
78    --         ...
79    --         Unlock (Y);
80
81    --  Locks with lower (smaller) level number cannot be locked
82    --  while holding a lock with a higher level number. (The level
83
84    --  1. System.Tasking.PO_Simple.Protection.L (any PO lock)
85    --  2. System.Tasking.Initialization.Global_Task_Lock (in body)
86    --  3. System.Task_Primitives.Operations.Single_RTS_Lock
87    --  4. System.Tasking.Ada_Task_Control_Block.LL.L (any TCB lock)
88
89    --  Clearly, there can be no circular chain of hold-and-wait
90    --  relationships involving locks in different ordering levels.
91
92    --  We used to have Global_Task_Lock before Protection.L but this was
93    --  clearly wrong since there can be calls to "new" inside protected
94    --  operations. The new ordering prevents these failures.
95
96    --  Sometimes we need to hold two ATCB locks at the same time. To allow us
97    --  to order the locking, each ATCB is given a unique serial number. If one
98    --  needs to hold locks on several ATCBs at once, the locks with lower
99    --  serial numbers must be locked first.
100
101    --  We don't always need to check the serial numbers, since the serial
102    --  numbers are assigned sequentially, and so:
103
104    --  . The parent of a task always has a lower serial number.
105    --  . The activator of a task always has a lower serial number.
106    --  . The environment task has a lower serial number than any other task.
107    --  . If the activator of a task is different from the task's parent,
108    --    the parent always has a lower serial number than the activator.
109
110    ---------------------------------
111    -- Task_Id related definitions --
112    ---------------------------------
113
114    type Ada_Task_Control_Block;
115
116    type Task_Id is access all Ada_Task_Control_Block;
117
118    Null_Task : constant Task_Id;
119
120    type Task_List is array (Positive range <>) of Task_Id;
121
122    function Self return Task_Id;
123    pragma Inline (Self);
124    --  This is the compiler interface version of this function. Do not call
125    --  from the run-time system.
126
127    function To_Task_Id is new Unchecked_Conversion (System.Address, Task_Id);
128    function To_Address is new Unchecked_Conversion (Task_Id, System.Address);
129
130    -----------------------
131    -- Enumeration types --
132    -----------------------
133
134    type Task_States is
135      (Unactivated,
136       --  Task has been created but has not been activated.
137       --  It cannot be executing.
138
139       --  Active states
140       --  For all states from here down, the task has been activated.
141       --  For all states from here down, except for Terminated, the task
142       --  may be executing.
143       --  Activator = null iff it has not yet completed activating.
144
145       --  For all states from here down,
146       --  the task has been activated, and may be executing.
147
148       Runnable,
149       --  Task is not blocked for any reason known to Ada.
150       --  (It may be waiting for a mutex, though.)
151       --  It is conceptually "executing" in normal mode.
152
153       Terminated,
154       --  The task is terminated, in the sense of ARM 9.3 (5).
155       --  Any dependents that were waiting on terminate
156       --  alternatives have been awakened and have terminated themselves.
157
158       Activator_Sleep,
159       --  Task is waiting for created tasks to complete activation
160
161       Acceptor_Sleep,
162       --  Task is waiting on an accept or selective wait statement
163
164       Entry_Caller_Sleep,
165       --  Task is waiting on an entry call
166
167       Async_Select_Sleep,
168       --  Task is waiting to start the abortable part of an
169       --  asynchronous select statement.
170
171       Delay_Sleep,
172       --  Task is waiting on a select statement with only a delay
173       --  alternative open.
174
175       Master_Completion_Sleep,
176       --  Master completion has two phases.
177       --  In Phase 1 the task is sleeping in Complete_Master
178       --  having completed a master within itself,
179       --  and is waiting for the tasks dependent on that master to become
180       --  terminated or waiting on a terminate Phase.
181
182       Master_Phase_2_Sleep,
183       --  In Phase 2 the task is sleeping in Complete_Master
184       --  waiting for tasks on terminate alternatives to finish
185       --  terminating.
186
187       --  The following are special uses of sleep, for server tasks
188       --  within the run-time system.
189
190       Interrupt_Server_Idle_Sleep,
191       Interrupt_Server_Blocked_Interrupt_Sleep,
192       Timer_Server_Sleep,
193       AST_Server_Sleep,
194
195       Asynchronous_Hold,
196       --  The task has been held by Asynchronous_Task_Control.Hold_Task
197
198       Interrupt_Server_Blocked_On_Event_Flag
199       --  The task has been blocked on a system call waiting for the
200       --  completion event.
201      );
202
203    type Call_Modes is
204      (Simple_Call, Conditional_Call, Asynchronous_Call, Timed_Call);
205
206    type Select_Modes is (Simple_Mode, Else_Mode, Terminate_Mode, Delay_Mode);
207
208    subtype Delay_Modes is Integer;
209
210    -------------------------------
211    -- Entry related definitions --
212    -------------------------------
213
214    Null_Entry : constant := 0;
215
216    Max_Entry : constant := Integer'Last;
217
218    Interrupt_Entry : constant := -2;
219
220    Cancelled_Entry : constant := -1;
221
222    type Entry_Index is range Interrupt_Entry .. Max_Entry;
223
224    Null_Task_Entry : constant := Null_Entry;
225
226    Max_Task_Entry : constant := Max_Entry;
227
228    type Task_Entry_Index is new Entry_Index
229      range Null_Task_Entry .. Max_Task_Entry;
230
231    type Entry_Call_Record;
232
233    type Entry_Call_Link is access all Entry_Call_Record;
234
235    type Entry_Queue is record
236       Head : Entry_Call_Link;
237       Tail : Entry_Call_Link;
238    end record;
239
240    type Task_Entry_Queue_Array is
241      array (Task_Entry_Index range <>) of Entry_Queue;
242
243    ----------------------------------
244    -- Entry_Call_Record definition --
245    ----------------------------------
246
247    type Entry_Call_State is
248      (Never_Abortable,
249       --  the call is not abortable, and never can be
250
251       Not_Yet_Abortable,
252       --  the call is not abortable, but may become so
253
254       Was_Abortable,
255       --  the call is not abortable, but once was
256
257       Now_Abortable,
258       --  the call is abortable
259
260       Done,
261       --  the call has been completed
262
263       Cancelled
264       --  the call was asynchronous, and was cancelled
265      );
266
267    --  Never_Abortable is used for calls that are made in a abort
268    --  deferred region (see ARM 9.8(5-11), 9.8 (20)).
269    --  Such a call is never abortable.
270
271    --  The Was_ vs. Not_Yet_ distinction is needed to decide whether it
272    --  is OK to advance into the abortable part of an async. select stmt.
273    --  That is allowed iff the mode is Now_ or Was_.
274
275    --  Done indicates the call has been completed, without cancellation,
276    --  or no call has been made yet at this ATC nesting level,
277    --  and so aborting the call is no longer an issue.
278    --  Completion of the call does not necessarily indicate "success";
279    --  the call may be returning an exception if Exception_To_Raise is
280    --  non-null.
281
282    --  Cancelled indicates the call was cancelled,
283    --  and so aborting the call is no longer an issue.
284
285    --  The call is on an entry queue unless
286    --  State >= Done, in which case it may or may not be still Onqueue.
287
288    --  Please do not modify the order of the values, without checking
289    --  all uses of this type. We rely on partial "monotonicity" of
290    --  Entry_Call_Record.State to avoid locking when we access this
291    --  value for certain tests. In particular:
292
293    --  1)  Once State >= Done, we can rely that the call has been
294    --      completed. If State >= Done, it will not
295    --      change until the task does another entry call at this level.
296
297    --  2)  Once State >= Was_Abortable, we can rely that the call has
298    --      been queued abortably at least once, and so the check for
299    --      whether it is OK to advance to the abortable part of an
300    --      async. select statement does not need to lock anything.
301
302    type Restricted_Entry_Call_Record is record
303       Self : Task_Id;
304       --  ID of the caller
305
306       Mode : Call_Modes;
307
308       State : Entry_Call_State;
309       pragma Atomic (State);
310       --  Indicates part of the state of the call.
311       --
312       --  Protection: If the call is not on a queue, it should only be
313       --  accessed by Self, and Self does not need any lock to modify this
314       --  field.
315       --
316       --  Once the call is on a queue, the value should be something other
317       --  than Done unless it is cancelled, and access is controller by the
318       --  "server" of the queue -- i.e., the lock of Checked_To_Protection
319       --  (Call_Target) if the call record is on the queue of a PO, or the
320       --  lock of Called_Target if the call is on the queue of a task. See
321       --  comments on type declaration for more details.
322
323       Uninterpreted_Data : System.Address;
324       --  Data passed by the compiler
325
326       Exception_To_Raise : Ada.Exceptions.Exception_Id;
327       --  The exception to raise once this call has been completed without
328       --  being aborted.
329    end record;
330    pragma Suppress_Initialization (Restricted_Entry_Call_Record);
331
332    ------------------------------------
333    -- Task related other definitions --
334    ------------------------------------
335
336    type Activation_Chain is limited private;
337    --  Comment required ???
338
339    type Activation_Chain_Access is access all Activation_Chain;
340    --  Comment required ???
341
342    type Task_Procedure_Access is access procedure (Arg : System.Address);
343
344    type Access_Boolean is access all Boolean;
345
346    function Detect_Blocking return Boolean;
347    pragma Inline (Detect_Blocking);
348    --  Return whether the Detect_Blocking pragma is enabled.
349
350    ----------------------------------------------
351    -- Ada_Task_Control_Block (ATCB) definition --
352    ----------------------------------------------
353
354    --  Notes on protection (synchronization) of TRTS data structures
355
356    --  Any field of the TCB can be written by the activator of a task when the
357    --  task is created, since no other task can access the new task's
358    --  state until creation is complete.
359
360    --  The protection for each field is described in a comment starting with
361    --  "Protection:".
362
363    --  When a lock is used to protect an ATCB field, this lock is simply named
364
365    --  Some protection is described in terms of tasks related to the
366    --  ATCB being protected. These are:
367
368    --    Self:      The task which is controlled by this ATCB
369    --    Acceptor:  A task accepting a call from Self
370    --    Caller:    A task calling an entry of Self
371    --    Parent:    The task executing the master on which Self depends
372    --    Dependent: A task dependent on Self
373    --    Activator: The task that created Self and initiated its activation
374    --    Created:   A task created and activated by Self
375
376    --  Note: The order of the fields is important to implement efficiently
377    --  tasking support under gdb.
378    --  Currently gdb relies on the order of the State, Parent, Base_Priority,
379    --  Task_Image, Task_Image_Len, Call and LL fields.
380
381    -------------------------
382    -- Common ATCB section --
383    -------------------------
384
385    --  Section used by all GNARL implementations (regular and restricted)
386
387    type Common_ATCB is record
388       State : Task_States;
389       pragma Atomic (State);
390       --  Encodes some basic information about the state of a task,
391       --  including whether it has been activated, whether it is sleeping,
392       --  and whether it is terminated.
393       --
394       --  Protection: Self.L
395
396       Parent : Task_Id;
397       --  The task on which this task depends.
398       --  See also Master_Level and Master_Within.
399
400       Base_Priority : System.Any_Priority;
401       --  Base priority, not changed during entry calls, only changed
402       --  via dynamic priorities package.
403       --
404       --  Protection: Only written by Self, accessed by anyone
405
406       Current_Priority : System.Any_Priority;
407       --  Active priority, except that the effects of protected object
408       --  priority ceilings are not reflected. This only reflects explicit
409       --  priority changes and priority inherited through task activation
410       --  and rendezvous.
411       --
412       --  Ada 95 notes: In Ada 95, this field will be transferred to the
413       --  Priority field of an Entry_Calls component when an entry call
414       --  is initiated. The Priority of the Entry_Calls component will not
415       --  change for the duration of the call. The accepting task can
416       --  use it to boost its own priority without fear of its changing in
417       --  the meantime.
418       --
419       --  This can safely be used in the priority ordering
420       --  of entry queues. Once a call is queued, its priority does not
421       --  change.
422       --
423       --  Since an entry call cannot be made while executing
424       --  a protected action, the priority of a task will never reflect a
425       --  priority ceiling change at the point of an entry call.
426       --
427       --  Protection: Only written by Self, and only accessed when Acceptor
428       --  accepts an entry or when Created activates, at which points Self is
429       --  suspended.
430
431       Protected_Action_Nesting : Natural;
432       pragma Atomic (Protected_Action_Nesting);
433       --  The dynamic level of protected action nesting for this task. This
434       --  field is needed for checking whether potentially blocking operations
435       --  are invoked from protected actions. pragma Atomic is used because it
436       --  can be read/written from protected interrupt handlers.
437
438       Task_Image : String (1 .. 32);
439       --  Hold a string that provides a readable id for task,
440       --  built from the variable of which it is a value or component.
441
442       Task_Image_Len : Natural;
443       --  Actual length of Task_Image
444
445       Call : Entry_Call_Link;
446       --  The entry call that has been accepted by this task.
447       --
448       --  Protection: Self.L. Self will modify this field when Self.Accepting
449       --  is False, and will not need the mutex to do so. Once a task sets
450       --  Pending_ATC_Level = 0, no other task can access this field.
451
452       LL : aliased Task_Primitives.Private_Data;
453       --  Control block used by the underlying low-level tasking service
454       --  (GNULLI).
455       --
456       --  Protection: This is used only by the GNULLI implementation, which
457       --  takes care of all of its synchronization.
458
459       Task_Arg : System.Address;
460       --  The argument to task procedure. Provide a handle for discriminant
461       --  information
462       --
463       --  Protection: Part of the synchronization between Self and Activator.
464       --  Activator writes it, once, before Self starts executing. Thereafter,
465       --  Self only reads it.
466
467       Task_Entry_Point : Task_Procedure_Access;
468       --  Information needed to call the procedure containing the code for
469       --  the body of this task.
470       --
471       --  Protection: Part of the synchronization between Self and Activator.
472       --  Activator writes it, once, before Self starts executing. Self reads
473       --  it, once, as part of its execution.
474
475       Compiler_Data : System.Soft_Links.TSD;
476       --  Task-specific data needed by the compiler to store per-task
477       --  structures.
478       --
479       --  Protection: Only accessed by Self
480
481       All_Tasks_Link : Task_Id;
482       --  Used to link this task to the list of all tasks in the system
483       --
484       --  Protection: RTS_Lock
485
486       Activation_Link : Task_Id;
487       --  Used to link this task to a list of tasks to be activated
488       --
489       --  Protection: Only used by Activator
490
491       Activator : Task_Id;
492       --  The task that created this task, either by declaring it as a task
493       --  object or by executing a task allocator. The value is null iff Self
494       --  has completed activation.
495       --
496       --  Protection: Set by Activator before Self is activated, and only read
497       --  and modified by Self after that.
498
499       Wait_Count : Integer;
500       --  This count is used by a task that is waiting for other tasks. At all
501       --  other times, the value should be zero. It is used differently in
502       --  several different states. Since a task cannot be in more than one of
503       --  these states at the same time, a single counter suffices.
504       --
505       --  Protection: Self.L
506
507       --  Activator_Sleep
508
509       --  This is the number of tasks that this task is activating, i.e. the
510       --  children that have started activation but have not completed it.
511       --
512       --  Protection: Self.L and Created.L. Both mutexes must be locked, since
513       --  Self.Activation_Count and Created.State must be synchronized.
514
515       --  Master_Completion_Sleep (phase 1)
516
517       --  This is the number dependent tasks of a master being completed by
518       --  Self that are not activated, not terminated, and not waiting on a
519       --  terminate alternative.
520
521       --  Master_Completion_2_Sleep (phase 2)
522
523       --  This is the count of tasks dependent on a master being completed by
524       --  Self which are waiting on a terminate alternative.
525
526       Elaborated : Access_Boolean;
527       --  Pointer to a flag indicating that this task's body has been
528       --  elaborated. The flag is created and managed by the
529       --  compiler-generated code.
530       --
531       --  Protection: The field itself is only accessed by Activator. The flag
532       --  that it points to is updated by Master and read by Activator; access
533       --  is assumed to be atomic.
534
535       Activation_Failed : Boolean;
536       --  Set to True if activation of a chain of tasks fails,
537       --  so that the activator should raise Tasking_Error.
538
539       Task_Info : System.Task_Info.Task_Info_Type;
540       --  System-specific attributes of the task as specified by the
541       --  Task_Info pragma.
542    end record;
543
544    ---------------------------------------
545    -- Restricted_Ada_Task_Control_Block --
546    ---------------------------------------
547
548    --  This type should only be used by the restricted GNARLI and by
549    --  restricted GNULL implementations to allocate an ATCB (see
550    --  System.Task_Primitives.Operations.New_ATCB) that will take
551    --  significantly less memory.
552
553    --  Note that the restricted GNARLI should only access fields that are
554    --  present in the Restricted_Ada_Task_Control_Block structure.
555
556    type Restricted_Ada_Task_Control_Block (Entry_Num : Task_Entry_Index) is
557    record
558       Common : Common_ATCB;
559       --  The common part between various tasking implementations
560
561       Entry_Call : aliased Restricted_Entry_Call_Record;
562       --  Protection: This field is used on entry call "queues" associated
563       --  with protected objects, and is protected by the protected object
564       --  lock.
565    end record;
566    pragma Suppress_Initialization (Restricted_Ada_Task_Control_Block);
567
568    Interrupt_Manager_ID : Task_Id;
569    --  This task ID is declared here to break circular dependencies.
570    --  Also declare Interrupt_Manager_ID after Task_Id is known, to avoid
571    --  generating unneeded finalization code.
572
573    -----------------------
574    -- List of all Tasks --
575    -----------------------
576
577    All_Tasks_List : Task_Id;
578    --  Global linked list of all tasks
579
580    ------------------------------------------
581    -- Regular (non restricted) definitions --
582    ------------------------------------------
583
584    --------------------------------
585    -- Master Related Definitions --
586    --------------------------------
587
588    subtype Master_Level is Integer;
589    subtype Master_ID is Master_Level;
590
591    --  Normally, a task starts out with internal master nesting level one
592    --  larger than external master nesting level. It is incremented to one by
593    --  Enter_Master, which is called in the task body only if the compiler
594    --  thinks the task may have dependent tasks. It is set to for the
595    --  environment task, the level 2 is reserved for server tasks of the
596    --  run-time system (the so called "independent tasks"), and the level 3 is
597    --  for the library level tasks.
598
599    Environment_Task_Level : constant Master_Level := 1;
600    Independent_Task_Level : constant Master_Level := 2;
601    Library_Task_Level     : constant Master_Level := 3;
602
603    ------------------------------
604    -- Task size, priority info --
605    ------------------------------
606
607    Unspecified_Priority : constant Integer := System.Priority'First - 1;
608
609    Priority_Not_Boosted : constant Integer := System.Priority'First - 1;
610    --  Definition of Priority actually has to come from the RTS configuration
611
612    subtype Rendezvous_Priority is Integer
613      range Priority_Not_Boosted .. System.Any_Priority'Last;
614
615    ------------------------------------
616    -- Rendezvous related definitions --
617    ------------------------------------
618
619    No_Rendezvous : constant := 0;
620
621    Max_Select : constant Integer := Integer'Last;
622    --  RTS-defined
623
624    subtype Select_Index is Integer range No_Rendezvous .. Max_Select;
625    --   type Select_Index is range No_Rendezvous .. Max_Select;
626
627    subtype Positive_Select_Index is
628      Select_Index range 1 .. Select_Index'Last;
629
630    type Accept_Alternative is record
631       Null_Body : Boolean;
632       S         : Task_Entry_Index;
633    end record;
634
635    type Accept_List is
636      array (Positive_Select_Index range <>) of Accept_Alternative;
637
638    type Accept_List_Access is access constant Accept_List;
639
640    -----------------------------------
641    -- ATC_Level related definitions --
642    -----------------------------------
643
644    Max_ATC_Nesting : constant Natural := 20;
645
646    subtype ATC_Level_Base is Integer range 0 .. Max_ATC_Nesting;
647
648    ATC_Level_Infinity : constant ATC_Level_Base := ATC_Level_Base'Last;
649
650    subtype ATC_Level is ATC_Level_Base range 0 .. ATC_Level_Base'Last - 1;
651
652    subtype ATC_Level_Index is ATC_Level range 1 .. ATC_Level'Last;
653
654    ----------------------------------
655    -- Entry_Call_Record definition --
656    ----------------------------------
657
658    type Entry_Call_Record is record
659       Self  : Task_Id;
660       --  ID of the caller
661
662       Mode : Call_Modes;
663
664       State : Entry_Call_State;
665       pragma Atomic (State);
666       --  Indicates part of the state of the call
667       --
668       --  Protection: If the call is not on a queue, it should only be
669       --  accessed by Self, and Self does not need any lock to modify this
670       --  field. Once the call is on a queue, the value should be something
671       --  other than Done unless it is cancelled, and access is controller by
672       --  the "server" of the queue -- i.e., the lock of Checked_To_Protection
673       --  (Call_Target) if the call record is on the queue of a PO, or the
674       --  lock of Called_Target if the call is on the queue of a task. See
675       --  comments on type declaration for more details.
676
677       Uninterpreted_Data : System.Address;
678       --  Data passed by the compiler
679
680       Exception_To_Raise : Ada.Exceptions.Exception_Id;
681       --  The exception to raise once this call has been completed without
682       --  being aborted.
683
684       Prev : Entry_Call_Link;
685
686       Next : Entry_Call_Link;
687
688       Level : ATC_Level;
689       --  One of Self and Level are redundant in this implementation, since
690       --  each Entry_Call_Record is at Self.Entry_Calls (Level). Since we must
691       --  have access to the entry call record to be reading this, we could
692       --  get Self from Level, or Level from Self. However, this requires
693       --  non-portable address arithmetic.
694
695       E : Entry_Index;
696
697       Prio : System.Any_Priority;
698
699       --  The above fields are those that there may be some hope of packing.
700       --  They are gathered together to allow for compilers that lay records
701       --  out contiguously, to allow for such packing.
702
703       Called_Task : Task_Id;
704       pragma Atomic (Called_Task);
705       --  Use for task entry calls. The value is null if the call record is
706       --  not in use. Conversely, unless State is Done and Onqueue is false,
707       --  Called_Task points to an ATCB.
708       --
709       --  Protection:  Called_Task.L
710
711       Called_PO : System.Address;
712       pragma Atomic (Called_PO);
713       --  Similar to Called_Task but for protected objects
714       --
715       --  Note that the previous implementation tried to merge both
716       --  Called_Task and Called_PO but this ended up in many unexpected
717       --  complications (e.g having to add a magic number in the ATCB, which
718       --  caused gdb lots of confusion) with no real gain since the
719       --  Lock_Server implementation still need to loop around chasing for
720       --  pointer changes even with a single pointer.
721
722       Acceptor_Prev_Call : Entry_Call_Link;
723       --  For task entry calls only
724
725       Acceptor_Prev_Priority : Rendezvous_Priority := Priority_Not_Boosted;
726       --  For task entry calls only. The priority of the most recent prior
727       --  call being serviced. For protected entry calls, this function should
728       --  be performed by GNULLI ceiling locking.
729
730       Cancellation_Attempted : Boolean := False;
731       pragma Atomic (Cancellation_Attempted);
732       --  Cancellation of the call has been attempted.
733       --  Consider merging this into State???
734
735       Requeue_With_Abort : Boolean := False;
736       --  Temporary to tell caller whether requeue is with abort.
737       --  Find a better way of doing this ???
738
739       Needs_Requeue : Boolean := False;
740       --  Temporary to tell acceptor of task entry call that
741       --  Exceptional_Complete_Rendezvous needs to do requeue.
742    end record;
743
744    ------------------------------------
745    -- Task related other definitions --
746    ------------------------------------
747
748    type Access_Address is access all System.Address;
749    --  Comment on what this is used for ???
750
751    pragma No_Strict_Aliasing (Access_Address);
752    --  This type is used in contexts where aliasing may be an issue (see
753    --  for example s-tataat.adb), so we avoid any incorrect aliasing
754    --  assumptions.
755
756    ----------------------------------------------
757    -- Ada_Task_Control_Block (ATCB) definition --
758    ----------------------------------------------
759
760    type Entry_Call_Array is array (ATC_Level_Index) of
761      aliased Entry_Call_Record;
762
763    type Direct_Index is range 0 .. Parameters.Default_Attribute_Count;
764    subtype Direct_Index_Range is Direct_Index range 1 .. Direct_Index'Last;
765    --  Attributes with indices in this range are stored directly in the task
766    --  control block. Such attributes must be Address-sized. Other attributes
767    --  will be held in dynamically allocated records chained off of the task
768    --  control block.
769
770    type Direct_Attribute_Element is mod Memory_Size;
771    pragma Atomic (Direct_Attribute_Element);
772
773    type Direct_Attribute_Array is
774      array (Direct_Index_Range) of aliased Direct_Attribute_Element;
775
776    type Direct_Index_Vector is mod 2 ** Parameters.Default_Attribute_Count;
777    --  This is a bit-vector type, used to store information about
778    --  the usage of the direct attribute fields.
779
780    type Task_Serial_Number is mod 2 ** 64;
781    --  Used to give each task a unique serial number
782
783    type Ada_Task_Control_Block (Entry_Num : Task_Entry_Index) is record
784       Common : Common_ATCB;
785       --  The common part between various tasking implementations
786
787       Entry_Calls : Entry_Call_Array;
788       --  An array of entry calls
789       --
790       --  Protection: The elements of this array are on entry call queues
791       --  associated with protected objects or task entries, and are protected
792       --  by the protected object lock or Acceptor.L, respectively.
793
794       New_Base_Priority : System.Any_Priority;
795       --  New value for Base_Priority (for dynamic priorities package)
796       --
797       --  Protection: Self.L
798
799       Global_Task_Lock_Nesting : Natural := 0;
800       --  This is the current nesting level of calls to
801       --  System.Tasking.Stages.Lock_Task_T. This allows a task to call
802       --  Lock_Task_T multiple times without deadlocking. A task only locks
803       --  All_Task_Lock when its All_Tasks_Nesting goes from 0 to 1, and only
804       --  unlocked when it goes from 1 to 0.
805       --
806       --  Protection: Only accessed by Self
807
808       Open_Accepts : Accept_List_Access;
809       --  This points to the Open_Accepts array of accept alternatives passed
810       --  to the RTS by the compiler-generated code to Selective_Wait. It is
811       --  non-null iff this task is ready to accept an entry call.
812       --
813       --  Protection: Self.L
814
815       Chosen_Index : Select_Index;
816       --  The index in Open_Accepts of the entry call accepted by a selective
817       --  wait executed by this task.
818       --
819       --  Protection: Written by both Self and Caller. Usually protected by
820       --  Self.L. However, once the selection is known to have been written it
821       --  can be accessed without protection. This happens after Self has
822       --  updated it itself using information from a suspended Caller, or
823       --  after Caller has updated it and awakened Self.
824
825       Master_of_Task : Master_Level;
826       --  The task executing the master of this task, and the ID of this task's
827       --  master (unique only among masters currently active within Parent).
828       --
829       --  Protection: Set by Activator before Self is activated, and read
830       --  after Self is activated.
831
832       Master_Within : Master_Level;
833       --  The ID of the master currently executing within this task; that is,
834       --  the most deeply nested currently active master.
835       --
836       --  Protection: Only written by Self, and only read by Self or by
837       --  dependents when Self is attempting to exit a master. Since Self will
838       --  not write this field until the master is complete, the
839       --  synchronization should be adequate to prevent races.
840
841       Alive_Count : Integer := 0;
842       --  Number of tasks directly dependent on this task (including itself)
843       --  that are still "alive", i.e. not terminated.
844       --
845       --  Protection: Self.L
846
847       Awake_Count : Integer := 0;
848       --  Number of tasks directly dependent on this task (including itself)
849       --  still "awake", i.e., are not terminated and not waiting on a
850       --  terminate alternative.
851       --
852       --  Invariant: Awake_Count <= Alive_Count
853
854       --  Protection: Self.L
855
856       --  Beginning of flags
857
858       Aborting : Boolean := False;
859       pragma Atomic (Aborting);
860       --  Self is in the process of aborting. While set, prevents multiple
861       --  abort signals from being sent by different aborter while abort
862       --  is acted upon. This is essential since an aborter which calls
863       --  Abort_To_Level could set the Pending_ATC_Level to yet a lower level
864       --  (than the current level), may be preempted and would send the
865       --  abort signal when resuming execution. At this point, the abortee
866       --  may have completed abort to the proper level such that the
867       --  signal (and resulting abort exception) are not handled any more.
868       --  In other words, the flag prevents a race between multiple aborters
869       --
870       --  Protection: protected by atomic access.
871
872       ATC_Hack : Boolean := False;
873       pragma Atomic (ATC_Hack);
874       --  ?????
875       --  Temporary fix, to allow Undefer_Abort to reset Aborting in the
876       --  handler for Abort_Signal that encloses an async. entry call.
877       --  For the longer term, this should be done via code in the
878       --  handler itself.
879
880       Callable : Boolean := True;
881       --  It is OK to call entries of this task
882
883       Dependents_Aborted : Boolean := False;
884       --  This is set to True by whichever task takes responsibility for
885       --  aborting the dependents of this task.
886       --
887       --  Protection: Self.L
888
889       Interrupt_Entry : Boolean := False;
890       --  Indicates if one or more Interrupt Entries are attached to the task.
891       --  This flag is needed for cleaning up the Interrupt Entry bindings.
892
893       Pending_Action : Boolean := False;
894       --  Unified flag indicating some action needs to be take when abort
895       --  next becomes undeferred. Currently set if:
896       --  . Pending_Priority_Change is set
897       --  . Pending_ATC_Level is changed
898       --  . Requeue involving POs
899       --    (Abortable field may have changed and the Wait_Until_Abortable
900       --     has to recheck the abortable status of the call.)
901       --  . Exception_To_Raise is non-null
902       --
903       --  Protection: Self.L
904       --
905       --  This should never be reset back to False outside of the procedure
906       --  Do_Pending_Action, which is called by Undefer_Abort. It should only
907       --  be set to True by Set_Priority and Abort_To_Level.
908
909       Pending_Priority_Change : Boolean := False;
910       --  Flag to indicate pending priority change (for dynamic priorities
911       --  package). The base priority is updated on the next abort
912       --  completion point (aka. synchronization point).
913       --
914       --  Protection: Self.L
915
916       Terminate_Alternative : Boolean := False;
917       --  Task is accepting Select with Terminate Alternative
918       --
919       --  Protection: Self.L
920
921       --  End of flags
922
923       --  Beginning of counts
924
925       ATC_Nesting_Level : ATC_Level := 1;
926       --  The dynamic level of ATC nesting (currently executing nested
927       --  asynchronous select statements) in this task.
928
929       --  Protection: Self_ID.L. Only Self reads or updates this field.
930       --  Decrementing it deallocates an Entry_Calls component, and care must
931       --  be taken that all references to that component are eliminated before
932       --  doing the decrement. This in turn will require locking a protected
933       --  object (for a protected entry call) or the Acceptor's lock (for a
934       --  task entry call). No other task should attempt to read or modify
935       --  this value.
936
937       Deferral_Level : Natural := 1;
938       --  This is the number of times that Defer_Abortion has been called by
939       --  this task without a matching Undefer_Abortion call. Abortion is only
940       --  allowed when this zero. It is initially 1, to protect the task at
941       --  startup.
942
943       --  Protection: Only updated by Self; access assumed to be atomic
944
945       Pending_ATC_Level : ATC_Level_Base := ATC_Level_Infinity;
946       --  The ATC level to which this task is currently being aborted. If the
947       --  value is zero, the entire task has "completed". That may be via
948       --  abort, exception propagation, or normal exit. If the value is
949       --  ATC_Level_Infinity, the task is not being aborted to any level. If
950       --  the value is positive, the task has not completed. This should ONLY
951       --  be modified by Abort_To_Level and Exit_One_ATC_Level.
952       --
953       --  Protection: Self.L
954
955       Serial_Number : Task_Serial_Number;
956       --  A growing number to provide some way to check locking  rules/ordering
957
958       Known_Tasks_Index : Integer := -1;
959       --  Index in the System.Tasking.Debug.Known_Tasks array
960
961       User_State : Long_Integer := 0;
962       --  User-writeable location, for use in debugging tasks; also provides a
963       --  simple task specific data.
964
965       Direct_Attributes : Direct_Attribute_Array;
966       --  For task attributes that have same size as Address
967
968       Is_Defined : Direct_Index_Vector := 0;
969       --  Bit I is 1 iff Direct_Attributes (I) is defined
970
971       Indirect_Attributes : Access_Address;
972       --  A pointer to chain of records for other attributes that are not
973       --  address-sized, including all tagged types.
974
975       Entry_Queues : Task_Entry_Queue_Array (1 .. Entry_Num);
976       --  An array of task entry queues
977       --
978       --  Protection: Self.L. Once a task has set Self.Stage to Completing, it
979       --  has exclusive access to this field.
980    end record;
981
982    --------------------
983    -- Initialization --
984    --------------------
985
986    procedure Initialize;
987    --  This procedure constitutes the first part of the initialization of the
988    --  GNARL. This includes creating data structures to make the initial thread
989    --  into the environment task. The last part of the initialization is done
990    --  in System.Tasking.Initialization or System.Tasking.Restricted.Stages.
991    --  All the initializations used to be in Tasking.Initialization, but this
992    --  is no longer possible with the run time simplification (including
993    --  optimized PO and the restricted run time) since one cannot rely on
994    --  System.Tasking.Initialization being present, as was done before.
995
996    procedure Initialize_ATCB
997      (Self_ID          : Task_Id;
998       Task_Entry_Point : Task_Procedure_Access;
999       Task_Arg         : System.Address;
1000       Parent           : Task_Id;
1001       Elaborated       : Access_Boolean;
1002       Base_Priority    : System.Any_Priority;
1003       Task_Info        : System.Task_Info.Task_Info_Type;
1004       Stack_Size       : System.Parameters.Size_Type;
1005       T                : Task_Id;
1006       Success          : out Boolean);
1007    --  Initialize fields of a TCB and link into global TCB structures Call
1008    --  this only with abort deferred and holding RTS_Lock. Need more
1009    --  documentation, mention T, and describe Success ???
1010
1011 private
1012    Null_Task : constant Task_Id := null;
1013
1014    type Activation_Chain is record
1015       T_ID : Task_Id;
1016    end record;
1017    pragma Volatile (Activation_Chain);
1018
1019    --  Activation_chain is an in-out parameter of initialization procedures
1020    --  and it must be passed by reference because the init proc may terminate
1021    --  abnormally after creating task components, and these must be properly
1022    --  registered for removal (Expunge_Unactivated_Tasks).
1023
1024 end System.Tasking;