OSDN Git Service

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