OSDN Git Service

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