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-2009, 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 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
27 -- GNARL was developed by the GNARL team at Florida State University. --
28 -- Extensive contributions were provided by Ada Core Technologies, Inc. --
30 ------------------------------------------------------------------------------
32 -- This is a Solaris (native) version of this package
34 -- This package contains all the GNULL primitives that interface directly with
38 -- Turn off polling, we do not want ATC polling to take place during tasking
39 -- operations. It causes infinite loops and other problems.
41 with Ada.Unchecked_Deallocation;
45 with System.Tasking.Debug;
46 with System.Interrupt_Management;
47 with System.OS_Primitives;
48 with System.Task_Info;
50 pragma Warnings (Off);
54 with System.Soft_Links;
55 -- We use System.Soft_Links instead of System.Tasking.Initialization
56 -- because the later is a higher level package that we shouldn't depend on.
57 -- For example when using the restricted run time, it is replaced by
58 -- System.Tasking.Restricted.Stages.
60 package body System.Task_Primitives.Operations is
62 package SSL renames System.Soft_Links;
64 use System.Tasking.Debug;
67 use System.OS_Interface;
68 use System.Parameters;
69 use System.OS_Primitives;
75 -- The following are logically constants, but need to be initialized
78 Environment_Task_Id : Task_Id;
79 -- A variable to hold Task_Id for the environment task.
80 -- If we use this variable to get the Task_Id, we need the following
81 -- ATCB_Key only for non-Ada threads.
83 Unblocked_Signal_Mask : aliased sigset_t;
84 -- The set of signals that should unblocked in all tasks
86 ATCB_Key : aliased thread_key_t;
87 -- Key used to find the Ada Task_Id associated with a thread,
88 -- at least for C threads unknown to the Ada run-time system.
90 Single_RTS_Lock : aliased RTS_Lock;
91 -- This is a lock to allow only one thread of control in the RTS at
92 -- a time; it is used to execute in mutual exclusion from all other tasks.
93 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
95 Next_Serial_Number : Task_Serial_Number := 100;
96 -- We start at 100, to reserve some special values for
97 -- using in error checking.
98 -- The following are internal configuration constants needed.
100 ----------------------
101 -- Priority Support --
102 ----------------------
104 Priority_Ceiling_Emulation : constant Boolean := True;
105 -- controls whether we emulate priority ceiling locking
107 -- To get a scheduling close to annex D requirements, we use the real-time
108 -- class provided for LWPs and map each task/thread to a specific and
109 -- unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
111 -- The real time class can only be set when the process has root
112 -- privileges, so in the other cases, we use the normal thread scheduling
113 -- and priority handling.
115 Using_Real_Time_Class : Boolean := False;
116 -- indicates whether the real time class is being used (i.e. the process
117 -- has root privileges).
119 Prio_Param : aliased struct_pcparms;
120 -- Hold priority info (Real_Time) initialized during the package
123 -----------------------------------
124 -- External Configuration Values --
125 -----------------------------------
127 Time_Slice_Val : Integer;
128 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
130 Locking_Policy : Character;
131 pragma Import (C, Locking_Policy, "__gl_locking_policy");
133 Dispatching_Policy : Character;
134 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
136 Foreign_Task_Elaborated : aliased Boolean := True;
137 -- Used to identified fake tasks (i.e., non-Ada Threads)
139 -----------------------
140 -- Local Subprograms --
141 -----------------------
143 function sysconf (name : System.OS_Interface.int) return processorid_t;
144 pragma Import (C, sysconf, "sysconf");
146 SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
149 (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
150 return processorid_t renames sysconf;
152 procedure Abort_Handler
154 Code : not null access siginfo_t;
155 Context : not null access ucontext_t);
156 -- Target-dependent binding of inter-thread Abort signal to
157 -- the raising of the Abort_Signal exception.
158 -- See also comments in 7staprop.adb
164 function Check_Initialize_Lock
166 Level : Lock_Level) return Boolean;
167 pragma Inline (Check_Initialize_Lock);
169 function Check_Lock (L : Lock_Ptr) return Boolean;
170 pragma Inline (Check_Lock);
172 function Record_Lock (L : Lock_Ptr) return Boolean;
173 pragma Inline (Record_Lock);
175 function Check_Sleep (Reason : Task_States) return Boolean;
176 pragma Inline (Check_Sleep);
178 function Record_Wakeup
180 Reason : Task_States) return Boolean;
181 pragma Inline (Record_Wakeup);
183 function Check_Wakeup
185 Reason : Task_States) return Boolean;
186 pragma Inline (Check_Wakeup);
188 function Check_Unlock (L : Lock_Ptr) return Boolean;
189 pragma Inline (Check_Unlock);
191 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
192 pragma Inline (Check_Finalize_Lock);
200 procedure Initialize (Environment_Task : Task_Id);
201 pragma Inline (Initialize);
202 -- Initialize various data needed by this package
204 function Is_Valid_Task return Boolean;
205 pragma Inline (Is_Valid_Task);
206 -- Does executing thread have a TCB?
208 procedure Set (Self_Id : Task_Id);
210 -- Set the self id for the current task
212 function Self return Task_Id;
213 pragma Inline (Self);
214 -- Return a pointer to the Ada Task Control Block of the calling task
218 package body Specific is separate;
219 -- The body of this package is target specific
221 ---------------------------------
222 -- Support for foreign threads --
223 ---------------------------------
225 function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
226 -- Allocate and Initialize a new ATCB for the current Thread
228 function Register_Foreign_Thread
229 (Thread : Thread_Id) return Task_Id is separate;
235 Check_Count : Integer := 0;
236 Lock_Count : Integer := 0;
237 Unlock_Count : Integer := 0;
243 procedure Abort_Handler
245 Code : not null access siginfo_t;
246 Context : not null access ucontext_t)
248 pragma Unreferenced (Sig);
249 pragma Unreferenced (Code);
250 pragma Unreferenced (Context);
252 Self_ID : constant Task_Id := Self;
253 Old_Set : aliased sigset_t;
255 Result : Interfaces.C.int;
256 pragma Warnings (Off, Result);
259 -- It is not safe to raise an exception when using ZCX and the GCC
260 -- exception handling mechanism.
262 if ZCX_By_Default and then GCC_ZCX_Support then
266 if Self_ID.Deferral_Level = 0
267 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
268 and then not Self_ID.Aborting
270 Self_ID.Aborting := True;
272 -- Make sure signals used for RTS internal purpose are unmasked
277 Unblocked_Signal_Mask'Unchecked_Access,
278 Old_Set'Unchecked_Access);
279 pragma Assert (Result = 0);
281 raise Standard'Abort_Signal;
289 -- The underlying thread system sets a guard page at the
290 -- bottom of a thread stack, so nothing is needed.
292 procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
293 pragma Unreferenced (T);
294 pragma Unreferenced (On);
303 function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
305 return T.Common.LL.Thread;
312 procedure Initialize (Environment_Task : ST.Task_Id) is
313 act : aliased struct_sigaction;
314 old_act : aliased struct_sigaction;
315 Tmp_Set : aliased sigset_t;
316 Result : Interfaces.C.int;
318 procedure Configure_Processors;
319 -- Processors configuration
320 -- The user can specify a processor which the program should run
321 -- on to emulate a single-processor system. This can be easily
322 -- done by setting environment variable GNAT_PROCESSOR to one of
325 -- -2 : use the default configuration (run the program on all
326 -- available processors) - this is the same as having
327 -- GNAT_PROCESSOR unset
328 -- -1 : let the RTS choose one processor and run the program on
330 -- 0 .. Last_Proc : run the program on the specified processor
332 -- Last_Proc is equal to the value of the system variable
333 -- _SC_NPROCESSORS_CONF, minus one.
335 procedure Configure_Processors is
336 Proc_Acc : constant System.OS_Lib.String_Access :=
337 System.OS_Lib.Getenv ("GNAT_PROCESSOR");
338 Proc : aliased processorid_t; -- User processor #
339 Last_Proc : processorid_t; -- Last processor #
342 if Proc_Acc.all'Length /= 0 then
344 -- Environment variable is defined
346 Last_Proc := Num_Procs - 1;
348 if Last_Proc /= -1 then
349 Proc := processorid_t'Value (Proc_Acc.all);
351 if Proc <= -2 or else Proc > Last_Proc then
353 -- Use the default configuration
359 -- Choose a processor
362 while Proc < Last_Proc loop
364 Result := p_online (Proc, PR_STATUS);
365 exit when Result = PR_ONLINE;
368 pragma Assert (Result = PR_ONLINE);
369 Result := processor_bind (P_PID, P_MYID, Proc, null);
370 pragma Assert (Result = 0);
373 -- Use user processor
375 Result := processor_bind (P_PID, P_MYID, Proc, null);
376 pragma Assert (Result = 0);
382 when Constraint_Error =>
384 -- Illegal environment variable GNAT_PROCESSOR - ignored
387 end Configure_Processors;
390 (Int : System.Interrupt_Management.Interrupt_ID) return Character;
391 pragma Import (C, State, "__gnat_get_interrupt_state");
392 -- Get interrupt state. Defined in a-init.c
393 -- The input argument is the interrupt number,
394 -- and the result is one of the following:
396 Default : constant Character := 's';
397 -- 'n' this interrupt not set by any Interrupt_State pragma
398 -- 'u' Interrupt_State pragma set state to User
399 -- 'r' Interrupt_State pragma set state to Runtime
400 -- 's' Interrupt_State pragma set state to System (use "default"
403 -- Start of processing for Initialize
406 Environment_Task_Id := Environment_Task;
408 Interrupt_Management.Initialize;
410 -- Prepare the set of signals that should unblocked in all tasks
412 Result := sigemptyset (Unblocked_Signal_Mask'Access);
413 pragma Assert (Result = 0);
415 for J in Interrupt_Management.Interrupt_ID loop
416 if System.Interrupt_Management.Keep_Unmasked (J) then
417 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
418 pragma Assert (Result = 0);
422 if Dispatching_Policy = 'F' then
424 Result : Interfaces.C.long;
425 Class_Info : aliased struct_pcinfo;
426 Secs, Nsecs : Interfaces.C.long;
429 -- If a pragma Time_Slice is specified, takes the value in account
431 if Time_Slice_Val > 0 then
433 -- Convert Time_Slice_Val (microseconds) to seconds/nanosecs
435 Secs := Interfaces.C.long (Time_Slice_Val / 1_000_000);
437 Interfaces.C.long ((Time_Slice_Val rem 1_000_000) * 1_000);
439 -- Otherwise, default to no time slicing (i.e run until blocked)
446 -- Get the real time class id
448 Class_Info.pc_clname (1) := 'R';
449 Class_Info.pc_clname (2) := 'T';
450 Class_Info.pc_clname (3) := ASCII.NUL;
452 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
455 -- Request the real time class
457 Prio_Param.pc_cid := Class_Info.pc_cid;
458 Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
459 Prio_Param.rt_tqsecs := Secs;
460 Prio_Param.rt_tqnsecs := Nsecs;
464 (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS, Prio_Param'Address);
466 Using_Real_Time_Class := Result /= -1;
470 Specific.Initialize (Environment_Task);
472 -- The following is done in Enter_Task, but this is too late for the
473 -- Environment Task, since we need to call Self in Check_Locks when
474 -- the run time is compiled with assertions on.
476 Specific.Set (Environment_Task);
478 -- Initialize the lock used to synchronize chain of all ATCBs
480 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
482 -- Make environment task known here because it doesn't go through
483 -- Activate_Tasks, which does it for all other tasks.
485 Known_Tasks (Known_Tasks'First) := Environment_Task;
486 Environment_Task.Known_Tasks_Index := Known_Tasks'First;
488 Enter_Task (Environment_Task);
490 -- Install the abort-signal handler
493 (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
495 -- Set sa_flags to SA_NODEFER so that during the handler execution
496 -- we do not change the Signal_Mask to be masked for the Abort_Signal
497 -- This is a temporary fix to the problem that the Signal_Mask is
498 -- not restored after the exception (longjmp) from the handler.
499 -- The right fix should be made in sigsetjmp so that we save
500 -- the Signal_Set and restore it after a longjmp.
501 -- In that case, this field should be changed back to 0. ???
505 act.sa_handler := Abort_Handler'Address;
506 Result := sigemptyset (Tmp_Set'Access);
507 pragma Assert (Result = 0);
508 act.sa_mask := Tmp_Set;
512 (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
513 act'Unchecked_Access,
514 old_act'Unchecked_Access);
515 pragma Assert (Result = 0);
518 Configure_Processors;
521 ---------------------
522 -- Initialize_Lock --
523 ---------------------
525 -- Note: mutexes and cond_variables needed per-task basis are initialized
526 -- in Initialize_TCB and the Storage_Error is handled. Other mutexes (such
527 -- as RTS_Lock, Memory_Lock...) used in RTS is initialized before any
528 -- status change of RTS. Therefore raising Storage_Error in the following
529 -- routines should be able to be handled safely.
531 procedure Initialize_Lock
532 (Prio : System.Any_Priority;
533 L : not null access Lock)
535 Result : Interfaces.C.int;
538 pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
540 if Priority_Ceiling_Emulation then
544 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
545 pragma Assert (Result = 0 or else Result = ENOMEM);
547 if Result = ENOMEM then
548 raise Storage_Error with "Failed to allocate a lock";
552 procedure Initialize_Lock
553 (L : not null access RTS_Lock;
556 Result : Interfaces.C.int;
560 (Check_Initialize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
561 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
562 pragma Assert (Result = 0 or else Result = ENOMEM);
564 if Result = ENOMEM then
565 raise Storage_Error with "Failed to allocate a lock";
573 procedure Finalize_Lock (L : not null access Lock) is
574 Result : Interfaces.C.int;
576 pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
577 Result := mutex_destroy (L.L'Access);
578 pragma Assert (Result = 0);
581 procedure Finalize_Lock (L : not null access RTS_Lock) is
582 Result : Interfaces.C.int;
584 pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
585 Result := mutex_destroy (L.L'Access);
586 pragma Assert (Result = 0);
594 (L : not null access Lock;
595 Ceiling_Violation : out Boolean)
597 Result : Interfaces.C.int;
600 pragma Assert (Check_Lock (Lock_Ptr (L)));
602 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
604 Self_Id : constant Task_Id := Self;
605 Saved_Priority : System.Any_Priority;
608 if Self_Id.Common.LL.Active_Priority > L.Ceiling then
609 Ceiling_Violation := True;
613 Saved_Priority := Self_Id.Common.LL.Active_Priority;
615 if Self_Id.Common.LL.Active_Priority < L.Ceiling then
616 Set_Priority (Self_Id, L.Ceiling);
619 Result := mutex_lock (L.L'Access);
620 pragma Assert (Result = 0);
621 Ceiling_Violation := False;
623 L.Saved_Priority := Saved_Priority;
627 Result := mutex_lock (L.L'Access);
628 pragma Assert (Result = 0);
629 Ceiling_Violation := False;
632 pragma Assert (Record_Lock (Lock_Ptr (L)));
636 (L : not null access RTS_Lock;
637 Global_Lock : Boolean := False)
639 Result : Interfaces.C.int;
641 if not Single_Lock or else Global_Lock then
642 pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
643 Result := mutex_lock (L.L'Access);
644 pragma Assert (Result = 0);
645 pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
649 procedure Write_Lock (T : Task_Id) is
650 Result : Interfaces.C.int;
652 if not Single_Lock then
653 pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
654 Result := mutex_lock (T.Common.LL.L.L'Access);
655 pragma Assert (Result = 0);
656 pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
665 (L : not null access Lock;
666 Ceiling_Violation : out Boolean) is
668 Write_Lock (L, Ceiling_Violation);
675 procedure Unlock (L : not null access Lock) is
676 Result : Interfaces.C.int;
679 pragma Assert (Check_Unlock (Lock_Ptr (L)));
681 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
683 Self_Id : constant Task_Id := Self;
686 Result := mutex_unlock (L.L'Access);
687 pragma Assert (Result = 0);
689 if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
690 Set_Priority (Self_Id, L.Saved_Priority);
694 Result := mutex_unlock (L.L'Access);
695 pragma Assert (Result = 0);
700 (L : not null access RTS_Lock;
701 Global_Lock : Boolean := False)
703 Result : Interfaces.C.int;
705 if not Single_Lock or else Global_Lock then
706 pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
707 Result := mutex_unlock (L.L'Access);
708 pragma Assert (Result = 0);
712 procedure Unlock (T : Task_Id) is
713 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);
726 -- Dynamic priority ceilings are not supported by the underlying system
728 procedure Set_Ceiling
729 (L : not null access Lock;
730 Prio : System.Any_Priority)
732 pragma Unreferenced (L, Prio);
737 -- For the time delay implementation, we need to make sure we
738 -- achieve following criteria:
740 -- 1) We have to delay at least for the amount requested.
741 -- 2) We have to give up CPU even though the actual delay does not
742 -- result in blocking.
743 -- 3) Except for restricted run-time systems that do not support
744 -- ATC or task abort, the delay must be interrupted by the
745 -- abort_task operation.
746 -- 4) The implementation has to be efficient so that the delay overhead
747 -- is relatively cheap.
748 -- (1)-(3) are Ada requirements. Even though (2) is an Annex-D
749 -- requirement we still want to provide the effect in all cases.
750 -- The reason is that users may want to use short delays to implement
751 -- their own scheduling effect in the absence of language provided
752 -- scheduling policies.
754 ---------------------
755 -- Monotonic_Clock --
756 ---------------------
758 function Monotonic_Clock return Duration is
759 TS : aliased timespec;
760 Result : Interfaces.C.int;
762 Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
763 pragma Assert (Result = 0);
764 return To_Duration (TS);
771 function RT_Resolution return Duration is
780 procedure Yield (Do_Yield : Boolean := True) is
783 System.OS_Interface.thr_yield;
791 function Self return Task_Id renames Specific.Self;
797 procedure Set_Priority
799 Prio : System.Any_Priority;
800 Loss_Of_Inheritance : Boolean := False)
802 pragma Unreferenced (Loss_Of_Inheritance);
804 Result : Interfaces.C.int;
805 pragma Unreferenced (Result);
807 Param : aliased struct_pcparms;
812 T.Common.Current_Priority := Prio;
814 if Priority_Ceiling_Emulation then
815 T.Common.LL.Active_Priority := Prio;
818 if Using_Real_Time_Class then
819 Param.pc_cid := Prio_Param.pc_cid;
820 Param.rt_pri := pri_t (Prio);
821 Param.rt_tqsecs := Prio_Param.rt_tqsecs;
822 Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
824 Result := Interfaces.C.int (
825 priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
829 if T.Common.Task_Info /= null
830 and then not T.Common.Task_Info.Bound_To_LWP
832 -- The task is not bound to a LWP, so use thr_setprio
835 thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
838 -- The task is bound to a LWP, use priocntl
850 function Get_Priority (T : Task_Id) return System.Any_Priority is
852 return T.Common.Current_Priority;
859 procedure Enter_Task (Self_ID : Task_Id) is
860 Result : Interfaces.C.int;
861 Proc : processorid_t; -- User processor #
862 Last_Proc : processorid_t; -- Last processor #
864 use System.Task_Info;
866 Self_ID.Common.LL.Thread := thr_self;
868 Self_ID.Common.LL.LWP := lwp_self;
870 if Self_ID.Common.Task_Info /= null then
871 if Self_ID.Common.Task_Info.New_LWP
872 and then Self_ID.Common.Task_Info.CPU /= CPU_UNCHANGED
874 Last_Proc := Num_Procs - 1;
876 if Self_ID.Common.Task_Info.CPU = ANY_CPU then
879 while Proc < Last_Proc loop
880 Result := p_online (Proc, PR_STATUS);
881 exit when Result = PR_ONLINE;
885 Result := processor_bind (P_LWPID, P_MYID, Proc, null);
886 pragma Assert (Result = 0);
889 -- Use specified processor
891 if Self_ID.Common.Task_Info.CPU < 0
892 or else Self_ID.Common.Task_Info.CPU > Last_Proc
894 raise Invalid_CPU_Number;
899 (P_LWPID, P_MYID, Self_ID.Common.Task_Info.CPU, null);
900 pragma Assert (Result = 0);
905 Specific.Set (Self_ID);
907 -- We need the above code even if we do direct fetch of Task_Id in Self
908 -- for the main task on Sun, x86 Solaris and for gcc 2.7.2.
915 function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
917 return new Ada_Task_Control_Block (Entry_Num);
924 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
926 -----------------------------
927 -- Register_Foreign_Thread --
928 -----------------------------
930 function Register_Foreign_Thread return Task_Id is
932 if Is_Valid_Task then
935 return Register_Foreign_Thread (thr_self);
937 end Register_Foreign_Thread;
943 procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
944 Result : Interfaces.C.int := 0;
947 -- Give the task a unique serial number
949 Self_ID.Serial_Number := Next_Serial_Number;
950 Next_Serial_Number := Next_Serial_Number + 1;
951 pragma Assert (Next_Serial_Number /= 0);
953 Self_ID.Common.LL.Thread := To_thread_t (-1);
955 if not Single_Lock then
958 (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
959 Self_ID.Common.LL.L.Level :=
960 Private_Task_Serial_Number (Self_ID.Serial_Number);
961 pragma Assert (Result = 0 or else Result = ENOMEM);
965 Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
966 pragma Assert (Result = 0 or else Result = ENOMEM);
972 if not Single_Lock then
973 Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
974 pragma Assert (Result = 0);
985 procedure Create_Task
987 Wrapper : System.Address;
988 Stack_Size : System.Parameters.Size_Type;
989 Priority : System.Any_Priority;
990 Succeeded : out Boolean)
992 pragma Unreferenced (Priority);
994 Result : Interfaces.C.int;
995 Adjusted_Stack_Size : Interfaces.C.size_t;
996 Opts : Interfaces.C.int := THR_DETACHED;
998 Page_Size : constant System.Parameters.Size_Type := 4096;
999 -- This constant is for reserving extra space at the
1000 -- end of the stack, which can be used by the stack
1001 -- checking as guard page. The idea is that we need
1002 -- to have at least Stack_Size bytes available for
1005 use System.Task_Info;
1008 Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size + Page_Size);
1010 -- Since the initial signal mask of a thread is inherited from the
1011 -- creator, and the Environment task has all its signals masked, we
1012 -- do not need to manipulate caller's signal mask at this point.
1013 -- All tasks in RTS will have All_Tasks_Mask initially.
1015 if T.Common.Task_Info /= null then
1016 if T.Common.Task_Info.New_LWP then
1017 Opts := Opts + THR_NEW_LWP;
1020 if T.Common.Task_Info.Bound_To_LWP then
1021 Opts := Opts + THR_BOUND;
1025 Opts := THR_DETACHED + THR_BOUND;
1030 (System.Null_Address,
1031 Adjusted_Stack_Size,
1032 Thread_Body_Access (Wrapper),
1035 T.Common.LL.Thread'Access);
1037 Succeeded := Result = 0;
1040 or else Result = ENOMEM
1041 or else Result = EAGAIN);
1048 procedure Finalize_TCB (T : Task_Id) is
1049 Result : Interfaces.C.int;
1051 Is_Self : constant Boolean := T = Self;
1053 procedure Free is new
1054 Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
1057 T.Common.LL.Thread := To_thread_t (0);
1059 if not Single_Lock then
1060 Result := mutex_destroy (T.Common.LL.L.L'Access);
1061 pragma Assert (Result = 0);
1064 Result := cond_destroy (T.Common.LL.CV'Access);
1065 pragma Assert (Result = 0);
1067 if T.Known_Tasks_Index /= -1 then
1068 Known_Tasks (T.Known_Tasks_Index) := null;
1074 Specific.Set (null);
1082 -- This procedure must be called with abort deferred. It can no longer
1083 -- call Self or access the current task's ATCB, since the ATCB has been
1086 procedure Exit_Task is
1088 Specific.Set (null);
1095 procedure Abort_Task (T : Task_Id) is
1096 Result : Interfaces.C.int;
1098 pragma Assert (T /= Self);
1101 (T.Common.LL.Thread,
1102 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1103 pragma Assert (Result = 0);
1112 Reason : Task_States)
1114 Result : Interfaces.C.int;
1117 pragma Assert (Check_Sleep (Reason));
1122 (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1126 (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1130 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1131 pragma Assert (Result = 0 or else Result = EINTR);
1134 -- Note that we are relying heavily here on GNAT representing
1135 -- Calendar.Time, System.Real_Time.Time, Duration,
1136 -- System.Real_Time.Time_Span in the same way, i.e., as a 64-bit count of
1139 -- This allows us to always pass the timeout value as a Duration
1142 -- We are taking liberties here with the semantics of the delays. That is,
1143 -- we make no distinction between delays on the Calendar clock and delays
1144 -- on the Real_Time clock. That is technically incorrect, if the Calendar
1145 -- clock happens to be reset or adjusted. To solve this defect will require
1146 -- modification to the compiler interface, so that it can pass through more
1147 -- information, to tell us here which clock to use!
1149 -- cond_timedwait will return if any of the following happens:
1150 -- 1) some other task did cond_signal on this condition variable
1151 -- In this case, the return value is 0
1152 -- 2) the call just returned, for no good reason
1153 -- This is called a "spurious wakeup".
1154 -- In this case, the return value may also be 0.
1155 -- 3) the time delay expires
1156 -- In this case, the return value is ETIME
1157 -- 4) this task received a signal, which was handled by some
1158 -- handler procedure, and now the thread is resuming execution
1159 -- UNIX calls this an "interrupted" system call.
1160 -- In this case, the return value is EINTR
1162 -- If the cond_timedwait returns 0 or EINTR, it is still possible that the
1163 -- time has actually expired, and by chance a signal or cond_signal
1164 -- occurred at around the same time.
1166 -- We have also observed that on some OS's the value ETIME will be
1167 -- returned, but the clock will show that the full delay has not yet
1170 -- For these reasons, we need to check the clock after return from
1171 -- cond_timedwait. If the time has expired, we will set Timedout = True.
1173 -- This check might be omitted for systems on which the cond_timedwait()
1174 -- never returns early or wakes up spuriously.
1176 -- Annex D requires that completion of a delay cause the task to go to the
1177 -- end of its priority queue, regardless of whether the task actually was
1178 -- suspended by the delay. Since cond_timedwait does not do this on
1179 -- Solaris, we add a call to thr_yield at the end. We might do this at the
1180 -- beginning, instead, but then the round-robin effect would not be the
1181 -- same; the delayed task would be ahead of other tasks of the same
1182 -- priority that awoke while it was sleeping.
1184 -- For Timed_Sleep, we are expecting possible cond_signals to indicate
1185 -- other events (e.g., completion of a RV or completion of the abortable
1186 -- part of an async. select), we want to always return if interrupted. The
1187 -- caller will be responsible for checking the task state to see whether
1188 -- the wakeup was spurious, and to go back to sleep again in that case. We
1189 -- don't need to check for pending abort or priority change on the way in
1190 -- our out; that is the caller's responsibility.
1192 -- For Timed_Delay, we are not expecting any cond_signals or other
1193 -- interruptions, except for priority changes and aborts. Therefore, we
1194 -- don't want to return unless the delay has actually expired, or the call
1195 -- has been aborted. In this case, since we want to implement the entire
1196 -- delay statement semantics, we do need to check for pending abort and
1197 -- priority changes. We can quietly handle priority changes inside the
1198 -- procedure, since there is no entry-queue reordering involved.
1204 procedure Timed_Sleep
1207 Mode : ST.Delay_Modes;
1208 Reason : System.Tasking.Task_States;
1209 Timedout : out Boolean;
1210 Yielded : out Boolean)
1212 Base_Time : constant Duration := Monotonic_Clock;
1213 Check_Time : Duration := Base_Time;
1214 Abs_Time : Duration;
1215 Request : aliased timespec;
1216 Result : Interfaces.C.int;
1219 pragma Assert (Check_Sleep (Reason));
1223 if Mode = Relative then
1224 Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
1226 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1229 if Abs_Time > Check_Time then
1230 Request := To_Timespec (Abs_Time);
1233 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1238 (Self_ID.Common.LL.CV'Access,
1239 Single_RTS_Lock.L'Access, Request'Access);
1243 (Self_ID.Common.LL.CV'Access,
1244 Self_ID.Common.LL.L.L'Access, Request'Access);
1249 Check_Time := Monotonic_Clock;
1250 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1252 if Result = 0 or Result = EINTR then
1254 -- Somebody may have called Wakeup for us
1260 pragma Assert (Result = ETIME);
1265 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1272 procedure Timed_Delay
1275 Mode : ST.Delay_Modes)
1277 Base_Time : constant Duration := Monotonic_Clock;
1278 Check_Time : Duration := Base_Time;
1279 Abs_Time : Duration;
1280 Request : aliased timespec;
1281 Result : Interfaces.C.int;
1282 Yielded : Boolean := False;
1289 Write_Lock (Self_ID);
1291 if Mode = Relative then
1292 Abs_Time := Time + Check_Time;
1294 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1297 if Abs_Time > Check_Time then
1298 Request := To_Timespec (Abs_Time);
1299 Self_ID.Common.State := Delay_Sleep;
1301 pragma Assert (Check_Sleep (Delay_Sleep));
1304 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1309 (Self_ID.Common.LL.CV'Access,
1310 Single_RTS_Lock.L'Access,
1315 (Self_ID.Common.LL.CV'Access,
1316 Self_ID.Common.LL.L.L'Access,
1322 Check_Time := Monotonic_Clock;
1323 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1327 Result = ETIME or else
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;
1359 pragma Assert (Check_Wakeup (T, Reason));
1360 Result := cond_signal (T.Common.LL.CV'Access);
1361 pragma Assert (Result = 0);
1364 ---------------------------
1365 -- Check_Initialize_Lock --
1366 ---------------------------
1368 -- The following code is intended to check some of the invariant assertions
1369 -- related to lock usage, on which we depend.
1371 function Check_Initialize_Lock
1373 Level : Lock_Level) return Boolean
1375 Self_ID : constant Task_Id := Self;
1378 -- Check that caller is abort-deferred
1380 if Self_ID.Deferral_Level = 0 then
1384 -- Check that the lock is not yet initialized
1386 if L.Level /= 0 then
1390 L.Level := Lock_Level'Pos (Level) + 1;
1392 end Check_Initialize_Lock;
1398 function Check_Lock (L : Lock_Ptr) return Boolean is
1399 Self_ID : constant Task_Id := Self;
1403 -- Check that the argument is not null
1409 -- Check that L is not frozen
1415 -- Check that caller is abort-deferred
1417 if Self_ID.Deferral_Level = 0 then
1421 -- Check that caller is not holding this lock already
1423 if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1431 -- Check that TCB lock order rules are satisfied
1433 P := Self_ID.Common.LL.Locks;
1435 if P.Level >= L.Level
1436 and then (P.Level > 2 or else L.Level > 2)
1449 function Record_Lock (L : Lock_Ptr) return Boolean is
1450 Self_ID : constant Task_Id := Self;
1454 Lock_Count := Lock_Count + 1;
1456 -- There should be no owner for this lock at this point
1458 if L.Owner /= null then
1464 L.Owner := To_Owner_ID (To_Address (Self_ID));
1470 -- Check that TCB lock order rules are satisfied
1472 P := Self_ID.Common.LL.Locks;
1478 Self_ID.Common.LL.Locking := null;
1479 Self_ID.Common.LL.Locks := L;
1487 function Check_Sleep (Reason : Task_States) return Boolean is
1488 pragma Unreferenced (Reason);
1490 Self_ID : constant Task_Id := Self;
1494 -- Check that caller is abort-deferred
1496 if Self_ID.Deferral_Level = 0 then
1504 -- Check that caller is holding own lock, on top of list
1506 if Self_ID.Common.LL.Locks /=
1507 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1512 -- Check that TCB lock order rules are satisfied
1514 if Self_ID.Common.LL.Locks.Next /= null then
1518 Self_ID.Common.LL.L.Owner := null;
1519 P := Self_ID.Common.LL.Locks;
1520 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1529 function Record_Wakeup
1531 Reason : Task_States) return Boolean
1533 pragma Unreferenced (Reason);
1535 Self_ID : constant Task_Id := Self;
1541 L.Owner := To_Owner_ID (To_Address (Self_ID));
1547 -- Check that TCB lock order rules are satisfied
1549 P := Self_ID.Common.LL.Locks;
1555 Self_ID.Common.LL.Locking := null;
1556 Self_ID.Common.LL.Locks := L;
1564 function Check_Wakeup
1566 Reason : Task_States) return Boolean
1568 Self_ID : constant Task_Id := Self;
1571 -- Is caller holding T's lock?
1573 if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1577 -- Are reasons for wakeup and sleep consistent?
1579 if T.Common.State /= Reason then
1590 function Check_Unlock (L : Lock_Ptr) return Boolean is
1591 Self_ID : constant Task_Id := Self;
1595 Unlock_Count := Unlock_Count + 1;
1601 if L.Buddy /= null then
1605 -- Magic constant 4???
1608 Check_Count := Unlock_Count;
1611 -- Magic constant 1000???
1613 if Unlock_Count - Check_Count > 1000 then
1614 Check_Count := Unlock_Count;
1617 -- Check that caller is abort-deferred
1619 if Self_ID.Deferral_Level = 0 then
1623 -- Check that caller is holding this lock, on top of list
1625 if Self_ID.Common.LL.Locks /= L then
1629 -- Record there is no owner now
1632 P := Self_ID.Common.LL.Locks;
1633 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1638 --------------------
1639 -- Check_Finalize --
1640 --------------------
1642 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1643 Self_ID : constant Task_Id := Self;
1646 -- Check that caller is abort-deferred
1648 if Self_ID.Deferral_Level = 0 then
1652 -- Check that no one is holding this lock
1654 if L.Owner /= null then
1660 end Check_Finalize_Lock;
1666 procedure Initialize (S : in out Suspension_Object) is
1667 Result : Interfaces.C.int;
1670 -- Initialize internal state (always to zero (RM D.10(6)))
1675 -- Initialize internal mutex
1677 Result := mutex_init (S.L'Access, USYNC_THREAD, System.Null_Address);
1678 pragma Assert (Result = 0 or else Result = ENOMEM);
1680 if Result = ENOMEM then
1681 raise Storage_Error with "Failed to allocate a lock";
1684 -- Initialize internal condition variable
1686 Result := cond_init (S.CV'Access, USYNC_THREAD, 0);
1687 pragma Assert (Result = 0 or else Result = ENOMEM);
1690 Result := mutex_destroy (S.L'Access);
1691 pragma Assert (Result = 0);
1693 if Result = ENOMEM then
1694 raise Storage_Error;
1703 procedure Finalize (S : in out Suspension_Object) is
1704 Result : Interfaces.C.int;
1707 -- Destroy internal mutex
1709 Result := mutex_destroy (S.L'Access);
1710 pragma Assert (Result = 0);
1712 -- Destroy internal condition variable
1714 Result := cond_destroy (S.CV'Access);
1715 pragma Assert (Result = 0);
1722 function Current_State (S : Suspension_Object) return Boolean is
1724 -- We do not want to use lock on this read operation. State is marked
1725 -- as Atomic so that we ensure that the value retrieved is correct.
1734 procedure Set_False (S : in out Suspension_Object) is
1735 Result : Interfaces.C.int;
1738 SSL.Abort_Defer.all;
1740 Result := mutex_lock (S.L'Access);
1741 pragma Assert (Result = 0);
1745 Result := mutex_unlock (S.L'Access);
1746 pragma Assert (Result = 0);
1748 SSL.Abort_Undefer.all;
1755 procedure Set_True (S : in out Suspension_Object) is
1756 Result : Interfaces.C.int;
1759 SSL.Abort_Defer.all;
1761 Result := mutex_lock (S.L'Access);
1762 pragma Assert (Result = 0);
1764 -- If there is already a task waiting on this suspension object then
1765 -- we resume it, leaving the state of the suspension object to False,
1766 -- as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1767 -- the state to True.
1773 Result := cond_signal (S.CV'Access);
1774 pragma Assert (Result = 0);
1780 Result := mutex_unlock (S.L'Access);
1781 pragma Assert (Result = 0);
1783 SSL.Abort_Undefer.all;
1786 ------------------------
1787 -- Suspend_Until_True --
1788 ------------------------
1790 procedure Suspend_Until_True (S : in out Suspension_Object) is
1791 Result : Interfaces.C.int;
1794 SSL.Abort_Defer.all;
1796 Result := mutex_lock (S.L'Access);
1797 pragma Assert (Result = 0);
1801 -- Program_Error must be raised upon calling Suspend_Until_True
1802 -- if another task is already waiting on that suspension object
1805 Result := mutex_unlock (S.L'Access);
1806 pragma Assert (Result = 0);
1808 SSL.Abort_Undefer.all;
1810 raise Program_Error;
1813 -- Suspend the task if the state is False. Otherwise, the task
1814 -- continues its execution, and the state of the suspension object
1815 -- is set to False (ARM D.10 par. 9).
1823 -- Loop in case pthread_cond_wait returns earlier than expected
1824 -- (e.g. in case of EINTR caused by a signal).
1826 Result := cond_wait (S.CV'Access, S.L'Access);
1827 pragma Assert (Result = 0 or else Result = EINTR);
1829 exit when not S.Waiting;
1833 Result := mutex_unlock (S.L'Access);
1834 pragma Assert (Result = 0);
1836 SSL.Abort_Undefer.all;
1838 end Suspend_Until_True;
1844 function Check_Exit (Self_ID : Task_Id) return Boolean is
1846 -- Check that caller is just holding Global_Task_Lock and no other locks
1848 if Self_ID.Common.LL.Locks = null then
1852 -- 2 = Global_Task_Level
1854 if Self_ID.Common.LL.Locks.Level /= 2 then
1858 if Self_ID.Common.LL.Locks.Next /= null then
1862 -- Check that caller is abort-deferred
1864 if Self_ID.Deferral_Level = 0 then
1871 --------------------
1872 -- Check_No_Locks --
1873 --------------------
1875 function Check_No_Locks (Self_ID : Task_Id) return Boolean is
1877 return Self_ID.Common.LL.Locks = null;
1880 ----------------------
1881 -- Environment_Task --
1882 ----------------------
1884 function Environment_Task return Task_Id is
1886 return Environment_Task_Id;
1887 end Environment_Task;
1893 procedure Lock_RTS is
1895 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1902 procedure Unlock_RTS is
1904 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1911 function Suspend_Task
1913 Thread_Self : Thread_Id) return Boolean
1916 if T.Common.LL.Thread /= Thread_Self then
1917 return thr_suspend (T.Common.LL.Thread) = 0;
1927 function Resume_Task
1929 Thread_Self : Thread_Id) return Boolean
1932 if T.Common.LL.Thread /= Thread_Self then
1933 return thr_continue (T.Common.LL.Thread) = 0;
1939 --------------------
1940 -- Stop_All_Tasks --
1941 --------------------
1943 procedure Stop_All_Tasks is
1952 function Stop_Task (T : ST.Task_Id) return Boolean is
1953 pragma Unreferenced (T);
1962 function Continue_Task (T : ST.Task_Id) return Boolean is
1963 pragma Unreferenced (T);
1968 end System.Task_Primitives.Operations;