OSDN Git Service

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