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-2008, 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 with
40 -- Turn off polling, we do not want ATC polling to take place during tasking
41 -- operations. It causes infinite loops and other problems.
43 with Ada.Unchecked_Deallocation;
47 with System.Tasking.Debug;
48 with System.Interrupt_Management;
49 with System.OS_Primitives;
50 with System.Task_Info;
52 pragma Warnings (Off);
56 with System.Soft_Links;
57 -- We use System.Soft_Links instead of System.Tasking.Initialization
58 -- because the later is a higher level package that we shouldn't depend on.
59 -- For example when using the restricted run time, it is replaced by
60 -- System.Tasking.Restricted.Stages.
62 package body System.Task_Primitives.Operations is
64 package SSL renames System.Soft_Links;
66 use System.Tasking.Debug;
69 use System.OS_Interface;
70 use System.Parameters;
71 use System.OS_Primitives;
77 -- The following are logically constants, but need to be initialized
80 Environment_Task_Id : Task_Id;
81 -- A variable to hold Task_Id for the environment task.
82 -- If we use this variable to get the Task_Id, we need the following
83 -- ATCB_Key only for non-Ada threads.
85 Unblocked_Signal_Mask : aliased sigset_t;
86 -- The set of signals that should unblocked in all tasks
88 ATCB_Key : aliased thread_key_t;
89 -- Key used to find the Ada Task_Id associated with a thread,
90 -- at least for C threads unknown to the Ada run-time system.
92 Single_RTS_Lock : aliased RTS_Lock;
93 -- This is a lock to allow only one thread of control in the RTS at
94 -- a time; it is used to execute in mutual exclusion from all other tasks.
95 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
97 Next_Serial_Number : Task_Serial_Number := 100;
98 -- We start at 100, to reserve some special values for
99 -- using in error checking.
100 -- The following are internal configuration constants needed.
102 ----------------------
103 -- Priority Support --
104 ----------------------
106 Priority_Ceiling_Emulation : constant Boolean := True;
107 -- controls whether we emulate priority ceiling locking
109 -- To get a scheduling close to annex D requirements, we use the real-time
110 -- class provided for LWP's and map each task/thread to a specific and
111 -- unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
113 -- The real time class can only be set when the process has root
114 -- priviledges, so in the other cases, we use the normal thread scheduling
115 -- and priority handling.
117 Using_Real_Time_Class : Boolean := False;
118 -- indicates wether the real time class is being used (i.e the process
119 -- has root priviledges).
121 Prio_Param : aliased struct_pcparms;
122 -- Hold priority info (Real_Time) initialized during the package
125 -----------------------------------
126 -- External Configuration Values --
127 -----------------------------------
129 Time_Slice_Val : Integer;
130 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
132 Locking_Policy : Character;
133 pragma Import (C, Locking_Policy, "__gl_locking_policy");
135 Dispatching_Policy : Character;
136 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
138 Foreign_Task_Elaborated : aliased Boolean := True;
139 -- Used to identified fake tasks (i.e., non-Ada Threads)
141 -----------------------
142 -- Local Subprograms --
143 -----------------------
145 function sysconf (name : System.OS_Interface.int) return processorid_t;
146 pragma Import (C, sysconf, "sysconf");
148 SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
151 (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
152 return processorid_t renames sysconf;
154 procedure Abort_Handler
156 Code : not null access siginfo_t;
157 Context : not null access ucontext_t);
158 -- Target-dependent binding of inter-thread Abort signal to
159 -- the raising of the Abort_Signal exception.
160 -- See also comments in 7staprop.adb
166 function Check_Initialize_Lock
168 Level : Lock_Level) return Boolean;
169 pragma Inline (Check_Initialize_Lock);
171 function Check_Lock (L : Lock_Ptr) return Boolean;
172 pragma Inline (Check_Lock);
174 function Record_Lock (L : Lock_Ptr) return Boolean;
175 pragma Inline (Record_Lock);
177 function Check_Sleep (Reason : Task_States) return Boolean;
178 pragma Inline (Check_Sleep);
180 function Record_Wakeup
182 Reason : Task_States) return Boolean;
183 pragma Inline (Record_Wakeup);
185 function Check_Wakeup
187 Reason : Task_States) return Boolean;
188 pragma Inline (Check_Wakeup);
190 function Check_Unlock (L : Lock_Ptr) return Boolean;
191 pragma Inline (Check_Unlock);
193 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
194 pragma Inline (Check_Finalize_Lock);
202 procedure Initialize (Environment_Task : Task_Id);
203 pragma Inline (Initialize);
204 -- Initialize various data needed by this package
206 function Is_Valid_Task return Boolean;
207 pragma Inline (Is_Valid_Task);
208 -- Does executing thread have a TCB?
210 procedure Set (Self_Id : Task_Id);
212 -- Set the self id for the current task
214 function Self return Task_Id;
215 pragma Inline (Self);
216 -- Return a pointer to the Ada Task Control Block of the calling task
220 package body Specific is separate;
221 -- The body of this package is target specific
223 ---------------------------------
224 -- Support for foreign threads --
225 ---------------------------------
227 function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
228 -- Allocate and Initialize a new ATCB for the current Thread
230 function Register_Foreign_Thread
231 (Thread : Thread_Id) return Task_Id is separate;
237 Check_Count : Integer := 0;
238 Lock_Count : Integer := 0;
239 Unlock_Count : Integer := 0;
245 procedure Abort_Handler
247 Code : not null access siginfo_t;
248 Context : not null access ucontext_t)
250 pragma Unreferenced (Sig);
251 pragma Unreferenced (Code);
252 pragma Unreferenced (Context);
254 Self_ID : constant Task_Id := Self;
255 Old_Set : aliased sigset_t;
257 Result : Interfaces.C.int;
258 pragma Warnings (Off, Result);
261 -- It is not safe to raise an exception when using ZCX and the GCC
262 -- exception handling mechanism.
264 if ZCX_By_Default and then GCC_ZCX_Support then
268 if Self_ID.Deferral_Level = 0
269 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
270 and then not Self_ID.Aborting
272 Self_ID.Aborting := True;
274 -- Make sure signals used for RTS internal purpose are unmasked
279 Unblocked_Signal_Mask'Unchecked_Access,
280 Old_Set'Unchecked_Access);
281 pragma Assert (Result = 0);
283 raise Standard'Abort_Signal;
291 -- The underlying thread system sets a guard page at the
292 -- bottom of a thread stack, so nothing is needed.
294 procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
295 pragma Unreferenced (T);
296 pragma Unreferenced (On);
305 function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
307 return T.Common.LL.Thread;
314 procedure Initialize (Environment_Task : ST.Task_Id) is
315 act : aliased struct_sigaction;
316 old_act : aliased struct_sigaction;
317 Tmp_Set : aliased sigset_t;
318 Result : Interfaces.C.int;
320 procedure Configure_Processors;
321 -- Processors configuration
322 -- The user can specify a processor which the program should run
323 -- on to emulate a single-processor system. This can be easily
324 -- done by setting environment variable GNAT_PROCESSOR to one of
327 -- -2 : use the default configuration (run the program on all
328 -- available processors) - this is the same as having
329 -- GNAT_PROCESSOR unset
330 -- -1 : let the RTS choose one processor and run the program on
332 -- 0 .. Last_Proc : run the program on the specified processor
334 -- Last_Proc is equal to the value of the system variable
335 -- _SC_NPROCESSORS_CONF, minus one.
337 procedure Configure_Processors is
338 Proc_Acc : constant System.OS_Lib.String_Access :=
339 System.OS_Lib.Getenv ("GNAT_PROCESSOR");
340 Proc : aliased processorid_t; -- User processor #
341 Last_Proc : processorid_t; -- Last processor #
344 if Proc_Acc.all'Length /= 0 then
346 -- Environment variable is defined
348 Last_Proc := Num_Procs - 1;
350 if Last_Proc /= -1 then
351 Proc := processorid_t'Value (Proc_Acc.all);
353 if Proc <= -2 or else Proc > Last_Proc then
355 -- Use the default configuration
361 -- Choose a processor
364 while Proc < Last_Proc loop
366 Result := p_online (Proc, PR_STATUS);
367 exit when Result = PR_ONLINE;
370 pragma Assert (Result = PR_ONLINE);
371 Result := processor_bind (P_PID, P_MYID, Proc, null);
372 pragma Assert (Result = 0);
375 -- Use user processor
377 Result := processor_bind (P_PID, P_MYID, Proc, null);
378 pragma Assert (Result = 0);
384 when Constraint_Error =>
386 -- Illegal environment variable GNAT_PROCESSOR - ignored
389 end Configure_Processors;
392 (Int : System.Interrupt_Management.Interrupt_ID) return Character;
393 pragma Import (C, State, "__gnat_get_interrupt_state");
394 -- Get interrupt state. Defined in a-init.c
395 -- The input argument is the interrupt number,
396 -- and the result is one of the following:
398 Default : constant Character := 's';
399 -- 'n' this interrupt not set by any Interrupt_State pragma
400 -- 'u' Interrupt_State pragma set state to User
401 -- 'r' Interrupt_State pragma set state to Runtime
402 -- 's' Interrupt_State pragma set state to System (use "default"
405 -- Start of processing for Initialize
408 Environment_Task_Id := Environment_Task;
410 Interrupt_Management.Initialize;
412 -- Prepare the set of signals that should unblocked in all tasks
414 Result := sigemptyset (Unblocked_Signal_Mask'Access);
415 pragma Assert (Result = 0);
417 for J in Interrupt_Management.Interrupt_ID loop
418 if System.Interrupt_Management.Keep_Unmasked (J) then
419 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
420 pragma Assert (Result = 0);
424 if Dispatching_Policy = 'F' then
426 Result : Interfaces.C.long;
427 Class_Info : aliased struct_pcinfo;
428 Secs, Nsecs : Interfaces.C.long;
431 -- If a pragma Time_Slice is specified, takes the value in account
433 if Time_Slice_Val > 0 then
435 -- Convert Time_Slice_Val (microseconds) to seconds/nanosecs
437 Secs := Interfaces.C.long (Time_Slice_Val / 1_000_000);
439 Interfaces.C.long ((Time_Slice_Val rem 1_000_000) * 1_000);
441 -- Otherwise, default to no time slicing (i.e run until blocked)
448 -- Get the real time class id
450 Class_Info.pc_clname (1) := 'R';
451 Class_Info.pc_clname (2) := 'T';
452 Class_Info.pc_clname (3) := ASCII.NUL;
454 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
457 -- Request the real time class
459 Prio_Param.pc_cid := Class_Info.pc_cid;
460 Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
461 Prio_Param.rt_tqsecs := Secs;
462 Prio_Param.rt_tqnsecs := Nsecs;
466 (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS, Prio_Param'Address);
468 Using_Real_Time_Class := Result /= -1;
472 Specific.Initialize (Environment_Task);
474 -- The following is done in Enter_Task, but this is too late for the
475 -- Environment Task, since we need to call Self in Check_Locks when
476 -- the run time is compiled with assertions on.
478 Specific.Set (Environment_Task);
480 -- Initialize the lock used to synchronize chain of all ATCBs
482 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
484 Enter_Task (Environment_Task);
486 -- Install the abort-signal handler
489 (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
491 -- Set sa_flags to SA_NODEFER so that during the handler execution
492 -- we do not change the Signal_Mask to be masked for the Abort_Signal
493 -- This is a temporary fix to the problem that the Signal_Mask is
494 -- not restored after the exception (longjmp) from the handler.
495 -- The right fix should be made in sigsetjmp so that we save
496 -- the Signal_Set and restore it after a longjmp.
497 -- In that case, this field should be changed back to 0. ???
501 act.sa_handler := Abort_Handler'Address;
502 Result := sigemptyset (Tmp_Set'Access);
503 pragma Assert (Result = 0);
504 act.sa_mask := Tmp_Set;
508 (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
509 act'Unchecked_Access,
510 old_act'Unchecked_Access);
511 pragma Assert (Result = 0);
514 Configure_Processors;
517 ---------------------
518 -- Initialize_Lock --
519 ---------------------
521 -- Note: mutexes and cond_variables needed per-task basis are initialized
522 -- in Initialize_TCB and the Storage_Error is handled. Other mutexes (such
523 -- as RTS_Lock, Memory_Lock...) used in RTS is initialized before any
524 -- status change of RTS. Therefore rasing Storage_Error in the following
525 -- routines should be able to be handled safely.
527 procedure Initialize_Lock
528 (Prio : System.Any_Priority;
529 L : not null access Lock)
531 Result : Interfaces.C.int;
534 pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
536 if Priority_Ceiling_Emulation then
540 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
541 pragma Assert (Result = 0 or else Result = ENOMEM);
543 if Result = ENOMEM then
544 raise Storage_Error with "Failed to allocate a lock";
548 procedure Initialize_Lock
549 (L : not null access RTS_Lock;
552 Result : Interfaces.C.int;
556 (Check_Initialize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
557 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
558 pragma Assert (Result = 0 or else Result = ENOMEM);
560 if Result = ENOMEM then
561 raise Storage_Error with "Failed to allocate a lock";
569 procedure Finalize_Lock (L : not null access Lock) is
570 Result : Interfaces.C.int;
572 pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
573 Result := mutex_destroy (L.L'Access);
574 pragma Assert (Result = 0);
577 procedure Finalize_Lock (L : not null access RTS_Lock) is
578 Result : Interfaces.C.int;
580 pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
581 Result := mutex_destroy (L.L'Access);
582 pragma Assert (Result = 0);
590 (L : not null access Lock;
591 Ceiling_Violation : out Boolean)
593 Result : Interfaces.C.int;
596 pragma Assert (Check_Lock (Lock_Ptr (L)));
598 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
600 Self_Id : constant Task_Id := Self;
601 Saved_Priority : System.Any_Priority;
604 if Self_Id.Common.LL.Active_Priority > L.Ceiling then
605 Ceiling_Violation := True;
609 Saved_Priority := Self_Id.Common.LL.Active_Priority;
611 if Self_Id.Common.LL.Active_Priority < L.Ceiling then
612 Set_Priority (Self_Id, L.Ceiling);
615 Result := mutex_lock (L.L'Access);
616 pragma Assert (Result = 0);
617 Ceiling_Violation := False;
619 L.Saved_Priority := Saved_Priority;
623 Result := mutex_lock (L.L'Access);
624 pragma Assert (Result = 0);
625 Ceiling_Violation := False;
628 pragma Assert (Record_Lock (Lock_Ptr (L)));
632 (L : not null access RTS_Lock;
633 Global_Lock : Boolean := False)
635 Result : Interfaces.C.int;
637 if not Single_Lock or else Global_Lock then
638 pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
639 Result := mutex_lock (L.L'Access);
640 pragma Assert (Result = 0);
641 pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
645 procedure Write_Lock (T : Task_Id) is
646 Result : Interfaces.C.int;
648 if not Single_Lock then
649 pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
650 Result := mutex_lock (T.Common.LL.L.L'Access);
651 pragma Assert (Result = 0);
652 pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
661 (L : not null access Lock;
662 Ceiling_Violation : out Boolean) is
664 Write_Lock (L, Ceiling_Violation);
671 procedure Unlock (L : not null access Lock) is
672 Result : Interfaces.C.int;
675 pragma Assert (Check_Unlock (Lock_Ptr (L)));
677 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
679 Self_Id : constant Task_Id := Self;
682 Result := mutex_unlock (L.L'Access);
683 pragma Assert (Result = 0);
685 if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
686 Set_Priority (Self_Id, L.Saved_Priority);
690 Result := mutex_unlock (L.L'Access);
691 pragma Assert (Result = 0);
696 (L : not null access RTS_Lock;
697 Global_Lock : Boolean := False)
699 Result : Interfaces.C.int;
701 if not Single_Lock or else Global_Lock then
702 pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
703 Result := mutex_unlock (L.L'Access);
704 pragma Assert (Result = 0);
708 procedure Unlock (T : Task_Id) is
709 Result : Interfaces.C.int;
711 if not Single_Lock then
712 pragma Assert (Check_Unlock (To_Lock_Ptr (T.Common.LL.L'Access)));
713 Result := mutex_unlock (T.Common.LL.L.L'Access);
714 pragma Assert (Result = 0);
722 -- Dynamic priority ceilings are not supported by the underlying system
724 procedure Set_Ceiling
725 (L : not null access Lock;
726 Prio : System.Any_Priority)
728 pragma Unreferenced (L, Prio);
733 -- For the time delay implementation, we need to make sure we
734 -- achieve following criteria:
736 -- 1) We have to delay at least for the amount requested.
737 -- 2) We have to give up CPU even though the actual delay does not
738 -- result in blocking.
739 -- 3) Except for restricted run-time systems that do not support
740 -- ATC or task abort, the delay must be interrupted by the
741 -- abort_task operation.
742 -- 4) The implementation has to be efficient so that the delay overhead
743 -- is relatively cheap.
744 -- (1)-(3) are Ada requirements. Even though (2) is an Annex-D
745 -- requirement we still want to provide the effect in all cases.
746 -- The reason is that users may want to use short delays to implement
747 -- their own scheduling effect in the absence of language provided
748 -- scheduling policies.
750 ---------------------
751 -- Monotonic_Clock --
752 ---------------------
754 function Monotonic_Clock return Duration is
755 TS : aliased timespec;
756 Result : Interfaces.C.int;
758 Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
759 pragma Assert (Result = 0);
760 return To_Duration (TS);
767 function RT_Resolution return Duration is
776 procedure Yield (Do_Yield : Boolean := True) is
779 System.OS_Interface.thr_yield;
787 function Self return Task_Id renames Specific.Self;
793 procedure Set_Priority
795 Prio : System.Any_Priority;
796 Loss_Of_Inheritance : Boolean := False)
798 pragma Unreferenced (Loss_Of_Inheritance);
800 Result : Interfaces.C.int;
801 pragma Unreferenced (Result);
803 Param : aliased struct_pcparms;
808 T.Common.Current_Priority := Prio;
810 if Priority_Ceiling_Emulation then
811 T.Common.LL.Active_Priority := Prio;
814 if Using_Real_Time_Class then
815 Param.pc_cid := Prio_Param.pc_cid;
816 Param.rt_pri := pri_t (Prio);
817 Param.rt_tqsecs := Prio_Param.rt_tqsecs;
818 Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
820 Result := Interfaces.C.int (
821 priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
825 if T.Common.Task_Info /= null
826 and then not T.Common.Task_Info.Bound_To_LWP
828 -- The task is not bound to a LWP, so use thr_setprio
831 thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
834 -- The task is bound to a LWP, use priocntl
846 function Get_Priority (T : Task_Id) return System.Any_Priority is
848 return T.Common.Current_Priority;
855 procedure Enter_Task (Self_ID : Task_Id) is
856 Result : Interfaces.C.int;
857 Proc : processorid_t; -- User processor #
858 Last_Proc : processorid_t; -- Last processor #
860 use System.Task_Info;
862 Self_ID.Common.LL.Thread := thr_self;
864 Self_ID.Common.LL.LWP := lwp_self;
866 if Self_ID.Common.Task_Info /= null then
867 if Self_ID.Common.Task_Info.New_LWP
868 and then Self_ID.Common.Task_Info.CPU /= CPU_UNCHANGED
870 Last_Proc := Num_Procs - 1;
872 if Self_ID.Common.Task_Info.CPU = ANY_CPU then
875 while Proc < Last_Proc loop
876 Result := p_online (Proc, PR_STATUS);
877 exit when Result = PR_ONLINE;
881 Result := processor_bind (P_LWPID, P_MYID, Proc, null);
882 pragma Assert (Result = 0);
885 -- Use specified processor
887 if Self_ID.Common.Task_Info.CPU < 0
888 or else Self_ID.Common.Task_Info.CPU > Last_Proc
890 raise Invalid_CPU_Number;
895 (P_LWPID, P_MYID, Self_ID.Common.Task_Info.CPU, null);
896 pragma Assert (Result = 0);
901 Specific.Set (Self_ID);
903 -- We need the above code even if we do direct fetch of Task_Id in Self
904 -- for the main task on Sun, x86 Solaris and for gcc 2.7.2.
908 for J in Known_Tasks'Range loop
909 if Known_Tasks (J) = null then
910 Known_Tasks (J) := Self_ID;
911 Self_ID.Known_Tasks_Index := J;
923 function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
925 return new Ada_Task_Control_Block (Entry_Num);
932 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
934 -----------------------------
935 -- Register_Foreign_Thread --
936 -----------------------------
938 function Register_Foreign_Thread return Task_Id is
940 if Is_Valid_Task then
943 return Register_Foreign_Thread (thr_self);
945 end Register_Foreign_Thread;
951 procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
952 Result : Interfaces.C.int := 0;
955 -- Give the task a unique serial number
957 Self_ID.Serial_Number := Next_Serial_Number;
958 Next_Serial_Number := Next_Serial_Number + 1;
959 pragma Assert (Next_Serial_Number /= 0);
961 Self_ID.Common.LL.Thread := To_thread_t (-1);
963 if not Single_Lock then
966 (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
967 Self_ID.Common.LL.L.Level :=
968 Private_Task_Serial_Number (Self_ID.Serial_Number);
969 pragma Assert (Result = 0 or else Result = ENOMEM);
973 Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
974 pragma Assert (Result = 0 or else Result = ENOMEM);
980 if not Single_Lock then
981 Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
982 pragma Assert (Result = 0);
993 procedure Create_Task
995 Wrapper : System.Address;
996 Stack_Size : System.Parameters.Size_Type;
997 Priority : System.Any_Priority;
998 Succeeded : out Boolean)
1000 pragma Unreferenced (Priority);
1002 Result : Interfaces.C.int;
1003 Adjusted_Stack_Size : Interfaces.C.size_t;
1004 Opts : Interfaces.C.int := THR_DETACHED;
1006 Page_Size : constant System.Parameters.Size_Type := 4096;
1007 -- This constant is for reserving extra space at the
1008 -- end of the stack, which can be used by the stack
1009 -- checking as guard page. The idea is that we need
1010 -- to have at least Stack_Size bytes available for
1013 use System.Task_Info;
1016 Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size + Page_Size);
1018 -- Since the initial signal mask of a thread is inherited from the
1019 -- creator, and the Environment task has all its signals masked, we
1020 -- do not need to manipulate caller's signal mask at this point.
1021 -- All tasks in RTS will have All_Tasks_Mask initially.
1023 if T.Common.Task_Info /= null then
1024 if T.Common.Task_Info.New_LWP then
1025 Opts := Opts + THR_NEW_LWP;
1028 if T.Common.Task_Info.Bound_To_LWP then
1029 Opts := Opts + THR_BOUND;
1033 Opts := THR_DETACHED + THR_BOUND;
1038 (System.Null_Address,
1039 Adjusted_Stack_Size,
1040 Thread_Body_Access (Wrapper),
1043 T.Common.LL.Thread'Access);
1045 Succeeded := Result = 0;
1048 or else Result = ENOMEM
1049 or else Result = EAGAIN);
1056 procedure Finalize_TCB (T : Task_Id) is
1057 Result : Interfaces.C.int;
1059 Is_Self : constant Boolean := T = Self;
1061 procedure Free is new
1062 Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
1065 T.Common.LL.Thread := To_thread_t (0);
1067 if not Single_Lock then
1068 Result := mutex_destroy (T.Common.LL.L.L'Access);
1069 pragma Assert (Result = 0);
1072 Result := cond_destroy (T.Common.LL.CV'Access);
1073 pragma Assert (Result = 0);
1075 if T.Known_Tasks_Index /= -1 then
1076 Known_Tasks (T.Known_Tasks_Index) := null;
1082 Specific.Set (null);
1090 -- This procedure must be called with abort deferred. It can no longer
1091 -- call Self or access the current task's ATCB, since the ATCB has been
1094 procedure Exit_Task is
1096 Specific.Set (null);
1103 procedure Abort_Task (T : Task_Id) is
1104 Result : Interfaces.C.int;
1106 pragma Assert (T /= Self);
1109 (T.Common.LL.Thread,
1110 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1111 pragma Assert (Result = 0);
1120 Reason : Task_States)
1122 Result : Interfaces.C.int;
1125 pragma Assert (Check_Sleep (Reason));
1130 (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1134 (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1138 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1139 pragma Assert (Result = 0 or else Result = EINTR);
1142 -- Note that we are relying heaviliy here on GNAT represting Calendar.Time,
1143 -- System.Real_Time.Time, Duration, System.Real_Time.Time_Span in the same
1144 -- way, i.e., as a 64-bit count of nanoseconds.
1146 -- This allows us to always pass the timeout value as a Duration
1149 -- We are taking liberties here with the semantics of the delays. That is,
1150 -- we make no distinction between delays on the Calendar clock and delays
1151 -- on the Real_Time clock. That is technically incorrect, if the Calendar
1152 -- clock happens to be reset or adjusted. To solve this defect will require
1153 -- modification to the compiler interface, so that it can pass through more
1154 -- information, to tell us here which clock to use!
1156 -- cond_timedwait will return if any of the following happens:
1157 -- 1) some other task did cond_signal on this condition variable
1158 -- In this case, the return value is 0
1159 -- 2) the call just returned, for no good reason
1160 -- This is called a "spurious wakeup".
1161 -- In this case, the return value may also be 0.
1162 -- 3) the time delay expires
1163 -- In this case, the return value is ETIME
1164 -- 4) this task received a signal, which was handled by some
1165 -- handler procedure, and now the thread is resuming execution
1166 -- UNIX calls this an "interrupted" system call.
1167 -- In this case, the return value is EINTR
1169 -- If the cond_timedwait returns 0 or EINTR, it is still possible that the
1170 -- time has actually expired, and by chance a signal or cond_signal
1171 -- occurred at around the same time.
1173 -- We have also observed that on some OS's the value ETIME will be
1174 -- returned, but the clock will show that the full delay has not yet
1177 -- For these reasons, we need to check the clock after return from
1178 -- cond_timedwait. If the time has expired, we will set Timedout = True.
1180 -- This check might be omitted for systems on which the cond_timedwait()
1181 -- never returns early or wakes up spuriously.
1183 -- Annex D requires that completion of a delay cause the task to go to the
1184 -- end of its priority queue, regardless of whether the task actually was
1185 -- suspended by the delay. Since cond_timedwait does not do this on
1186 -- Solaris, we add a call to thr_yield at the end. We might do this at the
1187 -- beginning, instead, but then the round-robin effect would not be the
1188 -- same; the delayed task would be ahead of other tasks of the same
1189 -- priority that awoke while it was sleeping.
1191 -- For Timed_Sleep, we are expecting possible cond_signals to indicate
1192 -- other events (e.g., completion of a RV or completion of the abortable
1193 -- part of an async. select), we want to always return if interrupted. The
1194 -- caller will be responsible for checking the task state to see whether
1195 -- the wakeup was spurious, and to go back to sleep again in that case. We
1196 -- don't need to check for pending abort or priority change on the way in
1197 -- our out; that is the caller's responsibility.
1199 -- For Timed_Delay, we are not expecting any cond_signals or other
1200 -- interruptions, except for priority changes and aborts. Therefore, we
1201 -- don't want to return unless the delay has actually expired, or the call
1202 -- has been aborted. In this case, since we want to implement the entire
1203 -- delay statement semantics, we do need to check for pending abort and
1204 -- priority 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 Base_Time : constant Duration := Monotonic_Clock;
1220 Check_Time : Duration := Base_Time;
1221 Abs_Time : Duration;
1222 Request : aliased timespec;
1223 Result : Interfaces.C.int;
1226 pragma Assert (Check_Sleep (Reason));
1230 if Mode = Relative then
1231 Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
1233 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1236 if Abs_Time > Check_Time then
1237 Request := To_Timespec (Abs_Time);
1240 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1245 (Self_ID.Common.LL.CV'Access,
1246 Single_RTS_Lock.L'Access, Request'Access);
1250 (Self_ID.Common.LL.CV'Access,
1251 Self_ID.Common.LL.L.L'Access, Request'Access);
1256 Check_Time := Monotonic_Clock;
1257 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1259 if Result = 0 or Result = EINTR then
1261 -- Somebody may have called Wakeup for us
1267 pragma Assert (Result = ETIME);
1272 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1279 procedure Timed_Delay
1282 Mode : ST.Delay_Modes)
1284 Base_Time : constant Duration := Monotonic_Clock;
1285 Check_Time : Duration := Base_Time;
1286 Abs_Time : Duration;
1287 Request : aliased timespec;
1288 Result : Interfaces.C.int;
1289 Yielded : Boolean := False;
1296 Write_Lock (Self_ID);
1298 if Mode = Relative then
1299 Abs_Time := Time + Check_Time;
1301 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1304 if Abs_Time > Check_Time then
1305 Request := To_Timespec (Abs_Time);
1306 Self_ID.Common.State := Delay_Sleep;
1308 pragma Assert (Check_Sleep (Delay_Sleep));
1311 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1316 (Self_ID.Common.LL.CV'Access,
1317 Single_RTS_Lock.L'Access,
1322 (Self_ID.Common.LL.CV'Access,
1323 Self_ID.Common.LL.L.L'Access,
1329 Check_Time := Monotonic_Clock;
1330 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1334 Result = ETIME or else
1340 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1342 Self_ID.Common.State := Runnable;
1362 Reason : Task_States)
1364 Result : Interfaces.C.int;
1366 pragma Assert (Check_Wakeup (T, Reason));
1367 Result := cond_signal (T.Common.LL.CV'Access);
1368 pragma Assert (Result = 0);
1371 ---------------------------
1372 -- Check_Initialize_Lock --
1373 ---------------------------
1375 -- The following code is intended to check some of the invariant assertions
1376 -- related to lock usage, on which we depend.
1378 function Check_Initialize_Lock
1380 Level : Lock_Level) return Boolean
1382 Self_ID : constant Task_Id := Self;
1385 -- Check that caller is abort-deferred
1387 if Self_ID.Deferral_Level = 0 then
1391 -- Check that the lock is not yet initialized
1393 if L.Level /= 0 then
1397 L.Level := Lock_Level'Pos (Level) + 1;
1399 end Check_Initialize_Lock;
1405 function Check_Lock (L : Lock_Ptr) return Boolean is
1406 Self_ID : constant Task_Id := Self;
1410 -- Check that the argument is not null
1416 -- Check that L is not frozen
1422 -- Check that caller is abort-deferred
1424 if Self_ID.Deferral_Level = 0 then
1428 -- Check that caller is not holding this lock already
1430 if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1438 -- Check that TCB lock order rules are satisfied
1440 P := Self_ID.Common.LL.Locks;
1442 if P.Level >= L.Level
1443 and then (P.Level > 2 or else L.Level > 2)
1456 function Record_Lock (L : Lock_Ptr) return Boolean is
1457 Self_ID : constant Task_Id := Self;
1461 Lock_Count := Lock_Count + 1;
1463 -- There should be no owner for this lock at this point
1465 if L.Owner /= null then
1471 L.Owner := To_Owner_ID (To_Address (Self_ID));
1477 -- Check that TCB lock order rules are satisfied
1479 P := Self_ID.Common.LL.Locks;
1485 Self_ID.Common.LL.Locking := null;
1486 Self_ID.Common.LL.Locks := L;
1494 function Check_Sleep (Reason : Task_States) return Boolean is
1495 pragma Unreferenced (Reason);
1497 Self_ID : constant Task_Id := Self;
1501 -- Check that caller is abort-deferred
1503 if Self_ID.Deferral_Level = 0 then
1511 -- Check that caller is holding own lock, on top of list
1513 if Self_ID.Common.LL.Locks /=
1514 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1519 -- Check that TCB lock order rules are satisfied
1521 if Self_ID.Common.LL.Locks.Next /= null then
1525 Self_ID.Common.LL.L.Owner := null;
1526 P := Self_ID.Common.LL.Locks;
1527 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1536 function Record_Wakeup
1538 Reason : Task_States) return Boolean
1540 pragma Unreferenced (Reason);
1542 Self_ID : constant Task_Id := Self;
1548 L.Owner := To_Owner_ID (To_Address (Self_ID));
1554 -- Check that TCB lock order rules are satisfied
1556 P := Self_ID.Common.LL.Locks;
1562 Self_ID.Common.LL.Locking := null;
1563 Self_ID.Common.LL.Locks := L;
1571 function Check_Wakeup
1573 Reason : Task_States) return Boolean
1575 Self_ID : constant Task_Id := Self;
1578 -- Is caller holding T's lock?
1580 if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1584 -- Are reasons for wakeup and sleep consistent?
1586 if T.Common.State /= Reason then
1597 function Check_Unlock (L : Lock_Ptr) return Boolean is
1598 Self_ID : constant Task_Id := Self;
1602 Unlock_Count := Unlock_Count + 1;
1608 if L.Buddy /= null then
1612 -- Magic constant 4???
1615 Check_Count := Unlock_Count;
1618 -- Magic constant 1000???
1620 if Unlock_Count - Check_Count > 1000 then
1621 Check_Count := Unlock_Count;
1624 -- Check that caller is abort-deferred
1626 if Self_ID.Deferral_Level = 0 then
1630 -- Check that caller is holding this lock, on top of list
1632 if Self_ID.Common.LL.Locks /= L then
1636 -- Record there is no owner now
1639 P := Self_ID.Common.LL.Locks;
1640 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1645 --------------------
1646 -- Check_Finalize --
1647 --------------------
1649 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1650 Self_ID : constant Task_Id := Self;
1653 -- Check that caller is abort-deferred
1655 if Self_ID.Deferral_Level = 0 then
1659 -- Check that no one is holding this lock
1661 if L.Owner /= null then
1667 end Check_Finalize_Lock;
1673 procedure Initialize (S : in out Suspension_Object) is
1674 Result : Interfaces.C.int;
1677 -- Initialize internal state (always to zero (RM D.10(6)))
1682 -- Initialize internal mutex
1684 Result := mutex_init (S.L'Access, USYNC_THREAD, System.Null_Address);
1685 pragma Assert (Result = 0 or else Result = ENOMEM);
1687 if Result = ENOMEM then
1688 raise Storage_Error with "Failed to allocate a lock";
1691 -- Initialize internal condition variable
1693 Result := cond_init (S.CV'Access, USYNC_THREAD, 0);
1694 pragma Assert (Result = 0 or else Result = ENOMEM);
1697 Result := mutex_destroy (S.L'Access);
1698 pragma Assert (Result = 0);
1700 if Result = ENOMEM then
1701 raise Storage_Error;
1710 procedure Finalize (S : in out Suspension_Object) is
1711 Result : Interfaces.C.int;
1714 -- Destroy internal mutex
1716 Result := mutex_destroy (S.L'Access);
1717 pragma Assert (Result = 0);
1719 -- Destroy internal condition variable
1721 Result := cond_destroy (S.CV'Access);
1722 pragma Assert (Result = 0);
1729 function Current_State (S : Suspension_Object) return Boolean is
1731 -- We do not want to use lock on this read operation. State is marked
1732 -- as Atomic so that we ensure that the value retrieved is correct.
1741 procedure Set_False (S : in out Suspension_Object) is
1742 Result : Interfaces.C.int;
1745 SSL.Abort_Defer.all;
1747 Result := mutex_lock (S.L'Access);
1748 pragma Assert (Result = 0);
1752 Result := mutex_unlock (S.L'Access);
1753 pragma Assert (Result = 0);
1755 SSL.Abort_Undefer.all;
1762 procedure Set_True (S : in out Suspension_Object) is
1763 Result : Interfaces.C.int;
1766 SSL.Abort_Defer.all;
1768 Result := mutex_lock (S.L'Access);
1769 pragma Assert (Result = 0);
1771 -- If there is already a task waiting on this suspension object then
1772 -- we resume it, leaving the state of the suspension object to False,
1773 -- as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1774 -- the state to True.
1780 Result := cond_signal (S.CV'Access);
1781 pragma Assert (Result = 0);
1787 Result := mutex_unlock (S.L'Access);
1788 pragma Assert (Result = 0);
1790 SSL.Abort_Undefer.all;
1793 ------------------------
1794 -- Suspend_Until_True --
1795 ------------------------
1797 procedure Suspend_Until_True (S : in out Suspension_Object) is
1798 Result : Interfaces.C.int;
1801 SSL.Abort_Defer.all;
1803 Result := mutex_lock (S.L'Access);
1804 pragma Assert (Result = 0);
1808 -- Program_Error must be raised upon calling Suspend_Until_True
1809 -- if another task is already waiting on that suspension object
1812 Result := mutex_unlock (S.L'Access);
1813 pragma Assert (Result = 0);
1815 SSL.Abort_Undefer.all;
1817 raise Program_Error;
1820 -- Suspend the task if the state is False. Otherwise, the task
1821 -- continues its execution, and the state of the suspension object
1822 -- is set to False (ARM D.10 par. 9).
1828 Result := cond_wait (S.CV'Access, S.L'Access);
1831 Result := mutex_unlock (S.L'Access);
1832 pragma Assert (Result = 0);
1834 SSL.Abort_Undefer.all;
1836 end Suspend_Until_True;
1842 function Check_Exit (Self_ID : Task_Id) return Boolean is
1844 -- Check that caller is just holding Global_Task_Lock and no other locks
1846 if Self_ID.Common.LL.Locks = null then
1850 -- 2 = Global_Task_Level
1852 if Self_ID.Common.LL.Locks.Level /= 2 then
1856 if Self_ID.Common.LL.Locks.Next /= null then
1860 -- Check that caller is abort-deferred
1862 if Self_ID.Deferral_Level = 0 then
1869 --------------------
1870 -- Check_No_Locks --
1871 --------------------
1873 function Check_No_Locks (Self_ID : Task_Id) return Boolean is
1875 return Self_ID.Common.LL.Locks = null;
1878 ----------------------
1879 -- Environment_Task --
1880 ----------------------
1882 function Environment_Task return Task_Id is
1884 return Environment_Task_Id;
1885 end Environment_Task;
1891 procedure Lock_RTS is
1893 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1900 procedure Unlock_RTS is
1902 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1909 function Suspend_Task
1911 Thread_Self : Thread_Id) return Boolean
1914 if T.Common.LL.Thread /= Thread_Self then
1915 return thr_suspend (T.Common.LL.Thread) = 0;
1925 function Resume_Task
1927 Thread_Self : Thread_Id) return Boolean
1930 if T.Common.LL.Thread /= Thread_Self then
1931 return thr_continue (T.Common.LL.Thread) = 0;
1937 --------------------
1938 -- Stop_All_Tasks --
1939 --------------------
1941 procedure Stop_All_Tasks is
1950 function Stop_Task (T : ST.Task_Id) return Boolean is
1951 pragma Unreferenced (T);
1960 function Continue_Task (T : ST.Task_Id) return Boolean is
1961 pragma Unreferenced (T);
1966 end System.Task_Primitives.Operations;