OSDN Git Service

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