OSDN Git Service

a47e4b1a0a0b513fc90f2b664d935fa7ed435cfc
[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       Adjusted_Stack_Size :=
822          Interfaces.C.size_t (Stack_Size + Alternate_Stack_Size);
823
824       Result := pthread_attr_init (Attributes'Access);
825       pragma Assert (Result = 0 or else Result = ENOMEM);
826
827       if Result /= 0 then
828          Succeeded := False;
829          return;
830       end if;
831
832       Result :=
833         pthread_attr_setstacksize
834           (Attributes'Access, Adjusted_Stack_Size);
835       pragma Assert (Result = 0);
836
837       Result :=
838         pthread_attr_setdetachstate
839           (Attributes'Access, PTHREAD_CREATE_DETACHED);
840       pragma Assert (Result = 0);
841
842       --  Set the required attributes for the creation of the thread
843
844       --  Note: Previously, we called pthread_setaffinity_np (after thread
845       --  creation but before thread activation) to set the affinity but it was
846       --  not behaving as expected. Setting the required attributes for the
847       --  creation of the thread works correctly and it is more appropriate.
848
849       --  Do nothing if required support not provided by the operating system
850
851       if pthread_attr_setaffinity_np'Address = System.Null_Address then
852          null;
853
854       --  Support is available
855
856       elsif T.Common.Base_CPU /= System.Multiprocessors.Not_A_Specific_CPU then
857          declare
858             CPU_Set : aliased cpu_set_t := (bits => (others => False));
859          begin
860             CPU_Set.bits (Integer (T.Common.Base_CPU)) := True;
861             Result :=
862               pthread_attr_setaffinity_np
863                 (Attributes'Access,
864                  CPU_SETSIZE / 8,
865                  CPU_Set'Access);
866             pragma Assert (Result = 0);
867          end;
868
869       --  Handle Task_Info
870
871       elsif T.Common.Task_Info /= null
872         and then T.Common.Task_Info.CPU_Affinity /= Task_Info.Any_CPU
873       then
874          Result :=
875            pthread_attr_setaffinity_np
876              (Attributes'Access,
877               CPU_SETSIZE / 8,
878               T.Common.Task_Info.CPU_Affinity'Access);
879          pragma Assert (Result = 0);
880
881       --  Handle dispatching domains
882
883       elsif T.Common.Domain /= null then
884          declare
885             CPU_Set : aliased cpu_set_t := (bits => (others => False));
886
887          begin
888             --  Set the affinity to all the processors belonging to the
889             --  dispatching domain.
890
891             for Proc in T.Common.Domain'Range loop
892                CPU_Set.bits (Integer (Proc)) := T.Common.Domain (Proc);
893             end loop;
894
895             Result :=
896               pthread_attr_setaffinity_np
897                 (Attributes'Access,
898                  CPU_SETSIZE / 8,
899                  CPU_Set'Access);
900             pragma Assert (Result = 0);
901          end;
902       end if;
903
904       --  Since the initial signal mask of a thread is inherited from the
905       --  creator, and the Environment task has all its signals masked, we
906       --  do not need to manipulate caller's signal mask at this point.
907       --  All tasks in RTS will have All_Tasks_Mask initially.
908
909       Result := pthread_create
910         (T.Common.LL.Thread'Access,
911          Attributes'Access,
912          Thread_Body_Access (Wrapper),
913          To_Address (T));
914       pragma Assert
915         (Result = 0 or else Result = EAGAIN or else Result = ENOMEM);
916
917       if Result /= 0 then
918          Succeeded := False;
919          Result := pthread_attr_destroy (Attributes'Access);
920          pragma Assert (Result = 0);
921          return;
922       end if;
923
924       Succeeded := True;
925
926       Result := pthread_attr_destroy (Attributes'Access);
927       pragma Assert (Result = 0);
928
929       Set_Priority (T, Priority);
930    end Create_Task;
931
932    ------------------
933    -- Finalize_TCB --
934    ------------------
935
936    procedure Finalize_TCB (T : Task_Id) is
937       Result  : Interfaces.C.int;
938       Tmp     : Task_Id := T;
939       Is_Self : constant Boolean := T = Self;
940
941       procedure Free is new
942         Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
943
944    begin
945       if not Single_Lock then
946          Result := pthread_mutex_destroy (T.Common.LL.L'Access);
947          pragma Assert (Result = 0);
948       end if;
949
950       Result := pthread_cond_destroy (T.Common.LL.CV'Access);
951       pragma Assert (Result = 0);
952
953       if T.Known_Tasks_Index /= -1 then
954          Known_Tasks (T.Known_Tasks_Index) := null;
955       end if;
956       SC.Invalidate_Stack_Cache (T.Common.Compiler_Data.Pri_Stack_Info'Access);
957       Free (Tmp);
958
959       if Is_Self then
960          Specific.Set (null);
961       end if;
962    end Finalize_TCB;
963
964    ---------------
965    -- Exit_Task --
966    ---------------
967
968    procedure Exit_Task is
969    begin
970       Specific.Set (null);
971    end Exit_Task;
972
973    ----------------
974    -- Abort_Task --
975    ----------------
976
977    procedure Abort_Task (T : Task_Id) is
978       Result : Interfaces.C.int;
979    begin
980       if Abort_Handler_Installed then
981          Result :=
982            pthread_kill
983              (T.Common.LL.Thread,
984               Signal (System.Interrupt_Management.Abort_Task_Interrupt));
985          pragma Assert (Result = 0);
986       end if;
987    end Abort_Task;
988
989    ----------------
990    -- Initialize --
991    ----------------
992
993    procedure Initialize (S : in out Suspension_Object) is
994       Result : Interfaces.C.int;
995
996    begin
997       --  Initialize internal state (always to False (RM D.10(6)))
998
999       S.State := False;
1000       S.Waiting := False;
1001
1002       --  Initialize internal mutex
1003
1004       Result := pthread_mutex_init (S.L'Access, Mutex_Attr'Access);
1005
1006       pragma Assert (Result = 0 or else Result = ENOMEM);
1007
1008       if Result = ENOMEM then
1009          raise Storage_Error;
1010       end if;
1011
1012       --  Initialize internal condition variable
1013
1014       Result := pthread_cond_init (S.CV'Access, Cond_Attr'Access);
1015
1016       pragma Assert (Result = 0 or else Result = ENOMEM);
1017
1018       if Result /= 0 then
1019          Result := pthread_mutex_destroy (S.L'Access);
1020          pragma Assert (Result = 0);
1021
1022          if Result = ENOMEM then
1023             raise Storage_Error;
1024          end if;
1025       end if;
1026    end Initialize;
1027
1028    --------------
1029    -- Finalize --
1030    --------------
1031
1032    procedure Finalize (S : in out Suspension_Object) is
1033       Result : Interfaces.C.int;
1034
1035    begin
1036       --  Destroy internal mutex
1037
1038       Result := pthread_mutex_destroy (S.L'Access);
1039       pragma Assert (Result = 0);
1040
1041       --  Destroy internal condition variable
1042
1043       Result := pthread_cond_destroy (S.CV'Access);
1044       pragma Assert (Result = 0);
1045    end Finalize;
1046
1047    -------------------
1048    -- Current_State --
1049    -------------------
1050
1051    function Current_State (S : Suspension_Object) return Boolean is
1052    begin
1053       --  We do not want to use lock on this read operation. State is marked
1054       --  as Atomic so that we ensure that the value retrieved is correct.
1055
1056       return S.State;
1057    end Current_State;
1058
1059    ---------------
1060    -- Set_False --
1061    ---------------
1062
1063    procedure Set_False (S : in out Suspension_Object) is
1064       Result : Interfaces.C.int;
1065
1066    begin
1067       SSL.Abort_Defer.all;
1068
1069       Result := pthread_mutex_lock (S.L'Access);
1070       pragma Assert (Result = 0);
1071
1072       S.State := False;
1073
1074       Result := pthread_mutex_unlock (S.L'Access);
1075       pragma Assert (Result = 0);
1076
1077       SSL.Abort_Undefer.all;
1078    end Set_False;
1079
1080    --------------
1081    -- Set_True --
1082    --------------
1083
1084    procedure Set_True (S : in out Suspension_Object) is
1085       Result : Interfaces.C.int;
1086
1087    begin
1088       SSL.Abort_Defer.all;
1089
1090       Result := pthread_mutex_lock (S.L'Access);
1091       pragma Assert (Result = 0);
1092
1093       --  If there is already a task waiting on this suspension object then
1094       --  we resume it, leaving the state of the suspension object to False,
1095       --  as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1096       --  the state to True.
1097
1098       if S.Waiting then
1099          S.Waiting := False;
1100          S.State := False;
1101
1102          Result := pthread_cond_signal (S.CV'Access);
1103          pragma Assert (Result = 0);
1104
1105       else
1106          S.State := True;
1107       end if;
1108
1109       Result := pthread_mutex_unlock (S.L'Access);
1110       pragma Assert (Result = 0);
1111
1112       SSL.Abort_Undefer.all;
1113    end Set_True;
1114
1115    ------------------------
1116    -- Suspend_Until_True --
1117    ------------------------
1118
1119    procedure Suspend_Until_True (S : in out Suspension_Object) is
1120       Result : Interfaces.C.int;
1121
1122    begin
1123       SSL.Abort_Defer.all;
1124
1125       Result := pthread_mutex_lock (S.L'Access);
1126       pragma Assert (Result = 0);
1127
1128       if S.Waiting then
1129
1130          --  Program_Error must be raised upon calling Suspend_Until_True
1131          --  if another task is already waiting on that suspension object
1132          --  (RM D.10(10)).
1133
1134          Result := pthread_mutex_unlock (S.L'Access);
1135          pragma Assert (Result = 0);
1136
1137          SSL.Abort_Undefer.all;
1138
1139          raise Program_Error;
1140
1141       else
1142          --  Suspend the task if the state is False. Otherwise, the task
1143          --  continues its execution, and the state of the suspension object
1144          --  is set to False (ARM D.10 par. 9).
1145
1146          if S.State then
1147             S.State := False;
1148          else
1149             S.Waiting := True;
1150
1151             loop
1152                --  Loop in case pthread_cond_wait returns earlier than expected
1153                --  (e.g. in case of EINTR caused by a signal). This should not
1154                --  happen with the current Linux implementation of pthread, but
1155                --  POSIX does not guarantee it so this may change in future.
1156
1157                Result := pthread_cond_wait (S.CV'Access, S.L'Access);
1158                pragma Assert (Result = 0 or else Result = EINTR);
1159
1160                exit when not S.Waiting;
1161             end loop;
1162          end if;
1163
1164          Result := pthread_mutex_unlock (S.L'Access);
1165          pragma Assert (Result = 0);
1166
1167          SSL.Abort_Undefer.all;
1168       end if;
1169    end Suspend_Until_True;
1170
1171    ----------------
1172    -- Check_Exit --
1173    ----------------
1174
1175    --  Dummy version
1176
1177    function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1178       pragma Unreferenced (Self_ID);
1179    begin
1180       return True;
1181    end Check_Exit;
1182
1183    --------------------
1184    -- Check_No_Locks --
1185    --------------------
1186
1187    function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1188       pragma Unreferenced (Self_ID);
1189    begin
1190       return True;
1191    end Check_No_Locks;
1192
1193    ----------------------
1194    -- Environment_Task --
1195    ----------------------
1196
1197    function Environment_Task return Task_Id is
1198    begin
1199       return Environment_Task_Id;
1200    end Environment_Task;
1201
1202    ------------------
1203    -- Suspend_Task --
1204    ------------------
1205
1206    function Suspend_Task
1207      (T           : ST.Task_Id;
1208       Thread_Self : Thread_Id) return Boolean
1209    is
1210    begin
1211       if T.Common.LL.Thread /= Thread_Self then
1212          return pthread_kill (T.Common.LL.Thread, SIGSTOP) = 0;
1213       else
1214          return True;
1215       end if;
1216    end Suspend_Task;
1217
1218    -----------------
1219    -- Resume_Task --
1220    -----------------
1221
1222    function Resume_Task
1223      (T           : ST.Task_Id;
1224       Thread_Self : Thread_Id) return Boolean
1225    is
1226    begin
1227       if T.Common.LL.Thread /= Thread_Self then
1228          return pthread_kill (T.Common.LL.Thread, SIGCONT) = 0;
1229       else
1230          return True;
1231       end if;
1232    end Resume_Task;
1233
1234    --------------------
1235    -- Stop_All_Tasks --
1236    --------------------
1237
1238    procedure Stop_All_Tasks is
1239    begin
1240       null;
1241    end Stop_All_Tasks;
1242
1243    ---------------
1244    -- Stop_Task --
1245    ---------------
1246
1247    function Stop_Task (T : ST.Task_Id) return Boolean is
1248       pragma Unreferenced (T);
1249    begin
1250       return False;
1251    end Stop_Task;
1252
1253    -------------------
1254    -- Continue_Task --
1255    -------------------
1256
1257    function Continue_Task (T : ST.Task_Id) return Boolean is
1258       pragma Unreferenced (T);
1259    begin
1260       return False;
1261    end Continue_Task;
1262
1263    ----------------
1264    -- Initialize --
1265    ----------------
1266
1267    procedure Initialize (Environment_Task : Task_Id) is
1268       act     : aliased struct_sigaction;
1269       old_act : aliased struct_sigaction;
1270       Tmp_Set : aliased sigset_t;
1271       Result  : Interfaces.C.int;
1272       --  Whether to use an alternate signal stack for stack overflows
1273
1274       function State
1275         (Int : System.Interrupt_Management.Interrupt_ID) return Character;
1276       pragma Import (C, State, "__gnat_get_interrupt_state");
1277       --  Get interrupt state.  Defined in a-init.c
1278       --  The input argument is the interrupt number,
1279       --  and the result is one of the following:
1280
1281       Default : constant Character := 's';
1282       --    'n'   this interrupt not set by any Interrupt_State pragma
1283       --    'u'   Interrupt_State pragma set state to User
1284       --    'r'   Interrupt_State pragma set state to Runtime
1285       --    's'   Interrupt_State pragma set state to System (use "default"
1286       --           system handler)
1287
1288       use type System.Multiprocessors.CPU_Range;
1289
1290    begin
1291       Environment_Task_Id := Environment_Task;
1292
1293       Interrupt_Management.Initialize;
1294
1295       --  Prepare the set of signals that should be unblocked in all tasks
1296
1297       Result := sigemptyset (Unblocked_Signal_Mask'Access);
1298       pragma Assert (Result = 0);
1299
1300       for J in Interrupt_Management.Interrupt_ID loop
1301          if System.Interrupt_Management.Keep_Unmasked (J) then
1302             Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1303             pragma Assert (Result = 0);
1304          end if;
1305       end loop;
1306
1307       Result := pthread_mutexattr_init (Mutex_Attr'Access);
1308       pragma Assert (Result = 0);
1309
1310       Result := pthread_condattr_init (Cond_Attr'Access);
1311       pragma Assert (Result = 0);
1312
1313       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1314
1315       --  Initialize the global RTS lock
1316
1317       Specific.Initialize (Environment_Task);
1318
1319       if Use_Alternate_Stack then
1320          Environment_Task.Common.Task_Alternate_Stack :=
1321            Alternate_Stack'Address;
1322       end if;
1323
1324       --  Make environment task known here because it doesn't go through
1325       --  Activate_Tasks, which does it for all other tasks.
1326
1327       Known_Tasks (Known_Tasks'First) := Environment_Task;
1328       Environment_Task.Known_Tasks_Index := Known_Tasks'First;
1329
1330       Enter_Task (Environment_Task);
1331
1332       if State
1333           (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
1334       then
1335          act.sa_flags := 0;
1336          act.sa_handler := Abort_Handler'Address;
1337
1338          Result := sigemptyset (Tmp_Set'Access);
1339          pragma Assert (Result = 0);
1340          act.sa_mask := Tmp_Set;
1341
1342          Result :=
1343            sigaction
1344            (Signal (Interrupt_Management.Abort_Task_Interrupt),
1345             act'Unchecked_Access,
1346             old_act'Unchecked_Access);
1347          pragma Assert (Result = 0);
1348          Abort_Handler_Installed := True;
1349       end if;
1350
1351       --  pragma CPU and dispatching domains for the environment task
1352
1353       Set_Task_Affinity (Environment_Task);
1354    end Initialize;
1355
1356    -----------------------
1357    -- Set_Task_Affinity --
1358    -----------------------
1359
1360    procedure Set_Task_Affinity (T : ST.Task_Id) is
1361       use type System.Multiprocessors.CPU_Range;
1362
1363    begin
1364       --  Do nothing if there is no support for setting affinities or the
1365       --  underlying thread has not yet been created. If the thread has not
1366       --  yet been created then the proper affinity will be set during its
1367       --  creation.
1368
1369       if pthread_setaffinity_np'Address /= System.Null_Address
1370         and then T.Common.LL.Thread /= Null_Thread_Id
1371       then
1372          declare
1373             type cpu_set_t_ptr is access all cpu_set_t;
1374
1375             CPU_Set : cpu_set_t_ptr := null;
1376             Result  : Interfaces.C.int;
1377
1378          begin
1379             --  We look at the specific CPU (Base_CPU) first, then at the
1380             --  Task_Info field, and finally at the assigned dispatching
1381             --  domain, if any.
1382
1383             if T.Common.Base_CPU /= Multiprocessors.Not_A_Specific_CPU then
1384
1385                --  Set the affinity to an unique CPU
1386
1387                CPU_Set := new cpu_set_t'(bits => (others => False));
1388                CPU_Set.bits (Integer (T.Common.Base_CPU)) := True;
1389
1390             --  Handle Task_Info
1391
1392             elsif T.Common.Task_Info /= null
1393               and then T.Common.Task_Info.CPU_Affinity /= Task_Info.Any_CPU
1394             then
1395                CPU_Set := T.Common.Task_Info.CPU_Affinity'Access;
1396
1397             --  Handle dispatching domains
1398
1399             elsif T.Common.Domain /= null and then
1400               (T.Common.Domain /= ST.System_Domain
1401                 or else T.Common.Domain.all /=
1402                           (Multiprocessors.CPU'First ..
1403                            Multiprocessors.Number_Of_CPUs => True))
1404             then
1405                --  Set the affinity to all the processors belonging to the
1406                --  dispatching domain. To avoid changing CPU affinities when
1407                --  not needed, we set the affinity only when assigning to a
1408                --  domain other than the default one, or when the default one
1409                --  has been modified.
1410
1411                CPU_Set := new cpu_set_t'(bits => (others => False));
1412
1413                for Proc in T.Common.Domain'Range loop
1414                   CPU_Set.bits (Integer (Proc)) := T.Common.Domain (Proc);
1415                end loop;
1416             end if;
1417
1418             --  We set the new affinity if needed. Otherwise, the new task
1419             --  will inherit its creator's CPU affinity mask (according to
1420             --  the documentation of pthread_setaffinity_np), which is
1421             --  consistent with Ada's required semantics.
1422
1423             if CPU_Set /= null then
1424                Result :=
1425                  pthread_setaffinity_np
1426                    (T.Common.LL.Thread, CPU_SETSIZE / 8, CPU_Set);
1427                pragma Assert (Result = 0);
1428             end if;
1429          end;
1430       end if;
1431    end Set_Task_Affinity;
1432
1433 end System.Task_Primitives.Operations;