OSDN Git Service

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