OSDN Git Service

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