OSDN Git Service

* approved by rth
[pf3gnuchains/gcc-fork.git] / gcc / ada / 7staprop.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 --                                                                          --
10 --         Copyright (C) 1992-2001, Free Software Foundation, Inc.          --
11 --                                                                          --
12 -- GNARL is free software; you can  redistribute it  and/or modify it under --
13 -- terms of the  GNU General Public License as published  by the Free Soft- --
14 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
15 -- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
16 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
17 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
18 -- for  more details.  You should have  received  a copy of the GNU General --
19 -- Public License  distributed with GNARL; see file COPYING.  If not, write --
20 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
21 -- MA 02111-1307, USA.                                                      --
22 --                                                                          --
23 -- As a special exception,  if other files  instantiate  generics from this --
24 -- unit, or you link  this unit with other files  to produce an executable, --
25 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
26 -- covered  by the  GNU  General  Public  License.  This exception does not --
27 -- however invalidate  any other reasons why  the executable file  might be --
28 -- covered by the  GNU Public License.                                      --
29 --                                                                          --
30 -- GNARL was developed by the GNARL team at Florida State University. It is --
31 -- now maintained by Ada Core Technologies Inc. in cooperation with Florida --
32 -- State University (http://www.gnat.com).                                  --
33 --                                                                          --
34 ------------------------------------------------------------------------------
35
36 --  This is a POSIX-like version of this package
37
38 --  This package contains all the GNULL primitives that interface directly
39 --  with the underlying OS.
40
41 --  Note: this file can only be used for POSIX compliant systems that
42 --  implement SCHED_FIFO and Ceiling Locking correctly.
43
44 --  For configurations where SCHED_FIFO and priority ceiling are not a
45 --  requirement, this file can also be used (e.g AiX threads)
46
47 pragma Polling (Off);
48 --  Turn off polling, we do not want ATC polling to take place during
49 --  tasking operations. It causes infinite loops and other problems.
50
51 with System.Tasking.Debug;
52 --  used for Known_Tasks
53
54 with System.Task_Info;
55 --  used for Task_Info_Type
56
57 with Interfaces.C;
58 --  used for int
59 --           size_t
60
61 with System.Interrupt_Management;
62 --  used for Keep_Unmasked
63 --           Abort_Task_Interrupt
64 --           Interrupt_ID
65
66 with System.Interrupt_Management.Operations;
67 --  used for Set_Interrupt_Mask
68 --           All_Tasks_Mask
69 pragma Elaborate_All (System.Interrupt_Management.Operations);
70
71 with System.Parameters;
72 --  used for Size_Type
73
74 with System.Tasking;
75 --  used for Ada_Task_Control_Block
76 --           Task_ID
77
78 with System.Soft_Links;
79 --  used for Defer/Undefer_Abort
80
81 --  Note that we do not use System.Tasking.Initialization directly since
82 --  this is a higher level package that we shouldn't depend on. For example
83 --  when using the restricted run time, it is replaced by
84 --  System.Tasking.Restricted.Initialization
85
86 with System.OS_Primitives;
87 --  used for Delay_Modes
88
89 with Unchecked_Conversion;
90 with Unchecked_Deallocation;
91
92 package body System.Task_Primitives.Operations is
93
94    use System.Tasking.Debug;
95    use System.Tasking;
96    use Interfaces.C;
97    use System.OS_Interface;
98    use System.Parameters;
99    use System.OS_Primitives;
100
101    package SSL renames System.Soft_Links;
102
103    ----------------
104    -- Local Data --
105    ----------------
106
107    --  The followings are logically constants, but need to be initialized
108    --  at run time.
109
110    Single_RTS_Lock : aliased RTS_Lock;
111    --  This is a lock to allow only one thread of control in the RTS at
112    --  a time; it is used to execute in mutual exclusion from all other tasks.
113    --  Used mainly in Single_Lock mode, but also to protect All_Tasks_List
114
115    Environment_Task_ID : Task_ID;
116    --  A variable to hold Task_ID for the environment task.
117
118    Locking_Policy : Character;
119    pragma Import (C, Locking_Policy, "__gl_locking_policy");
120    --  Value of the pragma Locking_Policy:
121    --    'C' for Ceiling_Locking
122    --    'I' for Inherit_Locking
123    --    ' ' for none.
124
125    Unblocked_Signal_Mask : aliased sigset_t;
126    --  The set of signals that should unblocked in all tasks
127
128    --  The followings are internal configuration constants needed.
129
130    Next_Serial_Number : Task_Serial_Number := 100;
131    --  We start at 100, to reserve some special values for
132    --  using in error checking.
133
134    Time_Slice_Val : Integer;
135    pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
136
137    Dispatching_Policy : Character;
138    pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
139
140    FIFO_Within_Priorities : constant Boolean := Dispatching_Policy = 'F';
141    --  Indicates whether FIFO_Within_Priorities is set.
142
143    -----------------------
144    -- Local Subprograms --
145    -----------------------
146
147    procedure Abort_Handler (Sig : Signal);
148
149    function To_Task_ID is new Unchecked_Conversion (System.Address, Task_ID);
150
151    function To_Address is new Unchecked_Conversion (Task_ID, System.Address);
152
153    --------------------
154    -- Local Packages --
155    --------------------
156
157    package Specific is
158
159       procedure Initialize (Environment_Task : Task_ID);
160       pragma Inline (Initialize);
161       --  Initialize various data needed by this package.
162
163       procedure Set (Self_Id : Task_ID);
164       pragma Inline (Set);
165       --  Set the self id for the current task.
166
167       function Self return Task_ID;
168       pragma Inline (Self);
169       --  Return a pointer to the Ada Task Control Block of the calling task.
170
171    end Specific;
172
173    package body Specific is separate;
174    --  The body of this package is target specific.
175
176    -------------------
177    -- Abort_Handler --
178    -------------------
179
180    --  Target-dependent binding of inter-thread Abort signal to
181    --  the raising of the Abort_Signal exception.
182
183    --  The technical issues and alternatives here are essentially
184    --  the same as for raising exceptions in response to other
185    --  signals (e.g. Storage_Error). See code and comments in
186    --  the package body System.Interrupt_Management.
187
188    --  Some implementations may not allow an exception to be propagated
189    --  out of a handler, and others might leave the signal or
190    --  interrupt that invoked this handler masked after the exceptional
191    --  return to the application code.
192
193    --  GNAT exceptions are originally implemented using setjmp()/longjmp().
194    --  On most UNIX systems, this will allow transfer out of a signal handler,
195    --  which is usually the only mechanism available for implementing
196    --  asynchronous handlers of this kind. However, some
197    --  systems do not restore the signal mask on longjmp(), leaving the
198    --  abort signal masked.
199
200    --  Alternative solutions include:
201
202    --       1. Change the PC saved in the system-dependent Context
203    --          parameter to point to code that raises the exception.
204    --          Normal return from this handler will then raise
205    --          the exception after the mask and other system state has
206    --          been restored (see example below).
207
208    --       2. Use siglongjmp()/sigsetjmp() to implement exceptions.
209
210    --       3. Unmask the signal in the Abortion_Signal exception handler
211    --          (in the RTS).
212
213    --  The following procedure would be needed if we can't lonjmp out of
214    --  a signal handler  (See below)
215
216    --  procedure Raise_Abort_Signal is
217    --  begin
218    --     raise Standard'Abort_Signal;
219    --  end if;
220
221    procedure Abort_Handler
222      (Sig     : Signal) is
223
224       T       : Task_ID := Self;
225       Result  : Interfaces.C.int;
226       Old_Set : aliased sigset_t;
227
228    begin
229       --  Assuming it is safe to longjmp out of a signal handler, the
230       --  following code can be used:
231
232       if T.Deferral_Level = 0
233         and then T.Pending_ATC_Level < T.ATC_Nesting_Level and then
234         not T.Aborting
235       then
236          T.Aborting := True;
237
238          --  Make sure signals used for RTS internal purpose are unmasked
239
240          Result := pthread_sigmask (SIG_UNBLOCK,
241            Unblocked_Signal_Mask'Unchecked_Access, Old_Set'Unchecked_Access);
242          pragma Assert (Result = 0);
243
244          raise Standard'Abort_Signal;
245       end if;
246
247       --  Otherwise, something like this is required:
248       --  if not Abort_Is_Deferred.all then
249       --    --  Overwrite the return PC address with the address of the
250       --    --  special raise routine, and "return" to that routine's
251       --    --  starting address.
252       --    Context.PC := Raise_Abort_Signal'Address;
253       --    return;
254       --  end if;
255    end Abort_Handler;
256
257    -----------------
258    -- Stack_Guard --
259    -----------------
260
261    procedure Stack_Guard (T : ST.Task_ID; On : Boolean) is
262       Stack_Base : constant Address := Get_Stack_Base (T.Common.LL.Thread);
263       Guard_Page_Address : Address;
264
265       Res : Interfaces.C.int;
266
267    begin
268       if Stack_Base_Available then
269          --  Compute the guard page address
270
271          Guard_Page_Address :=
272            Stack_Base - (Stack_Base mod Get_Page_Size) + Get_Page_Size;
273
274          if On then
275             Res := mprotect (Guard_Page_Address, Get_Page_Size, PROT_ON);
276          else
277             Res := mprotect (Guard_Page_Address, Get_Page_Size, PROT_OFF);
278          end if;
279
280          pragma Assert (Res = 0);
281       end if;
282    end Stack_Guard;
283
284    --------------------
285    -- Get_Thread_Id  --
286    --------------------
287
288    function Get_Thread_Id (T : ST.Task_ID) return OSI.Thread_Id is
289    begin
290       return T.Common.LL.Thread;
291    end Get_Thread_Id;
292
293    ----------
294    -- Self --
295    ----------
296
297    function Self return Task_ID renames Specific.Self;
298
299    ---------------------
300    -- Initialize_Lock --
301    ---------------------
302
303    --  Note: mutexes and cond_variables needed per-task basis are
304    --        initialized in Initialize_TCB and the Storage_Error is
305    --        handled. Other mutexes (such as RTS_Lock, Memory_Lock...)
306    --        used in RTS is initialized before any status change of RTS.
307    --        Therefore rasing Storage_Error in the following routines
308    --        should be able to be handled safely.
309
310    procedure Initialize_Lock
311      (Prio : System.Any_Priority;
312       L    : access Lock)
313    is
314       Attributes : aliased pthread_mutexattr_t;
315       Result : Interfaces.C.int;
316
317    begin
318       Result := pthread_mutexattr_init (Attributes'Access);
319       pragma Assert (Result = 0 or else Result = ENOMEM);
320
321       if Result = ENOMEM then
322          raise Storage_Error;
323       end if;
324
325       if Locking_Policy = 'C' then
326          Result := pthread_mutexattr_setprotocol
327            (Attributes'Access, PTHREAD_PRIO_PROTECT);
328          pragma Assert (Result = 0);
329
330          Result := pthread_mutexattr_setprioceiling
331             (Attributes'Access, Interfaces.C.int (Prio));
332          pragma Assert (Result = 0);
333
334       elsif Locking_Policy = 'I' then
335          Result := pthread_mutexattr_setprotocol
336            (Attributes'Access, PTHREAD_PRIO_INHERIT);
337          pragma Assert (Result = 0);
338       end if;
339
340       Result := pthread_mutex_init (L, Attributes'Access);
341       pragma Assert (Result = 0 or else Result = ENOMEM);
342
343       if Result = ENOMEM then
344          raise Storage_Error;
345       end if;
346
347       Result := pthread_mutexattr_destroy (Attributes'Access);
348       pragma Assert (Result = 0);
349    end Initialize_Lock;
350
351    procedure Initialize_Lock (L : access RTS_Lock; Level : Lock_Level) is
352       Attributes : aliased pthread_mutexattr_t;
353       Result : Interfaces.C.int;
354
355    begin
356       Result := pthread_mutexattr_init (Attributes'Access);
357       pragma Assert (Result = 0 or else Result = ENOMEM);
358
359       if Result = ENOMEM then
360          raise Storage_Error;
361       end if;
362
363       if Locking_Policy = 'C' then
364          Result := pthread_mutexattr_setprotocol
365            (Attributes'Access, PTHREAD_PRIO_PROTECT);
366          pragma Assert (Result = 0);
367
368          Result := pthread_mutexattr_setprioceiling
369             (Attributes'Access, Interfaces.C.int (System.Any_Priority'Last));
370          pragma Assert (Result = 0);
371
372       elsif Locking_Policy = 'I' then
373          Result := pthread_mutexattr_setprotocol
374            (Attributes'Access, PTHREAD_PRIO_INHERIT);
375          pragma Assert (Result = 0);
376       end if;
377
378       Result := pthread_mutex_init (L, Attributes'Access);
379       pragma Assert (Result = 0 or else Result = ENOMEM);
380
381       if Result = ENOMEM then
382          Result := pthread_mutexattr_destroy (Attributes'Access);
383          raise Storage_Error;
384       end if;
385
386       Result := pthread_mutexattr_destroy (Attributes'Access);
387       pragma Assert (Result = 0);
388    end Initialize_Lock;
389
390    -------------------
391    -- Finalize_Lock --
392    -------------------
393
394    procedure Finalize_Lock (L : access Lock) is
395       Result : Interfaces.C.int;
396    begin
397       Result := pthread_mutex_destroy (L);
398       pragma Assert (Result = 0);
399    end Finalize_Lock;
400
401    procedure Finalize_Lock (L : access RTS_Lock) is
402       Result : Interfaces.C.int;
403    begin
404       Result := pthread_mutex_destroy (L);
405       pragma Assert (Result = 0);
406    end Finalize_Lock;
407
408    ----------------
409    -- Write_Lock --
410    ----------------
411
412    procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
413       Result : Interfaces.C.int;
414    begin
415       Result := pthread_mutex_lock (L);
416
417       --  Assume that the cause of EINVAL is a priority ceiling violation
418
419       Ceiling_Violation := (Result = EINVAL);
420       pragma Assert (Result = 0 or else Result = EINVAL);
421    end Write_Lock;
422
423    procedure Write_Lock
424      (L : access RTS_Lock; Global_Lock : Boolean := False)
425    is
426       Result : Interfaces.C.int;
427    begin
428       if not Single_Lock or else Global_Lock then
429          Result := pthread_mutex_lock (L);
430          pragma Assert (Result = 0);
431       end if;
432    end Write_Lock;
433
434    procedure Write_Lock (T : Task_ID) is
435       Result : Interfaces.C.int;
436    begin
437       if not Single_Lock then
438          Result := pthread_mutex_lock (T.Common.LL.L'Access);
439          pragma Assert (Result = 0);
440       end if;
441    end Write_Lock;
442
443    ---------------
444    -- Read_Lock --
445    ---------------
446
447    procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
448    begin
449       Write_Lock (L, Ceiling_Violation);
450    end Read_Lock;
451
452    ------------
453    -- Unlock --
454    ------------
455
456    procedure Unlock (L : access Lock) is
457       Result : Interfaces.C.int;
458    begin
459       Result := pthread_mutex_unlock (L);
460       pragma Assert (Result = 0);
461    end Unlock;
462
463    procedure Unlock (L : access RTS_Lock; Global_Lock : Boolean := False) is
464       Result : Interfaces.C.int;
465    begin
466       if not Single_Lock or else Global_Lock then
467          Result := pthread_mutex_unlock (L);
468          pragma Assert (Result = 0);
469       end if;
470    end Unlock;
471
472    procedure Unlock (T : Task_ID) is
473       Result : Interfaces.C.int;
474    begin
475       if not Single_Lock then
476          Result := pthread_mutex_unlock (T.Common.LL.L'Access);
477          pragma Assert (Result = 0);
478       end if;
479    end Unlock;
480
481    -----------
482    -- Sleep --
483    -----------
484
485    procedure Sleep
486      (Self_ID : Task_ID;
487       Reason   : System.Tasking.Task_States)
488    is
489       Result : Interfaces.C.int;
490    begin
491       if Single_Lock then
492          Result := pthread_cond_wait
493            (Self_ID.Common.LL.CV'Access, Single_RTS_Lock'Access);
494       else
495          Result := pthread_cond_wait
496            (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access);
497       end if;
498
499       --  EINTR is not considered a failure.
500
501       pragma Assert (Result = 0 or else Result = EINTR);
502    end Sleep;
503
504    -----------------
505    -- Timed_Sleep --
506    -----------------
507
508    --  This is for use within the run-time system, so abort is
509    --  assumed to be already deferred, and the caller should be
510    --  holding its own ATCB lock.
511
512    procedure Timed_Sleep
513      (Self_ID  : Task_ID;
514       Time     : Duration;
515       Mode     : ST.Delay_Modes;
516       Reason   : Task_States;
517       Timedout : out Boolean;
518       Yielded  : out Boolean)
519    is
520       Check_Time : constant Duration := Monotonic_Clock;
521       Rel_Time   : Duration;
522       Abs_Time   : Duration;
523       Request    : aliased timespec;
524       Result     : Interfaces.C.int;
525
526    begin
527       Timedout := True;
528       Yielded := False;
529
530       if Mode = Relative then
531          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
532
533          if Relative_Timed_Wait then
534             Rel_Time := Duration'Min (Max_Sensible_Delay, Time);
535          end if;
536
537       else
538          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
539
540          if Relative_Timed_Wait then
541             Rel_Time := Duration'Min (Max_Sensible_Delay, Time - Check_Time);
542          end if;
543       end if;
544
545       if Abs_Time > Check_Time then
546          if Relative_Timed_Wait then
547             Request := To_Timespec (Rel_Time);
548          else
549             Request := To_Timespec (Abs_Time);
550          end if;
551
552          loop
553             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
554               or else Self_ID.Pending_Priority_Change;
555
556             if Single_Lock then
557                Result := pthread_cond_timedwait
558                  (Self_ID.Common.LL.CV'Access, Single_RTS_Lock'Access,
559                   Request'Access);
560
561             else
562                Result := pthread_cond_timedwait
563                  (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access,
564                   Request'Access);
565             end if;
566
567             exit when Abs_Time <= Monotonic_Clock;
568
569             if Result = 0 or Result = EINTR then
570
571                --  Somebody may have called Wakeup for us
572
573                Timedout := False;
574                exit;
575             end if;
576
577             pragma Assert (Result = ETIMEDOUT);
578          end loop;
579       end if;
580    end Timed_Sleep;
581
582    -----------------
583    -- Timed_Delay --
584    -----------------
585
586    --  This is for use in implementing delay statements, so
587    --  we assume the caller is abort-deferred but is holding
588    --  no locks.
589
590    procedure Timed_Delay
591      (Self_ID  : Task_ID;
592       Time     : Duration;
593       Mode     : ST.Delay_Modes)
594    is
595       Check_Time : constant Duration := Monotonic_Clock;
596       Abs_Time   : Duration;
597       Rel_Time   : Duration;
598       Request    : aliased timespec;
599       Result     : Interfaces.C.int;
600
601    begin
602       --  Only the little window between deferring abort and
603       --  locking Self_ID is the reason we need to
604       --  check for pending abort and priority change below! :(
605
606       SSL.Abort_Defer.all;
607
608       if Single_Lock then
609          Lock_RTS;
610       end if;
611
612       Write_Lock (Self_ID);
613
614       if Mode = Relative then
615          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
616
617          if Relative_Timed_Wait then
618             Rel_Time := Duration'Min (Max_Sensible_Delay, Time);
619          end if;
620
621       else
622          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
623
624          if Relative_Timed_Wait then
625             Rel_Time := Duration'Min (Max_Sensible_Delay, Time - Check_Time);
626          end if;
627       end if;
628
629       if Abs_Time > Check_Time then
630          if Relative_Timed_Wait then
631             Request := To_Timespec (Rel_Time);
632          else
633             Request := To_Timespec (Abs_Time);
634          end if;
635
636          Self_ID.Common.State := Delay_Sleep;
637
638          loop
639             if Self_ID.Pending_Priority_Change then
640                Self_ID.Pending_Priority_Change := False;
641                Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
642                Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
643             end if;
644
645             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
646
647             if Single_Lock then
648                Result := pthread_cond_timedwait (Self_ID.Common.LL.CV'Access,
649                  Single_RTS_Lock'Access, Request'Access);
650             else
651                Result := pthread_cond_timedwait (Self_ID.Common.LL.CV'Access,
652                  Self_ID.Common.LL.L'Access, Request'Access);
653             end if;
654
655             exit when Abs_Time <= Monotonic_Clock;
656
657             pragma Assert (Result = 0
658                              or else Result = ETIMEDOUT
659                              or else Result = EINTR);
660          end loop;
661
662          Self_ID.Common.State := Runnable;
663       end if;
664
665       Unlock (Self_ID);
666
667       if Single_Lock then
668          Unlock_RTS;
669       end if;
670
671       Result := sched_yield;
672       SSL.Abort_Undefer.all;
673    end Timed_Delay;
674
675    ---------------------
676    -- Monotonic_Clock --
677    ---------------------
678
679    function Monotonic_Clock return Duration is
680       TS     : aliased timespec;
681       Result : Interfaces.C.int;
682
683    begin
684       Result := clock_gettime
685         (clock_id => CLOCK_REALTIME, tp => TS'Unchecked_Access);
686       pragma Assert (Result = 0);
687       return To_Duration (TS);
688    end Monotonic_Clock;
689
690    -------------------
691    -- RT_Resolution --
692    -------------------
693
694    function RT_Resolution return Duration is
695    begin
696       return 10#1.0#E-6;
697    end RT_Resolution;
698
699    ------------
700    -- Wakeup --
701    ------------
702
703    procedure Wakeup (T : Task_ID; Reason : System.Tasking.Task_States) is
704       Result : Interfaces.C.int;
705    begin
706       Result := pthread_cond_signal (T.Common.LL.CV'Access);
707       pragma Assert (Result = 0);
708    end Wakeup;
709
710    -----------
711    -- Yield --
712    -----------
713
714    procedure Yield (Do_Yield : Boolean := True) is
715       Result : Interfaces.C.int;
716    begin
717       if Do_Yield then
718          Result := sched_yield;
719       end if;
720    end Yield;
721
722    ------------------
723    -- Set_Priority --
724    ------------------
725
726    procedure Set_Priority
727      (T                   : Task_ID;
728       Prio                : System.Any_Priority;
729       Loss_Of_Inheritance : Boolean := False)
730    is
731       Result : Interfaces.C.int;
732       Param  : aliased struct_sched_param;
733
734    begin
735       T.Common.Current_Priority := Prio;
736       Param.sched_priority := Interfaces.C.int (Prio);
737
738       if Time_Slice_Supported and then Time_Slice_Val > 0 then
739          Result := pthread_setschedparam
740            (T.Common.LL.Thread, SCHED_RR, Param'Access);
741
742       elsif FIFO_Within_Priorities or else Time_Slice_Val = 0 then
743          Result := pthread_setschedparam
744            (T.Common.LL.Thread, SCHED_FIFO, Param'Access);
745
746       else
747          Result := pthread_setschedparam
748            (T.Common.LL.Thread, SCHED_OTHER, Param'Access);
749       end if;
750
751       pragma Assert (Result = 0);
752    end Set_Priority;
753
754    ------------------
755    -- Get_Priority --
756    ------------------
757
758    function Get_Priority (T : Task_ID) return System.Any_Priority is
759    begin
760       return T.Common.Current_Priority;
761    end Get_Priority;
762
763    ----------------
764    -- Enter_Task --
765    ----------------
766
767    procedure Enter_Task (Self_ID : Task_ID) is
768    begin
769       Self_ID.Common.LL.Thread := pthread_self;
770       Self_ID.Common.LL.LWP := lwp_self;
771
772       Specific.Set (Self_ID);
773
774       Lock_RTS;
775
776       for J in Known_Tasks'Range loop
777          if Known_Tasks (J) = null then
778             Known_Tasks (J) := Self_ID;
779             Self_ID.Known_Tasks_Index := J;
780             exit;
781          end if;
782       end loop;
783
784       Unlock_RTS;
785    end Enter_Task;
786
787    --------------
788    -- New_ATCB --
789    --------------
790
791    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_ID is
792    begin
793       return new Ada_Task_Control_Block (Entry_Num);
794    end New_ATCB;
795
796    ----------------------
797    --  Initialize_TCB  --
798    ----------------------
799
800    procedure Initialize_TCB (Self_ID : Task_ID; Succeeded : out Boolean) is
801       Mutex_Attr : aliased pthread_mutexattr_t;
802       Result     : Interfaces.C.int;
803       Cond_Attr  : aliased pthread_condattr_t;
804
805    begin
806       --  Give the task a unique serial number.
807
808       Self_ID.Serial_Number := Next_Serial_Number;
809       Next_Serial_Number := Next_Serial_Number + 1;
810       pragma Assert (Next_Serial_Number /= 0);
811
812       if not Single_Lock then
813          Result := pthread_mutexattr_init (Mutex_Attr'Access);
814          pragma Assert (Result = 0 or else Result = ENOMEM);
815
816          if Result = 0 then
817             Result := pthread_mutexattr_setprotocol
818               (Mutex_Attr'Access, PTHREAD_PRIO_PROTECT);
819             pragma Assert (Result = 0);
820
821             Result := pthread_mutexattr_setprioceiling
822               (Mutex_Attr'Access, Interfaces.C.int (System.Any_Priority'Last));
823             pragma Assert (Result = 0);
824
825             Result := pthread_mutex_init (Self_ID.Common.LL.L'Access,
826               Mutex_Attr'Access);
827             pragma Assert (Result = 0 or else Result = ENOMEM);
828          end if;
829
830          if Result /= 0 then
831             Succeeded := False;
832             return;
833          end if;
834
835          Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
836          pragma Assert (Result = 0);
837       end if;
838
839       Result := pthread_condattr_init (Cond_Attr'Access);
840       pragma Assert (Result = 0 or else Result = ENOMEM);
841
842       if Result = 0 then
843          Result := pthread_cond_init (Self_ID.Common.LL.CV'Access,
844            Cond_Attr'Access);
845          pragma Assert (Result = 0 or else Result = ENOMEM);
846       end if;
847
848       if Result = 0 then
849          Succeeded := True;
850       else
851          if not Single_Lock then
852             Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access);
853             pragma Assert (Result = 0);
854          end if;
855
856          Succeeded := False;
857       end if;
858
859       Result := pthread_condattr_destroy (Cond_Attr'Access);
860       pragma Assert (Result = 0);
861    end Initialize_TCB;
862
863    -----------------
864    -- Create_Task --
865    -----------------
866
867    procedure Create_Task
868      (T          : Task_ID;
869       Wrapper    : System.Address;
870       Stack_Size : System.Parameters.Size_Type;
871       Priority   : System.Any_Priority;
872       Succeeded  : out Boolean)
873    is
874       Attributes          : aliased pthread_attr_t;
875       Adjusted_Stack_Size : Interfaces.C.size_t;
876       Result              : Interfaces.C.int;
877
878       function Thread_Body_Access is new
879         Unchecked_Conversion (System.Address, Thread_Body);
880
881       use System.Task_Info;
882
883    begin
884       if Stack_Size = Unspecified_Size then
885          Adjusted_Stack_Size := Interfaces.C.size_t (Default_Stack_Size);
886
887       elsif Stack_Size < Minimum_Stack_Size then
888          Adjusted_Stack_Size := Interfaces.C.size_t (Minimum_Stack_Size);
889
890       else
891          Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size);
892       end if;
893
894       if Stack_Base_Available then
895          --  If Stack Checking is supported then allocate 2 additional pages:
896          --
897          --  In the worst case, stack is allocated at something like
898          --  N * Get_Page_Size - epsilon, we need to add the size for 2 pages
899          --  to be sure the effective stack size is greater than what
900          --  has been asked.
901
902          Adjusted_Stack_Size := Adjusted_Stack_Size + 2 * Get_Page_Size;
903       end if;
904
905       Result := pthread_attr_init (Attributes'Access);
906       pragma Assert (Result = 0 or else Result = ENOMEM);
907
908       if Result /= 0 then
909          Succeeded := False;
910          return;
911       end if;
912
913       Result := pthread_attr_setdetachstate
914         (Attributes'Access, PTHREAD_CREATE_DETACHED);
915       pragma Assert (Result = 0);
916
917       Result := pthread_attr_setstacksize
918         (Attributes'Access, Adjusted_Stack_Size);
919       pragma Assert (Result = 0);
920
921       if T.Common.Task_Info /= Default_Scope then
922
923          --  We are assuming that Scope_Type has the same values than the
924          --  corresponding C macros
925
926          Result := pthread_attr_setscope
927            (Attributes'Access, Task_Info_Type'Pos (T.Common.Task_Info));
928          pragma Assert (Result = 0);
929       end if;
930
931       --  Since the initial signal mask of a thread is inherited from the
932       --  creator, and the Environment task has all its signals masked, we
933       --  do not need to manipulate caller's signal mask at this point.
934       --  All tasks in RTS will have All_Tasks_Mask initially.
935
936       Result := pthread_create
937         (T.Common.LL.Thread'Access,
938          Attributes'Access,
939          Thread_Body_Access (Wrapper),
940          To_Address (T));
941       pragma Assert (Result = 0 or else Result = EAGAIN);
942
943       Succeeded := Result = 0;
944
945       Result := pthread_attr_destroy (Attributes'Access);
946       pragma Assert (Result = 0);
947
948       Set_Priority (T, Priority);
949    end Create_Task;
950
951    ------------------
952    -- Finalize_TCB --
953    ------------------
954
955    procedure Finalize_TCB (T : Task_ID) is
956       Result : Interfaces.C.int;
957       Tmp    : Task_ID := T;
958
959       procedure Free is new
960         Unchecked_Deallocation (Ada_Task_Control_Block, Task_ID);
961
962    begin
963       if not Single_Lock then
964          Result := pthread_mutex_destroy (T.Common.LL.L'Access);
965          pragma Assert (Result = 0);
966       end if;
967
968       Result := pthread_cond_destroy (T.Common.LL.CV'Access);
969       pragma Assert (Result = 0);
970
971       if T.Known_Tasks_Index /= -1 then
972          Known_Tasks (T.Known_Tasks_Index) := null;
973       end if;
974
975       Free (Tmp);
976    end Finalize_TCB;
977
978    ---------------
979    -- Exit_Task --
980    ---------------
981
982    procedure Exit_Task is
983    begin
984       pthread_exit (System.Null_Address);
985    end Exit_Task;
986
987    ----------------
988    -- Abort_Task --
989    ----------------
990
991    procedure Abort_Task (T : Task_ID) is
992       Result : Interfaces.C.int;
993
994    begin
995       Result := pthread_kill (T.Common.LL.Thread,
996         Signal (System.Interrupt_Management.Abort_Task_Interrupt));
997       pragma Assert (Result = 0);
998    end Abort_Task;
999
1000    ----------------
1001    -- Check_Exit --
1002    ----------------
1003
1004    --  Dummy versions. The only currently working versions is for solaris
1005    --  (native).
1006
1007    function Check_Exit (Self_ID : ST.Task_ID) return Boolean is
1008    begin
1009       return True;
1010    end Check_Exit;
1011
1012    --------------------
1013    -- Check_No_Locks --
1014    --------------------
1015
1016    function Check_No_Locks (Self_ID : ST.Task_ID) return Boolean is
1017    begin
1018       return True;
1019    end Check_No_Locks;
1020
1021    ----------------------
1022    -- Environment_Task --
1023    ----------------------
1024
1025    function Environment_Task return Task_ID is
1026    begin
1027       return Environment_Task_ID;
1028    end Environment_Task;
1029
1030    --------------
1031    -- Lock_RTS --
1032    --------------
1033
1034    procedure Lock_RTS is
1035    begin
1036       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1037    end Lock_RTS;
1038
1039    ----------------
1040    -- Unlock_RTS --
1041    ----------------
1042
1043    procedure Unlock_RTS is
1044    begin
1045       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1046    end Unlock_RTS;
1047
1048    ------------------
1049    -- Suspend_Task --
1050    ------------------
1051
1052    function Suspend_Task
1053      (T           : ST.Task_ID;
1054       Thread_Self : Thread_Id) return Boolean is
1055    begin
1056       return False;
1057    end Suspend_Task;
1058
1059    -----------------
1060    -- Resume_Task --
1061    -----------------
1062
1063    function Resume_Task
1064      (T           : ST.Task_ID;
1065       Thread_Self : Thread_Id) return Boolean is
1066    begin
1067       return False;
1068    end Resume_Task;
1069
1070    ----------------
1071    -- Initialize --
1072    ----------------
1073
1074    procedure Initialize (Environment_Task : Task_ID) is
1075       act     : aliased struct_sigaction;
1076       old_act : aliased struct_sigaction;
1077       Tmp_Set : aliased sigset_t;
1078       Result  : Interfaces.C.int;
1079
1080    begin
1081       Environment_Task_ID := Environment_Task;
1082
1083       --  Initialize the lock used to synchronize chain of all ATCBs.
1084
1085       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1086
1087       Specific.Initialize (Environment_Task);
1088
1089       Enter_Task (Environment_Task);
1090
1091       --  Install the abort-signal handler
1092
1093       act.sa_flags := 0;
1094       act.sa_handler := Abort_Handler'Address;
1095
1096       Result := sigemptyset (Tmp_Set'Access);
1097       pragma Assert (Result = 0);
1098       act.sa_mask := Tmp_Set;
1099
1100       Result :=
1101         sigaction (
1102           Signal (System.Interrupt_Management.Abort_Task_Interrupt),
1103           act'Unchecked_Access,
1104           old_act'Unchecked_Access);
1105
1106       pragma Assert (Result = 0);
1107    end Initialize;
1108
1109 begin
1110    declare
1111       Result : Interfaces.C.int;
1112    begin
1113       --  Mask Environment task for all signals. The original mask of the
1114       --  Environment task will be recovered by Interrupt_Server task
1115       --  during the elaboration of s-interr.adb.
1116
1117       System.Interrupt_Management.Operations.Set_Interrupt_Mask
1118         (System.Interrupt_Management.Operations.All_Tasks_Mask'Access);
1119
1120       --  Prepare the set of signals that should unblocked in all tasks
1121
1122       Result := sigemptyset (Unblocked_Signal_Mask'Access);
1123       pragma Assert (Result = 0);
1124
1125       for J in Interrupt_Management.Interrupt_ID loop
1126          if System.Interrupt_Management.Keep_Unmasked (J) then
1127             Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1128             pragma Assert (Result = 0);
1129          end if;
1130       end loop;
1131    end;
1132 end System.Task_Primitives.Operations;