OSDN Git Service

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