OSDN Git Service

2011-08-05 Yannick Moy <moy@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-2011, 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    Environment_Task_Id : Task_Id;
82    --  A variable to hold Task_Id for the environment task
83
84    Locking_Policy : Character;
85    pragma Import (C, Locking_Policy, "__gl_locking_policy");
86
87    Time_Slice_Val : Integer;
88    pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
89
90    Dispatching_Policy : Character;
91    pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
92
93    Real_Time_Clock_Id : constant clockid_t := CLOCK_REALTIME;
94
95    Unblocked_Signal_Mask : aliased sigset_t;
96
97    Foreign_Task_Elaborated : aliased Boolean := True;
98    --  Used to identified fake tasks (i.e., non-Ada Threads)
99
100    Abort_Handler_Installed : Boolean := False;
101    --  True if a handler for the abort signal is installed
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's not safe to raise an exception when using GCC ZCX mechanism.
163       --  Note that we still need to install a signal handler, since in some
164       --  cases (e.g. shutdown of the Server_Task in System.Interrupts) we
165       --  need to send the Abort signal to a task.
166
167       if ZCX_By_Default and then GCC_ZCX_Support then
168          return;
169       end if;
170
171       if T.Deferral_Level = 0
172         and then T.Pending_ATC_Level < T.ATC_Nesting_Level
173       then
174          --  Make sure signals used for RTS internal purpose are unmasked
175
176          Result := pthread_sigmask
177            (SIG_UNBLOCK,
178             Unblocked_Signal_Mask'Access,
179             Old_Set'Access);
180          pragma Assert (Result = 0);
181
182          raise Standard'Abort_Signal;
183       end if;
184    end Abort_Handler;
185
186    -----------------
187    -- Stack_Guard --
188    -----------------
189
190    --  The underlying thread system sets a guard page at the
191    --  bottom of a thread stack, so nothing is needed.
192
193    procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
194       pragma Unreferenced (On);
195       pragma Unreferenced (T);
196    begin
197       null;
198    end Stack_Guard;
199
200    -------------------
201    -- Get_Thread_Id --
202    -------------------
203
204    function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
205    begin
206       return T.Common.LL.Thread;
207    end Get_Thread_Id;
208
209    ----------
210    -- Self --
211    ----------
212
213    function Self return Task_Id renames Specific.Self;
214
215    ---------------------
216    -- Initialize_Lock --
217    ---------------------
218
219    --  Note: mutexes and cond_variables needed per-task basis are initialized
220    --  in Initialize_TCB and the Storage_Error is handled. Other mutexes (such
221    --  as RTS_Lock, Memory_Lock...) used in RTS is initialized before any
222    --  status change of RTS. Therefore raising Storage_Error in the following
223    --  routines should be able to be handled safely.
224
225    procedure Initialize_Lock
226      (Prio : System.Any_Priority;
227       L    : not null access Lock)
228    is
229       Attributes : aliased pthread_mutexattr_t;
230       Result     : Interfaces.C.int;
231
232    begin
233       Result := pthread_mutexattr_init (Attributes'Access);
234       pragma Assert (Result = 0 or else Result = ENOMEM);
235
236       if Result = ENOMEM then
237          raise Storage_Error;
238       end if;
239
240       if Locking_Policy = 'C' then
241          Result :=
242            pthread_mutexattr_setprotocol
243              (Attributes'Access, PTHREAD_PRIO_PROTECT);
244          pragma Assert (Result = 0);
245
246          Result :=
247            pthread_mutexattr_setprioceiling
248              (Attributes'Access, Interfaces.C.int (Prio));
249          pragma Assert (Result = 0);
250       end if;
251
252       Result := pthread_mutex_init (L, Attributes'Access);
253       pragma Assert (Result = 0 or else Result = ENOMEM);
254
255       if Result = ENOMEM then
256          Result := pthread_mutexattr_destroy (Attributes'Access);
257          raise Storage_Error;
258       end if;
259
260       Result := pthread_mutexattr_destroy (Attributes'Access);
261       pragma Assert (Result = 0);
262    end Initialize_Lock;
263
264    procedure Initialize_Lock
265      (L     : not null access RTS_Lock;
266       Level : Lock_Level)
267    is
268       pragma Unreferenced (Level);
269
270       Attributes : aliased pthread_mutexattr_t;
271       Result : Interfaces.C.int;
272
273    begin
274       Result := pthread_mutexattr_init (Attributes'Access);
275       pragma Assert (Result = 0 or else Result = ENOMEM);
276
277       if Result = ENOMEM then
278          raise Storage_Error;
279       end if;
280
281       if Locking_Policy = 'C' then
282          Result := pthread_mutexattr_setprotocol
283            (Attributes'Access, PTHREAD_PRIO_PROTECT);
284          pragma Assert (Result = 0);
285
286          Result := pthread_mutexattr_setprioceiling
287             (Attributes'Access, Interfaces.C.int (System.Any_Priority'Last));
288          pragma Assert (Result = 0);
289       end if;
290
291       Result := pthread_mutex_init (L, Attributes'Access);
292
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);
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; Ceiling_Violation : out Boolean)
328    is
329       Result : Interfaces.C.int;
330
331    begin
332       Result := pthread_mutex_lock (L);
333       Ceiling_Violation := Result = EINVAL;
334
335       --  Assumes the cause of EINVAL is a priority ceiling violation
336
337       pragma Assert (Result = 0 or else Result = EINVAL);
338    end Write_Lock;
339
340    procedure Write_Lock
341      (L           : not null access RTS_Lock;
342       Global_Lock : Boolean := False)
343    is
344       Result : Interfaces.C.int;
345    begin
346       if not Single_Lock or else Global_Lock then
347          Result := pthread_mutex_lock (L);
348          pragma Assert (Result = 0);
349       end if;
350    end Write_Lock;
351
352    procedure Write_Lock (T : Task_Id) is
353       Result : Interfaces.C.int;
354    begin
355       if not Single_Lock then
356          Result := pthread_mutex_lock (T.Common.LL.L'Access);
357          pragma Assert (Result = 0);
358       end if;
359    end Write_Lock;
360
361    ---------------
362    -- Read_Lock --
363    ---------------
364
365    procedure Read_Lock
366      (L : not null access Lock; Ceiling_Violation : out Boolean) is
367    begin
368       Write_Lock (L, Ceiling_Violation);
369    end Read_Lock;
370
371    ------------
372    -- Unlock --
373    ------------
374
375    procedure Unlock (L : not null access Lock) is
376       Result : Interfaces.C.int;
377    begin
378       Result := pthread_mutex_unlock (L);
379       pragma Assert (Result = 0);
380    end Unlock;
381
382    procedure Unlock
383      (L           : not null access RTS_Lock;
384       Global_Lock : Boolean := False)
385    is
386       Result : Interfaces.C.int;
387    begin
388       if not Single_Lock or else Global_Lock then
389          Result := pthread_mutex_unlock (L);
390          pragma Assert (Result = 0);
391       end if;
392    end Unlock;
393
394    procedure Unlock (T : Task_Id) is
395       Result : Interfaces.C.int;
396    begin
397       if not Single_Lock then
398          Result := pthread_mutex_unlock (T.Common.LL.L'Access);
399          pragma Assert (Result = 0);
400       end if;
401    end Unlock;
402
403    -----------------
404    -- Set_Ceiling --
405    -----------------
406
407    --  Dynamic priority ceilings are not supported by the underlying system
408
409    procedure Set_Ceiling
410      (L    : not null access Lock;
411       Prio : System.Any_Priority)
412    is
413       pragma Unreferenced (L, Prio);
414    begin
415       null;
416    end Set_Ceiling;
417
418    -----------
419    -- Sleep --
420    -----------
421
422    procedure Sleep
423      (Self_ID : ST.Task_Id;
424       Reason  : System.Tasking.Task_States)
425    is
426       pragma Unreferenced (Reason);
427       Result : Interfaces.C.int;
428
429    begin
430       Result :=
431         pthread_cond_wait
432           (cond  => Self_ID.Common.LL.CV'Access,
433            mutex => (if Single_Lock
434                      then Single_RTS_Lock'Access
435                      else Self_ID.Common.LL.L'Access));
436
437       --  EINTR is not considered a failure
438
439       pragma Assert (Result = 0 or else Result = EINTR);
440    end Sleep;
441
442    -----------------
443    -- Timed_Sleep --
444    -----------------
445
446    procedure Timed_Sleep
447      (Self_ID  : Task_Id;
448       Time     : Duration;
449       Mode     : ST.Delay_Modes;
450       Reason   : Task_States;
451       Timedout : out Boolean;
452       Yielded  : out Boolean)
453    is
454       pragma Unreferenced (Reason);
455
456       Base_Time  : constant Duration := Monotonic_Clock;
457       Check_Time : Duration := Base_Time;
458       Abs_Time   : Duration;
459       Request    : aliased timespec;
460       Result     : Interfaces.C.int;
461
462    begin
463       Timedout := True;
464       Yielded  := False;
465
466       Abs_Time :=
467         (if Mode = Relative
468          then Duration'Min (Time, Max_Sensible_Delay) + Check_Time
469          else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
470
471       if Abs_Time > Check_Time then
472          Request := To_Timespec (Abs_Time);
473
474          loop
475             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
476
477             Result :=
478               pthread_cond_timedwait
479                 (cond    => Self_ID.Common.LL.CV'Access,
480                  mutex   => (if Single_Lock
481                              then Single_RTS_Lock'Access
482                              else Self_ID.Common.LL.L'Access),
483                  abstime => Request'Access);
484
485             Check_Time := Monotonic_Clock;
486             exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
487
488             if Result = 0 or else errno = EINTR then
489                Timedout := False;
490                exit;
491             end if;
492          end loop;
493       end if;
494    end Timed_Sleep;
495
496    -----------------
497    -- Timed_Delay --
498    -----------------
499
500    --  This is for use in implementing delay statements, so we assume
501    --  the caller is abort-deferred but is holding no locks.
502
503    procedure Timed_Delay
504      (Self_ID : Task_Id;
505       Time    : Duration;
506       Mode    : ST.Delay_Modes)
507    is
508       Base_Time  : constant Duration := Monotonic_Clock;
509       Check_Time : Duration := Base_Time;
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       Abs_Time :=
522         (if Mode = Relative
523          then Time + Check_Time
524          else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
525
526       if Abs_Time > Check_Time then
527          Request := To_Timespec (Abs_Time);
528          Self_ID.Common.State := Delay_Sleep;
529
530          loop
531             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
532
533             Result :=
534               pthread_cond_timedwait
535                 (cond    => Self_ID.Common.LL.CV'Access,
536                  mutex   => (if Single_Lock
537                              then Single_RTS_Lock'Access
538                              else Self_ID.Common.LL.L'Access),
539                  abstime => Request'Access);
540
541             Check_Time := Monotonic_Clock;
542             exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
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 Ada.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 Ada.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    end Enter_Task;
701
702    --------------
703    -- New_ATCB --
704    --------------
705
706    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
707    begin
708       return new Ada_Task_Control_Block (Entry_Num);
709    end New_ATCB;
710
711    -------------------
712    -- Is_Valid_Task --
713    -------------------
714
715    function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
716
717    -----------------------------
718    -- Register_Foreign_Thread --
719    -----------------------------
720
721    function Register_Foreign_Thread return Task_Id is
722    begin
723       if Is_Valid_Task then
724          return Self;
725       else
726          return Register_Foreign_Thread (pthread_self);
727       end if;
728    end Register_Foreign_Thread;
729
730    --------------------
731    -- Initialize_TCB --
732    --------------------
733
734    procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
735       Result    : Interfaces.C.int;
736       Cond_Attr : aliased pthread_condattr_t;
737
738    begin
739       if not Single_Lock then
740          Initialize_Lock (Self_ID.Common.LL.L'Access, ATCB_Level);
741       end if;
742
743       Result := pthread_condattr_init (Cond_Attr'Access);
744       pragma Assert (Result = 0 or else Result = ENOMEM);
745
746       if Result = 0 then
747          Result :=
748            pthread_cond_init (Self_ID.Common.LL.CV'Access, Cond_Attr'Access);
749          pragma Assert (Result = 0 or else Result = ENOMEM);
750       end if;
751
752       if Result = 0 then
753          Succeeded := True;
754       else
755          if not Single_Lock then
756             Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access);
757             pragma Assert (Result = 0);
758          end if;
759
760          Succeeded := False;
761       end if;
762
763       Result := pthread_condattr_destroy (Cond_Attr'Access);
764       pragma Assert (Result = 0);
765    end Initialize_TCB;
766
767    -----------------
768    -- Create_Task --
769    -----------------
770
771    procedure Create_Task
772      (T          : Task_Id;
773       Wrapper    : System.Address;
774       Stack_Size : System.Parameters.Size_Type;
775       Priority   : System.Any_Priority;
776       Succeeded  : out Boolean)
777    is
778       use System.Task_Info;
779
780       Attributes  : aliased pthread_attr_t;
781       Sched_Param : aliased struct_sched_param;
782       Result      : Interfaces.C.int;
783
784       function Thread_Body_Access is new
785         Ada.Unchecked_Conversion (System.Address, Thread_Body);
786       function To_Int is new Ada.Unchecked_Conversion
787         (System.Task_Info.Thread_Scheduling_Scope, Interfaces.C.int);
788       function To_Int is new Ada.Unchecked_Conversion
789         (System.Task_Info.Thread_Scheduling_Inheritance, Interfaces.C.int);
790       function To_Int is new Ada.Unchecked_Conversion
791         (System.Task_Info.Thread_Scheduling_Policy, Interfaces.C.int);
792
793    begin
794       Result := pthread_attr_init (Attributes'Access);
795       pragma Assert (Result = 0 or else Result = ENOMEM);
796
797       if Result /= 0 then
798          Succeeded := False;
799          return;
800       end if;
801
802       Result :=
803         pthread_attr_setdetachstate
804           (Attributes'Access, PTHREAD_CREATE_DETACHED);
805       pragma Assert (Result = 0);
806
807       Result :=
808         pthread_attr_setstacksize
809           (Attributes'Access, Interfaces.C.size_t (Stack_Size));
810       pragma Assert (Result = 0);
811
812       if T.Common.Task_Info /= null then
813          Result :=
814            pthread_attr_setscope
815              (Attributes'Access, To_Int (T.Common.Task_Info.Scope));
816          pragma Assert (Result = 0);
817
818          Result :=
819            pthread_attr_setinheritsched
820              (Attributes'Access, To_Int (T.Common.Task_Info.Inheritance));
821          pragma Assert (Result = 0);
822
823          Result :=
824            pthread_attr_setschedpolicy
825              (Attributes'Access, To_Int (T.Common.Task_Info.Policy));
826          pragma Assert (Result = 0);
827
828          Sched_Param.sched_priority :=
829            Interfaces.C.int (T.Common.Task_Info.Priority);
830
831          Result :=
832            pthread_attr_setschedparam
833              (Attributes'Access, Sched_Param'Access);
834          pragma Assert (Result = 0);
835       end if;
836
837       --  Since the initial signal mask of a thread is inherited from the
838       --  creator, and the Environment task has all its signals masked, we
839       --  do not need to manipulate caller's signal mask at this point.
840       --  All tasks in RTS will have All_Tasks_Mask initially.
841
842       Result :=
843         pthread_create
844           (T.Common.LL.Thread'Access,
845            Attributes'Access,
846            Thread_Body_Access (Wrapper),
847            To_Address (T));
848
849       if Result /= 0
850         and then T.Common.Task_Info /= null
851         and then T.Common.Task_Info.Scope = PTHREAD_SCOPE_SYSTEM
852       then
853          --  The pthread_create call may have failed because we asked for a
854          --  system scope pthread and none were available (probably because
855          --  the program was not executed by the superuser). Let's try for
856          --  a process scope pthread instead of raising Tasking_Error.
857
858          System.IO.Put_Line
859            ("Request for PTHREAD_SCOPE_SYSTEM in Task_Info pragma for task");
860          System.IO.Put ("""");
861          System.IO.Put (T.Common.Task_Image (1 .. T.Common.Task_Image_Len));
862          System.IO.Put_Line (""" could not be honored. ");
863          System.IO.Put_Line ("Scope changed to PTHREAD_SCOPE_PROCESS");
864
865          T.Common.Task_Info.Scope := PTHREAD_SCOPE_PROCESS;
866          Result :=
867            pthread_attr_setscope
868              (Attributes'Access, To_Int (T.Common.Task_Info.Scope));
869          pragma Assert (Result = 0);
870
871          Result :=
872            pthread_create
873              (T.Common.LL.Thread'Access,
874               Attributes'Access,
875               Thread_Body_Access (Wrapper),
876               To_Address (T));
877       end if;
878
879       pragma Assert (Result = 0 or else Result = EAGAIN);
880
881       Succeeded := Result = 0;
882
883       if Succeeded then
884
885          --  The following needs significant commenting ???
886
887          if T.Common.Task_Info /= null then
888             T.Common.Base_Priority := T.Common.Task_Info.Priority;
889             Set_Priority (T, T.Common.Task_Info.Priority);
890          else
891             Set_Priority (T, Priority);
892          end if;
893       end if;
894
895       Result := pthread_attr_destroy (Attributes'Access);
896       pragma Assert (Result = 0);
897    end Create_Task;
898
899    ------------------
900    -- Finalize_TCB --
901    ------------------
902
903    procedure Finalize_TCB (T : Task_Id) is
904       Result  : Interfaces.C.int;
905       Tmp     : Task_Id := T;
906       Is_Self : constant Boolean := T = Self;
907
908       procedure Free is new
909         Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
910
911    begin
912       if not Single_Lock then
913          Result := pthread_mutex_destroy (T.Common.LL.L'Access);
914          pragma Assert (Result = 0);
915       end if;
916
917       Result := pthread_cond_destroy (T.Common.LL.CV'Access);
918       pragma Assert (Result = 0);
919
920       if T.Known_Tasks_Index /= -1 then
921          Known_Tasks (T.Known_Tasks_Index) := null;
922       end if;
923
924       Free (Tmp);
925
926       if Is_Self then
927          Specific.Set (null);
928       end if;
929    end Finalize_TCB;
930
931    ---------------
932    -- Exit_Task --
933    ---------------
934
935    procedure Exit_Task is
936    begin
937       Specific.Set (null);
938    end Exit_Task;
939
940    ----------------
941    -- Abort_Task --
942    ----------------
943
944    procedure Abort_Task (T : Task_Id) is
945       Result : Interfaces.C.int;
946    begin
947       if Abort_Handler_Installed then
948          Result :=
949            pthread_kill
950              (T.Common.LL.Thread,
951               Signal (System.Interrupt_Management.Abort_Task_Interrupt));
952          pragma Assert (Result = 0);
953       end if;
954    end Abort_Task;
955
956    ----------------
957    -- Initialize --
958    ----------------
959
960    procedure Initialize (S : in out Suspension_Object) is
961       Mutex_Attr : aliased pthread_mutexattr_t;
962       Cond_Attr  : aliased pthread_condattr_t;
963       Result     : Interfaces.C.int;
964
965    begin
966       --  Initialize internal state (always to False (RM D.10(6))
967
968       S.State := False;
969       S.Waiting := False;
970
971       --  Initialize internal mutex
972
973       Result := pthread_mutexattr_init (Mutex_Attr'Access);
974       pragma Assert (Result = 0 or else Result = ENOMEM);
975
976       if Result = ENOMEM then
977          raise Storage_Error;
978       end if;
979
980       Result := pthread_mutex_init (S.L'Access, Mutex_Attr'Access);
981       pragma Assert (Result = 0 or else Result = ENOMEM);
982
983       if Result = ENOMEM then
984          Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
985          pragma Assert (Result = 0);
986
987          raise Storage_Error;
988       end if;
989
990       Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
991       pragma Assert (Result = 0);
992
993       --  Initialize internal condition variable
994
995       Result := pthread_condattr_init (Cond_Attr'Access);
996       pragma Assert (Result = 0 or else Result = ENOMEM);
997
998       if Result /= 0 then
999          Result := pthread_mutex_destroy (S.L'Access);
1000          pragma Assert (Result = 0);
1001
1002          if Result = ENOMEM then
1003             raise Storage_Error;
1004          end if;
1005       end if;
1006
1007       Result := pthread_cond_init (S.CV'Access, Cond_Attr'Access);
1008       pragma Assert (Result = 0 or else Result = ENOMEM);
1009
1010       if Result /= 0 then
1011          Result := pthread_mutex_destroy (S.L'Access);
1012          pragma Assert (Result = 0);
1013
1014          if Result = ENOMEM then
1015             Result := pthread_condattr_destroy (Cond_Attr'Access);
1016             pragma Assert (Result = 0);
1017             raise Storage_Error;
1018          end if;
1019       end if;
1020
1021       Result := pthread_condattr_destroy (Cond_Attr'Access);
1022       pragma Assert (Result = 0);
1023    end Initialize;
1024
1025    --------------
1026    -- Finalize --
1027    --------------
1028
1029    procedure Finalize (S : in out Suspension_Object) is
1030       Result : Interfaces.C.int;
1031
1032    begin
1033       --  Destroy internal mutex
1034
1035       Result := pthread_mutex_destroy (S.L'Access);
1036       pragma Assert (Result = 0);
1037
1038       --  Destroy internal condition variable
1039
1040       Result := pthread_cond_destroy (S.CV'Access);
1041       pragma Assert (Result = 0);
1042    end Finalize;
1043
1044    -------------------
1045    -- Current_State --
1046    -------------------
1047
1048    function Current_State (S : Suspension_Object) return Boolean is
1049    begin
1050       --  We do not want to use lock on this read operation. State is marked
1051       --  as Atomic so that we ensure that the value retrieved is correct.
1052
1053       return S.State;
1054    end Current_State;
1055
1056    ---------------
1057    -- Set_False --
1058    ---------------
1059
1060    procedure Set_False (S : in out Suspension_Object) is
1061       Result : Interfaces.C.int;
1062
1063    begin
1064       SSL.Abort_Defer.all;
1065
1066       Result := pthread_mutex_lock (S.L'Access);
1067       pragma Assert (Result = 0);
1068
1069       S.State := False;
1070
1071       Result := pthread_mutex_unlock (S.L'Access);
1072       pragma Assert (Result = 0);
1073
1074       SSL.Abort_Undefer.all;
1075    end Set_False;
1076
1077    --------------
1078    -- Set_True --
1079    --------------
1080
1081    procedure Set_True (S : in out Suspension_Object) is
1082       Result : Interfaces.C.int;
1083
1084    begin
1085       SSL.Abort_Defer.all;
1086
1087       Result := pthread_mutex_lock (S.L'Access);
1088       pragma Assert (Result = 0);
1089
1090       --  If there is already a task waiting on this suspension object then
1091       --  we resume it, leaving the state of the suspension object to False,
1092       --  as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1093       --  the state to True.
1094
1095       if S.Waiting then
1096          S.Waiting := False;
1097          S.State := False;
1098
1099          Result := pthread_cond_signal (S.CV'Access);
1100          pragma Assert (Result = 0);
1101
1102       else
1103          S.State := True;
1104       end if;
1105
1106       Result := pthread_mutex_unlock (S.L'Access);
1107       pragma Assert (Result = 0);
1108
1109       SSL.Abort_Undefer.all;
1110    end Set_True;
1111
1112    ------------------------
1113    -- Suspend_Until_True --
1114    ------------------------
1115
1116    procedure Suspend_Until_True (S : in out Suspension_Object) is
1117       Result : Interfaces.C.int;
1118
1119    begin
1120       SSL.Abort_Defer.all;
1121
1122       Result := pthread_mutex_lock (S.L'Access);
1123       pragma Assert (Result = 0);
1124
1125       if S.Waiting then
1126
1127          --  Program_Error must be raised upon calling Suspend_Until_True
1128          --  if another task is already waiting on that suspension object
1129          --  (RM D.10(10)).
1130
1131          Result := pthread_mutex_unlock (S.L'Access);
1132          pragma Assert (Result = 0);
1133
1134          SSL.Abort_Undefer.all;
1135
1136          raise Program_Error;
1137       else
1138          --  Suspend the task if the state is False. Otherwise, the task
1139          --  continues its execution, and the state of the suspension object
1140          --  is set to False (ARM D.10 par. 9).
1141
1142          if S.State then
1143             S.State := False;
1144          else
1145             S.Waiting := True;
1146
1147             loop
1148                --  Loop in case pthread_cond_wait returns earlier than expected
1149                --  (e.g. in case of EINTR caused by a signal).
1150
1151                Result := pthread_cond_wait (S.CV'Access, S.L'Access);
1152                pragma Assert (Result = 0 or else Result = EINTR);
1153
1154                exit when not S.Waiting;
1155             end loop;
1156          end if;
1157
1158          Result := pthread_mutex_unlock (S.L'Access);
1159          pragma Assert (Result = 0);
1160
1161          SSL.Abort_Undefer.all;
1162       end if;
1163    end Suspend_Until_True;
1164
1165    ----------------
1166    -- Check_Exit --
1167    ----------------
1168
1169    --  Dummy version
1170
1171    function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1172       pragma Unreferenced (Self_ID);
1173    begin
1174       return True;
1175    end Check_Exit;
1176
1177    --------------------
1178    -- Check_No_Locks --
1179    --------------------
1180
1181    function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1182       pragma Unreferenced (Self_ID);
1183    begin
1184       return True;
1185    end Check_No_Locks;
1186
1187    ----------------------
1188    -- Environment_Task --
1189    ----------------------
1190
1191    function Environment_Task return Task_Id is
1192    begin
1193       return Environment_Task_Id;
1194    end Environment_Task;
1195
1196    --------------
1197    -- Lock_RTS --
1198    --------------
1199
1200    procedure Lock_RTS is
1201    begin
1202       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1203    end Lock_RTS;
1204
1205    ----------------
1206    -- Unlock_RTS --
1207    ----------------
1208
1209    procedure Unlock_RTS is
1210    begin
1211       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1212    end Unlock_RTS;
1213
1214    ------------------
1215    -- Suspend_Task --
1216    ------------------
1217
1218    function Suspend_Task
1219      (T           : ST.Task_Id;
1220       Thread_Self : Thread_Id) return Boolean
1221    is
1222       pragma Unreferenced (T);
1223       pragma Unreferenced (Thread_Self);
1224    begin
1225       return False;
1226    end Suspend_Task;
1227
1228    -----------------
1229    -- Resume_Task --
1230    -----------------
1231
1232    function Resume_Task
1233      (T           : ST.Task_Id;
1234       Thread_Self : Thread_Id) return Boolean
1235    is
1236       pragma Unreferenced (T);
1237       pragma Unreferenced (Thread_Self);
1238    begin
1239       return False;
1240    end Resume_Task;
1241
1242    --------------------
1243    -- Stop_All_Tasks --
1244    --------------------
1245
1246    procedure Stop_All_Tasks is
1247    begin
1248       null;
1249    end Stop_All_Tasks;
1250
1251    ---------------
1252    -- Stop_Task --
1253    ---------------
1254
1255    function Stop_Task (T : ST.Task_Id) return Boolean is
1256       pragma Unreferenced (T);
1257    begin
1258       return False;
1259    end Stop_Task;
1260
1261    -------------------
1262    -- Continue_Task --
1263    -------------------
1264
1265    function Continue_Task (T : ST.Task_Id) return Boolean is
1266       pragma Unreferenced (T);
1267    begin
1268       return False;
1269    end Continue_Task;
1270
1271    ----------------
1272    -- Initialize --
1273    ----------------
1274
1275    procedure Initialize (Environment_Task : Task_Id) is
1276       act     : aliased struct_sigaction;
1277       old_act : aliased struct_sigaction;
1278       Tmp_Set : aliased sigset_t;
1279       Result  : Interfaces.C.int;
1280
1281       function State
1282         (Int : System.Interrupt_Management.Interrupt_ID) return Character;
1283       pragma Import (C, State, "__gnat_get_interrupt_state");
1284       --  Get interrupt state. Defined in a-init.c. The input argument is
1285       --  the interrupt number, and the result is one of the following:
1286
1287       Default : constant Character := 's';
1288       --    'n'   this interrupt not set by any Interrupt_State pragma
1289       --    'u'   Interrupt_State pragma set state to User
1290       --    'r'   Interrupt_State pragma set state to Runtime
1291       --    's'   Interrupt_State pragma set state to System (use "default"
1292       --           system handler)
1293
1294    begin
1295       Environment_Task_Id := Environment_Task;
1296
1297       Interrupt_Management.Initialize;
1298
1299       --  Initialize the lock used to synchronize chain of all ATCBs
1300
1301       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1302
1303       Specific.Initialize (Environment_Task);
1304
1305       --  Make environment task known here because it doesn't go through
1306       --  Activate_Tasks, which does it for all other tasks.
1307
1308       Known_Tasks (Known_Tasks'First) := Environment_Task;
1309       Environment_Task.Known_Tasks_Index := Known_Tasks'First;
1310
1311       Enter_Task (Environment_Task);
1312
1313       --  Prepare the set of signals that should unblocked in all tasks
1314
1315       Result := sigemptyset (Unblocked_Signal_Mask'Access);
1316       pragma Assert (Result = 0);
1317
1318       for J in Interrupt_Management.Interrupt_ID loop
1319          if System.Interrupt_Management.Keep_Unmasked (J) then
1320             Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1321             pragma Assert (Result = 0);
1322          end if;
1323       end loop;
1324
1325       if State
1326           (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
1327       then
1328          act.sa_flags := 0;
1329          act.sa_handler := Abort_Handler'Address;
1330
1331          Result := sigemptyset (Tmp_Set'Access);
1332          pragma Assert (Result = 0);
1333          act.sa_mask := Tmp_Set;
1334
1335          Result :=
1336            sigaction
1337              (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
1338               act'Unchecked_Access,
1339               old_act'Unchecked_Access);
1340          pragma Assert (Result = 0);
1341          Abort_Handler_Installed := True;
1342       end if;
1343    end Initialize;
1344
1345 end System.Task_Primitives.Operations;