OSDN Git Service

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