OSDN Git Service

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