OSDN Git Service

Renaming of target specific files for clarity
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-taprop-solaris.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-2004, 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,  59 Temple Place - Suite 330,  Boston, --
20 -- MA 02111-1307, 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 Solaris (native) version of this package
35
36 --  This package contains all the GNULL primitives that interface directly
37 --  with the underlying OS.
38
39 pragma Polling (Off);
40 --  Turn off polling, we do not want ATC polling to take place during
41 --  tasking operations. It causes infinite loops and other problems.
42
43 with System.Tasking.Debug;
44 --  used for Known_Tasks
45
46 with Ada.Exceptions;
47 --  used for Raise_Exception
48
49 with GNAT.OS_Lib;
50 --  used for String_Access, Getenv
51
52 with Interfaces.C;
53 --  used for int
54 --           size_t
55
56 with System.Interrupt_Management;
57 --  used for Keep_Unmasked
58 --           Abort_Task_Interrupt
59 --           Interrupt_ID
60
61 with System.Interrupt_Management.Operations;
62 --  used for Set_Interrupt_Mask
63 --           All_Tasks_Mask
64 pragma Elaborate_All (System.Interrupt_Management.Operations);
65
66 with System.Parameters;
67 --  used for Size_Type
68
69 with System.Tasking;
70 --  used for Ada_Task_Control_Block
71 --           Task_ID
72 --           ATCB components and types
73
74 with System.Task_Info;
75 --  to initialize Task_Info for a C thread, in function Self
76
77 with System.Soft_Links;
78 --  used for Defer/Undefer_Abort
79 --       to initialize TSD for a C thread, in function Self
80
81 --  Note that we do not use System.Tasking.Initialization directly since
82 --  this is a higher level package that we shouldn't depend on. For example
83 --  when using the restricted run time, it is replaced by
84 --  System.Tasking.Restricted.Initialization
85
86 with System.OS_Primitives;
87 --  used for Delay_Modes
88
89 with Unchecked_Deallocation;
90
91 package body System.Task_Primitives.Operations is
92
93    use System.Tasking.Debug;
94    use System.Tasking;
95    use Interfaces.C;
96    use System.OS_Interface;
97    use System.Parameters;
98    use Ada.Exceptions;
99    use System.OS_Primitives;
100
101    package SSL renames System.Soft_Links;
102
103    ----------------
104    -- Local Data --
105    ----------------
106
107    --  The following are logically constants, but need to be initialized
108    --  at run time.
109
110    Environment_Task_ID : Task_ID;
111    --  A variable to hold Task_ID for the environment task.
112    --  If we use this variable to get the Task_ID, we need the following
113    --  ATCB_Key only for non-Ada threads.
114
115    Unblocked_Signal_Mask : aliased sigset_t;
116    --  The set of signals that should unblocked in all tasks
117
118    ATCB_Key : aliased thread_key_t;
119    --  Key used to find the Ada Task_ID associated with a thread,
120    --  at least for C threads unknown to the Ada run-time system.
121
122    Single_RTS_Lock : aliased RTS_Lock;
123    --  This is a lock to allow only one thread of control in the RTS at
124    --  a time; it is used to execute in mutual exclusion from all other tasks.
125    --  Used mainly in Single_Lock mode, but also to protect All_Tasks_List
126
127    Next_Serial_Number : Task_Serial_Number := 100;
128    --  We start at 100, to reserve some special values for
129    --  using in error checking.
130    --  The following are internal configuration constants needed.
131
132    ----------------------
133    -- Priority Support --
134    ----------------------
135
136    Priority_Ceiling_Emulation : constant Boolean := True;
137    --  controls whether we emulate priority ceiling locking
138
139    --  To get a scheduling close to annex D requirements, we use the real-time
140    --  class provided for LWP's and map each task/thread to a specific and
141    --  unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
142
143    --  The real time class can only be set when the process has root
144    --  priviledges, so in the other cases, we use the normal thread scheduling
145    --  and priority handling.
146
147    Using_Real_Time_Class : Boolean := False;
148    --  indicates wether the real time class is being used (i.e the process
149    --  has root priviledges).
150
151    Prio_Param : aliased struct_pcparms;
152    --  Hold priority info (Real_Time) initialized during the package
153    --  elaboration.
154
155    -----------------------------------
156    -- External Configuration Values --
157    -----------------------------------
158
159    Time_Slice_Val : Interfaces.C.long;
160    pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
161
162    Locking_Policy : Character;
163    pragma Import (C, Locking_Policy, "__gl_locking_policy");
164
165    Dispatching_Policy : Character;
166    pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
167
168    Foreign_Task_Elaborated : aliased Boolean := True;
169    --  Used to identified fake tasks (i.e., non-Ada Threads).
170
171    -----------------------
172    -- Local Subprograms --
173    -----------------------
174
175    function sysconf (name : System.OS_Interface.int) return processorid_t;
176    pragma Import (C, sysconf, "sysconf");
177
178    SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
179
180    function Num_Procs
181      (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
182       return processorid_t renames sysconf;
183
184    procedure Abort_Handler
185      (Sig     : Signal;
186       Code    : access siginfo_t;
187       Context : access ucontext_t);
188    --  Target-dependent binding of inter-thread Abort signal to
189    --  the raising of the Abort_Signal exception.
190    --  See also comments in 7staprop.adb
191
192    ------------
193    -- Checks --
194    ------------
195
196    function Check_Initialize_Lock
197      (L     : Lock_Ptr;
198       Level : Lock_Level) return Boolean;
199    pragma Inline (Check_Initialize_Lock);
200
201    function Check_Lock (L : Lock_Ptr) return Boolean;
202    pragma Inline (Check_Lock);
203
204    function Record_Lock (L : Lock_Ptr) return Boolean;
205    pragma Inline (Record_Lock);
206
207    function Check_Sleep (Reason : Task_States) return Boolean;
208    pragma Inline (Check_Sleep);
209
210    function Record_Wakeup
211      (L      : Lock_Ptr;
212       Reason : Task_States) return Boolean;
213    pragma Inline (Record_Wakeup);
214
215    function Check_Wakeup
216      (T      : Task_ID;
217       Reason : Task_States) return Boolean;
218    pragma Inline (Check_Wakeup);
219
220    function Check_Unlock (L : Lock_Ptr) return Boolean;
221    pragma Inline (Check_Unlock);
222
223    function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
224    pragma Inline (Check_Finalize_Lock);
225
226    --------------------
227    -- Local Packages --
228    --------------------
229
230    package Specific is
231
232       procedure Initialize (Environment_Task : Task_ID);
233       pragma Inline (Initialize);
234       --  Initialize various data needed by this package.
235
236       function Is_Valid_Task return Boolean;
237       pragma Inline (Is_Valid_Task);
238       --  Does executing thread have a TCB?
239
240       procedure Set (Self_Id : Task_ID);
241       pragma Inline (Set);
242       --  Set the self id for the current task.
243
244       function Self return Task_ID;
245       pragma Inline (Self);
246       --  Return a pointer to the Ada Task Control Block of the calling task.
247
248    end Specific;
249
250    package body Specific is separate;
251    --  The body of this package is target specific.
252
253    ---------------------------------
254    -- Support for foreign threads --
255    ---------------------------------
256
257    function Register_Foreign_Thread (Thread : Thread_Id) return Task_ID;
258    --  Allocate and Initialize a new ATCB for the current Thread.
259
260    function Register_Foreign_Thread
261      (Thread : Thread_Id) return Task_ID is separate;
262
263    ------------
264    -- Checks --
265    ------------
266
267    Check_Count  : Integer := 0;
268    Lock_Count   : Integer := 0;
269    Unlock_Count : Integer := 0;
270
271    -------------------
272    -- Abort_Handler --
273    -------------------
274
275    procedure Abort_Handler
276      (Sig     : Signal;
277       Code    : access siginfo_t;
278       Context : access ucontext_t)
279    is
280       pragma Unreferenced (Sig);
281       pragma Unreferenced (Code);
282       pragma Unreferenced (Context);
283
284       Self_ID : constant Task_ID := Self;
285       Old_Set : aliased sigset_t;
286
287       Result : Interfaces.C.int;
288       pragma Unreferenced (Result);
289
290    begin
291       --  It is not safe to raise an exception when using ZCX and the GCC
292       --  exception handling mechanism.
293
294       if ZCX_By_Default and then GCC_ZCX_Support then
295          return;
296       end if;
297
298       if Self_ID.Deferral_Level = 0
299         and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
300         and then not Self_ID.Aborting
301       then
302          Self_ID.Aborting := True;
303
304          --  Make sure signals used for RTS internal purpose are unmasked
305
306          Result := thr_sigsetmask (SIG_UNBLOCK,
307            Unblocked_Signal_Mask'Unchecked_Access, Old_Set'Unchecked_Access);
308          pragma Assert (Result = 0);
309
310          raise Standard'Abort_Signal;
311       end if;
312    end Abort_Handler;
313
314    -------------------
315    --  Stack_Guard  --
316    -------------------
317
318    --  The underlying thread system sets a guard page at the
319    --  bottom of a thread stack, so nothing is needed.
320
321    procedure Stack_Guard (T : ST.Task_ID; On : Boolean) is
322       pragma Unreferenced (T);
323       pragma Unreferenced (On);
324
325    begin
326       null;
327    end Stack_Guard;
328
329    --------------------
330    -- Get_Thread_Id  --
331    --------------------
332
333    function Get_Thread_Id (T : ST.Task_ID) return OSI.Thread_Id is
334    begin
335       return T.Common.LL.Thread;
336    end Get_Thread_Id;
337
338    ----------------
339    -- Initialize --
340    ----------------
341
342    procedure Initialize (Environment_Task : ST.Task_ID) is
343       act     : aliased struct_sigaction;
344       old_act : aliased struct_sigaction;
345       Tmp_Set : aliased sigset_t;
346       Result  : Interfaces.C.int;
347
348       procedure Configure_Processors;
349       --  Processors configuration
350       --  The user can specify a processor which the program should run
351       --  on to emulate a single-processor system. This can be easily
352       --  done by setting environment variable GNAT_PROCESSOR to one of
353       --  the following :
354       --
355       --    -2 : use the default configuration (run the program on all
356       --         available processors) - this is the same as having
357       --         GNAT_PROCESSOR unset
358       --    -1 : let the RTS choose one processor and run the program on
359       --         that processor
360       --    0 .. Last_Proc : run the program on the specified processor
361       --
362       --  Last_Proc is equal to the value of the system variable
363       --  _SC_NPROCESSORS_CONF, minus one.
364
365       procedure Configure_Processors is
366          Proc_Acc  : constant GNAT.OS_Lib.String_Access :=
367                        GNAT.OS_Lib.Getenv ("GNAT_PROCESSOR");
368          Proc      : aliased processorid_t;  --  User processor #
369          Last_Proc : processorid_t;          --  Last processor #
370
371       begin
372          if Proc_Acc.all'Length /= 0 then
373             --  Environment variable is defined
374
375             Last_Proc := Num_Procs - 1;
376
377             if Last_Proc /= -1 then
378                Proc := processorid_t'Value (Proc_Acc.all);
379
380                if Proc <= -2  or else Proc > Last_Proc then
381                   --  Use the default configuration
382                   null;
383                elsif Proc = -1 then
384                   --  Choose a processor
385
386                   Result := 0;
387
388                   while Proc < Last_Proc loop
389                      Proc := Proc + 1;
390                      Result := p_online (Proc, PR_STATUS);
391                      exit when Result = PR_ONLINE;
392                   end loop;
393
394                   pragma Assert (Result = PR_ONLINE);
395                   Result := processor_bind (P_PID, P_MYID, Proc, null);
396                   pragma Assert (Result = 0);
397
398                else
399                   --  Use user processor
400
401                   Result := processor_bind (P_PID, P_MYID, Proc, null);
402                   pragma Assert (Result = 0);
403                end if;
404             end if;
405          end if;
406
407       exception
408          when Constraint_Error =>
409
410             --  Illegal environment variable GNAT_PROCESSOR - ignored
411
412             null;
413       end Configure_Processors;
414
415       function State (Int : System.Interrupt_Management.Interrupt_ID)
416                      return Character;
417       pragma Import (C, State, "__gnat_get_interrupt_state");
418       --  Get interrupt state.  Defined in a-init.c
419       --  The input argument is the interrupt number,
420       --  and the result is one of the following:
421
422       Default : constant Character := 's';
423       --    'n'   this interrupt not set by any Interrupt_State pragma
424       --    'u'   Interrupt_State pragma set state to User
425       --    'r'   Interrupt_State pragma set state to Runtime
426       --    's'   Interrupt_State pragma set state to System (use "default"
427       --           system handler)
428
429    --  Start of processing for Initialize
430
431    begin
432       Environment_Task_ID := Environment_Task;
433
434       --  This is done in Enter_Task, but this is too late for the
435       --  Environment Task, since we need to call Self in Check_Locks when
436       --  the run time is compiled with assertions on.
437
438       Specific.Initialize (Environment_Task);
439
440       --  Initialize the lock used to synchronize chain of all ATCBs.
441
442       Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
443
444       Enter_Task (Environment_Task);
445
446       --  Install the abort-signal handler
447
448       if State (System.Interrupt_Management.Abort_Task_Interrupt)
449         /= Default
450       then
451          --  Set sa_flags to SA_NODEFER so that during the handler execution
452          --  we do not change the Signal_Mask to be masked for the Abort_Signal
453          --  This is a temporary fix to the problem that the Signal_Mask is
454          --  not restored after the exception (longjmp) from the handler.
455          --  The right fix should be made in sigsetjmp so that we save
456          --  the Signal_Set and restore it after a longjmp.
457          --  In that case, this field should be changed back to 0. ???
458
459          act.sa_flags := 16;
460
461          act.sa_handler := Abort_Handler'Address;
462          Result := sigemptyset (Tmp_Set'Access);
463          pragma Assert (Result = 0);
464          act.sa_mask := Tmp_Set;
465
466          Result :=
467            sigaction (
468              Signal (System.Interrupt_Management.Abort_Task_Interrupt),
469              act'Unchecked_Access,
470              old_act'Unchecked_Access);
471          pragma Assert (Result = 0);
472       end if;
473
474       Configure_Processors;
475    end Initialize;
476
477    ---------------------
478    -- Initialize_Lock --
479    ---------------------
480
481    --  Note: mutexes and cond_variables needed per-task basis are
482    --        initialized in Initialize_TCB and the Storage_Error is
483    --        handled. Other mutexes (such as RTS_Lock, Memory_Lock...)
484    --        used in RTS is initialized before any status change of RTS.
485    --        Therefore rasing Storage_Error in the following routines
486    --        should be able to be handled safely.
487
488    procedure Initialize_Lock
489      (Prio : System.Any_Priority;
490       L    : access Lock)
491    is
492       Result : Interfaces.C.int;
493
494    begin
495       pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
496
497       if Priority_Ceiling_Emulation then
498          L.Ceiling := Prio;
499       end if;
500
501       Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
502       pragma Assert (Result = 0 or else Result = ENOMEM);
503
504       if Result = ENOMEM then
505          Raise_Exception (Storage_Error'Identity, "Failed to allocate a lock");
506       end if;
507    end Initialize_Lock;
508
509    procedure Initialize_Lock
510      (L : access RTS_Lock;
511       Level : Lock_Level)
512    is
513       Result : Interfaces.C.int;
514
515    begin
516       pragma Assert (Check_Initialize_Lock
517         (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
518       Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
519       pragma Assert (Result = 0 or else Result = ENOMEM);
520
521       if Result = ENOMEM then
522          Raise_Exception (Storage_Error'Identity, "Failed to allocate a lock");
523       end if;
524    end Initialize_Lock;
525
526    -------------------
527    -- Finalize_Lock --
528    -------------------
529
530    procedure Finalize_Lock (L : access Lock) is
531       Result : Interfaces.C.int;
532
533    begin
534       pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
535       Result := mutex_destroy (L.L'Access);
536       pragma Assert (Result = 0);
537    end Finalize_Lock;
538
539    procedure Finalize_Lock (L : access RTS_Lock) is
540       Result : Interfaces.C.int;
541
542    begin
543       pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
544       Result := mutex_destroy (L.L'Access);
545       pragma Assert (Result = 0);
546    end Finalize_Lock;
547
548    ----------------
549    -- Write_Lock --
550    ----------------
551
552    procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
553       Result : Interfaces.C.int;
554
555    begin
556       pragma Assert (Check_Lock (Lock_Ptr (L)));
557
558       if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
559          declare
560             Self_Id        : constant Task_ID := Self;
561             Saved_Priority : System.Any_Priority;
562
563          begin
564             if Self_Id.Common.LL.Active_Priority > L.Ceiling then
565                Ceiling_Violation := True;
566                return;
567             end if;
568
569             Saved_Priority := Self_Id.Common.LL.Active_Priority;
570
571             if Self_Id.Common.LL.Active_Priority < L.Ceiling then
572                Set_Priority (Self_Id, L.Ceiling);
573             end if;
574
575             Result := mutex_lock (L.L'Access);
576             pragma Assert (Result = 0);
577             Ceiling_Violation := False;
578
579             L.Saved_Priority := Saved_Priority;
580          end;
581
582       else
583          Result := mutex_lock (L.L'Access);
584          pragma Assert (Result = 0);
585          Ceiling_Violation := False;
586       end if;
587
588       pragma Assert (Record_Lock (Lock_Ptr (L)));
589    end Write_Lock;
590
591    procedure Write_Lock
592      (L          : access RTS_Lock;
593      Global_Lock : Boolean := False)
594    is
595       Result : Interfaces.C.int;
596
597    begin
598       if not Single_Lock or else Global_Lock then
599          pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
600          Result := mutex_lock (L.L'Access);
601          pragma Assert (Result = 0);
602          pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
603       end if;
604    end Write_Lock;
605
606    procedure Write_Lock (T : Task_ID) is
607       Result : Interfaces.C.int;
608
609    begin
610       if not Single_Lock then
611          pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
612          Result := mutex_lock (T.Common.LL.L.L'Access);
613          pragma Assert (Result = 0);
614          pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
615       end if;
616    end Write_Lock;
617
618    ---------------
619    -- Read_Lock --
620    ---------------
621
622    procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
623    begin
624       Write_Lock (L, Ceiling_Violation);
625    end Read_Lock;
626
627    ------------
628    -- Unlock --
629    ------------
630
631    procedure Unlock (L : access Lock) is
632       Result  : Interfaces.C.int;
633
634    begin
635       pragma Assert (Check_Unlock (Lock_Ptr (L)));
636
637       if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
638          declare
639             Self_Id : constant Task_ID := Self;
640
641          begin
642             Result := mutex_unlock (L.L'Access);
643             pragma Assert (Result = 0);
644
645             if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
646                Set_Priority (Self_Id, L.Saved_Priority);
647             end if;
648          end;
649       else
650          Result := mutex_unlock (L.L'Access);
651          pragma Assert (Result = 0);
652       end if;
653    end Unlock;
654
655    procedure Unlock (L : access RTS_Lock; Global_Lock : Boolean := False) is
656       Result : Interfaces.C.int;
657
658    begin
659       if not Single_Lock or else Global_Lock then
660          pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
661          Result := mutex_unlock (L.L'Access);
662          pragma Assert (Result = 0);
663       end if;
664    end Unlock;
665
666    procedure Unlock (T : Task_ID) is
667       Result : Interfaces.C.int;
668
669    begin
670       if not Single_Lock then
671          pragma Assert (Check_Unlock (To_Lock_Ptr (T.Common.LL.L'Access)));
672          Result := mutex_unlock (T.Common.LL.L.L'Access);
673          pragma Assert (Result = 0);
674       end if;
675    end Unlock;
676
677    --  For the time delay implementation, we need to make sure we
678    --  achieve following criteria:
679
680    --  1) We have to delay at least for the amount requested.
681    --  2) We have to give up CPU even though the actual delay does not
682    --     result in blocking.
683    --  3) Except for restricted run-time systems that do not support
684    --     ATC or task abort, the delay must be interrupted by the
685    --     abort_task operation.
686    --  4) The implementation has to be efficient so that the delay overhead
687    --     is relatively cheap.
688    --  (1)-(3) are Ada requirements. Even though (2) is an Annex-D
689    --     requirement we still want to provide the effect in all cases.
690    --     The reason is that users may want to use short delays to implement
691    --     their own scheduling effect in the absence of language provided
692    --     scheduling policies.
693
694    ---------------------
695    -- Monotonic_Clock --
696    ---------------------
697
698    function Monotonic_Clock return Duration is
699       TS     : aliased timespec;
700       Result : Interfaces.C.int;
701
702    begin
703       Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
704       pragma Assert (Result = 0);
705       return To_Duration (TS);
706    end Monotonic_Clock;
707
708    -------------------
709    -- RT_Resolution --
710    -------------------
711
712    function RT_Resolution return Duration is
713    begin
714       return 10#1.0#E-6;
715    end RT_Resolution;
716
717    -----------
718    -- Yield --
719    -----------
720
721    procedure Yield (Do_Yield : Boolean := True) is
722    begin
723       if Do_Yield then
724          System.OS_Interface.thr_yield;
725       end if;
726    end Yield;
727
728    -----------
729    -- Self ---
730    -----------
731
732    function Self return Task_ID renames Specific.Self;
733
734    ------------------
735    -- Set_Priority --
736    ------------------
737
738    procedure Set_Priority
739      (T                   : Task_ID;
740       Prio                : System.Any_Priority;
741       Loss_Of_Inheritance : Boolean := False)
742    is
743       pragma Unreferenced (Loss_Of_Inheritance);
744
745       Result : Interfaces.C.int;
746       pragma Unreferenced (Result);
747
748       Param   : aliased struct_pcparms;
749
750       use Task_Info;
751
752    begin
753       T.Common.Current_Priority := Prio;
754
755       if Priority_Ceiling_Emulation then
756          T.Common.LL.Active_Priority := Prio;
757       end if;
758
759       if Using_Real_Time_Class then
760          Param.pc_cid := Prio_Param.pc_cid;
761          Param.rt_pri := pri_t (Prio);
762          Param.rt_tqsecs := Prio_Param.rt_tqsecs;
763          Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
764
765          Result := Interfaces.C.int (
766            priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
767              Param'Address));
768
769       else
770          if T.Common.Task_Info /= null
771            and then not T.Common.Task_Info.Bound_To_LWP
772          then
773             --  The task is not bound to a LWP, so use thr_setprio
774
775             Result :=
776               thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
777
778          else
779
780             --  The task is bound to a LWP, use priocntl
781             --  ??? TBD
782
783             null;
784          end if;
785       end if;
786    end Set_Priority;
787
788    ------------------
789    -- Get_Priority --
790    ------------------
791
792    function Get_Priority (T : Task_ID) return System.Any_Priority is
793    begin
794       return T.Common.Current_Priority;
795    end Get_Priority;
796
797    ----------------
798    -- Enter_Task --
799    ----------------
800
801    procedure Enter_Task (Self_ID : Task_ID) is
802       Result    : Interfaces.C.int;
803       Proc      : processorid_t;  --  User processor #
804       Last_Proc : processorid_t;  --  Last processor #
805
806       use System.Task_Info;
807    begin
808       Self_ID.Common.LL.Thread := thr_self;
809
810       Self_ID.Common.LL.LWP := lwp_self;
811
812       if Self_ID.Common.Task_Info /= null then
813          if Self_ID.Common.Task_Info.New_LWP
814            and then Self_ID.Common.Task_Info.CPU /= CPU_UNCHANGED
815          then
816             Last_Proc := Num_Procs - 1;
817
818             if Self_ID.Common.Task_Info.CPU = ANY_CPU then
819                Result := 0;
820                Proc := 0;
821
822                while Proc < Last_Proc loop
823                   Result := p_online (Proc, PR_STATUS);
824                   exit when Result = PR_ONLINE;
825                   Proc := Proc + 1;
826                end loop;
827
828                Result := processor_bind (P_LWPID, P_MYID, Proc, null);
829                pragma Assert (Result = 0);
830
831             else
832                --  Use specified processor
833
834                if Self_ID.Common.Task_Info.CPU < 0
835                  or else Self_ID.Common.Task_Info.CPU > Last_Proc
836                then
837                   raise Invalid_CPU_Number;
838                end if;
839
840                Result := processor_bind
841                  (P_LWPID, P_MYID, Self_ID.Common.Task_Info.CPU, null);
842                pragma Assert (Result = 0);
843             end if;
844          end if;
845       end if;
846
847       Specific.Set (Self_ID);
848
849       --  We need the above code even if we do direct fetch of Task_ID in Self
850       --  for the main task on Sun, x86 Solaris and for gcc 2.7.2.
851
852       Lock_RTS;
853
854       for J in Known_Tasks'Range loop
855          if Known_Tasks (J) = null then
856             Known_Tasks (J) := Self_ID;
857             Self_ID.Known_Tasks_Index := J;
858             exit;
859          end if;
860       end loop;
861
862       Unlock_RTS;
863    end Enter_Task;
864
865    --------------
866    -- New_ATCB --
867    --------------
868
869    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_ID is
870    begin
871       return new Ada_Task_Control_Block (Entry_Num);
872    end New_ATCB;
873
874    -------------------
875    -- Is_Valid_Task --
876    -------------------
877
878    function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
879
880    -----------------------------
881    -- Register_Foreign_Thread --
882    -----------------------------
883
884    function Register_Foreign_Thread return Task_ID is
885    begin
886       if Is_Valid_Task then
887          return Self;
888       else
889          return Register_Foreign_Thread (thr_self);
890       end if;
891    end Register_Foreign_Thread;
892
893    --------------------
894    -- Initialize_TCB --
895    --------------------
896
897    procedure Initialize_TCB (Self_ID : Task_ID; Succeeded : out Boolean) is
898       Result : Interfaces.C.int := 0;
899
900    begin
901       --  Give the task a unique serial number.
902
903       Self_ID.Serial_Number := Next_Serial_Number;
904       Next_Serial_Number := Next_Serial_Number + 1;
905       pragma Assert (Next_Serial_Number /= 0);
906
907       Self_ID.Common.LL.Thread := To_thread_t (-1);
908
909       if not Single_Lock then
910          Result := mutex_init
911            (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
912          Self_ID.Common.LL.L.Level :=
913            Private_Task_Serial_Number (Self_ID.Serial_Number);
914          pragma Assert (Result = 0 or else Result = ENOMEM);
915       end if;
916
917       if Result = 0 then
918          Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
919          pragma Assert (Result = 0 or else Result = ENOMEM);
920       end if;
921
922       if Result = 0 then
923          Succeeded := True;
924       else
925          if not Single_Lock then
926             Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
927             pragma Assert (Result = 0);
928          end if;
929
930          Succeeded := False;
931       end if;
932    end Initialize_TCB;
933
934    -----------------
935    -- Create_Task --
936    -----------------
937
938    procedure Create_Task
939      (T          : Task_ID;
940       Wrapper    : System.Address;
941       Stack_Size : System.Parameters.Size_Type;
942       Priority   : System.Any_Priority;
943       Succeeded  : out Boolean)
944    is
945       pragma Unreferenced (Priority);
946
947       Result     : Interfaces.C.int;
948       Adjusted_Stack_Size : Interfaces.C.size_t;
949       Opts       : Interfaces.C.int := THR_DETACHED;
950
951       Page_Size  : constant System.Parameters.Size_Type := 4096;
952       --  This constant is for reserving extra space at the
953       --  end of the stack, which can be used by the stack
954       --  checking as guard page. The idea is that we need
955       --  to have at least Stack_Size bytes available for
956       --  actual use.
957
958       use System.Task_Info;
959
960    begin
961       if Stack_Size = System.Parameters.Unspecified_Size then
962          Adjusted_Stack_Size :=
963            Interfaces.C.size_t (Default_Stack_Size + Page_Size);
964
965       elsif Stack_Size < Minimum_Stack_Size then
966          Adjusted_Stack_Size :=
967            Interfaces.C.size_t (Minimum_Stack_Size + Page_Size);
968
969       else
970          Adjusted_Stack_Size :=
971            Interfaces.C.size_t (Stack_Size + Page_Size);
972       end if;
973
974       --  Since the initial signal mask of a thread is inherited from the
975       --  creator, and the Environment task has all its signals masked, we
976       --  do not need to manipulate caller's signal mask at this point.
977       --  All tasks in RTS will have All_Tasks_Mask initially.
978
979       if T.Common.Task_Info /= null then
980          if T.Common.Task_Info.New_LWP then
981             Opts := Opts + THR_NEW_LWP;
982          end if;
983
984          if T.Common.Task_Info.Bound_To_LWP then
985             Opts := Opts + THR_BOUND;
986          end if;
987
988       else
989          Opts := THR_DETACHED + THR_BOUND;
990       end if;
991
992       Result := thr_create
993         (System.Null_Address,
994          Adjusted_Stack_Size,
995          Thread_Body_Access (Wrapper),
996          To_Address (T),
997          Opts,
998          T.Common.LL.Thread'Access);
999
1000       Succeeded := Result = 0;
1001       pragma Assert
1002         (Result = 0
1003           or else Result = ENOMEM
1004           or else Result = EAGAIN);
1005    end Create_Task;
1006
1007    ------------------
1008    -- Finalize_TCB --
1009    ------------------
1010
1011    procedure Finalize_TCB (T : Task_ID) is
1012       Result : Interfaces.C.int;
1013       Tmp    : Task_ID := T;
1014       Is_Self : constant Boolean := T = Self;
1015
1016       procedure Free is new
1017         Unchecked_Deallocation (Ada_Task_Control_Block, Task_ID);
1018
1019    begin
1020       T.Common.LL.Thread := To_thread_t (0);
1021
1022       if not Single_Lock then
1023          Result := mutex_destroy (T.Common.LL.L.L'Access);
1024          pragma Assert (Result = 0);
1025       end if;
1026
1027       Result := cond_destroy (T.Common.LL.CV'Access);
1028       pragma Assert (Result = 0);
1029
1030       if T.Known_Tasks_Index /= -1 then
1031          Known_Tasks (T.Known_Tasks_Index) := null;
1032       end if;
1033
1034       Free (Tmp);
1035
1036       if Is_Self then
1037          Specific.Set (null);
1038       end if;
1039    end Finalize_TCB;
1040
1041    ---------------
1042    -- Exit_Task --
1043    ---------------
1044
1045    --  This procedure must be called with abort deferred.
1046    --  It can no longer call Self or access
1047    --  the current task's ATCB, since the ATCB has been deallocated.
1048
1049    procedure Exit_Task is
1050    begin
1051       Specific.Set (null);
1052    end Exit_Task;
1053
1054    ----------------
1055    -- Abort_Task --
1056    ----------------
1057
1058    procedure Abort_Task (T : Task_ID) is
1059       Result : Interfaces.C.int;
1060    begin
1061       pragma Assert (T /= Self);
1062
1063       Result := thr_kill (T.Common.LL.Thread,
1064         Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1065       null;
1066
1067       pragma Assert (Result = 0);
1068    end Abort_Task;
1069
1070    -----------
1071    -- Sleep --
1072    -----------
1073
1074    procedure Sleep
1075      (Self_ID : Task_ID;
1076       Reason  : Task_States)
1077    is
1078       Result : Interfaces.C.int;
1079
1080    begin
1081       pragma Assert (Check_Sleep (Reason));
1082
1083       if Dynamic_Priority_Support
1084         and then Self_ID.Pending_Priority_Change
1085       then
1086          Self_ID.Pending_Priority_Change := False;
1087          Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1088          Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1089       end if;
1090
1091       if Single_Lock then
1092          Result := cond_wait
1093            (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1094       else
1095          Result := cond_wait
1096            (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1097       end if;
1098
1099       pragma Assert (Record_Wakeup
1100         (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1101       pragma Assert (Result = 0 or else Result = EINTR);
1102    end Sleep;
1103
1104    --  Note that we are relying heaviliy here on the GNAT feature
1105    --  that Calendar.Time, System.Real_Time.Time, Duration, and
1106    --  System.Real_Time.Time_Span are all represented in the same
1107    --  way, i.e., as a 64-bit count of nanoseconds.
1108
1109    --  This allows us to always pass the timeout value as a Duration.
1110
1111    --  ???
1112    --  We are taking liberties here with the semantics of the delays.
1113    --  That is, we make no distinction between delays on the Calendar clock
1114    --  and delays on the Real_Time clock. That is technically incorrect, if
1115    --  the Calendar clock happens to be reset or adjusted.
1116    --  To solve this defect will require modification to the compiler
1117    --  interface, so that it can pass through more information, to tell
1118    --  us here which clock to use!
1119
1120    --  cond_timedwait will return if any of the following happens:
1121    --  1) some other task did cond_signal on this condition variable
1122    --     In this case, the return value is 0
1123    --  2) the call just returned, for no good reason
1124    --     This is called a "spurious wakeup".
1125    --     In this case, the return value may also be 0.
1126    --  3) the time delay expires
1127    --     In this case, the return value is ETIME
1128    --  4) this task received a signal, which was handled by some
1129    --     handler procedure, and now the thread is resuming execution
1130    --     UNIX calls this an "interrupted" system call.
1131    --     In this case, the return value is EINTR
1132
1133    --  If the cond_timedwait returns 0 or EINTR, it is still
1134    --  possible that the time has actually expired, and by chance
1135    --  a signal or cond_signal occurred at around the same time.
1136
1137    --  We have also observed that on some OS's the value ETIME
1138    --  will be returned, but the clock will show that the full delay
1139    --  has not yet expired.
1140
1141    --  For these reasons, we need to check the clock after return
1142    --  from cond_timedwait.  If the time has expired, we will set
1143    --  Timedout = True.
1144
1145    --  This check might be omitted for systems on which the
1146    --  cond_timedwait() never returns early or wakes up spuriously.
1147
1148    --  Annex D requires that completion of a delay cause the task
1149    --  to go to the end of its priority queue, regardless of whether
1150    --  the task actually was suspended by the delay. Since
1151    --  cond_timedwait does not do this on Solaris, we add a call
1152    --  to thr_yield at the end. We might do this at the beginning,
1153    --  instead, but then the round-robin effect would not be the
1154    --  same; the delayed task would be ahead of other tasks of the
1155    --  same priority that awoke while it was sleeping.
1156
1157    --  For Timed_Sleep, we are expecting possible cond_signals
1158    --  to indicate other events (e.g., completion of a RV or
1159    --  completion of the abortable part of an async. select),
1160    --  we want to always return if interrupted. The caller will
1161    --  be responsible for checking the task state to see whether
1162    --  the wakeup was spurious, and to go back to sleep again
1163    --  in that case.  We don't need to check for pending abort
1164    --  or priority change on the way in our out; that is the
1165    --  caller's responsibility.
1166
1167    --  For Timed_Delay, we are not expecting any cond_signals or
1168    --  other interruptions, except for priority changes and aborts.
1169    --  Therefore, we don't want to return unless the delay has
1170    --  actually expired, or the call has been aborted. In this
1171    --  case, since we want to implement the entire delay statement
1172    --  semantics, we do need to check for pending abort and priority
1173    --  changes. We can quietly handle priority changes inside the
1174    --  procedure, since there is no entry-queue reordering involved.
1175
1176    -----------------
1177    -- Timed_Sleep --
1178    -----------------
1179
1180    procedure Timed_Sleep
1181      (Self_ID  : Task_ID;
1182       Time     : Duration;
1183       Mode     : ST.Delay_Modes;
1184       Reason   : System.Tasking.Task_States;
1185       Timedout : out Boolean;
1186       Yielded  : out Boolean)
1187    is
1188       Check_Time : constant Duration := Monotonic_Clock;
1189       Abs_Time   : Duration;
1190       Request    : aliased timespec;
1191       Result     : Interfaces.C.int;
1192
1193    begin
1194       pragma Assert (Check_Sleep (Reason));
1195       Timedout := True;
1196       Yielded := False;
1197
1198       if Mode = Relative then
1199          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
1200       else
1201          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1202       end if;
1203
1204       if Abs_Time > Check_Time then
1205          Request := To_Timespec (Abs_Time);
1206
1207          loop
1208             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
1209               or else (Dynamic_Priority_Support and then
1210                 Self_ID.Pending_Priority_Change);
1211
1212             if Single_Lock then
1213                Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1214                  Single_RTS_Lock.L'Access, Request'Access);
1215             else
1216                Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1217                  Self_ID.Common.LL.L.L'Access, Request'Access);
1218             end if;
1219
1220             Yielded := True;
1221
1222             exit when Abs_Time <= Monotonic_Clock;
1223
1224             if Result = 0 or Result = EINTR then
1225
1226                --  Somebody may have called Wakeup for us
1227
1228                Timedout := False;
1229                exit;
1230             end if;
1231
1232             pragma Assert (Result = ETIME);
1233          end loop;
1234       end if;
1235
1236       pragma Assert (Record_Wakeup
1237         (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1238    end Timed_Sleep;
1239
1240    -----------------
1241    -- Timed_Delay --
1242    -----------------
1243
1244    procedure Timed_Delay
1245      (Self_ID  : Task_ID;
1246       Time     : Duration;
1247       Mode     : ST.Delay_Modes)
1248    is
1249       Check_Time : constant Duration := Monotonic_Clock;
1250       Abs_Time   : Duration;
1251       Request    : aliased timespec;
1252       Result     : Interfaces.C.int;
1253       Yielded    : Boolean := False;
1254
1255    begin
1256       --  Only the little window between deferring abort and
1257       --  locking Self_ID is the reason we need to
1258       --  check for pending abort and priority change below!
1259
1260       SSL.Abort_Defer.all;
1261
1262       if Single_Lock then
1263          Lock_RTS;
1264       end if;
1265
1266       Write_Lock (Self_ID);
1267
1268       if Mode = Relative then
1269          Abs_Time := Time + Check_Time;
1270       else
1271          Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1272       end if;
1273
1274       if Abs_Time > Check_Time then
1275          Request := To_Timespec (Abs_Time);
1276          Self_ID.Common.State := Delay_Sleep;
1277
1278          pragma Assert (Check_Sleep (Delay_Sleep));
1279
1280          loop
1281             if Dynamic_Priority_Support and then
1282               Self_ID.Pending_Priority_Change then
1283                Self_ID.Pending_Priority_Change := False;
1284                Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1285                Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1286             end if;
1287
1288             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1289
1290             if Single_Lock then
1291                Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1292                  Single_RTS_Lock.L'Access, Request'Access);
1293             else
1294                Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1295                  Self_ID.Common.LL.L.L'Access, Request'Access);
1296             end if;
1297
1298             Yielded := True;
1299
1300             exit when Abs_Time <= Monotonic_Clock;
1301
1302             pragma Assert (Result = 0 or else
1303               Result = ETIME or else
1304               Result = EINTR);
1305          end loop;
1306
1307          pragma Assert (Record_Wakeup
1308            (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1309
1310          Self_ID.Common.State := Runnable;
1311       end if;
1312
1313       Unlock (Self_ID);
1314
1315       if Single_Lock then
1316          Unlock_RTS;
1317       end if;
1318
1319       if not Yielded then
1320          thr_yield;
1321       end if;
1322
1323       SSL.Abort_Undefer.all;
1324    end Timed_Delay;
1325
1326    ------------
1327    -- Wakeup --
1328    ------------
1329
1330    procedure Wakeup
1331      (T : Task_ID;
1332       Reason : Task_States)
1333    is
1334       Result : Interfaces.C.int;
1335
1336    begin
1337       pragma Assert (Check_Wakeup (T, Reason));
1338       Result := cond_signal (T.Common.LL.CV'Access);
1339       pragma Assert (Result = 0);
1340    end Wakeup;
1341
1342    ---------------------------
1343    -- Check_Initialize_Lock --
1344    ---------------------------
1345
1346    --  The following code is intended to check some of the invariant
1347    --  assertions related to lock usage, on which we depend.
1348
1349    function Check_Initialize_Lock
1350      (L     : Lock_Ptr;
1351       Level : Lock_Level) return Boolean
1352    is
1353       Self_ID : constant Task_ID := Self;
1354
1355    begin
1356       --  Check that caller is abort-deferred
1357
1358       if Self_ID.Deferral_Level <= 0 then
1359          return False;
1360       end if;
1361
1362       --  Check that the lock is not yet initialized
1363
1364       if L.Level /= 0 then
1365          return False;
1366       end if;
1367
1368       L.Level := Lock_Level'Pos (Level) + 1;
1369       return True;
1370    end Check_Initialize_Lock;
1371
1372    ----------------
1373    -- Check_Lock --
1374    ----------------
1375
1376    function Check_Lock (L : Lock_Ptr) return Boolean is
1377       Self_ID : constant Task_ID := Self;
1378       P       : Lock_Ptr;
1379
1380    begin
1381       --  Check that the argument is not null
1382
1383       if L = null then
1384          return False;
1385       end if;
1386
1387       --  Check that L is not frozen
1388
1389       if L.Frozen then
1390          return False;
1391       end if;
1392
1393       --  Check that caller is abort-deferred
1394
1395       if Self_ID.Deferral_Level <= 0 then
1396          return False;
1397       end if;
1398
1399       --  Check that caller is not holding this lock already
1400
1401       if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1402          return False;
1403       end if;
1404
1405       if Single_Lock then
1406          return True;
1407       end if;
1408
1409       --  Check that TCB lock order rules are satisfied
1410
1411       P := Self_ID.Common.LL.Locks;
1412       if P /= null then
1413          if P.Level >= L.Level
1414            and then (P.Level > 2 or else L.Level > 2)
1415          then
1416             return False;
1417          end if;
1418       end if;
1419
1420       return True;
1421    end Check_Lock;
1422
1423    -----------------
1424    -- Record_Lock --
1425    -----------------
1426
1427    function Record_Lock (L : Lock_Ptr) return Boolean is
1428       Self_ID : constant Task_ID := Self;
1429       P       : Lock_Ptr;
1430
1431    begin
1432       Lock_Count := Lock_Count + 1;
1433
1434       --  There should be no owner for this lock at this point
1435
1436       if L.Owner /= null then
1437          return False;
1438       end if;
1439
1440       --  Record new owner
1441
1442       L.Owner := To_Owner_ID (To_Address (Self_ID));
1443
1444       if Single_Lock then
1445          return True;
1446       end if;
1447
1448       --  Check that TCB lock order rules are satisfied
1449
1450       P := Self_ID.Common.LL.Locks;
1451
1452       if P /= null then
1453          L.Next := P;
1454       end if;
1455
1456       Self_ID.Common.LL.Locking := null;
1457       Self_ID.Common.LL.Locks := L;
1458       return True;
1459    end Record_Lock;
1460
1461    -----------------
1462    -- Check_Sleep --
1463    -----------------
1464
1465    function Check_Sleep (Reason : Task_States) return Boolean is
1466       pragma Unreferenced (Reason);
1467
1468       Self_ID : constant Task_ID := Self;
1469       P       : Lock_Ptr;
1470
1471    begin
1472       --  Check that caller is abort-deferred
1473
1474       if Self_ID.Deferral_Level <= 0 then
1475          return False;
1476       end if;
1477
1478       if Single_Lock then
1479          return True;
1480       end if;
1481
1482       --  Check that caller is holding own lock, on top of list
1483
1484       if Self_ID.Common.LL.Locks /=
1485         To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1486       then
1487          return False;
1488       end if;
1489
1490       --  Check that TCB lock order rules are satisfied
1491
1492       if Self_ID.Common.LL.Locks.Next /= null then
1493          return False;
1494       end if;
1495
1496       Self_ID.Common.LL.L.Owner := null;
1497       P := Self_ID.Common.LL.Locks;
1498       Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1499       P.Next := null;
1500       return True;
1501    end Check_Sleep;
1502
1503    -------------------
1504    -- Record_Wakeup --
1505    -------------------
1506
1507    function Record_Wakeup
1508      (L      : Lock_Ptr;
1509       Reason : Task_States) return Boolean
1510    is
1511       pragma Unreferenced (Reason);
1512
1513       Self_ID : constant Task_ID := Self;
1514       P       : Lock_Ptr;
1515
1516    begin
1517       --  Record new owner
1518
1519       L.Owner := To_Owner_ID (To_Address (Self_ID));
1520
1521       if Single_Lock then
1522          return True;
1523       end if;
1524
1525       --  Check that TCB lock order rules are satisfied
1526
1527       P := Self_ID.Common.LL.Locks;
1528
1529       if P /= null then
1530          L.Next := P;
1531       end if;
1532
1533       Self_ID.Common.LL.Locking := null;
1534       Self_ID.Common.LL.Locks := L;
1535       return True;
1536    end Record_Wakeup;
1537
1538    ------------------
1539    -- Check_Wakeup --
1540    ------------------
1541
1542    function Check_Wakeup
1543      (T      : Task_ID;
1544       Reason : Task_States) return Boolean
1545    is
1546       Self_ID : constant Task_ID := Self;
1547
1548    begin
1549       --  Is caller holding T's lock?
1550
1551       if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1552          return False;
1553       end if;
1554
1555       --  Are reasons for wakeup and sleep consistent?
1556
1557       if T.Common.State /= Reason then
1558          return False;
1559       end if;
1560
1561       return True;
1562    end Check_Wakeup;
1563
1564    ------------------
1565    -- Check_Unlock --
1566    ------------------
1567
1568    function Check_Unlock (L : Lock_Ptr) return Boolean is
1569       Self_ID : constant Task_ID := Self;
1570       P       : Lock_Ptr;
1571
1572    begin
1573       Unlock_Count := Unlock_Count + 1;
1574
1575       if L = null then
1576          return False;
1577       end if;
1578
1579       if L.Buddy /= null then
1580          return False;
1581       end if;
1582
1583       if L.Level = 4 then
1584          Check_Count := Unlock_Count;
1585       end if;
1586
1587       if Unlock_Count - Check_Count > 1000 then
1588          Check_Count := Unlock_Count;
1589       end if;
1590
1591       --  Check that caller is abort-deferred
1592
1593       if Self_ID.Deferral_Level <= 0 then
1594          return False;
1595       end if;
1596
1597       --  Check that caller is holding this lock, on top of list
1598
1599       if Self_ID.Common.LL.Locks /= L then
1600          return False;
1601       end if;
1602
1603       --  Record there is no owner now
1604
1605       L.Owner := null;
1606       P := Self_ID.Common.LL.Locks;
1607       Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1608       P.Next := null;
1609       return True;
1610    end Check_Unlock;
1611
1612    --------------------
1613    -- Check_Finalize --
1614    --------------------
1615
1616    function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1617       Self_ID : constant Task_ID := Self;
1618
1619    begin
1620       --  Check that caller is abort-deferred
1621
1622       if Self_ID.Deferral_Level <= 0 then
1623          return False;
1624       end if;
1625
1626       --  Check that no one is holding this lock
1627
1628       if L.Owner /= null then
1629          return False;
1630       end if;
1631
1632       L.Frozen := True;
1633       return True;
1634    end Check_Finalize_Lock;
1635
1636    ----------------
1637    -- Check_Exit --
1638    ----------------
1639
1640    function Check_Exit (Self_ID : Task_ID) return Boolean is
1641    begin
1642       --  Check that caller is just holding Global_Task_Lock
1643       --  and no other locks
1644
1645       if Self_ID.Common.LL.Locks = null then
1646          return False;
1647       end if;
1648
1649       --  2 = Global_Task_Level
1650
1651       if Self_ID.Common.LL.Locks.Level /= 2 then
1652          return False;
1653       end if;
1654
1655       if Self_ID.Common.LL.Locks.Next /= null then
1656          return False;
1657       end if;
1658
1659       --  Check that caller is abort-deferred
1660
1661       if Self_ID.Deferral_Level <= 0 then
1662          return False;
1663       end if;
1664
1665       return True;
1666    end Check_Exit;
1667
1668    --------------------
1669    -- Check_No_Locks --
1670    --------------------
1671
1672    function Check_No_Locks (Self_ID : Task_ID) return Boolean is
1673    begin
1674       return Self_ID.Common.LL.Locks = null;
1675    end Check_No_Locks;
1676
1677    ----------------------
1678    -- Environment_Task --
1679    ----------------------
1680
1681    function Environment_Task return Task_ID is
1682    begin
1683       return Environment_Task_ID;
1684    end Environment_Task;
1685
1686    --------------
1687    -- Lock_RTS --
1688    --------------
1689
1690    procedure Lock_RTS is
1691    begin
1692       Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1693    end Lock_RTS;
1694
1695    ----------------
1696    -- Unlock_RTS --
1697    ----------------
1698
1699    procedure Unlock_RTS is
1700    begin
1701       Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1702    end Unlock_RTS;
1703
1704    ------------------
1705    -- Suspend_Task --
1706    ------------------
1707
1708    function Suspend_Task
1709      (T           : ST.Task_ID;
1710       Thread_Self : Thread_Id) return Boolean
1711    is
1712    begin
1713       if T.Common.LL.Thread /= Thread_Self then
1714          return thr_suspend (T.Common.LL.Thread) = 0;
1715       else
1716          return True;
1717       end if;
1718    end Suspend_Task;
1719
1720    -----------------
1721    -- Resume_Task --
1722    -----------------
1723
1724    function Resume_Task
1725      (T           : ST.Task_ID;
1726       Thread_Self : Thread_Id) return Boolean
1727    is
1728    begin
1729       if T.Common.LL.Thread /= Thread_Self then
1730          return thr_continue (T.Common.LL.Thread) = 0;
1731       else
1732          return True;
1733       end if;
1734    end Resume_Task;
1735
1736 --  Package elaboration
1737
1738 begin
1739    declare
1740       Result : Interfaces.C.int;
1741
1742    begin
1743       --  Mask Environment task for all signals. The original mask of the
1744       --  Environment task will be recovered by Interrupt_Server task
1745       --  during the elaboration of s-interr.adb.
1746
1747       System.Interrupt_Management.Operations.Set_Interrupt_Mask
1748         (System.Interrupt_Management.Operations.All_Tasks_Mask'Access);
1749
1750       --  Prepare the set of signals that should unblocked in all tasks
1751
1752       Result := sigemptyset (Unblocked_Signal_Mask'Access);
1753       pragma Assert (Result = 0);
1754
1755       for J in Interrupt_Management.Interrupt_ID loop
1756          if System.Interrupt_Management.Keep_Unmasked (J) then
1757             Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1758             pragma Assert (Result = 0);
1759          end if;
1760       end loop;
1761
1762       --  We need the following code to support automatic creation of fake
1763       --  ATCB's for C threads that call the Ada run-time system, even if
1764       --  we use a faster way of getting Self for real Ada tasks.
1765
1766       Result := thr_keycreate (ATCB_Key'Access, System.Null_Address);
1767       pragma Assert (Result = 0);
1768    end;
1769
1770    if Dispatching_Policy = 'F' then
1771       declare
1772          Result      : Interfaces.C.long;
1773          Class_Info  : aliased struct_pcinfo;
1774          Secs, Nsecs : Interfaces.C.long;
1775
1776       begin
1777          --  If a pragma Time_Slice is specified, takes the value in account.
1778
1779          if Time_Slice_Val > 0 then
1780             --  Convert Time_Slice_Val (microseconds) into seconds and
1781             --  nanoseconds
1782
1783             Secs := Time_Slice_Val / 1_000_000;
1784             Nsecs := (Time_Slice_Val rem 1_000_000) * 1_000;
1785
1786          --  Otherwise, default to no time slicing (i.e run until blocked)
1787
1788          else
1789             Secs := RT_TQINF;
1790             Nsecs := RT_TQINF;
1791          end if;
1792
1793          --  Get the real time class id.
1794
1795          Class_Info.pc_clname (1) := 'R';
1796          Class_Info.pc_clname (2) := 'T';
1797          Class_Info.pc_clname (3) := ASCII.NUL;
1798
1799          Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
1800            Class_Info'Address);
1801
1802          --  Request the real time class
1803
1804          Prio_Param.pc_cid := Class_Info.pc_cid;
1805          Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
1806          Prio_Param.rt_tqsecs := Secs;
1807          Prio_Param.rt_tqnsecs := Nsecs;
1808
1809          Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS,
1810            Prio_Param'Address);
1811
1812          Using_Real_Time_Class := Result /= -1;
1813       end;
1814    end if;
1815 end System.Task_Primitives.Operations;