OSDN Git Service

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