OSDN Git Service

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