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