OSDN Git Service

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