OSDN Git Service

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