OSDN Git Service

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