OSDN Git Service

* tree-data-ref.c: Rename DDR_SIZE_VECT to DDR_NB_LOOPS.
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-taprop-lynxos.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                 GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS                 --
4 --                                                                          --
5 --     S Y S T E M . T A S K _ P R I M I T I V E S . O P E R A T I O N S    --
6 --                                                                          --
7 --                                  B o d y                                 --
8 --                                                                          --
9 --         Copyright (C) 1992-2006, 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 is a LynxOS version of this file, adapted to make
35 --  SCHED_FIFO and ceiling locking (Annex D compliance) work properly
36
37 --  This package contains all the GNULL primitives that interface directly
38 --  with the underlying OS.
39
40 pragma Polling (Off);
41 --  Turn off polling, we do not want ATC polling to take place during
42 --  tasking operations. It causes infinite loops and other problems.
43
44 with System.Tasking.Debug;
45 --  used for Known_Tasks
46
47 with System.Interrupt_Management;
48 --  used for Keep_Unmasked
49 --           Abort_Task_Interrupt
50 --           Interrupt_ID
51
52 with System.OS_Primitives;
53 --  used for Delay_Modes
54
55 with System.Task_Info;
56 --  used for Task_Info_Type
57
58 with Interfaces.C;
59 --  used for int
60 --           size_t
61
62 with System.Soft_Links;
63 --  used for Abort_Defer/Undefer
64
65 --  We use System.Soft_Links instead of System.Tasking.Initialization
66 --  because the later is a higher level package that we shouldn't depend on.
67 --  For example when using the restricted run time, it is replaced by
68 --  System.Tasking.Restricted.Stages.
69
70 with Unchecked_Deallocation;
71
72 package body System.Task_Primitives.Operations is
73
74    package SSL renames System.Soft_Links;
75
76    use System.Tasking.Debug;
77    use System.Tasking;
78    use Interfaces.C;
79    use System.OS_Interface;
80    use System.Parameters;
81    use System.OS_Primitives;
82
83    ----------------
84    -- Local Data --
85    ----------------
86
87    --  The followings are logically constants, but need to be initialized
88    --  at run time.
89
90    Single_RTS_Lock : aliased RTS_Lock;
91    --  This is a lock to allow only one thread of control in the RTS at
92    --  a time; it is used to execute in mutual exclusion from all other tasks.
93    --  Used mainly in Single_Lock mode, but also to protect All_Tasks_List
94
95    ATCB_Key : aliased pthread_key_t;
96    --  Key used to find the Ada Task_Id associated with a thread
97
98    Environment_Task_Id : Task_Id;
99    --  A variable to hold Task_Id for the environment task
100
101    Locking_Policy : Character;
102    pragma Import (C, Locking_Policy, "__gl_locking_policy");
103    --  Value of the pragma Locking_Policy:
104    --    'C' for Ceiling_Locking
105    --    'I' for Inherit_Locking
106    --    ' ' for none.
107
108    Unblocked_Signal_Mask : aliased sigset_t;
109    --  The set of signals that should unblocked in all tasks
110
111    --  The followings are internal configuration constants needed
112
113    Next_Serial_Number : Task_Serial_Number := 100;
114    --  We start at 100, to reserve some special values for
115    --  using in error checking.
116
117    Time_Slice_Val : Integer;
118    pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
119
120    Dispatching_Policy : Character;
121    pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
122
123    Foreign_Task_Elaborated : aliased Boolean := True;
124    --  Used to identified fake tasks (i.e., non-Ada Threads)
125
126    --------------------
127    -- Local Packages --
128    --------------------
129
130    package Specific is
131
132       procedure Initialize (Environment_Task : Task_Id);
133       pragma Inline (Initialize);
134       --  Initialize various data needed by this package
135
136       function Is_Valid_Task return Boolean;
137       pragma Inline (Is_Valid_Task);
138       --  Does the current thread have an ATCB?
139
140       procedure Set (Self_Id : Task_Id);
141       pragma Inline (Set);
142       --  Set the self id for the current task
143
144       function Self return Task_Id;
145       pragma Inline (Self);
146       --  Return a pointer to the Ada Task Control Block of the calling task
147
148    end Specific;
149
150    package body Specific is separate;
151    --  The body of this package is target specific
152
153    ---------------------------------
154    -- Support for foreign threads --
155    ---------------------------------
156
157    function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
158    --  Allocate and Initialize a new ATCB for the current Thread
159
160    function Register_Foreign_Thread
161      (Thread : Thread_Id) return Task_Id is separate;
162
163    -----------------------
164    -- Local Subprograms --
165    -----------------------
166
167    procedure Abort_Handler (Sig : Signal);
168    --  Signal handler used to implement asynchronous abort
169
170    procedure Set_OS_Priority (T : Task_Id; Prio : System.Any_Priority);
171    --  This procedure calls the scheduler of the OS to set thread's priority
172
173    -------------------
174    -- Abort_Handler --
175    -------------------
176
177    procedure Abort_Handler (Sig : Signal) is
178       pragma Unreferenced (Sig);
179
180       T       : constant Task_Id := Self;
181       Result  : Interfaces.C.int;
182       Old_Set : aliased sigset_t;
183
184    begin
185       --  It is not safe to raise an exception when using ZCX and the GCC
186       --  exception handling mechanism.
187
188       if ZCX_By_Default and then GCC_ZCX_Support then
189          return;
190       end if;
191
192       if T.Deferral_Level = 0
193         and then T.Pending_ATC_Level < T.ATC_Nesting_Level and then
194         not T.Aborting
195       then
196          T.Aborting := True;
197
198          --  Make sure signals used for RTS internal purpose are unmasked
199
200          Result :=
201            pthread_sigmask (SIG_UNBLOCK,
202                             Unblocked_Signal_Mask'Unchecked_Access,
203                             Old_Set'Unchecked_Access);
204          pragma Assert (Result = 0);
205
206          raise Standard'Abort_Signal;
207       end if;
208    end Abort_Handler;
209
210    -----------------
211    -- Stack_Guard --
212    -----------------
213
214    procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
215       Stack_Base : constant Address := Get_Stack_Base (T.Common.LL.Thread);
216       Guard_Page_Address : Address;
217
218       Res : Interfaces.C.int;
219
220    begin
221       if Stack_Base_Available then
222
223          --  Compute the guard page address
224
225          Guard_Page_Address :=
226            Stack_Base - (Stack_Base mod Get_Page_Size) + Get_Page_Size;
227
228          if On then
229             Res := mprotect (Guard_Page_Address, Get_Page_Size, PROT_ON);
230          else
231             Res := mprotect (Guard_Page_Address, Get_Page_Size, PROT_OFF);
232          end if;
233
234          pragma Assert (Res = 0);
235       end if;
236    end Stack_Guard;
237
238    --------------------
239    -- Get_Thread_Id  --
240    --------------------
241
242    function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
243    begin
244       return T.Common.LL.Thread;
245    end Get_Thread_Id;
246
247    ----------
248    -- Self --
249    ----------
250
251    function Self return Task_Id renames Specific.Self;
252
253    ---------------------
254    -- Initialize_Lock --
255    ---------------------
256
257    procedure Initialize_Lock
258      (Prio : System.Any_Priority;
259       L    : access Lock)
260    is
261       Attributes : aliased pthread_mutexattr_t;
262       Result : Interfaces.C.int;
263
264    begin
265       Result := pthread_mutexattr_init (Attributes'Access);
266       pragma Assert (Result = 0 or else Result = ENOMEM);
267
268       if Result = ENOMEM then
269          raise Storage_Error;
270       end if;
271
272       if Locking_Policy = 'C' then
273          L.Ceiling := Prio;
274       end if;
275
276       Result := pthread_mutex_init (L.Mutex'Access, Attributes'Access);
277       pragma Assert (Result = 0 or else Result = ENOMEM);
278
279       if Result = ENOMEM then
280          raise Storage_Error;
281       end if;
282
283       Result := pthread_mutexattr_destroy (Attributes'Access);
284       pragma Assert (Result = 0);
285    end Initialize_Lock;
286
287    procedure Initialize_Lock (L : access RTS_Lock; Level : Lock_Level) is
288       pragma Unreferenced (Level);
289
290       Attributes : aliased pthread_mutexattr_t;
291       Result : Interfaces.C.int;
292
293    begin
294       Result := pthread_mutexattr_init (Attributes'Access);
295       pragma Assert (Result = 0 or else Result = ENOMEM);
296
297       if Result = ENOMEM then
298          raise Storage_Error;
299       end if;
300
301       Result := pthread_mutex_init (L, Attributes'Access);
302       pragma Assert (Result = 0 or else Result = ENOMEM);
303
304       if Result = ENOMEM then
305          Result := pthread_mutexattr_destroy (Attributes'Access);
306          raise Storage_Error;
307       end if;
308
309       Result := pthread_mutexattr_destroy (Attributes'Access);
310       pragma Assert (Result = 0);
311    end Initialize_Lock;
312
313    -------------------
314    -- Finalize_Lock --
315    -------------------
316
317    procedure Finalize_Lock (L : access Lock) is
318       Result : Interfaces.C.int;
319    begin
320       Result := pthread_mutex_destroy (L.Mutex'Access);
321       pragma Assert (Result = 0);
322    end Finalize_Lock;
323
324    procedure Finalize_Lock (L : access RTS_Lock) is
325       Result : Interfaces.C.int;
326    begin
327       Result := pthread_mutex_destroy (L);
328       pragma Assert (Result = 0);
329    end Finalize_Lock;
330
331    ----------------
332    -- Write_Lock --
333    ----------------
334
335    procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
336       Result : Interfaces.C.int;
337       T : constant Task_Id := Self;
338
339    begin
340       if Locking_Policy = 'C' then
341          if T.Common.Current_Priority > L.Ceiling then
342             Ceiling_Violation := True;
343             return;
344          end if;
345
346          L.Saved_Priority := T.Common.Current_Priority;
347
348          if T.Common.Current_Priority < L.Ceiling then
349             Set_OS_Priority (T, L.Ceiling);
350          end if;
351       end if;
352
353       Result := pthread_mutex_lock (L.Mutex'Access);
354
355       --  Assume that the cause of EINVAL is a priority ceiling violation
356
357       Ceiling_Violation := (Result = EINVAL);
358       pragma Assert (Result = 0 or else Result = EINVAL);
359    end Write_Lock;
360
361    --  No tricks on RTS_Locks
362
363    procedure Write_Lock
364      (L : access RTS_Lock; Global_Lock : Boolean := False)
365    is
366       Result : Interfaces.C.int;
367    begin
368       if not Single_Lock or else Global_Lock then
369          Result := pthread_mutex_lock (L);
370          pragma Assert (Result = 0);
371       end if;
372    end Write_Lock;
373
374    procedure Write_Lock (T : Task_Id) is
375       Result : Interfaces.C.int;
376    begin
377       if not Single_Lock then
378          Result := pthread_mutex_lock (T.Common.LL.L'Access);
379          pragma Assert (Result = 0);
380       end if;
381    end Write_Lock;
382
383    ---------------
384    -- Read_Lock --
385    ---------------
386
387    procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
388    begin
389       Write_Lock (L, Ceiling_Violation);
390    end Read_Lock;
391
392    ------------
393    -- Unlock --
394    ------------
395
396    procedure Unlock (L : access Lock) is
397       Result : Interfaces.C.int;
398       T : constant Task_Id := Self;
399
400    begin
401       Result := pthread_mutex_unlock (L.Mutex'Access);
402       pragma Assert (Result = 0);
403
404       if Locking_Policy = 'C' then
405          if T.Common.Current_Priority > L.Saved_Priority then
406             Set_OS_Priority (T, L.Saved_Priority);
407          end if;
408       end if;
409    end Unlock;
410
411    procedure Unlock (L : access RTS_Lock; Global_Lock : Boolean := False) is
412       Result : Interfaces.C.int;
413    begin
414       if not Single_Lock or else Global_Lock then
415          Result := pthread_mutex_unlock (L);
416          pragma Assert (Result = 0);
417       end if;
418    end Unlock;
419
420    procedure Unlock (T : Task_Id) is
421       Result : Interfaces.C.int;
422    begin
423       if not Single_Lock then
424          Result := pthread_mutex_unlock (T.Common.LL.L'Access);
425          pragma Assert (Result = 0);
426       end if;
427    end Unlock;
428
429    -----------
430    -- Sleep --
431    -----------
432
433    procedure Sleep
434      (Self_ID : Task_Id;
435       Reason   : System.Tasking.Task_States)
436    is
437       pragma Unreferenced (Reason);
438       Result : Interfaces.C.int;
439
440    begin
441       if Single_Lock then
442          Result := pthread_cond_wait
443            (Self_ID.Common.LL.CV'Access, Single_RTS_Lock'Access);
444       else
445          Result := pthread_cond_wait
446            (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access);
447       end if;
448
449       --  EINTR is not considered a failure
450
451       pragma Assert (Result = 0 or else Result = EINTR);
452    end Sleep;
453
454    -----------------
455    -- Timed_Sleep --
456    -----------------
457
458    --  This is for use within the run-time system, so abort is
459    --  assumed to be already deferred, and the caller should be
460    --  holding its own ATCB lock.
461
462    procedure Timed_Sleep
463      (Self_ID  : Task_Id;
464       Time     : Duration;
465       Mode     : ST.Delay_Modes;
466       Reason   : Task_States;
467       Timedout : out Boolean;
468       Yielded  : out Boolean)
469    is
470       pragma Unreferenced (Reason);
471
472       Check_Time : constant Duration := Monotonic_Clock;
473       Rel_Time   : Duration;
474       Abs_Time   : Duration;
475       Request    : aliased timespec;
476       Result     : Interfaces.C.int;
477
478    begin
479       Timedout := True;
480       Yielded := False;
481
482       if Mode = Relative then
483          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
484
485          if Relative_Timed_Wait then
486             Rel_Time := Duration'Min (Max_Sensible_Delay, Time);
487          end if;
488
489       else
490          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
491
492          if Relative_Timed_Wait then
493             Rel_Time := Duration'Min (Max_Sensible_Delay, Time - Check_Time);
494          end if;
495       end if;
496
497       if Abs_Time > Check_Time then
498          if Relative_Timed_Wait then
499             Request := To_Timespec (Rel_Time);
500          else
501             Request := To_Timespec (Abs_Time);
502          end if;
503
504          loop
505             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
506               or else Self_ID.Pending_Priority_Change;
507
508             if Single_Lock then
509                Result := pthread_cond_timedwait
510                  (Self_ID.Common.LL.CV'Access, Single_RTS_Lock'Access,
511                   Request'Access);
512
513             else
514                Result := pthread_cond_timedwait
515                  (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access,
516                   Request'Access);
517             end if;
518
519             exit when Abs_Time <= Monotonic_Clock;
520
521             if Result = 0 or Result = EINTR then
522
523                --  Somebody may have called Wakeup for us
524
525                Timedout := False;
526                exit;
527             end if;
528
529             pragma Assert (Result = ETIMEDOUT);
530          end loop;
531       end if;
532    end Timed_Sleep;
533
534    -----------------
535    -- Timed_Delay --
536    -----------------
537
538    --  This is for use in implementing delay statements, so we assume
539    --  the caller is abort-deferred but is holding no locks.
540
541    procedure Timed_Delay
542      (Self_ID  : Task_Id;
543       Time     : Duration;
544       Mode     : ST.Delay_Modes)
545    is
546       Check_Time : constant Duration := Monotonic_Clock;
547       Abs_Time   : Duration;
548       Rel_Time   : Duration;
549       Request    : aliased timespec;
550       Result     : Interfaces.C.int;
551
552    begin
553       if Single_Lock then
554          Lock_RTS;
555       end if;
556
557       --  Comments needed in code below ???
558
559       Write_Lock (Self_ID);
560
561       if Mode = Relative then
562          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
563
564          if Relative_Timed_Wait then
565             Rel_Time := Duration'Min (Max_Sensible_Delay, Time);
566          end if;
567
568       else
569          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
570
571          if Relative_Timed_Wait then
572             Rel_Time := Duration'Min (Max_Sensible_Delay, Time - Check_Time);
573          end if;
574       end if;
575
576       if Abs_Time > Check_Time then
577          if Relative_Timed_Wait then
578             Request := To_Timespec (Rel_Time);
579          else
580             Request := To_Timespec (Abs_Time);
581          end if;
582
583          Self_ID.Common.State := Delay_Sleep;
584
585          loop
586             if Self_ID.Pending_Priority_Change then
587                Self_ID.Pending_Priority_Change := False;
588                Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
589                Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
590             end if;
591
592             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
593
594             if Single_Lock then
595                Result := pthread_cond_timedwait (Self_ID.Common.LL.CV'Access,
596                  Single_RTS_Lock'Access, Request'Access);
597             else
598                Result := pthread_cond_timedwait (Self_ID.Common.LL.CV'Access,
599                  Self_ID.Common.LL.L'Access, Request'Access);
600             end if;
601
602             exit when Abs_Time <= Monotonic_Clock;
603
604             pragma Assert (Result = 0
605                              or else Result = ETIMEDOUT
606                              or else Result = EINTR);
607          end loop;
608
609          Self_ID.Common.State := Runnable;
610       end if;
611
612       Unlock (Self_ID);
613
614       if Single_Lock then
615          Unlock_RTS;
616       end if;
617
618       Result := sched_yield;
619    end Timed_Delay;
620
621    ---------------------
622    -- Monotonic_Clock --
623    ---------------------
624
625    function Monotonic_Clock return Duration is
626       TS     : aliased timespec;
627       Result : Interfaces.C.int;
628    begin
629       Result := clock_gettime
630         (clock_id => CLOCK_REALTIME, tp => TS'Unchecked_Access);
631       pragma Assert (Result = 0);
632       return To_Duration (TS);
633    end Monotonic_Clock;
634
635    -------------------
636    -- RT_Resolution --
637    -------------------
638
639    function RT_Resolution return Duration is
640       Res    : aliased timespec;
641       Result : Interfaces.C.int;
642    begin
643       Result := clock_getres
644         (clock_id => CLOCK_REALTIME, Res => Res'Unchecked_Access);
645       pragma Assert (Result = 0);
646       return To_Duration (Res);
647    end RT_Resolution;
648
649    ------------
650    -- Wakeup --
651    ------------
652
653    procedure Wakeup (T : Task_Id; Reason : System.Tasking.Task_States) is
654       pragma Unreferenced (Reason);
655       Result : Interfaces.C.int;
656    begin
657       Result := pthread_cond_signal (T.Common.LL.CV'Access);
658       pragma Assert (Result = 0);
659    end Wakeup;
660
661    -----------
662    -- Yield --
663    -----------
664
665    procedure Yield (Do_Yield : Boolean := True) is
666       Result : Interfaces.C.int;
667       pragma Unreferenced (Result);
668    begin
669       if Do_Yield then
670          Result := sched_yield;
671       end if;
672    end Yield;
673
674    ------------------
675    -- Set_Priority --
676    ------------------
677
678    procedure Set_OS_Priority (T : Task_Id; Prio : System.Any_Priority) is
679       Result : Interfaces.C.int;
680       Param  : aliased struct_sched_param;
681
682    begin
683       Param.sched_priority := Interfaces.C.int (Prio);
684
685       if Time_Slice_Supported and then Time_Slice_Val > 0 then
686          Result := pthread_setschedparam
687            (T.Common.LL.Thread, SCHED_RR, Param'Access);
688
689       elsif Dispatching_Policy = 'F' or else Time_Slice_Val = 0 then
690          Result := pthread_setschedparam
691            (T.Common.LL.Thread, SCHED_FIFO, Param'Access);
692
693       else
694          Result := pthread_setschedparam
695            (T.Common.LL.Thread, SCHED_OTHER, Param'Access);
696       end if;
697
698       pragma Assert (Result = 0);
699    end Set_OS_Priority;
700
701    type Prio_Array_Type is array (System.Any_Priority) of Integer;
702    pragma Atomic_Components (Prio_Array_Type);
703    Prio_Array : Prio_Array_Type;
704    --  Comments needed for these declarations ???
705
706    procedure Set_Priority
707      (T                   : Task_Id;
708       Prio                : System.Any_Priority;
709       Loss_Of_Inheritance : Boolean := False)
710    is
711       Array_Item : Integer;
712
713    begin
714       Set_OS_Priority (T, Prio);
715
716       if Locking_Policy = 'C' then
717          --  Annex D requirements: loss of inheritance puts task at the
718          --  beginning of the queue for that prio; copied from 5ztaprop
719          --  (VxWorks)
720
721          if Loss_Of_Inheritance
722            and then Prio < T.Common.Current_Priority then
723
724             Array_Item := Prio_Array (T.Common.Base_Priority) + 1;
725             Prio_Array (T.Common.Base_Priority) := Array_Item;
726
727             loop
728                Yield;
729                exit when Array_Item = Prio_Array (T.Common.Base_Priority)
730                  or else Prio_Array (T.Common.Base_Priority) = 1;
731             end loop;
732
733             Prio_Array (T.Common.Base_Priority) :=
734               Prio_Array (T.Common.Base_Priority) - 1;
735          end if;
736       end if;
737
738       T.Common.Current_Priority := Prio;
739    end Set_Priority;
740
741    ------------------
742    -- Get_Priority --
743    ------------------
744
745    function Get_Priority (T : Task_Id) return System.Any_Priority is
746    begin
747       return T.Common.Current_Priority;
748    end Get_Priority;
749
750    ----------------
751    -- Enter_Task --
752    ----------------
753
754    procedure Enter_Task (Self_ID : Task_Id) is
755    begin
756       Self_ID.Common.LL.Thread := pthread_self;
757       Self_ID.Common.LL.LWP := lwp_self;
758
759       Specific.Set (Self_ID);
760
761       Lock_RTS;
762
763       for J in Known_Tasks'Range loop
764          if Known_Tasks (J) = null then
765             Known_Tasks (J) := Self_ID;
766             Self_ID.Known_Tasks_Index := J;
767             exit;
768          end if;
769       end loop;
770
771       Unlock_RTS;
772    end Enter_Task;
773
774    --------------
775    -- New_ATCB --
776    --------------
777
778    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
779    begin
780       return new Ada_Task_Control_Block (Entry_Num);
781    end New_ATCB;
782
783    -------------------
784    -- Is_Valid_Task --
785    -------------------
786
787    function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
788
789    -----------------------------
790    -- Register_Foreign_Thread --
791    -----------------------------
792
793    function Register_Foreign_Thread return Task_Id is
794    begin
795       if Is_Valid_Task then
796          return Self;
797       else
798          return Register_Foreign_Thread (pthread_self);
799       end if;
800    end Register_Foreign_Thread;
801
802    --------------------
803    -- Initialize_TCB --
804    --------------------
805
806    procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
807       Mutex_Attr : aliased pthread_mutexattr_t;
808       Result     : Interfaces.C.int;
809       Cond_Attr  : aliased pthread_condattr_t;
810
811    begin
812       --  Give the task a unique serial number
813
814       Self_ID.Serial_Number := Next_Serial_Number;
815       Next_Serial_Number := Next_Serial_Number + 1;
816       pragma Assert (Next_Serial_Number /= 0);
817
818       if not Single_Lock then
819          Result := pthread_mutexattr_init (Mutex_Attr'Access);
820          pragma Assert (Result = 0 or else Result = ENOMEM);
821
822          if Result = 0 then
823             Result := pthread_mutex_init (Self_ID.Common.LL.L'Access,
824               Mutex_Attr'Access);
825             pragma Assert (Result = 0 or else Result = ENOMEM);
826          end if;
827
828          if Result /= 0 then
829             Succeeded := False;
830             return;
831          end if;
832
833          Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
834          pragma Assert (Result = 0);
835       end if;
836
837       Result := pthread_condattr_init (Cond_Attr'Access);
838       pragma Assert (Result = 0 or else Result = ENOMEM);
839
840       if Result = 0 then
841          Result := pthread_cond_init (Self_ID.Common.LL.CV'Access,
842            Cond_Attr'Access);
843          pragma Assert (Result = 0 or else Result = ENOMEM);
844       end if;
845
846       if Result = 0 then
847          Succeeded := True;
848       else
849          if not Single_Lock then
850             Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access);
851             pragma Assert (Result = 0);
852          end if;
853
854          Succeeded := False;
855       end if;
856
857       Result := pthread_condattr_destroy (Cond_Attr'Access);
858       pragma Assert (Result = 0);
859    end Initialize_TCB;
860
861    -----------------
862    -- Create_Task --
863    -----------------
864
865    procedure Create_Task
866      (T          : Task_Id;
867       Wrapper    : System.Address;
868       Stack_Size : System.Parameters.Size_Type;
869       Priority   : System.Any_Priority;
870       Succeeded  : out Boolean)
871    is
872       Attributes          : aliased pthread_attr_t;
873       Adjusted_Stack_Size : Interfaces.C.size_t;
874       Result              : Interfaces.C.int;
875
876       use System.Task_Info;
877
878    begin
879       Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size);
880
881       if Stack_Base_Available then
882
883          --  If Stack Checking is supported then allocate 2 additional pages:
884          --
885          --  In the worst case, stack is allocated at something like
886          --  N * Get_Page_Size - epsilon, we need to add the size for 2 pages
887          --  to be sure the effective stack size is greater than what
888          --  has been asked.
889
890          Adjusted_Stack_Size := Adjusted_Stack_Size + 2 * Get_Page_Size;
891       end if;
892
893       Result := pthread_attr_init (Attributes'Access);
894       pragma Assert (Result = 0 or else Result = ENOMEM);
895
896       if Result /= 0 then
897          Succeeded := False;
898          return;
899       end if;
900
901       Result := pthread_attr_setdetachstate
902         (Attributes'Access, PTHREAD_CREATE_DETACHED);
903       pragma Assert (Result = 0);
904
905       Result := pthread_attr_setstacksize
906         (Attributes'Access, Adjusted_Stack_Size);
907       pragma Assert (Result = 0);
908
909       if T.Common.Task_Info /= Default_Scope then
910
911          --  We are assuming that Scope_Type has the same values than the
912          --  corresponding C macros
913
914          Result := pthread_attr_setscope
915            (Attributes'Access, Task_Info_Type'Pos (T.Common.Task_Info));
916          pragma Assert (Result = 0);
917       end if;
918
919       --  Since the initial signal mask of a thread is inherited from the
920       --  creator, and the Environment task has all its signals masked, we
921       --  do not need to manipulate caller's signal mask at this point.
922       --  All tasks in RTS will have All_Tasks_Mask initially.
923
924       Result := pthread_create
925         (T.Common.LL.Thread'Access,
926          Attributes'Access,
927          Thread_Body_Access (Wrapper),
928          To_Address (T));
929       pragma Assert (Result = 0 or else Result = EAGAIN);
930
931       Succeeded := Result = 0;
932
933       Result := pthread_attr_destroy (Attributes'Access);
934       pragma Assert (Result = 0);
935
936       Set_Priority (T, Priority);
937    end Create_Task;
938
939    ------------------
940    -- Finalize_TCB --
941    ------------------
942
943    procedure Finalize_TCB (T : Task_Id) is
944       Result : Interfaces.C.int;
945       Tmp    : Task_Id := T;
946       Is_Self : constant Boolean := T = Self;
947
948       procedure Free is new
949         Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
950
951    begin
952       if not Single_Lock then
953          Result := pthread_mutex_destroy (T.Common.LL.L'Access);
954          pragma Assert (Result = 0);
955       end if;
956
957       Result := pthread_cond_destroy (T.Common.LL.CV'Access);
958       pragma Assert (Result = 0);
959
960       if T.Known_Tasks_Index /= -1 then
961          Known_Tasks (T.Known_Tasks_Index) := null;
962       end if;
963
964       Free (Tmp);
965
966       if Is_Self then
967          Result := st_setspecific (ATCB_Key, System.Null_Address);
968          pragma Assert (Result = 0);
969       end if;
970
971    end Finalize_TCB;
972
973    ---------------
974    -- Exit_Task --
975    ---------------
976
977    procedure Exit_Task is
978    begin
979       Specific.Set (null);
980    end Exit_Task;
981
982    ----------------
983    -- Abort_Task --
984    ----------------
985
986    procedure Abort_Task (T : Task_Id) is
987       Result : Interfaces.C.int;
988    begin
989       Result := pthread_kill (T.Common.LL.Thread,
990          Signal (System.Interrupt_Management.Abort_Task_Interrupt));
991       pragma Assert (Result = 0);
992    end Abort_Task;
993
994    ----------------
995    -- Initialize --
996    ----------------
997
998    procedure Initialize (S : in out Suspension_Object) is
999       Mutex_Attr : aliased pthread_mutexattr_t;
1000       Cond_Attr  : aliased pthread_condattr_t;
1001       Result     : Interfaces.C.int;
1002
1003    begin
1004       --  Initialize internal state. It is always initialized to False (ARM
1005       --  D.10 par. 6).
1006
1007       S.State := False;
1008       S.Waiting := False;
1009
1010       --  Initialize internal mutex
1011
1012       Result := pthread_mutexattr_init (Mutex_Attr'Access);
1013       pragma Assert (Result = 0 or else Result = ENOMEM);
1014
1015       if Result = ENOMEM then
1016          raise Storage_Error;
1017       end if;
1018
1019       Result := pthread_mutex_init (S.L'Access, Mutex_Attr'Access);
1020       pragma Assert (Result = 0 or else Result = ENOMEM);
1021
1022       if Result = ENOMEM then
1023          Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
1024          pragma Assert (Result = 0);
1025
1026          raise Storage_Error;
1027       end if;
1028
1029       Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
1030       pragma Assert (Result = 0);
1031
1032       --  Initialize internal condition variable
1033
1034       Result := pthread_condattr_init (Cond_Attr'Access);
1035       pragma Assert (Result = 0 or else Result = ENOMEM);
1036
1037       if Result /= 0 then
1038          Result := pthread_mutex_destroy (S.L'Access);
1039          pragma Assert (Result = 0);
1040
1041          if Result = ENOMEM then
1042             raise Storage_Error;
1043          end if;
1044       end if;
1045
1046       Result := pthread_cond_init (S.CV'Access, Cond_Attr'Access);
1047       pragma Assert (Result = 0 or else Result = ENOMEM);
1048
1049       if Result /= 0 then
1050          Result := pthread_mutex_destroy (S.L'Access);
1051          pragma Assert (Result = 0);
1052
1053          if Result = ENOMEM then
1054             Result := pthread_condattr_destroy (Cond_Attr'Access);
1055             pragma Assert (Result = 0);
1056
1057             raise Storage_Error;
1058          end if;
1059       end if;
1060
1061       Result := pthread_condattr_destroy (Cond_Attr'Access);
1062       pragma Assert (Result = 0);
1063    end Initialize;
1064
1065    --------------
1066    -- Finalize --
1067    --------------
1068
1069    procedure Finalize (S : in out Suspension_Object) is
1070       Result  : Interfaces.C.int;
1071    begin
1072       --  Destroy internal mutex
1073
1074       Result := pthread_mutex_destroy (S.L'Access);
1075       pragma Assert (Result = 0);
1076
1077       --  Destroy internal condition variable
1078
1079       Result := pthread_cond_destroy (S.CV'Access);
1080       pragma Assert (Result = 0);
1081    end Finalize;
1082
1083    -------------------
1084    -- Current_State --
1085    -------------------
1086
1087    function Current_State (S : Suspension_Object) return Boolean is
1088    begin
1089       --  We do not want to use lock on this read operation. State is marked
1090       --  as Atomic so that we ensure that the value retrieved is correct.
1091
1092       return S.State;
1093    end Current_State;
1094
1095    ---------------
1096    -- Set_False --
1097    ---------------
1098
1099    procedure Set_False (S : in out Suspension_Object) is
1100       Result  : Interfaces.C.int;
1101    begin
1102       SSL.Abort_Defer.all;
1103
1104       Result := pthread_mutex_lock (S.L'Access);
1105       pragma Assert (Result = 0);
1106
1107       S.State := False;
1108
1109       Result := pthread_mutex_unlock (S.L'Access);
1110       pragma Assert (Result = 0);
1111
1112       SSL.Abort_Undefer.all;
1113    end Set_False;
1114
1115    --------------
1116    -- Set_True --
1117    --------------
1118
1119    procedure Set_True (S : in out Suspension_Object) is
1120       Result : Interfaces.C.int;
1121    begin
1122       SSL.Abort_Defer.all;
1123
1124       Result := pthread_mutex_lock (S.L'Access);
1125       pragma Assert (Result = 0);
1126
1127       --  If there is already a task waiting on this suspension object then
1128       --  we resume it, leaving the state of the suspension object to False,
1129       --  as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1130       --  the state to True.
1131
1132       if S.Waiting then
1133          S.Waiting := False;
1134          S.State := False;
1135
1136          Result := pthread_cond_signal (S.CV'Access);
1137          pragma Assert (Result = 0);
1138       else
1139          S.State := True;
1140       end if;
1141
1142       Result := pthread_mutex_unlock (S.L'Access);
1143       pragma Assert (Result = 0);
1144
1145       SSL.Abort_Undefer.all;
1146    end Set_True;
1147
1148    ------------------------
1149    -- Suspend_Until_True --
1150    ------------------------
1151
1152    procedure Suspend_Until_True (S : in out Suspension_Object) is
1153       Result : Interfaces.C.int;
1154    begin
1155       SSL.Abort_Defer.all;
1156
1157       Result := pthread_mutex_lock (S.L'Access);
1158       pragma Assert (Result = 0);
1159
1160       if S.Waiting then
1161          --  Program_Error must be raised upon calling Suspend_Until_True
1162          --  if another task is already waiting on that suspension object
1163          --  (ARM D.10 par. 10).
1164
1165          Result := pthread_mutex_unlock (S.L'Access);
1166          pragma Assert (Result = 0);
1167
1168          SSL.Abort_Undefer.all;
1169
1170          raise Program_Error;
1171       else
1172          --  Suspend the task if the state is False. Otherwise, the task
1173          --  continues its execution, and the state of the suspension object
1174          --  is set to False (ARM D.10 par. 9).
1175
1176          if S.State then
1177             S.State := False;
1178          else
1179             S.Waiting := True;
1180             Result := pthread_cond_wait (S.CV'Access, S.L'Access);
1181          end if;
1182
1183          Result := pthread_mutex_unlock (S.L'Access);
1184          pragma Assert (Result = 0);
1185
1186          SSL.Abort_Undefer.all;
1187       end if;
1188    end Suspend_Until_True;
1189
1190    ----------------
1191    -- Check_Exit --
1192    ----------------
1193
1194    --  Dummy versions
1195
1196    function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1197       pragma Unreferenced (Self_ID);
1198    begin
1199       return True;
1200    end Check_Exit;
1201
1202    --------------------
1203    -- Check_No_Locks --
1204    --------------------
1205
1206    function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1207       pragma Unreferenced (Self_ID);
1208    begin
1209       return True;
1210    end Check_No_Locks;
1211
1212    ----------------------
1213    -- Environment_Task --
1214    ----------------------
1215
1216    function Environment_Task return Task_Id is
1217    begin
1218       return Environment_Task_Id;
1219    end Environment_Task;
1220
1221    --------------
1222    -- Lock_RTS --
1223    --------------
1224
1225    procedure Lock_RTS is
1226    begin
1227       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1228    end Lock_RTS;
1229
1230    ----------------
1231    -- Unlock_RTS --
1232    ----------------
1233
1234    procedure Unlock_RTS is
1235    begin
1236       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1237    end Unlock_RTS;
1238
1239    ------------------
1240    -- Suspend_Task --
1241    ------------------
1242
1243    function Suspend_Task
1244      (T           : ST.Task_Id;
1245       Thread_Self : Thread_Id) return Boolean
1246    is
1247       pragma Unreferenced (T);
1248       pragma Unreferenced (Thread_Self);
1249    begin
1250       return False;
1251    end Suspend_Task;
1252
1253    -----------------
1254    -- Resume_Task --
1255    -----------------
1256
1257    function Resume_Task
1258      (T           : ST.Task_Id;
1259       Thread_Self : Thread_Id) return Boolean
1260    is
1261       pragma Unreferenced (T);
1262       pragma Unreferenced (Thread_Self);
1263    begin
1264       return False;
1265    end Resume_Task;
1266
1267    ----------------
1268    -- Initialize --
1269    ----------------
1270
1271    procedure Initialize (Environment_Task : Task_Id) is
1272       act     : aliased struct_sigaction;
1273       old_act : aliased struct_sigaction;
1274       Tmp_Set : aliased sigset_t;
1275       Result  : Interfaces.C.int;
1276
1277       function State
1278         (Int  : System.Interrupt_Management.Interrupt_ID) return Character;
1279       pragma Import (C, State, "__gnat_get_interrupt_state");
1280       --  Get interrupt state.  Defined in a-init.c
1281       --  The input argument is the interrupt number,
1282       --  and the result is one of the following:
1283
1284       Default : constant Character := 's';
1285       --    'n'   this interrupt not set by any Interrupt_State pragma
1286       --    'u'   Interrupt_State pragma set state to User
1287       --    'r'   Interrupt_State pragma set state to Runtime
1288       --    's'   Interrupt_State pragma set state to System (use "default"
1289       --           system handler)
1290
1291    begin
1292       Environment_Task_Id := Environment_Task;
1293
1294       Interrupt_Management.Initialize;
1295
1296       --  Prepare the set of signals that should unblocked in all tasks
1297
1298       Result := sigemptyset (Unblocked_Signal_Mask'Access);
1299       pragma Assert (Result = 0);
1300
1301       for J in Interrupt_Management.Interrupt_ID loop
1302          if System.Interrupt_Management.Keep_Unmasked (J) then
1303             Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1304             pragma Assert (Result = 0);
1305          end if;
1306       end loop;
1307
1308       --  Initialize the lock used to synchronize chain of all ATCBs
1309
1310       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1311
1312       Specific.Initialize (Environment_Task);
1313
1314       Enter_Task (Environment_Task);
1315
1316       --  Install the abort-signal handler
1317
1318       if State (System.Interrupt_Management.Abort_Task_Interrupt)
1319         /= Default
1320       then
1321          act.sa_flags := 0;
1322          act.sa_handler := Abort_Handler'Address;
1323
1324          Result := sigemptyset (Tmp_Set'Access);
1325          pragma Assert (Result = 0);
1326          act.sa_mask := Tmp_Set;
1327
1328          Result :=
1329            sigaction
1330            (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
1331             act'Unchecked_Access,
1332             old_act'Unchecked_Access);
1333
1334          pragma Assert (Result = 0);
1335       end if;
1336    end Initialize;
1337
1338 end System.Task_Primitives.Operations;