OSDN Git Service

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