OSDN Git Service

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