OSDN Git Service

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