OSDN Git Service

ce4195b8029dbf937df3eb04f2689f6cf7760d76
[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       Specific.Set (Self_ID);
711
712       Lock_RTS;
713
714       for J in Known_Tasks'Range loop
715          if Known_Tasks (J) = null then
716             Known_Tasks (J) := Self_ID;
717             Self_ID.Known_Tasks_Index := J;
718             exit;
719          end if;
720       end loop;
721
722       Unlock_RTS;
723    end Enter_Task;
724
725    --------------
726    -- New_ATCB --
727    --------------
728
729    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
730    begin
731       return new Ada_Task_Control_Block (Entry_Num);
732    end New_ATCB;
733
734    -------------------
735    -- Is_Valid_Task --
736    -------------------
737
738    function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
739
740    -----------------------------
741    -- Register_Foreign_Thread --
742    -----------------------------
743
744    function Register_Foreign_Thread return Task_Id is
745    begin
746       if Is_Valid_Task then
747          return Self;
748       else
749          return Register_Foreign_Thread (pthread_self);
750       end if;
751    end Register_Foreign_Thread;
752
753    --------------------
754    -- Initialize_TCB --
755    --------------------
756
757    procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
758       Mutex_Attr : aliased pthread_mutexattr_t;
759       Result     : Interfaces.C.int;
760       Cond_Attr  : aliased pthread_condattr_t;
761
762    begin
763       if not Single_Lock then
764          Result := pthread_mutexattr_init (Mutex_Attr'Access);
765          pragma Assert (Result = 0 or else Result = ENOMEM);
766
767          if Result = 0 then
768             Result :=
769               pthread_mutex_init
770                 (Self_ID.Common.LL.L'Access, Mutex_Attr'Access);
771             pragma Assert (Result = 0 or else Result = ENOMEM);
772          end if;
773
774          if Result /= 0 then
775             Succeeded := False;
776             return;
777          end if;
778
779          Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
780          pragma Assert (Result = 0);
781       end if;
782
783       Result := pthread_condattr_init (Cond_Attr'Access);
784       pragma Assert (Result = 0 or else Result = ENOMEM);
785
786       if Result = 0 then
787          Result :=
788            pthread_cond_init
789              (Self_ID.Common.LL.CV'Access, Cond_Attr'Access);
790          pragma Assert (Result = 0 or else Result = ENOMEM);
791       end if;
792
793       if Result = 0 then
794          Succeeded := True;
795       else
796          if not Single_Lock then
797             Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access);
798             pragma Assert (Result = 0);
799          end if;
800
801          Succeeded := False;
802       end if;
803
804       Result := pthread_condattr_destroy (Cond_Attr'Access);
805       pragma Assert (Result = 0);
806    end Initialize_TCB;
807
808    -----------------
809    -- Create_Task --
810    -----------------
811
812    procedure Create_Task
813      (T          : Task_Id;
814       Wrapper    : System.Address;
815       Stack_Size : System.Parameters.Size_Type;
816       Priority   : System.Any_Priority;
817       Succeeded  : out Boolean)
818    is
819       Attributes          : aliased pthread_attr_t;
820       Adjusted_Stack_Size : Interfaces.C.size_t;
821       Result              : Interfaces.C.int;
822       Param               : aliased System.OS_Interface.struct_sched_param;
823
824       Priority_Specific_Policy : constant Character := Get_Policy (Priority);
825       --  Upper case first character of the policy name corresponding to the
826       --  task as set by a Priority_Specific_Dispatching pragma.
827
828       use System.Task_Info;
829
830    begin
831       --  Account for the Yellow Zone (2 pages) and the guard page right above.
832       --  See Hide_Unhide_Yellow_Zone for the rationale.
833
834       Adjusted_Stack_Size :=
835         Interfaces.C.size_t (Stack_Size) + 3 * Get_Page_Size;
836
837       Result := pthread_attr_init (Attributes'Access);
838       pragma Assert (Result = 0 or else Result = ENOMEM);
839
840       if Result /= 0 then
841          Succeeded := False;
842          return;
843       end if;
844
845       Result :=
846         pthread_attr_setdetachstate
847           (Attributes'Access, PTHREAD_CREATE_DETACHED);
848       pragma Assert (Result = 0);
849
850       Result :=
851         pthread_attr_setstacksize
852           (Attributes'Access, Adjusted_Stack_Size);
853       pragma Assert (Result = 0);
854
855       Param.sched_priority :=
856         Interfaces.C.int (Underlying_Priorities (Priority));
857       Result :=
858         pthread_attr_setschedparam
859           (Attributes'Access, Param'Access);
860       pragma Assert (Result = 0);
861
862       if Dispatching_Policy = 'R'
863         or else Priority_Specific_Policy = 'R'
864         or else Time_Slice_Val > 0
865       then
866          Result :=
867            pthread_attr_setschedpolicy
868              (Attributes'Access, System.OS_Interface.SCHED_RR);
869
870       elsif Dispatching_Policy = 'F'
871         or else Priority_Specific_Policy = 'F'
872         or else Time_Slice_Val = 0
873       then
874          Result :=
875            pthread_attr_setschedpolicy
876              (Attributes'Access, System.OS_Interface.SCHED_FIFO);
877
878       else
879          Result :=
880            pthread_attr_setschedpolicy
881              (Attributes'Access, System.OS_Interface.SCHED_OTHER);
882       end if;
883
884       pragma Assert (Result = 0);
885
886       --  Set the scheduling parameters explicitly, since this is the only way
887       --  to force the OS to take e.g. the sched policy and scope attributes
888       --  into account.
889
890       Result :=
891         pthread_attr_setinheritsched
892           (Attributes'Access, PTHREAD_EXPLICIT_SCHED);
893       pragma Assert (Result = 0);
894
895       T.Common.Current_Priority := Priority;
896
897       if T.Common.Task_Info /= null then
898          case T.Common.Task_Info.Contention_Scope is
899             when System.Task_Info.Process_Scope =>
900                Result :=
901                  pthread_attr_setscope
902                    (Attributes'Access, PTHREAD_SCOPE_PROCESS);
903
904             when System.Task_Info.System_Scope =>
905                Result :=
906                  pthread_attr_setscope
907                    (Attributes'Access, PTHREAD_SCOPE_SYSTEM);
908
909             when System.Task_Info.Default_Scope =>
910                Result := 0;
911          end case;
912
913          pragma Assert (Result = 0);
914       end if;
915
916       --  Since the initial signal mask of a thread is inherited from the
917       --  creator, and the Environment task has all its signals masked, we
918       --  do not need to manipulate caller's signal mask at this point.
919       --  All tasks in RTS will have All_Tasks_Mask initially.
920
921       Result :=
922         pthread_create
923           (T.Common.LL.Thread'Access,
924            Attributes'Access,
925            Thread_Body_Access (Wrapper),
926            To_Address (T));
927       pragma Assert (Result = 0 or else Result = EAGAIN);
928
929       Succeeded := Result = 0;
930
931       Result := pthread_attr_destroy (Attributes'Access);
932       pragma Assert (Result = 0);
933
934       if Succeeded and then T.Common.Task_Info /= null then
935
936          --  ??? We're using a process-wide function to implement a task
937          --  specific characteristic.
938
939          if T.Common.Task_Info.Bind_To_Cpu_Number = 0 then
940             Result := bind_to_cpu (Curpid, 0);
941
942          elsif T.Common.Task_Info.Bind_To_Cpu_Number > 0 then
943             Result :=
944               bind_to_cpu
945                 (Curpid,
946                  Interfaces.C.unsigned_long (
947                    Interfaces.Shift_Left
948                      (Interfaces.Unsigned_64'(1),
949                       T.Common.Task_Info.Bind_To_Cpu_Number - 1)));
950             pragma Assert (Result = 0);
951          end if;
952       end if;
953    end Create_Task;
954
955    ------------------
956    -- Finalize_TCB --
957    ------------------
958
959    procedure Finalize_TCB (T : Task_Id) is
960       Result  : Interfaces.C.int;
961       Tmp     : Task_Id := T;
962       Is_Self : constant Boolean := T = Self;
963
964       procedure Free is new
965         Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
966
967    begin
968       if not Single_Lock then
969          Result := pthread_mutex_destroy (T.Common.LL.L'Access);
970          pragma Assert (Result = 0);
971       end if;
972
973       Result := pthread_cond_destroy (T.Common.LL.CV'Access);
974       pragma Assert (Result = 0);
975
976       if T.Known_Tasks_Index /= -1 then
977          Known_Tasks (T.Known_Tasks_Index) := null;
978       end if;
979
980       Free (Tmp);
981
982       if Is_Self then
983          Specific.Set (null);
984       end if;
985    end Finalize_TCB;
986
987    ---------------
988    -- Exit_Task --
989    ---------------
990
991    procedure Exit_Task is
992    begin
993       Specific.Set (null);
994       Hide_Unhide_Yellow_Zone (Hide => False);
995    end Exit_Task;
996
997    ----------------
998    -- Abort_Task --
999    ----------------
1000
1001    procedure Abort_Task (T : Task_Id) is
1002       Result : Interfaces.C.int;
1003    begin
1004       Result := pthread_kill (T.Common.LL.Thread,
1005         Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1006       pragma Assert (Result = 0);
1007    end Abort_Task;
1008
1009    ----------------
1010    -- Initialize --
1011    ----------------
1012
1013    procedure Initialize (S : in out Suspension_Object) is
1014       Mutex_Attr : aliased pthread_mutexattr_t;
1015       Cond_Attr  : aliased pthread_condattr_t;
1016       Result     : Interfaces.C.int;
1017
1018    begin
1019       --  Initialize internal state (always to False (RM D.10(6)))
1020
1021       S.State := False;
1022       S.Waiting := False;
1023
1024       --  Initialize internal mutex
1025
1026       Result := pthread_mutexattr_init (Mutex_Attr'Access);
1027       pragma Assert (Result = 0 or else Result = ENOMEM);
1028
1029       if Result = ENOMEM then
1030          raise Storage_Error;
1031       end if;
1032
1033       Result := pthread_mutex_init (S.L'Access, Mutex_Attr'Access);
1034       pragma Assert (Result = 0 or else Result = ENOMEM);
1035
1036       if Result = ENOMEM then
1037          Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
1038          raise Storage_Error;
1039       end if;
1040
1041       Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
1042       pragma Assert (Result = 0);
1043
1044       --  Initialize internal condition variable
1045
1046       Result := pthread_condattr_init (Cond_Attr'Access);
1047       pragma Assert (Result = 0 or else Result = ENOMEM);
1048
1049       Result := pthread_cond_init (S.CV'Access, Cond_Attr'Access);
1050
1051       pragma Assert (Result = 0 or else Result = ENOMEM);
1052
1053       if Result /= 0 then
1054          Result := pthread_mutex_destroy (S.L'Access);
1055          pragma Assert (Result = 0);
1056
1057          if Result = ENOMEM then
1058             raise Storage_Error;
1059          end if;
1060       end if;
1061    end Initialize;
1062
1063    --------------
1064    -- Finalize --
1065    --------------
1066
1067    procedure Finalize (S : in out Suspension_Object) is
1068       Result  : Interfaces.C.int;
1069
1070    begin
1071       --  Destroy internal mutex
1072
1073       Result := pthread_mutex_destroy (S.L'Access);
1074       pragma Assert (Result = 0);
1075
1076       --  Destroy internal condition variable
1077
1078       Result := pthread_cond_destroy (S.CV'Access);
1079       pragma Assert (Result = 0);
1080    end Finalize;
1081
1082    -------------------
1083    -- Current_State --
1084    -------------------
1085
1086    function Current_State (S : Suspension_Object) return Boolean is
1087    begin
1088       --  We do not want to use lock on this read operation. State is marked
1089       --  as Atomic so that we ensure that the value retrieved is correct.
1090
1091       return S.State;
1092    end Current_State;
1093
1094    ---------------
1095    -- Set_False --
1096    ---------------
1097
1098    procedure Set_False (S : in out Suspension_Object) is
1099       Result  : Interfaces.C.int;
1100
1101    begin
1102       SSL.Abort_Defer.all;
1103
1104       Result := pthread_mutex_lock (S.L'Access);
1105       pragma Assert (Result = 0);
1106
1107       S.State := False;
1108
1109       Result := pthread_mutex_unlock (S.L'Access);
1110       pragma Assert (Result = 0);
1111
1112       SSL.Abort_Undefer.all;
1113    end Set_False;
1114
1115    --------------
1116    -- Set_True --
1117    --------------
1118
1119    procedure Set_True (S : in out Suspension_Object) is
1120       Result : Interfaces.C.int;
1121
1122    begin
1123       SSL.Abort_Defer.all;
1124
1125       Result := pthread_mutex_lock (S.L'Access);
1126       pragma Assert (Result = 0);
1127
1128       --  If there is already a task waiting on this suspension object then we
1129       --  resume it, leaving the state of the suspension object to False, as
1130       --  specified in (RM D.10(9)). Otherwise, leave the state set to True.
1131
1132       if S.Waiting then
1133          S.Waiting := False;
1134          S.State := False;
1135
1136          Result := pthread_cond_signal (S.CV'Access);
1137          pragma Assert (Result = 0);
1138
1139       else
1140          S.State := True;
1141       end if;
1142
1143       Result := pthread_mutex_unlock (S.L'Access);
1144       pragma Assert (Result = 0);
1145
1146       SSL.Abort_Undefer.all;
1147    end Set_True;
1148
1149    ------------------------
1150    -- Suspend_Until_True --
1151    ------------------------
1152
1153    procedure Suspend_Until_True (S : in out Suspension_Object) is
1154       Result : Interfaces.C.int;
1155
1156    begin
1157       SSL.Abort_Defer.all;
1158
1159       Result := pthread_mutex_lock (S.L'Access);
1160       pragma Assert (Result = 0);
1161
1162       if S.Waiting then
1163
1164          --  Program_Error must be raised upon calling Suspend_Until_True
1165          --  if another task is already waiting on that suspension object
1166          --  (AM D.10(10)).
1167
1168          Result := pthread_mutex_unlock (S.L'Access);
1169          pragma Assert (Result = 0);
1170
1171          SSL.Abort_Undefer.all;
1172
1173          raise Program_Error;
1174
1175       else
1176          --  Suspend the task if the state is False. Otherwise, the task
1177          --  continues its execution, and the state of the suspension object
1178          --  is set to False (RM D.10(9)).
1179
1180          if S.State then
1181             S.State := False;
1182          else
1183             S.Waiting := True;
1184             Result := pthread_cond_wait (S.CV'Access, S.L'Access);
1185          end if;
1186
1187          Result := pthread_mutex_unlock (S.L'Access);
1188          pragma Assert (Result = 0);
1189
1190          SSL.Abort_Undefer.all;
1191       end if;
1192    end Suspend_Until_True;
1193
1194    ----------------
1195    -- Check_Exit --
1196    ----------------
1197
1198    --  Dummy version
1199
1200    function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1201       pragma Unreferenced (Self_ID);
1202    begin
1203       return True;
1204    end Check_Exit;
1205
1206    --------------------
1207    -- Check_No_Locks --
1208    --------------------
1209
1210    function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1211       pragma Unreferenced (Self_ID);
1212    begin
1213       return True;
1214    end Check_No_Locks;
1215
1216    ----------------------
1217    -- Environment_Task --
1218    ----------------------
1219
1220    function Environment_Task return Task_Id is
1221    begin
1222       return Environment_Task_Id;
1223    end Environment_Task;
1224
1225    --------------
1226    -- Lock_RTS --
1227    --------------
1228
1229    procedure Lock_RTS is
1230    begin
1231       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1232    end Lock_RTS;
1233
1234    ----------------
1235    -- Unlock_RTS --
1236    ----------------
1237
1238    procedure Unlock_RTS is
1239    begin
1240       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1241    end Unlock_RTS;
1242
1243    ------------------
1244    -- Suspend_Task --
1245    ------------------
1246
1247    function Suspend_Task
1248      (T           : ST.Task_Id;
1249       Thread_Self : Thread_Id) return Boolean
1250    is
1251       pragma Unreferenced (T, Thread_Self);
1252    begin
1253       return False;
1254    end Suspend_Task;
1255
1256    -----------------
1257    -- Resume_Task --
1258    -----------------
1259
1260    function Resume_Task
1261      (T           : ST.Task_Id;
1262       Thread_Self : Thread_Id) return Boolean
1263    is
1264       pragma Unreferenced (T, Thread_Self);
1265    begin
1266       return False;
1267    end Resume_Task;
1268
1269    --------------------
1270    -- Stop_All_Tasks --
1271    --------------------
1272
1273    procedure Stop_All_Tasks is
1274    begin
1275       null;
1276    end Stop_All_Tasks;
1277
1278    ---------------
1279    -- Stop_Task --
1280    ---------------
1281
1282    function Stop_Task (T : ST.Task_Id) return Boolean is
1283       pragma Unreferenced (T);
1284    begin
1285       return False;
1286    end Stop_Task;
1287
1288    -------------------
1289    -- Continue_Task --
1290    -------------------
1291
1292    function Continue_Task (T : ST.Task_Id) return Boolean is
1293       pragma Unreferenced (T);
1294    begin
1295       return False;
1296    end Continue_Task;
1297
1298    ----------------
1299    -- Initialize --
1300    ----------------
1301
1302    procedure Initialize (Environment_Task : Task_Id) is
1303       act     : aliased struct_sigaction;
1304       old_act : aliased struct_sigaction;
1305       Tmp_Set : aliased sigset_t;
1306       Result  : Interfaces.C.int;
1307
1308       function State
1309         (Int : System.Interrupt_Management.Interrupt_ID) return Character;
1310       pragma Import (C, State, "__gnat_get_interrupt_state");
1311       --  Get interrupt state. Defined in a-init.c. The input argument is
1312       --  the interrupt number, and the result is one of the following:
1313
1314       Default : constant Character := 's';
1315       --    'n'   this interrupt not set by any Interrupt_State pragma
1316       --    'u'   Interrupt_State pragma set state to User
1317       --    'r'   Interrupt_State pragma set state to Runtime
1318       --    's'   Interrupt_State pragma set state to System (use "default"
1319       --           system handler)
1320
1321    begin
1322       Environment_Task_Id := Environment_Task;
1323
1324       Interrupt_Management.Initialize;
1325
1326       --  Prepare the set of signals that should unblocked in all tasks
1327
1328       Result := sigemptyset (Unblocked_Signal_Mask'Access);
1329       pragma Assert (Result = 0);
1330
1331       for J in Interrupt_Management.Interrupt_ID loop
1332          if System.Interrupt_Management.Keep_Unmasked (J) then
1333             Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1334             pragma Assert (Result = 0);
1335          end if;
1336       end loop;
1337
1338       Curpid := getpid;
1339
1340       --  Initialize the lock used to synchronize chain of all ATCBs
1341
1342       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1343
1344       Specific.Initialize (Environment_Task);
1345
1346       Enter_Task (Environment_Task);
1347
1348       --  Install the abort-signal handler
1349
1350       if State
1351           (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
1352       then
1353          act.sa_flags := 0;
1354          act.sa_handler := Abort_Handler'Address;
1355
1356          Result := sigemptyset (Tmp_Set'Access);
1357          pragma Assert (Result = 0);
1358          act.sa_mask := Tmp_Set;
1359
1360          Result :=
1361            sigaction
1362              (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
1363               act'Unchecked_Access,
1364               old_act'Unchecked_Access);
1365          pragma Assert (Result = 0);
1366       end if;
1367    end Initialize;
1368
1369 end System.Task_Primitives.Operations;