OSDN Git Service

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