OSDN Git Service

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