OSDN Git Service

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