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 LWPs 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 -- privileges, so in the other cases, we use the normal thread scheduling
115 -- and priority handling.
117 Using_Real_Time_Class : Boolean := False;
118 -- indicates whether the real time class is being used (i.e. the process
119 -- has root privileges).
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 raising 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 heavily here on GNAT representing
1143 -- Calendar.Time, System.Real_Time.Time, Duration,
1144 -- System.Real_Time.Time_Span in the same way, i.e., as a 64-bit count of
1147 -- This allows us to always pass the timeout value as a Duration.
1150 -- We are taking liberties here with the semantics of the delays. That is,
1151 -- we make no distinction between delays on the Calendar clock and delays
1152 -- on the Real_Time clock. That is technically incorrect, if the Calendar
1153 -- clock happens to be reset or adjusted. To solve this defect will require
1154 -- modification to the compiler interface, so that it can pass through more
1155 -- information, to tell us here which clock to use!
1157 -- cond_timedwait will return if any of the following happens:
1158 -- 1) some other task did cond_signal on this condition variable
1159 -- In this case, the return value is 0
1160 -- 2) the call just returned, for no good reason
1161 -- This is called a "spurious wakeup".
1162 -- In this case, the return value may also be 0.
1163 -- 3) the time delay expires
1164 -- In this case, the return value is ETIME
1165 -- 4) this task received a signal, which was handled by some
1166 -- handler procedure, and now the thread is resuming execution
1167 -- UNIX calls this an "interrupted" system call.
1168 -- In this case, the return value is EINTR
1170 -- If the cond_timedwait returns 0 or EINTR, it is still possible that the
1171 -- time has actually expired, and by chance a signal or cond_signal
1172 -- occurred at around the same time.
1174 -- We have also observed that on some OS's the value ETIME will be
1175 -- returned, but the clock will show that the full delay has not yet
1178 -- For these reasons, we need to check the clock after return from
1179 -- cond_timedwait. If the time has expired, we will set Timedout = True.
1181 -- This check might be omitted for systems on which the cond_timedwait()
1182 -- never returns early or wakes up spuriously.
1184 -- Annex D requires that completion of a delay cause the task to go to the
1185 -- end of its priority queue, regardless of whether the task actually was
1186 -- suspended by the delay. Since cond_timedwait does not do this on
1187 -- Solaris, we add a call to thr_yield at the end. We might do this at the
1188 -- beginning, instead, but then the round-robin effect would not be the
1189 -- same; the delayed task would be ahead of other tasks of the same
1190 -- priority that awoke while it was sleeping.
1192 -- For Timed_Sleep, we are expecting possible cond_signals to indicate
1193 -- other events (e.g., completion of a RV or completion of the abortable
1194 -- part of an async. select), we want to always return if interrupted. The
1195 -- caller will be responsible for checking the task state to see whether
1196 -- the wakeup was spurious, and to go back to sleep again in that case. We
1197 -- don't need to check for pending abort or priority change on the way in
1198 -- our out; that is the caller's responsibility.
1200 -- For Timed_Delay, we are not expecting any cond_signals or other
1201 -- interruptions, except for priority changes and aborts. Therefore, we
1202 -- don't want to return unless the delay has actually expired, or the call
1203 -- has been aborted. In this case, since we want to implement the entire
1204 -- delay statement semantics, we do need to check for pending abort and
1205 -- priority changes. We can quietly handle priority changes inside the
1206 -- procedure, since there is no entry-queue reordering involved.
1212 procedure Timed_Sleep
1215 Mode : ST.Delay_Modes;
1216 Reason : System.Tasking.Task_States;
1217 Timedout : out Boolean;
1218 Yielded : out Boolean)
1220 Base_Time : constant Duration := Monotonic_Clock;
1221 Check_Time : Duration := Base_Time;
1222 Abs_Time : Duration;
1223 Request : aliased timespec;
1224 Result : Interfaces.C.int;
1227 pragma Assert (Check_Sleep (Reason));
1231 if Mode = Relative then
1232 Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
1234 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1237 if Abs_Time > Check_Time then
1238 Request := To_Timespec (Abs_Time);
1241 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1246 (Self_ID.Common.LL.CV'Access,
1247 Single_RTS_Lock.L'Access, Request'Access);
1251 (Self_ID.Common.LL.CV'Access,
1252 Self_ID.Common.LL.L.L'Access, Request'Access);
1257 Check_Time := Monotonic_Clock;
1258 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1260 if Result = 0 or Result = EINTR then
1262 -- Somebody may have called Wakeup for us
1268 pragma Assert (Result = ETIME);
1273 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1280 procedure Timed_Delay
1283 Mode : ST.Delay_Modes)
1285 Base_Time : constant Duration := Monotonic_Clock;
1286 Check_Time : Duration := Base_Time;
1287 Abs_Time : Duration;
1288 Request : aliased timespec;
1289 Result : Interfaces.C.int;
1290 Yielded : Boolean := False;
1297 Write_Lock (Self_ID);
1299 if Mode = Relative then
1300 Abs_Time := Time + Check_Time;
1302 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1305 if Abs_Time > Check_Time then
1306 Request := To_Timespec (Abs_Time);
1307 Self_ID.Common.State := Delay_Sleep;
1309 pragma Assert (Check_Sleep (Delay_Sleep));
1312 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1317 (Self_ID.Common.LL.CV'Access,
1318 Single_RTS_Lock.L'Access,
1323 (Self_ID.Common.LL.CV'Access,
1324 Self_ID.Common.LL.L.L'Access,
1330 Check_Time := Monotonic_Clock;
1331 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1335 Result = ETIME or else
1341 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1343 Self_ID.Common.State := Runnable;
1363 Reason : Task_States)
1365 Result : Interfaces.C.int;
1367 pragma Assert (Check_Wakeup (T, Reason));
1368 Result := cond_signal (T.Common.LL.CV'Access);
1369 pragma Assert (Result = 0);
1372 ---------------------------
1373 -- Check_Initialize_Lock --
1374 ---------------------------
1376 -- The following code is intended to check some of the invariant assertions
1377 -- related to lock usage, on which we depend.
1379 function Check_Initialize_Lock
1381 Level : Lock_Level) return Boolean
1383 Self_ID : constant Task_Id := Self;
1386 -- Check that caller is abort-deferred
1388 if Self_ID.Deferral_Level = 0 then
1392 -- Check that the lock is not yet initialized
1394 if L.Level /= 0 then
1398 L.Level := Lock_Level'Pos (Level) + 1;
1400 end Check_Initialize_Lock;
1406 function Check_Lock (L : Lock_Ptr) return Boolean is
1407 Self_ID : constant Task_Id := Self;
1411 -- Check that the argument is not null
1417 -- Check that L is not frozen
1423 -- Check that caller is abort-deferred
1425 if Self_ID.Deferral_Level = 0 then
1429 -- Check that caller is not holding this lock already
1431 if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1439 -- Check that TCB lock order rules are satisfied
1441 P := Self_ID.Common.LL.Locks;
1443 if P.Level >= L.Level
1444 and then (P.Level > 2 or else L.Level > 2)
1457 function Record_Lock (L : Lock_Ptr) return Boolean is
1458 Self_ID : constant Task_Id := Self;
1462 Lock_Count := Lock_Count + 1;
1464 -- There should be no owner for this lock at this point
1466 if L.Owner /= null then
1472 L.Owner := To_Owner_ID (To_Address (Self_ID));
1478 -- Check that TCB lock order rules are satisfied
1480 P := Self_ID.Common.LL.Locks;
1486 Self_ID.Common.LL.Locking := null;
1487 Self_ID.Common.LL.Locks := L;
1495 function Check_Sleep (Reason : Task_States) return Boolean is
1496 pragma Unreferenced (Reason);
1498 Self_ID : constant Task_Id := Self;
1502 -- Check that caller is abort-deferred
1504 if Self_ID.Deferral_Level = 0 then
1512 -- Check that caller is holding own lock, on top of list
1514 if Self_ID.Common.LL.Locks /=
1515 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1520 -- Check that TCB lock order rules are satisfied
1522 if Self_ID.Common.LL.Locks.Next /= null then
1526 Self_ID.Common.LL.L.Owner := null;
1527 P := Self_ID.Common.LL.Locks;
1528 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1537 function Record_Wakeup
1539 Reason : Task_States) return Boolean
1541 pragma Unreferenced (Reason);
1543 Self_ID : constant Task_Id := Self;
1549 L.Owner := To_Owner_ID (To_Address (Self_ID));
1555 -- Check that TCB lock order rules are satisfied
1557 P := Self_ID.Common.LL.Locks;
1563 Self_ID.Common.LL.Locking := null;
1564 Self_ID.Common.LL.Locks := L;
1572 function Check_Wakeup
1574 Reason : Task_States) return Boolean
1576 Self_ID : constant Task_Id := Self;
1579 -- Is caller holding T's lock?
1581 if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1585 -- Are reasons for wakeup and sleep consistent?
1587 if T.Common.State /= Reason then
1598 function Check_Unlock (L : Lock_Ptr) return Boolean is
1599 Self_ID : constant Task_Id := Self;
1603 Unlock_Count := Unlock_Count + 1;
1609 if L.Buddy /= null then
1613 -- Magic constant 4???
1616 Check_Count := Unlock_Count;
1619 -- Magic constant 1000???
1621 if Unlock_Count - Check_Count > 1000 then
1622 Check_Count := Unlock_Count;
1625 -- Check that caller is abort-deferred
1627 if Self_ID.Deferral_Level = 0 then
1631 -- Check that caller is holding this lock, on top of list
1633 if Self_ID.Common.LL.Locks /= L then
1637 -- Record there is no owner now
1640 P := Self_ID.Common.LL.Locks;
1641 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1646 --------------------
1647 -- Check_Finalize --
1648 --------------------
1650 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1651 Self_ID : constant Task_Id := Self;
1654 -- Check that caller is abort-deferred
1656 if Self_ID.Deferral_Level = 0 then
1660 -- Check that no one is holding this lock
1662 if L.Owner /= null then
1668 end Check_Finalize_Lock;
1674 procedure Initialize (S : in out Suspension_Object) is
1675 Result : Interfaces.C.int;
1678 -- Initialize internal state (always to zero (RM D.10(6)))
1683 -- Initialize internal mutex
1685 Result := mutex_init (S.L'Access, USYNC_THREAD, System.Null_Address);
1686 pragma Assert (Result = 0 or else Result = ENOMEM);
1688 if Result = ENOMEM then
1689 raise Storage_Error with "Failed to allocate a lock";
1692 -- Initialize internal condition variable
1694 Result := cond_init (S.CV'Access, USYNC_THREAD, 0);
1695 pragma Assert (Result = 0 or else Result = ENOMEM);
1698 Result := mutex_destroy (S.L'Access);
1699 pragma Assert (Result = 0);
1701 if Result = ENOMEM then
1702 raise Storage_Error;
1711 procedure Finalize (S : in out Suspension_Object) is
1712 Result : Interfaces.C.int;
1715 -- Destroy internal mutex
1717 Result := mutex_destroy (S.L'Access);
1718 pragma Assert (Result = 0);
1720 -- Destroy internal condition variable
1722 Result := cond_destroy (S.CV'Access);
1723 pragma Assert (Result = 0);
1730 function Current_State (S : Suspension_Object) return Boolean is
1732 -- We do not want to use lock on this read operation. State is marked
1733 -- as Atomic so that we ensure that the value retrieved is correct.
1742 procedure Set_False (S : in out Suspension_Object) is
1743 Result : Interfaces.C.int;
1746 SSL.Abort_Defer.all;
1748 Result := mutex_lock (S.L'Access);
1749 pragma Assert (Result = 0);
1753 Result := mutex_unlock (S.L'Access);
1754 pragma Assert (Result = 0);
1756 SSL.Abort_Undefer.all;
1763 procedure Set_True (S : in out Suspension_Object) is
1764 Result : Interfaces.C.int;
1767 SSL.Abort_Defer.all;
1769 Result := mutex_lock (S.L'Access);
1770 pragma Assert (Result = 0);
1772 -- If there is already a task waiting on this suspension object then
1773 -- we resume it, leaving the state of the suspension object to False,
1774 -- as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1775 -- the state to True.
1781 Result := cond_signal (S.CV'Access);
1782 pragma Assert (Result = 0);
1788 Result := mutex_unlock (S.L'Access);
1789 pragma Assert (Result = 0);
1791 SSL.Abort_Undefer.all;
1794 ------------------------
1795 -- Suspend_Until_True --
1796 ------------------------
1798 procedure Suspend_Until_True (S : in out Suspension_Object) is
1799 Result : Interfaces.C.int;
1802 SSL.Abort_Defer.all;
1804 Result := mutex_lock (S.L'Access);
1805 pragma Assert (Result = 0);
1809 -- Program_Error must be raised upon calling Suspend_Until_True
1810 -- if another task is already waiting on that suspension object
1813 Result := mutex_unlock (S.L'Access);
1814 pragma Assert (Result = 0);
1816 SSL.Abort_Undefer.all;
1818 raise Program_Error;
1821 -- Suspend the task if the state is False. Otherwise, the task
1822 -- continues its execution, and the state of the suspension object
1823 -- is set to False (ARM D.10 par. 9).
1829 Result := cond_wait (S.CV'Access, S.L'Access);
1832 Result := mutex_unlock (S.L'Access);
1833 pragma Assert (Result = 0);
1835 SSL.Abort_Undefer.all;
1837 end Suspend_Until_True;
1843 function Check_Exit (Self_ID : Task_Id) return Boolean is
1845 -- Check that caller is just holding Global_Task_Lock and no other locks
1847 if Self_ID.Common.LL.Locks = null then
1851 -- 2 = Global_Task_Level
1853 if Self_ID.Common.LL.Locks.Level /= 2 then
1857 if Self_ID.Common.LL.Locks.Next /= null then
1861 -- Check that caller is abort-deferred
1863 if Self_ID.Deferral_Level = 0 then
1870 --------------------
1871 -- Check_No_Locks --
1872 --------------------
1874 function Check_No_Locks (Self_ID : Task_Id) return Boolean is
1876 return Self_ID.Common.LL.Locks = null;
1879 ----------------------
1880 -- Environment_Task --
1881 ----------------------
1883 function Environment_Task return Task_Id is
1885 return Environment_Task_Id;
1886 end Environment_Task;
1892 procedure Lock_RTS is
1894 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1901 procedure Unlock_RTS is
1903 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1910 function Suspend_Task
1912 Thread_Self : Thread_Id) return Boolean
1915 if T.Common.LL.Thread /= Thread_Self then
1916 return thr_suspend (T.Common.LL.Thread) = 0;
1926 function Resume_Task
1928 Thread_Self : Thread_Id) return Boolean
1931 if T.Common.LL.Thread /= Thread_Self then
1932 return thr_continue (T.Common.LL.Thread) = 0;
1938 --------------------
1939 -- Stop_All_Tasks --
1940 --------------------
1942 procedure Stop_All_Tasks is
1951 function Stop_Task (T : ST.Task_Id) return Boolean is
1952 pragma Unreferenced (T);
1961 function Continue_Task (T : ST.Task_Id) return Boolean is
1962 pragma Unreferenced (T);
1967 end System.Task_Primitives.Operations;