1 ------------------------------------------------------------------------------
3 -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
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 --
9 -- Copyright (C) 1992-2006, Free Software Foundation, Inc. --
11 -- GNARL is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 2, or (at your option) any later ver- --
14 -- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNARL; see file COPYING. If not, write --
19 -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
20 -- Boston, MA 02110-1301, USA. --
22 -- As a special exception, if other files instantiate generics from this --
23 -- unit, or you link this unit with other files to produce an executable, --
24 -- this unit does not by itself cause the resulting executable to be --
25 -- covered by the GNU General Public License. This exception does not --
26 -- however invalidate any other reasons why the executable file might be --
27 -- covered by the GNU Public License. --
29 -- GNARL was developed by the GNARL team at Florida State University. --
30 -- Extensive contributions were provided by Ada Core Technologies, Inc. --
32 ------------------------------------------------------------------------------
34 -- This is a Solaris (native) version of this package
36 -- This package contains all the GNULL primitives that interface directly
37 -- with the underlying OS.
40 -- Turn off polling, we do not want ATC polling to take place during
41 -- tasking operations. It causes infinite loops and other problems.
43 with System.Tasking.Debug;
44 -- used for Known_Tasks
46 with System.Interrupt_Management;
47 -- used for Keep_Unmasked
48 -- Abort_Task_Interrupt
51 with System.OS_Primitives;
52 -- used for Delay_Modes
54 pragma Warnings (Off);
56 -- used for String_Access, Getenv
64 with System.Task_Info;
65 -- to initialize Task_Info for a C thread, in function Self
67 with System.Soft_Links;
68 -- used for Defer/Undefer_Abort
70 -- We use System.Soft_Links instead of System.Tasking.Initialization
71 -- because the later is a higher level package that we shouldn't depend on.
72 -- For example when using the restricted run time, it is replaced by
73 -- System.Tasking.Restricted.Stages.
75 with Unchecked_Deallocation;
77 package body System.Task_Primitives.Operations is
79 package SSL renames System.Soft_Links;
81 use System.Tasking.Debug;
84 use System.OS_Interface;
85 use System.Parameters;
86 use System.OS_Primitives;
92 -- The following are logically constants, but need to be initialized
95 Environment_Task_Id : Task_Id;
96 -- A variable to hold Task_Id for the environment task.
97 -- If we use this variable to get the Task_Id, we need the following
98 -- ATCB_Key only for non-Ada threads.
100 Unblocked_Signal_Mask : aliased sigset_t;
101 -- The set of signals that should unblocked in all tasks
103 ATCB_Key : aliased thread_key_t;
104 -- Key used to find the Ada Task_Id associated with a thread,
105 -- at least for C threads unknown to the Ada run-time system.
107 Single_RTS_Lock : aliased RTS_Lock;
108 -- This is a lock to allow only one thread of control in the RTS at
109 -- a time; it is used to execute in mutual exclusion from all other tasks.
110 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
112 Next_Serial_Number : Task_Serial_Number := 100;
113 -- We start at 100, to reserve some special values for
114 -- using in error checking.
115 -- The following are internal configuration constants needed.
117 ----------------------
118 -- Priority Support --
119 ----------------------
121 Priority_Ceiling_Emulation : constant Boolean := True;
122 -- controls whether we emulate priority ceiling locking
124 -- To get a scheduling close to annex D requirements, we use the real-time
125 -- class provided for LWP's and map each task/thread to a specific and
126 -- unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
128 -- The real time class can only be set when the process has root
129 -- priviledges, so in the other cases, we use the normal thread scheduling
130 -- and priority handling.
132 Using_Real_Time_Class : Boolean := False;
133 -- indicates wether the real time class is being used (i.e the process
134 -- has root priviledges).
136 Prio_Param : aliased struct_pcparms;
137 -- Hold priority info (Real_Time) initialized during the package
140 -----------------------------------
141 -- External Configuration Values --
142 -----------------------------------
144 Time_Slice_Val : Interfaces.C.long;
145 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
147 Locking_Policy : Character;
148 pragma Import (C, Locking_Policy, "__gl_locking_policy");
150 Dispatching_Policy : Character;
151 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
153 Foreign_Task_Elaborated : aliased Boolean := True;
154 -- Used to identified fake tasks (i.e., non-Ada Threads).
156 -----------------------
157 -- Local Subprograms --
158 -----------------------
160 function sysconf (name : System.OS_Interface.int) return processorid_t;
161 pragma Import (C, sysconf, "sysconf");
163 SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
166 (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
167 return processorid_t renames sysconf;
169 procedure Abort_Handler
171 Code : access siginfo_t;
172 Context : access ucontext_t);
173 -- Target-dependent binding of inter-thread Abort signal to
174 -- the raising of the Abort_Signal exception.
175 -- See also comments in 7staprop.adb
181 function Check_Initialize_Lock
183 Level : Lock_Level) return Boolean;
184 pragma Inline (Check_Initialize_Lock);
186 function Check_Lock (L : Lock_Ptr) return Boolean;
187 pragma Inline (Check_Lock);
189 function Record_Lock (L : Lock_Ptr) return Boolean;
190 pragma Inline (Record_Lock);
192 function Check_Sleep (Reason : Task_States) return Boolean;
193 pragma Inline (Check_Sleep);
195 function Record_Wakeup
197 Reason : Task_States) return Boolean;
198 pragma Inline (Record_Wakeup);
200 function Check_Wakeup
202 Reason : Task_States) return Boolean;
203 pragma Inline (Check_Wakeup);
205 function Check_Unlock (L : Lock_Ptr) return Boolean;
206 pragma Inline (Check_Unlock);
208 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
209 pragma Inline (Check_Finalize_Lock);
217 procedure Initialize (Environment_Task : Task_Id);
218 pragma Inline (Initialize);
219 -- Initialize various data needed by this package.
221 function Is_Valid_Task return Boolean;
222 pragma Inline (Is_Valid_Task);
223 -- Does executing thread have a TCB?
225 procedure Set (Self_Id : Task_Id);
227 -- Set the self id for the current task.
229 function Self return Task_Id;
230 pragma Inline (Self);
231 -- Return a pointer to the Ada Task Control Block of the calling task.
235 package body Specific is separate;
236 -- The body of this package is target specific.
238 ---------------------------------
239 -- Support for foreign threads --
240 ---------------------------------
242 function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
243 -- Allocate and Initialize a new ATCB for the current Thread.
245 function Register_Foreign_Thread
246 (Thread : Thread_Id) return Task_Id is separate;
252 Check_Count : Integer := 0;
253 Lock_Count : Integer := 0;
254 Unlock_Count : Integer := 0;
260 procedure Abort_Handler
262 Code : access siginfo_t;
263 Context : access ucontext_t)
265 pragma Unreferenced (Sig);
266 pragma Unreferenced (Code);
267 pragma Unreferenced (Context);
269 Self_ID : constant Task_Id := Self;
270 Old_Set : aliased sigset_t;
272 Result : Interfaces.C.int;
275 -- It is not safe to raise an exception when using ZCX and the GCC
276 -- exception handling mechanism.
278 if ZCX_By_Default and then GCC_ZCX_Support then
282 if Self_ID.Deferral_Level = 0
283 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
284 and then not Self_ID.Aborting
286 Self_ID.Aborting := True;
288 -- Make sure signals used for RTS internal purpose are unmasked
290 Result := thr_sigsetmask (SIG_UNBLOCK,
291 Unblocked_Signal_Mask'Unchecked_Access, Old_Set'Unchecked_Access);
292 pragma Assert (Result = 0);
294 raise Standard'Abort_Signal;
302 -- The underlying thread system sets a guard page at the
303 -- bottom of a thread stack, so nothing is needed.
305 procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
306 pragma Unreferenced (T);
307 pragma Unreferenced (On);
316 function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
318 return T.Common.LL.Thread;
325 procedure Initialize (Environment_Task : ST.Task_Id) is
326 act : aliased struct_sigaction;
327 old_act : aliased struct_sigaction;
328 Tmp_Set : aliased sigset_t;
329 Result : Interfaces.C.int;
331 procedure Configure_Processors;
332 -- Processors configuration
333 -- The user can specify a processor which the program should run
334 -- on to emulate a single-processor system. This can be easily
335 -- done by setting environment variable GNAT_PROCESSOR to one of
338 -- -2 : use the default configuration (run the program on all
339 -- available processors) - this is the same as having
340 -- GNAT_PROCESSOR unset
341 -- -1 : let the RTS choose one processor and run the program on
343 -- 0 .. Last_Proc : run the program on the specified processor
345 -- Last_Proc is equal to the value of the system variable
346 -- _SC_NPROCESSORS_CONF, minus one.
348 procedure Configure_Processors is
349 Proc_Acc : constant GNAT.OS_Lib.String_Access :=
350 GNAT.OS_Lib.Getenv ("GNAT_PROCESSOR");
351 Proc : aliased processorid_t; -- User processor #
352 Last_Proc : processorid_t; -- Last processor #
355 if Proc_Acc.all'Length /= 0 then
356 -- Environment variable is defined
358 Last_Proc := Num_Procs - 1;
360 if Last_Proc /= -1 then
361 Proc := processorid_t'Value (Proc_Acc.all);
363 if Proc <= -2 or else Proc > Last_Proc then
364 -- Use the default configuration
367 -- Choose a processor
371 while Proc < Last_Proc loop
373 Result := p_online (Proc, PR_STATUS);
374 exit when Result = PR_ONLINE;
377 pragma Assert (Result = PR_ONLINE);
378 Result := processor_bind (P_PID, P_MYID, Proc, null);
379 pragma Assert (Result = 0);
382 -- Use user processor
384 Result := processor_bind (P_PID, P_MYID, Proc, null);
385 pragma Assert (Result = 0);
391 when Constraint_Error =>
393 -- Illegal environment variable GNAT_PROCESSOR - ignored
396 end Configure_Processors;
399 (Int : System.Interrupt_Management.Interrupt_ID) return Character;
400 pragma Import (C, State, "__gnat_get_interrupt_state");
401 -- Get interrupt state. Defined in a-init.c
402 -- The input argument is the interrupt number,
403 -- and the result is one of the following:
405 Default : constant Character := 's';
406 -- 'n' this interrupt not set by any Interrupt_State pragma
407 -- 'u' Interrupt_State pragma set state to User
408 -- 'r' Interrupt_State pragma set state to Runtime
409 -- 's' Interrupt_State pragma set state to System (use "default"
412 -- Start of processing for Initialize
415 Environment_Task_Id := Environment_Task;
417 Interrupt_Management.Initialize;
419 -- Prepare the set of signals that should unblocked in all tasks
421 Result := sigemptyset (Unblocked_Signal_Mask'Access);
422 pragma Assert (Result = 0);
424 for J in Interrupt_Management.Interrupt_ID loop
425 if System.Interrupt_Management.Keep_Unmasked (J) then
426 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
427 pragma Assert (Result = 0);
431 if Dispatching_Policy = 'F' then
433 Result : Interfaces.C.long;
434 Class_Info : aliased struct_pcinfo;
435 Secs, Nsecs : Interfaces.C.long;
438 -- If a pragma Time_Slice is specified, takes the value in account
440 if Time_Slice_Val > 0 then
441 -- Convert Time_Slice_Val (microseconds) into seconds and
444 Secs := Time_Slice_Val / 1_000_000;
445 Nsecs := (Time_Slice_Val rem 1_000_000) * 1_000;
447 -- Otherwise, default to no time slicing (i.e run until blocked)
454 -- Get the real time class id.
456 Class_Info.pc_clname (1) := 'R';
457 Class_Info.pc_clname (2) := 'T';
458 Class_Info.pc_clname (3) := ASCII.NUL;
460 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
463 -- Request the real time class
465 Prio_Param.pc_cid := Class_Info.pc_cid;
466 Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
467 Prio_Param.rt_tqsecs := Secs;
468 Prio_Param.rt_tqnsecs := Nsecs;
470 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS,
473 Using_Real_Time_Class := Result /= -1;
477 Specific.Initialize (Environment_Task);
479 -- The following is done in Enter_Task, but this is too late for the
480 -- Environment Task, since we need to call Self in Check_Locks when
481 -- the run time is compiled with assertions on.
483 Specific.Set (Environment_Task);
485 -- Initialize the lock used to synchronize chain of all ATCBs.
487 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
489 Enter_Task (Environment_Task);
491 -- Install the abort-signal handler
493 if State (System.Interrupt_Management.Abort_Task_Interrupt)
496 -- Set sa_flags to SA_NODEFER so that during the handler execution
497 -- we do not change the Signal_Mask to be masked for the Abort_Signal
498 -- This is a temporary fix to the problem that the Signal_Mask is
499 -- not restored after the exception (longjmp) from the handler.
500 -- The right fix should be made in sigsetjmp so that we save
501 -- the Signal_Set and restore it after a longjmp.
502 -- In that case, this field should be changed back to 0. ???
506 act.sa_handler := Abort_Handler'Address;
507 Result := sigemptyset (Tmp_Set'Access);
508 pragma Assert (Result = 0);
509 act.sa_mask := Tmp_Set;
513 Signal (System.Interrupt_Management.Abort_Task_Interrupt),
514 act'Unchecked_Access,
515 old_act'Unchecked_Access);
516 pragma Assert (Result = 0);
519 Configure_Processors;
522 ---------------------
523 -- Initialize_Lock --
524 ---------------------
526 -- Note: mutexes and cond_variables needed per-task basis are
527 -- initialized in Initialize_TCB and the Storage_Error is
528 -- handled. Other mutexes (such as RTS_Lock, Memory_Lock...)
529 -- used in RTS is initialized before any status change of RTS.
530 -- Therefore rasing Storage_Error in the following routines
531 -- should be able to be handled safely.
533 procedure Initialize_Lock
534 (Prio : System.Any_Priority;
537 Result : Interfaces.C.int;
540 pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
542 if Priority_Ceiling_Emulation then
546 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
547 pragma Assert (Result = 0 or else Result = ENOMEM);
549 if Result = ENOMEM then
550 raise Storage_Error with "Failed to allocate a lock";
554 procedure Initialize_Lock
555 (L : access RTS_Lock;
558 Result : Interfaces.C.int;
561 pragma Assert (Check_Initialize_Lock
562 (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
563 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
564 pragma Assert (Result = 0 or else Result = ENOMEM);
566 if Result = ENOMEM then
567 raise Storage_Error with "Failed to allocate a lock";
575 procedure Finalize_Lock (L : access Lock) is
576 Result : Interfaces.C.int;
579 pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
580 Result := mutex_destroy (L.L'Access);
581 pragma Assert (Result = 0);
584 procedure Finalize_Lock (L : access RTS_Lock) is
585 Result : Interfaces.C.int;
588 pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
589 Result := mutex_destroy (L.L'Access);
590 pragma Assert (Result = 0);
597 procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
598 Result : Interfaces.C.int;
601 pragma Assert (Check_Lock (Lock_Ptr (L)));
603 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
605 Self_Id : constant Task_Id := Self;
606 Saved_Priority : System.Any_Priority;
609 if Self_Id.Common.LL.Active_Priority > L.Ceiling then
610 Ceiling_Violation := True;
614 Saved_Priority := Self_Id.Common.LL.Active_Priority;
616 if Self_Id.Common.LL.Active_Priority < L.Ceiling then
617 Set_Priority (Self_Id, L.Ceiling);
620 Result := mutex_lock (L.L'Access);
621 pragma Assert (Result = 0);
622 Ceiling_Violation := False;
624 L.Saved_Priority := Saved_Priority;
628 Result := mutex_lock (L.L'Access);
629 pragma Assert (Result = 0);
630 Ceiling_Violation := False;
633 pragma Assert (Record_Lock (Lock_Ptr (L)));
637 (L : access RTS_Lock;
638 Global_Lock : Boolean := False)
640 Result : Interfaces.C.int;
643 if not Single_Lock or else Global_Lock then
644 pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
645 Result := mutex_lock (L.L'Access);
646 pragma Assert (Result = 0);
647 pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
651 procedure Write_Lock (T : Task_Id) is
652 Result : Interfaces.C.int;
655 if not Single_Lock then
656 pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
657 Result := mutex_lock (T.Common.LL.L.L'Access);
658 pragma Assert (Result = 0);
659 pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
667 procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
669 Write_Lock (L, Ceiling_Violation);
676 procedure Unlock (L : access Lock) is
677 Result : Interfaces.C.int;
680 pragma Assert (Check_Unlock (Lock_Ptr (L)));
682 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
684 Self_Id : constant Task_Id := Self;
687 Result := mutex_unlock (L.L'Access);
688 pragma Assert (Result = 0);
690 if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
691 Set_Priority (Self_Id, L.Saved_Priority);
695 Result := mutex_unlock (L.L'Access);
696 pragma Assert (Result = 0);
700 procedure Unlock (L : access RTS_Lock; Global_Lock : Boolean := False) is
701 Result : Interfaces.C.int;
704 if not Single_Lock or else Global_Lock then
705 pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
706 Result := mutex_unlock (L.L'Access);
707 pragma Assert (Result = 0);
711 procedure Unlock (T : Task_Id) is
712 Result : Interfaces.C.int;
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);
722 -- For the time delay implementation, we need to make sure we
723 -- achieve following criteria:
725 -- 1) We have to delay at least for the amount requested.
726 -- 2) We have to give up CPU even though the actual delay does not
727 -- result in blocking.
728 -- 3) Except for restricted run-time systems that do not support
729 -- ATC or task abort, the delay must be interrupted by the
730 -- abort_task operation.
731 -- 4) The implementation has to be efficient so that the delay overhead
732 -- is relatively cheap.
733 -- (1)-(3) are Ada requirements. Even though (2) is an Annex-D
734 -- requirement we still want to provide the effect in all cases.
735 -- The reason is that users may want to use short delays to implement
736 -- their own scheduling effect in the absence of language provided
737 -- scheduling policies.
739 ---------------------
740 -- Monotonic_Clock --
741 ---------------------
743 function Monotonic_Clock return Duration is
744 TS : aliased timespec;
745 Result : Interfaces.C.int;
747 Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
748 pragma Assert (Result = 0);
749 return To_Duration (TS);
756 function RT_Resolution return Duration is
765 procedure Yield (Do_Yield : Boolean := True) is
768 System.OS_Interface.thr_yield;
776 function Self return Task_Id renames Specific.Self;
782 procedure Set_Priority
784 Prio : System.Any_Priority;
785 Loss_Of_Inheritance : Boolean := False)
787 pragma Unreferenced (Loss_Of_Inheritance);
789 Result : Interfaces.C.int;
790 pragma Unreferenced (Result);
792 Param : aliased struct_pcparms;
797 T.Common.Current_Priority := Prio;
799 if Priority_Ceiling_Emulation then
800 T.Common.LL.Active_Priority := Prio;
803 if Using_Real_Time_Class then
804 Param.pc_cid := Prio_Param.pc_cid;
805 Param.rt_pri := pri_t (Prio);
806 Param.rt_tqsecs := Prio_Param.rt_tqsecs;
807 Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
809 Result := Interfaces.C.int (
810 priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
814 if T.Common.Task_Info /= null
815 and then not T.Common.Task_Info.Bound_To_LWP
817 -- The task is not bound to a LWP, so use thr_setprio
820 thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
824 -- The task is bound to a LWP, use priocntl
836 function Get_Priority (T : Task_Id) return System.Any_Priority is
838 return T.Common.Current_Priority;
845 procedure Enter_Task (Self_ID : Task_Id) is
846 Result : Interfaces.C.int;
847 Proc : processorid_t; -- User processor #
848 Last_Proc : processorid_t; -- Last processor #
850 use System.Task_Info;
852 Self_ID.Common.LL.Thread := thr_self;
854 Self_ID.Common.LL.LWP := lwp_self;
856 if Self_ID.Common.Task_Info /= null then
857 if Self_ID.Common.Task_Info.New_LWP
858 and then Self_ID.Common.Task_Info.CPU /= CPU_UNCHANGED
860 Last_Proc := Num_Procs - 1;
862 if Self_ID.Common.Task_Info.CPU = ANY_CPU then
866 while Proc < Last_Proc loop
867 Result := p_online (Proc, PR_STATUS);
868 exit when Result = PR_ONLINE;
872 Result := processor_bind (P_LWPID, P_MYID, Proc, null);
873 pragma Assert (Result = 0);
876 -- Use specified processor
878 if Self_ID.Common.Task_Info.CPU < 0
879 or else Self_ID.Common.Task_Info.CPU > Last_Proc
881 raise Invalid_CPU_Number;
884 Result := processor_bind
885 (P_LWPID, P_MYID, Self_ID.Common.Task_Info.CPU, null);
886 pragma Assert (Result = 0);
891 Specific.Set (Self_ID);
893 -- We need the above code even if we do direct fetch of Task_Id in Self
894 -- for the main task on Sun, x86 Solaris and for gcc 2.7.2.
898 for J in Known_Tasks'Range loop
899 if Known_Tasks (J) = null then
900 Known_Tasks (J) := Self_ID;
901 Self_ID.Known_Tasks_Index := J;
913 function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
915 return new Ada_Task_Control_Block (Entry_Num);
922 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
924 -----------------------------
925 -- Register_Foreign_Thread --
926 -----------------------------
928 function Register_Foreign_Thread return Task_Id is
930 if Is_Valid_Task then
933 return Register_Foreign_Thread (thr_self);
935 end Register_Foreign_Thread;
941 procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
942 Result : Interfaces.C.int := 0;
945 -- Give the task a unique serial number.
947 Self_ID.Serial_Number := Next_Serial_Number;
948 Next_Serial_Number := Next_Serial_Number + 1;
949 pragma Assert (Next_Serial_Number /= 0);
951 Self_ID.Common.LL.Thread := To_thread_t (-1);
953 if not Single_Lock then
955 (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
956 Self_ID.Common.LL.L.Level :=
957 Private_Task_Serial_Number (Self_ID.Serial_Number);
958 pragma Assert (Result = 0 or else Result = ENOMEM);
962 Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
963 pragma Assert (Result = 0 or else Result = ENOMEM);
969 if not Single_Lock then
970 Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
971 pragma Assert (Result = 0);
982 procedure Create_Task
984 Wrapper : System.Address;
985 Stack_Size : System.Parameters.Size_Type;
986 Priority : System.Any_Priority;
987 Succeeded : out Boolean)
989 pragma Unreferenced (Priority);
991 Result : Interfaces.C.int;
992 Adjusted_Stack_Size : Interfaces.C.size_t;
993 Opts : Interfaces.C.int := THR_DETACHED;
995 Page_Size : constant System.Parameters.Size_Type := 4096;
996 -- This constant is for reserving extra space at the
997 -- end of the stack, which can be used by the stack
998 -- checking as guard page. The idea is that we need
999 -- to have at least Stack_Size bytes available for
1002 use System.Task_Info;
1005 Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size + Page_Size);
1007 -- Since the initial signal mask of a thread is inherited from the
1008 -- creator, and the Environment task has all its signals masked, we
1009 -- do not need to manipulate caller's signal mask at this point.
1010 -- All tasks in RTS will have All_Tasks_Mask initially.
1012 if T.Common.Task_Info /= null then
1013 if T.Common.Task_Info.New_LWP then
1014 Opts := Opts + THR_NEW_LWP;
1017 if T.Common.Task_Info.Bound_To_LWP then
1018 Opts := Opts + THR_BOUND;
1022 Opts := THR_DETACHED + THR_BOUND;
1025 Result := thr_create
1026 (System.Null_Address,
1027 Adjusted_Stack_Size,
1028 Thread_Body_Access (Wrapper),
1031 T.Common.LL.Thread'Access);
1033 Succeeded := Result = 0;
1036 or else Result = ENOMEM
1037 or else Result = EAGAIN);
1044 procedure Finalize_TCB (T : Task_Id) is
1045 Result : Interfaces.C.int;
1047 Is_Self : constant Boolean := T = Self;
1049 procedure Free is new
1050 Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
1053 T.Common.LL.Thread := To_thread_t (0);
1055 if not Single_Lock then
1056 Result := mutex_destroy (T.Common.LL.L.L'Access);
1057 pragma Assert (Result = 0);
1060 Result := cond_destroy (T.Common.LL.CV'Access);
1061 pragma Assert (Result = 0);
1063 if T.Known_Tasks_Index /= -1 then
1064 Known_Tasks (T.Known_Tasks_Index) := null;
1070 Specific.Set (null);
1078 -- This procedure must be called with abort deferred.
1079 -- It can no longer call Self or access
1080 -- the current task's ATCB, since the ATCB has been deallocated.
1082 procedure Exit_Task is
1084 Specific.Set (null);
1091 procedure Abort_Task (T : Task_Id) is
1092 Result : Interfaces.C.int;
1094 pragma Assert (T /= Self);
1096 Result := thr_kill (T.Common.LL.Thread,
1097 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1098 pragma Assert (Result = 0);
1107 Reason : Task_States)
1109 Result : Interfaces.C.int;
1112 pragma Assert (Check_Sleep (Reason));
1114 if Dynamic_Priority_Support
1115 and then Self_ID.Pending_Priority_Change
1117 Self_ID.Pending_Priority_Change := False;
1118 Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1119 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1124 (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1127 (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1130 pragma Assert (Record_Wakeup
1131 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1132 pragma Assert (Result = 0 or else Result = EINTR);
1135 -- Note that we are relying heaviliy here on the GNAT feature
1136 -- that Calendar.Time, System.Real_Time.Time, Duration, and
1137 -- System.Real_Time.Time_Span are all represented in the same
1138 -- way, i.e., as a 64-bit count of nanoseconds.
1140 -- This allows us to always pass the timeout value as a Duration.
1143 -- We are taking liberties here with the semantics of the delays.
1144 -- That is, we make no distinction between delays on the Calendar clock
1145 -- and delays on the Real_Time clock. That is technically incorrect, if
1146 -- the Calendar clock happens to be reset or adjusted.
1147 -- To solve this defect will require modification to the compiler
1148 -- interface, so that it can pass through more information, to tell
1149 -- us here which clock to use!
1151 -- cond_timedwait will return if any of the following happens:
1152 -- 1) some other task did cond_signal on this condition variable
1153 -- In this case, the return value is 0
1154 -- 2) the call just returned, for no good reason
1155 -- This is called a "spurious wakeup".
1156 -- In this case, the return value may also be 0.
1157 -- 3) the time delay expires
1158 -- In this case, the return value is ETIME
1159 -- 4) this task received a signal, which was handled by some
1160 -- handler procedure, and now the thread is resuming execution
1161 -- UNIX calls this an "interrupted" system call.
1162 -- In this case, the return value is EINTR
1164 -- If the cond_timedwait returns 0 or EINTR, it is still
1165 -- possible that the time has actually expired, and by chance
1166 -- a signal or cond_signal occurred at around the same time.
1168 -- We have also observed that on some OS's the value ETIME
1169 -- will be returned, but the clock will show that the full delay
1170 -- has not yet expired.
1172 -- For these reasons, we need to check the clock after return
1173 -- from cond_timedwait. If the time has expired, we will set
1176 -- This check might be omitted for systems on which the
1177 -- cond_timedwait() never returns early or wakes up spuriously.
1179 -- Annex D requires that completion of a delay cause the task
1180 -- to go to the end of its priority queue, regardless of whether
1181 -- the task actually was suspended by the delay. Since
1182 -- cond_timedwait does not do this on Solaris, we add a call
1183 -- to thr_yield at the end. We might do this at the beginning,
1184 -- instead, but then the round-robin effect would not be the
1185 -- same; the delayed task would be ahead of other tasks of the
1186 -- same priority that awoke while it was sleeping.
1188 -- For Timed_Sleep, we are expecting possible cond_signals
1189 -- to indicate other events (e.g., completion of a RV or
1190 -- completion of the abortable part of an async. select),
1191 -- we want to always return if interrupted. The caller will
1192 -- be responsible for checking the task state to see whether
1193 -- the wakeup was spurious, and to go back to sleep again
1194 -- in that case. We don't need to check for pending abort
1195 -- or priority change on the way in our out; that is the
1196 -- caller's responsibility.
1198 -- For Timed_Delay, we are not expecting any cond_signals or
1199 -- other interruptions, except for priority changes and aborts.
1200 -- Therefore, we don't want to return unless the delay has
1201 -- actually expired, or the call has been aborted. In this
1202 -- case, since we want to implement the entire delay statement
1203 -- semantics, we do need to check for pending abort and priority
1204 -- changes. We can quietly handle priority changes inside the
1205 -- procedure, since there is no entry-queue reordering involved.
1211 procedure Timed_Sleep
1214 Mode : ST.Delay_Modes;
1215 Reason : System.Tasking.Task_States;
1216 Timedout : out Boolean;
1217 Yielded : out Boolean)
1219 Check_Time : constant Duration := Monotonic_Clock;
1220 Abs_Time : Duration;
1221 Request : aliased timespec;
1222 Result : Interfaces.C.int;
1225 pragma Assert (Check_Sleep (Reason));
1229 if Mode = Relative then
1230 Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
1232 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1235 if Abs_Time > Check_Time then
1236 Request := To_Timespec (Abs_Time);
1239 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
1240 or else (Dynamic_Priority_Support and then
1241 Self_ID.Pending_Priority_Change);
1244 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1245 Single_RTS_Lock.L'Access, Request'Access);
1247 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1248 Self_ID.Common.LL.L.L'Access, Request'Access);
1253 exit when Abs_Time <= Monotonic_Clock;
1255 if Result = 0 or Result = EINTR then
1257 -- Somebody may have called Wakeup for us
1263 pragma Assert (Result = ETIME);
1267 pragma Assert (Record_Wakeup
1268 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1275 procedure Timed_Delay
1278 Mode : ST.Delay_Modes)
1280 Check_Time : constant Duration := Monotonic_Clock;
1281 Abs_Time : Duration;
1282 Request : aliased timespec;
1283 Result : Interfaces.C.int;
1284 Yielded : Boolean := False;
1291 Write_Lock (Self_ID);
1293 if Mode = Relative then
1294 Abs_Time := Time + Check_Time;
1296 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1299 if Abs_Time > Check_Time then
1300 Request := To_Timespec (Abs_Time);
1301 Self_ID.Common.State := Delay_Sleep;
1303 pragma Assert (Check_Sleep (Delay_Sleep));
1306 if Dynamic_Priority_Support and then
1307 Self_ID.Pending_Priority_Change then
1308 Self_ID.Pending_Priority_Change := False;
1309 Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1310 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1313 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1316 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1317 Single_RTS_Lock.L'Access, Request'Access);
1319 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1320 Self_ID.Common.LL.L.L'Access, Request'Access);
1325 exit when Abs_Time <= Monotonic_Clock;
1327 pragma Assert (Result = 0 or else
1328 Result = ETIME or else
1332 pragma Assert (Record_Wakeup
1333 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1335 Self_ID.Common.State := Runnable;
1355 Reason : Task_States)
1357 Result : Interfaces.C.int;
1360 pragma Assert (Check_Wakeup (T, Reason));
1361 Result := cond_signal (T.Common.LL.CV'Access);
1362 pragma Assert (Result = 0);
1365 ---------------------------
1366 -- Check_Initialize_Lock --
1367 ---------------------------
1369 -- The following code is intended to check some of the invariant
1370 -- assertions related to lock usage, on which we depend.
1372 function Check_Initialize_Lock
1374 Level : Lock_Level) return Boolean
1376 Self_ID : constant Task_Id := Self;
1379 -- Check that caller is abort-deferred
1381 if Self_ID.Deferral_Level = 0 then
1385 -- Check that the lock is not yet initialized
1387 if L.Level /= 0 then
1391 L.Level := Lock_Level'Pos (Level) + 1;
1393 end Check_Initialize_Lock;
1399 function Check_Lock (L : Lock_Ptr) return Boolean is
1400 Self_ID : constant Task_Id := Self;
1404 -- Check that the argument is not null
1410 -- Check that L is not frozen
1416 -- Check that caller is abort-deferred
1418 if Self_ID.Deferral_Level = 0 then
1422 -- Check that caller is not holding this lock already
1424 if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1432 -- Check that TCB lock order rules are satisfied
1434 P := Self_ID.Common.LL.Locks;
1436 if P.Level >= L.Level
1437 and then (P.Level > 2 or else L.Level > 2)
1450 function Record_Lock (L : Lock_Ptr) return Boolean is
1451 Self_ID : constant Task_Id := Self;
1455 Lock_Count := Lock_Count + 1;
1457 -- There should be no owner for this lock at this point
1459 if L.Owner /= null then
1465 L.Owner := To_Owner_ID (To_Address (Self_ID));
1471 -- Check that TCB lock order rules are satisfied
1473 P := Self_ID.Common.LL.Locks;
1479 Self_ID.Common.LL.Locking := null;
1480 Self_ID.Common.LL.Locks := L;
1488 function Check_Sleep (Reason : Task_States) return Boolean is
1489 pragma Unreferenced (Reason);
1491 Self_ID : constant Task_Id := Self;
1495 -- Check that caller is abort-deferred
1497 if Self_ID.Deferral_Level = 0 then
1505 -- Check that caller is holding own lock, on top of list
1507 if Self_ID.Common.LL.Locks /=
1508 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1513 -- Check that TCB lock order rules are satisfied
1515 if Self_ID.Common.LL.Locks.Next /= null then
1519 Self_ID.Common.LL.L.Owner := null;
1520 P := Self_ID.Common.LL.Locks;
1521 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1530 function Record_Wakeup
1532 Reason : Task_States) return Boolean
1534 pragma Unreferenced (Reason);
1536 Self_ID : constant Task_Id := Self;
1542 L.Owner := To_Owner_ID (To_Address (Self_ID));
1548 -- Check that TCB lock order rules are satisfied
1550 P := Self_ID.Common.LL.Locks;
1556 Self_ID.Common.LL.Locking := null;
1557 Self_ID.Common.LL.Locks := L;
1565 function Check_Wakeup
1567 Reason : Task_States) return Boolean
1569 Self_ID : constant Task_Id := Self;
1572 -- Is caller holding T's lock?
1574 if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1578 -- Are reasons for wakeup and sleep consistent?
1580 if T.Common.State /= Reason then
1591 function Check_Unlock (L : Lock_Ptr) return Boolean is
1592 Self_ID : constant Task_Id := Self;
1596 Unlock_Count := Unlock_Count + 1;
1602 if L.Buddy /= null then
1607 Check_Count := Unlock_Count;
1610 if Unlock_Count - Check_Count > 1000 then
1611 Check_Count := Unlock_Count;
1614 -- Check that caller is abort-deferred
1616 if Self_ID.Deferral_Level = 0 then
1620 -- Check that caller is holding this lock, on top of list
1622 if Self_ID.Common.LL.Locks /= L then
1626 -- Record there is no owner now
1629 P := Self_ID.Common.LL.Locks;
1630 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1635 --------------------
1636 -- Check_Finalize --
1637 --------------------
1639 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1640 Self_ID : constant Task_Id := Self;
1643 -- Check that caller is abort-deferred
1645 if Self_ID.Deferral_Level = 0 then
1649 -- Check that no one is holding this lock
1651 if L.Owner /= null then
1657 end Check_Finalize_Lock;
1663 procedure Initialize (S : in out Suspension_Object) is
1664 Result : Interfaces.C.int;
1666 -- Initialize internal state. It is always initialized to False (ARM
1672 -- Initialize internal mutex
1674 Result := mutex_init (S.L'Access, USYNC_THREAD, System.Null_Address);
1675 pragma Assert (Result = 0 or else Result = ENOMEM);
1677 if Result = ENOMEM then
1678 raise Storage_Error with "Failed to allocate a lock";
1681 -- Initialize internal condition variable
1683 Result := cond_init (S.CV'Access, USYNC_THREAD, 0);
1684 pragma Assert (Result = 0 or else Result = ENOMEM);
1687 Result := mutex_destroy (S.L'Access);
1688 pragma Assert (Result = 0);
1690 if Result = ENOMEM then
1691 raise Storage_Error;
1700 procedure Finalize (S : in out Suspension_Object) is
1701 Result : Interfaces.C.int;
1703 -- Destroy internal mutex
1705 Result := mutex_destroy (S.L'Access);
1706 pragma Assert (Result = 0);
1708 -- Destroy internal condition variable
1710 Result := cond_destroy (S.CV'Access);
1711 pragma Assert (Result = 0);
1718 function Current_State (S : Suspension_Object) return Boolean is
1720 -- We do not want to use lock on this read operation. State is marked
1721 -- as Atomic so that we ensure that the value retrieved is correct.
1730 procedure Set_False (S : in out Suspension_Object) is
1731 Result : Interfaces.C.int;
1733 SSL.Abort_Defer.all;
1735 Result := mutex_lock (S.L'Access);
1736 pragma Assert (Result = 0);
1740 Result := mutex_unlock (S.L'Access);
1741 pragma Assert (Result = 0);
1743 SSL.Abort_Undefer.all;
1750 procedure Set_True (S : in out Suspension_Object) is
1751 Result : Interfaces.C.int;
1753 SSL.Abort_Defer.all;
1755 Result := mutex_lock (S.L'Access);
1756 pragma Assert (Result = 0);
1758 -- If there is already a task waiting on this suspension object then
1759 -- we resume it, leaving the state of the suspension object to False,
1760 -- as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1761 -- the state to True.
1767 Result := cond_signal (S.CV'Access);
1768 pragma Assert (Result = 0);
1773 Result := mutex_unlock (S.L'Access);
1774 pragma Assert (Result = 0);
1776 SSL.Abort_Undefer.all;
1779 ------------------------
1780 -- Suspend_Until_True --
1781 ------------------------
1783 procedure Suspend_Until_True (S : in out Suspension_Object) is
1784 Result : Interfaces.C.int;
1786 SSL.Abort_Defer.all;
1788 Result := mutex_lock (S.L'Access);
1789 pragma Assert (Result = 0);
1792 -- Program_Error must be raised upon calling Suspend_Until_True
1793 -- if another task is already waiting on that suspension object
1794 -- (ARM D.10 par. 10).
1796 Result := mutex_unlock (S.L'Access);
1797 pragma Assert (Result = 0);
1799 SSL.Abort_Undefer.all;
1801 raise Program_Error;
1803 -- Suspend the task if the state is False. Otherwise, the task
1804 -- continues its execution, and the state of the suspension object
1805 -- is set to False (ARM D.10 par. 9).
1811 Result := cond_wait (S.CV'Access, S.L'Access);
1814 Result := mutex_unlock (S.L'Access);
1815 pragma Assert (Result = 0);
1817 SSL.Abort_Undefer.all;
1819 end Suspend_Until_True;
1825 function Check_Exit (Self_ID : Task_Id) return Boolean is
1827 -- Check that caller is just holding Global_Task_Lock
1828 -- and no other locks
1830 if Self_ID.Common.LL.Locks = null then
1834 -- 2 = Global_Task_Level
1836 if Self_ID.Common.LL.Locks.Level /= 2 then
1840 if Self_ID.Common.LL.Locks.Next /= null then
1844 -- Check that caller is abort-deferred
1846 if Self_ID.Deferral_Level = 0 then
1853 --------------------
1854 -- Check_No_Locks --
1855 --------------------
1857 function Check_No_Locks (Self_ID : Task_Id) return Boolean is
1859 return Self_ID.Common.LL.Locks = null;
1862 ----------------------
1863 -- Environment_Task --
1864 ----------------------
1866 function Environment_Task return Task_Id is
1868 return Environment_Task_Id;
1869 end Environment_Task;
1875 procedure Lock_RTS is
1877 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1884 procedure Unlock_RTS is
1886 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1893 function Suspend_Task
1895 Thread_Self : Thread_Id) return Boolean
1898 if T.Common.LL.Thread /= Thread_Self then
1899 return thr_suspend (T.Common.LL.Thread) = 0;
1909 function Resume_Task
1911 Thread_Self : Thread_Id) return Boolean
1914 if T.Common.LL.Thread /= Thread_Self then
1915 return thr_continue (T.Common.LL.Thread) = 0;
1921 end System.Task_Primitives.Operations;