OSDN Git Service

* java-tree.h (push_labeled_block, pop_labeled_block): Remove.
[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-2007, 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 2,  or (at your option) any later ver- --
14 -- sion. GNARL 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.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNARL; see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- As a special exception,  if other files  instantiate  generics from this --
23 -- unit, or you link  this unit with other files  to produce an executable, --
24 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
25 -- covered  by the  GNU  General  Public  License.  This exception does not --
26 -- however invalidate  any other reasons why  the executable file  might be --
27 -- covered by the  GNU Public License.                                      --
28 --                                                                          --
29 -- GNARL was developed by the GNARL team at Florida State University.       --
30 -- Extensive contributions were provided by Ada Core Technologies, Inc.     --
31 --                                                                          --
32 ------------------------------------------------------------------------------
33
34 --  This is a GNU/Linux (GNU/LinuxThreads) version of this package
35
36 --  This package contains all the GNULL primitives that interface directly
37 --  with the underlying OS.
38
39 pragma Polling (Off);
40 --  Turn off polling, we do not want ATC polling to take place during
41 --  tasking operations. It causes infinite loops and other problems.
42
43 with Interfaces.C;
44 --  used for int
45 --           size_t
46
47 with System.Tasking.Debug;
48 --  used for Known_Tasks
49
50 with System.Interrupt_Management;
51 --  used for Keep_Unmasked
52 --           Abort_Task_Interrupt
53 --           Interrupt_ID
54
55 with System.OS_Primitives;
56 --  used for Delay_Modes
57
58 with System.Soft_Links;
59 --  used for Abort_Defer/Undefer
60
61 --  We use System.Soft_Links instead of System.Tasking.Initialization
62 --  because the later is a higher level package that we shouldn't depend on.
63 --  For example when using the restricted run time, it is replaced by
64 --  System.Tasking.Restricted.Stages.
65
66 with System.Stack_Checking.Operations;
67 --  Used for Invalidate_Stack_Cache;
68
69 with Ada.Exceptions;
70 --  used for Raise_Exception
71 --           Raise_From_Signal_Handler
72 --           Exception_Id
73
74 with Ada.Unchecked_Conversion;
75 with Ada.Unchecked_Deallocation;
76
77 package body System.Task_Primitives.Operations is
78
79    package SSL renames System.Soft_Links;
80    package SC renames System.Stack_Checking.Operations;
81
82    use System.Tasking.Debug;
83    use System.Tasking;
84    use Interfaces.C;
85    use System.OS_Interface;
86    use System.Parameters;
87    use System.OS_Primitives;
88
89    ----------------
90    -- Local Data --
91    ----------------
92
93    --  The followings are logically constants, but need to be initialized
94    --  at run time.
95
96    Single_RTS_Lock : aliased RTS_Lock;
97    --  This is a lock to allow only one thread of control in the RTS at
98    --  a time; it is used to execute in mutual exclusion from all other tasks.
99    --  Used mainly in Single_Lock mode, but also to protect All_Tasks_List
100
101    ATCB_Key : aliased pthread_key_t;
102    --  Key used to find the Ada Task_Id associated with a thread
103
104    Environment_Task_Id : Task_Id;
105    --  A variable to hold Task_Id for the environment task
106
107    Unblocked_Signal_Mask : aliased sigset_t;
108    --  The set of signals that should be unblocked in all tasks
109
110    --  The followings are internal configuration constants needed
111
112    Next_Serial_Number : Task_Serial_Number := 100;
113    --  We start at 100 (reserve some special values for using in error checks)
114
115    Time_Slice_Val : Integer;
116    pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
117
118    Dispatching_Policy : Character;
119    pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
120
121    --  The following are effectively constants, but they need to be initialized
122    --  by calling a pthread_ function.
123
124    Mutex_Attr   : aliased pthread_mutexattr_t;
125    Cond_Attr    : aliased pthread_condattr_t;
126
127    Foreign_Task_Elaborated : aliased Boolean := True;
128    --  Used to identified fake tasks (i.e., non-Ada Threads)
129
130    --------------------
131    -- Local Packages --
132    --------------------
133
134    package Specific is
135
136       procedure Initialize (Environment_Task : Task_Id);
137       pragma Inline (Initialize);
138       --  Initialize various data needed by this package
139
140       function Is_Valid_Task return Boolean;
141       pragma Inline (Is_Valid_Task);
142       --  Does executing thread have a TCB?
143
144       procedure Set (Self_Id : Task_Id);
145       pragma Inline (Set);
146       --  Set the self id for the current task
147
148       function Self return Task_Id;
149       pragma Inline (Self);
150       --  Return a pointer to the Ada Task Control Block of the calling task
151
152    end Specific;
153
154    package body Specific is separate;
155    --  The body of this package is target specific
156
157    ---------------------------------
158    -- Support for foreign threads --
159    ---------------------------------
160
161    function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
162    --  Allocate and Initialize a new ATCB for the current Thread
163
164    function Register_Foreign_Thread
165      (Thread : Thread_Id) return Task_Id is separate;
166
167    -----------------------
168    -- Local Subprograms --
169    -----------------------
170
171    subtype unsigned_long is Interfaces.C.unsigned_long;
172
173    procedure Abort_Handler (signo : Signal);
174
175    function To_pthread_t is new Ada.Unchecked_Conversion
176      (unsigned_long, System.OS_Interface.pthread_t);
177
178    -------------------
179    -- Abort_Handler --
180    -------------------
181
182    procedure Abort_Handler (signo : Signal) is
183       pragma Unreferenced (signo);
184
185       Self_Id : constant Task_Id := Self;
186       Result  : Interfaces.C.int;
187       Old_Set : aliased sigset_t;
188
189    begin
190       if ZCX_By_Default and then GCC_ZCX_Support then
191          return;
192       end if;
193
194       if Self_Id.Deferral_Level = 0
195         and then Self_Id.Pending_ATC_Level < Self_Id.ATC_Nesting_Level
196         and then not Self_Id.Aborting
197       then
198          Self_Id.Aborting := True;
199
200          --  Make sure signals used for RTS internal purpose are unmasked
201
202          Result :=
203            pthread_sigmask
204              (SIG_UNBLOCK,
205               Unblocked_Signal_Mask'Unchecked_Access,
206               Old_Set'Unchecked_Access);
207          pragma Assert (Result = 0);
208
209          raise Standard'Abort_Signal;
210       end if;
211    end Abort_Handler;
212
213    --------------
214    -- Lock_RTS --
215    --------------
216
217    procedure Lock_RTS is
218    begin
219       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
220    end Lock_RTS;
221
222    ----------------
223    -- Unlock_RTS --
224    ----------------
225
226    procedure Unlock_RTS is
227    begin
228       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
229    end Unlock_RTS;
230
231    -----------------
232    -- Stack_Guard --
233    -----------------
234
235    --  The underlying thread system extends the memory (up to 2MB) when needed
236
237    procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
238       pragma Unreferenced (T);
239       pragma Unreferenced (On);
240    begin
241       null;
242    end Stack_Guard;
243
244    --------------------
245    -- Get_Thread_Id  --
246    --------------------
247
248    function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
249    begin
250       return T.Common.LL.Thread;
251    end Get_Thread_Id;
252
253    ----------
254    -- Self --
255    ----------
256
257    function Self return Task_Id renames Specific.Self;
258
259    ---------------------
260    -- Initialize_Lock --
261    ---------------------
262
263    --  Note: mutexes and cond_variables needed per-task basis are
264    --  initialized in Initialize_TCB and the Storage_Error is
265    --  handled. Other mutexes (such as RTS_Lock, Memory_Lock...)
266    --  used in RTS is initialized before any status change of RTS.
267    --  Therefore rasing Storage_Error in the following routines
268    --  should be able to be handled safely.
269
270    procedure Initialize_Lock
271      (Prio : System.Any_Priority;
272       L    : not null access Lock)
273    is
274       pragma Unreferenced (Prio);
275
276       Result : Interfaces.C.int;
277
278    begin
279       Result := pthread_mutex_init (L, Mutex_Attr'Access);
280
281       pragma Assert (Result = 0 or else Result = ENOMEM);
282
283       if Result = ENOMEM then
284          Ada.Exceptions.Raise_Exception (Storage_Error'Identity,
285            "Failed to allocate a lock");
286       end if;
287    end Initialize_Lock;
288
289    procedure Initialize_Lock
290      (L     : not null access RTS_Lock;
291       Level : Lock_Level)
292    is
293       pragma Unreferenced (Level);
294
295       Result : Interfaces.C.int;
296
297    begin
298       Result := pthread_mutex_init (L, Mutex_Attr'Access);
299
300       pragma Assert (Result = 0 or else Result = ENOMEM);
301
302       if Result = ENOMEM then
303          raise Storage_Error;
304       end if;
305    end Initialize_Lock;
306
307    -------------------
308    -- Finalize_Lock --
309    -------------------
310
311    procedure Finalize_Lock (L : not null access Lock) is
312       Result : Interfaces.C.int;
313    begin
314       Result := pthread_mutex_destroy (L);
315       pragma Assert (Result = 0);
316    end Finalize_Lock;
317
318    procedure Finalize_Lock (L : not null access RTS_Lock) is
319       Result : Interfaces.C.int;
320    begin
321       Result := pthread_mutex_destroy (L);
322       pragma Assert (Result = 0);
323    end Finalize_Lock;
324
325    ----------------
326    -- Write_Lock --
327    ----------------
328
329    procedure Write_Lock
330      (L                 : not null access Lock;
331       Ceiling_Violation : out Boolean)
332    is
333       Result : Interfaces.C.int;
334    begin
335       Result := pthread_mutex_lock (L);
336       Ceiling_Violation := Result = EINVAL;
337
338       --  Assume the cause of EINVAL is a priority ceiling violation
339
340       pragma Assert (Result = 0 or else Result = EINVAL);
341    end Write_Lock;
342
343    procedure Write_Lock
344      (L           : not null access RTS_Lock;
345       Global_Lock : Boolean := False)
346    is
347       Result : Interfaces.C.int;
348    begin
349       if not Single_Lock or else Global_Lock then
350          Result := pthread_mutex_lock (L);
351          pragma Assert (Result = 0);
352       end if;
353    end Write_Lock;
354
355    procedure Write_Lock (T : Task_Id) is
356       Result : Interfaces.C.int;
357    begin
358       if not Single_Lock then
359          Result := pthread_mutex_lock (T.Common.LL.L'Access);
360          pragma Assert (Result = 0);
361       end if;
362    end Write_Lock;
363
364    ---------------
365    -- Read_Lock --
366    ---------------
367
368    procedure Read_Lock
369      (L                 : not null access Lock;
370       Ceiling_Violation : out Boolean)
371    is
372    begin
373       Write_Lock (L, Ceiling_Violation);
374    end Read_Lock;
375
376    ------------
377    -- Unlock --
378    ------------
379
380    procedure Unlock (L : not null access Lock) is
381       Result : Interfaces.C.int;
382    begin
383       Result := pthread_mutex_unlock (L);
384       pragma Assert (Result = 0);
385    end Unlock;
386
387    procedure Unlock
388      (L           : not null access RTS_Lock;
389       Global_Lock : Boolean := False)
390    is
391       Result : Interfaces.C.int;
392    begin
393       if not Single_Lock or else Global_Lock then
394          Result := pthread_mutex_unlock (L);
395          pragma Assert (Result = 0);
396       end if;
397    end Unlock;
398
399    procedure Unlock (T : Task_Id) is
400       Result : Interfaces.C.int;
401    begin
402       if not Single_Lock then
403          Result := pthread_mutex_unlock (T.Common.LL.L'Access);
404          pragma Assert (Result = 0);
405       end if;
406    end Unlock;
407
408    -----------------
409    -- Set_Ceiling --
410    -----------------
411
412    --  Dynamic priority ceilings are not supported by the underlying system
413
414    procedure Set_Ceiling
415      (L    : not null access Lock;
416       Prio : System.Any_Priority)
417    is
418       pragma Unreferenced (L, Prio);
419    begin
420       null;
421    end Set_Ceiling;
422
423    -----------
424    -- Sleep --
425    -----------
426
427    procedure Sleep
428      (Self_ID  : Task_Id;
429       Reason   : System.Tasking.Task_States)
430    is
431       pragma Unreferenced (Reason);
432
433       Result : Interfaces.C.int;
434
435    begin
436       pragma Assert (Self_ID = Self);
437
438       if Single_Lock then
439          Result :=
440            pthread_cond_wait
441              (Self_ID.Common.LL.CV'Access, Single_RTS_Lock'Access);
442       else
443          Result :=
444            pthread_cond_wait
445              (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access);
446       end if;
447
448       --  EINTR is not considered a failure
449
450       pragma Assert (Result = 0 or else Result = EINTR);
451    end Sleep;
452
453    -----------------
454    -- Timed_Sleep --
455    -----------------
456
457    --  This is for use within the run-time system, so abort is
458    --  assumed to be already deferred, and the caller should be
459    --  holding its own ATCB lock.
460
461    procedure Timed_Sleep
462      (Self_ID  : Task_Id;
463       Time     : Duration;
464       Mode     : ST.Delay_Modes;
465       Reason   : System.Tasking.Task_States;
466       Timedout : out Boolean;
467       Yielded  : out Boolean)
468    is
469       pragma Unreferenced (Reason);
470
471       Base_Time  : constant Duration := Monotonic_Clock;
472       Check_Time : Duration := Base_Time;
473       Abs_Time   : Duration;
474       Request    : aliased timespec;
475       Result     : Interfaces.C.int;
476
477    begin
478       Timedout := True;
479       Yielded := False;
480
481       if Mode = Relative then
482          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
483       else
484          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
485       end if;
486
487       if Abs_Time > Check_Time then
488          Request := To_Timespec (Abs_Time);
489
490          loop
491             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
492
493             if Single_Lock then
494                Result :=
495                  pthread_cond_timedwait
496                    (Self_ID.Common.LL.CV'Access,
497                     Single_RTS_Lock'Access,
498                     Request'Access);
499
500             else
501                Result :=
502                  pthread_cond_timedwait
503                    (Self_ID.Common.LL.CV'Access,
504                     Self_ID.Common.LL.L'Access,
505                     Request'Access);
506             end if;
507
508             Check_Time := Monotonic_Clock;
509             exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
510
511             if Result = 0 or else Result = EINTR then
512
513                --  Somebody may have called Wakeup for us
514
515                Timedout := False;
516                exit;
517             end if;
518
519             pragma Assert (Result = ETIMEDOUT);
520          end loop;
521       end if;
522    end Timed_Sleep;
523
524    -----------------
525    -- Timed_Delay --
526    -----------------
527
528    --  This is for use in implementing delay statements, so we assume the
529    --  caller is abort-deferred but is holding no locks.
530
531    procedure Timed_Delay
532      (Self_ID : Task_Id;
533       Time    : Duration;
534       Mode    : ST.Delay_Modes)
535    is
536       Base_Time  : constant Duration := Monotonic_Clock;
537       Check_Time : Duration := Base_Time;
538       Abs_Time   : Duration;
539       Request    : aliased timespec;
540
541       Result : Interfaces.C.int;
542       pragma Warnings (Off, Result);
543
544    begin
545       if Single_Lock then
546          Lock_RTS;
547       end if;
548
549       Write_Lock (Self_ID);
550
551       if Mode = Relative then
552          Abs_Time := Time + Check_Time;
553       else
554          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
555       end if;
556
557       if Abs_Time > Check_Time then
558          Request := To_Timespec (Abs_Time);
559          Self_ID.Common.State := Delay_Sleep;
560
561          loop
562             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
563
564             if Single_Lock then
565                Result := pthread_cond_timedwait
566                            (Self_ID.Common.LL.CV'Access,
567                             Single_RTS_Lock'Access,
568                             Request'Access);
569             else
570                Result := pthread_cond_timedwait
571                            (Self_ID.Common.LL.CV'Access,
572                             Self_ID.Common.LL.L'Access,
573                             Request'Access);
574             end if;
575
576             Check_Time := Monotonic_Clock;
577             exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
578
579             pragma Assert (Result = 0 or else
580               Result = ETIMEDOUT or else
581               Result = EINTR);
582          end loop;
583
584          Self_ID.Common.State := Runnable;
585       end if;
586
587       Unlock (Self_ID);
588
589       if Single_Lock then
590          Unlock_RTS;
591       end if;
592
593       Result := sched_yield;
594    end Timed_Delay;
595
596    ---------------------
597    -- Monotonic_Clock --
598    ---------------------
599
600    function Monotonic_Clock return Duration is
601       TV     : aliased struct_timeval;
602       Result : Interfaces.C.int;
603    begin
604       Result := gettimeofday (TV'Access, System.Null_Address);
605       pragma Assert (Result = 0);
606       return To_Duration (TV);
607    end Monotonic_Clock;
608
609    -------------------
610    -- RT_Resolution --
611    -------------------
612
613    function RT_Resolution return Duration is
614    begin
615       return 10#1.0#E-6;
616    end RT_Resolution;
617
618    ------------
619    -- Wakeup --
620    ------------
621
622    procedure Wakeup (T : Task_Id; Reason : System.Tasking.Task_States) is
623       pragma Unreferenced (Reason);
624       Result : Interfaces.C.int;
625    begin
626       Result := pthread_cond_signal (T.Common.LL.CV'Access);
627       pragma Assert (Result = 0);
628    end Wakeup;
629
630    -----------
631    -- Yield --
632    -----------
633
634    procedure Yield (Do_Yield : Boolean := True) is
635       Result : Interfaces.C.int;
636       pragma Unreferenced (Result);
637    begin
638       if Do_Yield then
639          Result := sched_yield;
640       end if;
641    end Yield;
642
643    ------------------
644    -- Set_Priority --
645    ------------------
646
647    procedure Set_Priority
648      (T                   : Task_Id;
649       Prio                : System.Any_Priority;
650       Loss_Of_Inheritance : Boolean := False)
651    is
652       pragma Unreferenced (Loss_Of_Inheritance);
653
654       Result : Interfaces.C.int;
655       Param  : aliased struct_sched_param;
656
657       function Get_Policy (Prio : System.Any_Priority) return Character;
658       pragma Import (C, Get_Policy, "__gnat_get_specific_dispatching");
659       --  Get priority specific dispatching policy
660
661       Priority_Specific_Policy : constant Character := Get_Policy (Prio);
662       --  Upper case first character of the policy name corresponding to the
663       --  task as set by a Priority_Specific_Dispatching pragma.
664
665    begin
666       T.Common.Current_Priority := Prio;
667
668       --  Priorities are 1 .. 99 on GNU/Linux, so we map 0 .. 98 to 1 .. 99
669
670       Param.sched_priority := Interfaces.C.int (Prio) + 1;
671
672       if Dispatching_Policy = 'R'
673         or else Priority_Specific_Policy = 'R'
674         or else Time_Slice_Val > 0
675       then
676          Result :=
677            pthread_setschedparam
678              (T.Common.LL.Thread, SCHED_RR, Param'Access);
679
680       elsif Dispatching_Policy = 'F'
681         or else Priority_Specific_Policy = 'F'
682         or else Time_Slice_Val = 0
683       then
684          Result :=
685            pthread_setschedparam
686              (T.Common.LL.Thread, SCHED_FIFO, Param'Access);
687
688       else
689          Param.sched_priority := 0;
690          Result :=
691            pthread_setschedparam
692              (T.Common.LL.Thread,
693               SCHED_OTHER, Param'Access);
694       end if;
695
696       pragma Assert (Result = 0 or else Result = EPERM);
697    end Set_Priority;
698
699    ------------------
700    -- Get_Priority --
701    ------------------
702
703    function Get_Priority (T : Task_Id) return System.Any_Priority is
704    begin
705       return T.Common.Current_Priority;
706    end Get_Priority;
707
708    ----------------
709    -- Enter_Task --
710    ----------------
711
712    procedure Enter_Task (Self_ID : Task_Id) is
713    begin
714       Self_ID.Common.LL.Thread := pthread_self;
715
716       Specific.Set (Self_ID);
717
718       Lock_RTS;
719
720       for J in Known_Tasks'Range loop
721          if Known_Tasks (J) = null then
722             Known_Tasks (J) := Self_ID;
723             Self_ID.Known_Tasks_Index := J;
724             exit;
725          end if;
726       end loop;
727
728       Unlock_RTS;
729    end Enter_Task;
730
731    --------------
732    -- New_ATCB --
733    --------------
734
735    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
736    begin
737       return new Ada_Task_Control_Block (Entry_Num);
738    end New_ATCB;
739
740    -------------------
741    -- Is_Valid_Task --
742    -------------------
743
744    function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
745
746    -----------------------------
747    -- Register_Foreign_Thread --
748    -----------------------------
749
750    function Register_Foreign_Thread return Task_Id is
751    begin
752       if Is_Valid_Task then
753          return Self;
754       else
755          return Register_Foreign_Thread (pthread_self);
756       end if;
757    end Register_Foreign_Thread;
758
759    --------------------
760    -- Initialize_TCB --
761    --------------------
762
763    procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
764       Result : Interfaces.C.int;
765
766    begin
767       --  Give the task a unique serial number
768
769       Self_ID.Serial_Number := Next_Serial_Number;
770       Next_Serial_Number := Next_Serial_Number + 1;
771       pragma Assert (Next_Serial_Number /= 0);
772
773       Self_ID.Common.LL.Thread := To_pthread_t (-1);
774
775       if not Single_Lock then
776          Result := pthread_mutex_init (Self_ID.Common.LL.L'Access,
777            Mutex_Attr'Access);
778          pragma Assert (Result = 0 or else Result = ENOMEM);
779
780          if Result /= 0 then
781             Succeeded := False;
782             return;
783          end if;
784       end if;
785
786       Result := pthread_cond_init (Self_ID.Common.LL.CV'Access,
787         Cond_Attr'Access);
788       pragma Assert (Result = 0 or else Result = ENOMEM);
789
790       if Result = 0 then
791          Succeeded := True;
792       else
793          if not Single_Lock then
794             Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access);
795             pragma Assert (Result = 0);
796          end if;
797
798          Succeeded := False;
799       end if;
800    end Initialize_TCB;
801
802    -----------------
803    -- Create_Task --
804    -----------------
805
806    procedure Create_Task
807      (T          : Task_Id;
808       Wrapper    : System.Address;
809       Stack_Size : System.Parameters.Size_Type;
810       Priority   : System.Any_Priority;
811       Succeeded  : out Boolean)
812    is
813       Attributes : aliased pthread_attr_t;
814       Result     : Interfaces.C.int;
815
816    begin
817       Result := pthread_attr_init (Attributes'Access);
818       pragma Assert (Result = 0 or else Result = ENOMEM);
819
820       if Result /= 0 then
821          Succeeded := False;
822          return;
823       end if;
824
825       Result :=
826         pthread_attr_setstacksize
827           (Attributes'Access, Interfaces.C.size_t (Stack_Size));
828       pragma Assert (Result = 0);
829
830       Result :=
831         pthread_attr_setdetachstate
832           (Attributes'Access, PTHREAD_CREATE_DETACHED);
833       pragma Assert (Result = 0);
834
835       --  Since the initial signal mask of a thread is inherited from the
836       --  creator, and the Environment task has all its signals masked, we
837       --  do not need to manipulate caller's signal mask at this point.
838       --  All tasks in RTS will have All_Tasks_Mask initially.
839
840       Result := pthread_create
841         (T.Common.LL.Thread'Access,
842          Attributes'Access,
843          Thread_Body_Access (Wrapper),
844          To_Address (T));
845       pragma Assert (Result = 0 or else Result = EAGAIN);
846
847       Succeeded := Result = 0;
848
849       Result := pthread_attr_destroy (Attributes'Access);
850       pragma Assert (Result = 0);
851
852       Set_Priority (T, Priority);
853    end Create_Task;
854
855    ------------------
856    -- Finalize_TCB --
857    ------------------
858
859    procedure Finalize_TCB (T : Task_Id) is
860       Result  : Interfaces.C.int;
861       Tmp     : Task_Id := T;
862       Is_Self : constant Boolean := T = Self;
863
864       procedure Free is new
865         Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
866
867    begin
868       if not Single_Lock then
869          Result := pthread_mutex_destroy (T.Common.LL.L'Access);
870          pragma Assert (Result = 0);
871       end if;
872
873       Result := pthread_cond_destroy (T.Common.LL.CV'Access);
874       pragma Assert (Result = 0);
875
876       if T.Known_Tasks_Index /= -1 then
877          Known_Tasks (T.Known_Tasks_Index) := null;
878       end if;
879       SC.Invalidate_Stack_Cache (T.Common.Compiler_Data.Pri_Stack_Info'Access);
880       Free (Tmp);
881
882       if Is_Self then
883          Specific.Set (null);
884       end if;
885    end Finalize_TCB;
886
887    ---------------
888    -- Exit_Task --
889    ---------------
890
891    procedure Exit_Task is
892    begin
893       Specific.Set (null);
894    end Exit_Task;
895
896    ----------------
897    -- Abort_Task --
898    ----------------
899
900    procedure Abort_Task (T : Task_Id) is
901       Result : Interfaces.C.int;
902    begin
903       Result :=
904         pthread_kill
905           (T.Common.LL.Thread,
906            Signal (System.Interrupt_Management.Abort_Task_Interrupt));
907       pragma Assert (Result = 0);
908    end Abort_Task;
909
910    ----------------
911    -- Initialize --
912    ----------------
913
914    procedure Initialize (S : in out Suspension_Object) is
915       Result : Interfaces.C.int;
916
917    begin
918       --  Initialize internal state (always to False (RM D.10(6)))
919
920       S.State := False;
921       S.Waiting := False;
922
923       --  Initialize internal mutex
924
925       Result := pthread_mutex_init (S.L'Access, Mutex_Attr'Access);
926
927       pragma Assert (Result = 0 or else Result = ENOMEM);
928
929       if Result = ENOMEM then
930          raise Storage_Error;
931       end if;
932
933       --  Initialize internal condition variable
934
935       Result := pthread_cond_init (S.CV'Access, Cond_Attr'Access);
936
937       pragma Assert (Result = 0 or else Result = ENOMEM);
938
939       if Result /= 0 then
940          Result := pthread_mutex_destroy (S.L'Access);
941          pragma Assert (Result = 0);
942
943          if Result = ENOMEM then
944             raise Storage_Error;
945          end if;
946       end if;
947    end Initialize;
948
949    --------------
950    -- Finalize --
951    --------------
952
953    procedure Finalize (S : in out Suspension_Object) is
954       Result : Interfaces.C.int;
955
956    begin
957       --  Destroy internal mutex
958
959       Result := pthread_mutex_destroy (S.L'Access);
960       pragma Assert (Result = 0);
961
962       --  Destroy internal condition variable
963
964       Result := pthread_cond_destroy (S.CV'Access);
965       pragma Assert (Result = 0);
966    end Finalize;
967
968    -------------------
969    -- Current_State --
970    -------------------
971
972    function Current_State (S : Suspension_Object) return Boolean is
973    begin
974       --  We do not want to use lock on this read operation. State is marked
975       --  as Atomic so that we ensure that the value retrieved is correct.
976
977       return S.State;
978    end Current_State;
979
980    ---------------
981    -- Set_False --
982    ---------------
983
984    procedure Set_False (S : in out Suspension_Object) is
985       Result : Interfaces.C.int;
986
987    begin
988       SSL.Abort_Defer.all;
989
990       Result := pthread_mutex_lock (S.L'Access);
991       pragma Assert (Result = 0);
992
993       S.State := False;
994
995       Result := pthread_mutex_unlock (S.L'Access);
996       pragma Assert (Result = 0);
997
998       SSL.Abort_Undefer.all;
999    end Set_False;
1000
1001    --------------
1002    -- Set_True --
1003    --------------
1004
1005    procedure Set_True (S : in out Suspension_Object) is
1006       Result : Interfaces.C.int;
1007
1008    begin
1009       SSL.Abort_Defer.all;
1010
1011       Result := pthread_mutex_lock (S.L'Access);
1012       pragma Assert (Result = 0);
1013
1014       --  If there is already a task waiting on this suspension object then
1015       --  we resume it, leaving the state of the suspension object to False,
1016       --  as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1017       --  the state to True.
1018
1019       if S.Waiting then
1020          S.Waiting := False;
1021          S.State := False;
1022
1023          Result := pthread_cond_signal (S.CV'Access);
1024          pragma Assert (Result = 0);
1025
1026       else
1027          S.State := True;
1028       end if;
1029
1030       Result := pthread_mutex_unlock (S.L'Access);
1031       pragma Assert (Result = 0);
1032
1033       SSL.Abort_Undefer.all;
1034    end Set_True;
1035
1036    ------------------------
1037    -- Suspend_Until_True --
1038    ------------------------
1039
1040    procedure Suspend_Until_True (S : in out Suspension_Object) is
1041       Result : Interfaces.C.int;
1042
1043    begin
1044       SSL.Abort_Defer.all;
1045
1046       Result := pthread_mutex_lock (S.L'Access);
1047       pragma Assert (Result = 0);
1048
1049       if S.Waiting then
1050
1051          --  Program_Error must be raised upon calling Suspend_Until_True
1052          --  if another task is already waiting on that suspension object
1053          --  (RM D.10(10)).
1054
1055          Result := pthread_mutex_unlock (S.L'Access);
1056          pragma Assert (Result = 0);
1057
1058          SSL.Abort_Undefer.all;
1059
1060          raise Program_Error;
1061       else
1062          --  Suspend the task if the state is False. Otherwise, the task
1063          --  continues its execution, and the state of the suspension object
1064          --  is set to False (ARM D.10 par. 9).
1065
1066          if S.State then
1067             S.State := False;
1068          else
1069             S.Waiting := True;
1070             Result := pthread_cond_wait (S.CV'Access, S.L'Access);
1071          end if;
1072
1073          Result := pthread_mutex_unlock (S.L'Access);
1074          pragma Assert (Result = 0);
1075
1076          SSL.Abort_Undefer.all;
1077       end
1078       if;
1079    end Suspend_Until_True;
1080
1081    ----------------
1082    -- Check_Exit --
1083    ----------------
1084
1085    --  Dummy version
1086
1087    function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1088       pragma Unreferenced (Self_ID);
1089    begin
1090       return True;
1091    end Check_Exit;
1092
1093    --------------------
1094    -- Check_No_Locks --
1095    --------------------
1096
1097    function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1098       pragma Unreferenced (Self_ID);
1099    begin
1100       return True;
1101    end Check_No_Locks;
1102
1103    ----------------------
1104    -- Environment_Task --
1105    ----------------------
1106
1107    function Environment_Task return Task_Id is
1108    begin
1109       return Environment_Task_Id;
1110    end Environment_Task;
1111
1112    ------------------
1113    -- Suspend_Task --
1114    ------------------
1115
1116    function Suspend_Task
1117      (T           : ST.Task_Id;
1118       Thread_Self : Thread_Id) return Boolean
1119    is
1120    begin
1121       if T.Common.LL.Thread /= Thread_Self then
1122          return pthread_kill (T.Common.LL.Thread, SIGSTOP) = 0;
1123       else
1124          return True;
1125       end if;
1126    end Suspend_Task;
1127
1128    -----------------
1129    -- Resume_Task --
1130    -----------------
1131
1132    function Resume_Task
1133      (T           : ST.Task_Id;
1134       Thread_Self : Thread_Id) return Boolean
1135    is
1136    begin
1137       if T.Common.LL.Thread /= Thread_Self then
1138          return pthread_kill (T.Common.LL.Thread, SIGCONT) = 0;
1139       else
1140          return True;
1141       end if;
1142    end Resume_Task;
1143
1144    ----------------
1145    -- Initialize --
1146    ----------------
1147
1148    procedure Initialize (Environment_Task : Task_Id) is
1149       act     : aliased struct_sigaction;
1150       old_act : aliased struct_sigaction;
1151       Tmp_Set : aliased sigset_t;
1152       Result  : Interfaces.C.int;
1153
1154       function State
1155         (Int : System.Interrupt_Management.Interrupt_ID) return Character;
1156       pragma Import (C, State, "__gnat_get_interrupt_state");
1157       --  Get interrupt state.  Defined in a-init.c
1158       --  The input argument is the interrupt number,
1159       --  and the result is one of the following:
1160
1161       Default : constant Character := 's';
1162       --    'n'   this interrupt not set by any Interrupt_State pragma
1163       --    'u'   Interrupt_State pragma set state to User
1164       --    'r'   Interrupt_State pragma set state to Runtime
1165       --    's'   Interrupt_State pragma set state to System (use "default"
1166       --           system handler)
1167
1168    begin
1169       Environment_Task_Id := Environment_Task;
1170
1171       Interrupt_Management.Initialize;
1172
1173       --  Prepare the set of signals that should be unblocked in all tasks
1174
1175       Result := sigemptyset (Unblocked_Signal_Mask'Access);
1176       pragma Assert (Result = 0);
1177
1178       for J in Interrupt_Management.Interrupt_ID loop
1179          if System.Interrupt_Management.Keep_Unmasked (J) then
1180             Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1181             pragma Assert (Result = 0);
1182          end if;
1183       end loop;
1184
1185       Result := pthread_mutexattr_init (Mutex_Attr'Access);
1186       pragma Assert (Result = 0);
1187
1188       Result := pthread_condattr_init (Cond_Attr'Access);
1189       pragma Assert (Result = 0);
1190
1191       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1192
1193       --  Initialize the global RTS lock
1194
1195       Specific.Initialize (Environment_Task);
1196
1197       Enter_Task (Environment_Task);
1198
1199       --  Install the abort-signal handler
1200
1201       if State
1202           (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
1203       then
1204          act.sa_flags := 0;
1205          act.sa_handler := Abort_Handler'Address;
1206
1207          Result := sigemptyset (Tmp_Set'Access);
1208          pragma Assert (Result = 0);
1209          act.sa_mask := Tmp_Set;
1210
1211          Result :=
1212            sigaction
1213            (Signal (Interrupt_Management.Abort_Task_Interrupt),
1214             act'Unchecked_Access,
1215             old_act'Unchecked_Access);
1216          pragma Assert (Result = 0);
1217       end if;
1218    end Initialize;
1219
1220 end System.Task_Primitives.Operations;