OSDN Git Service

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