OSDN Git Service

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