OSDN Git Service

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