OSDN Git Service

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