OSDN Git Service

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