OSDN Git Service

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