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-2011, 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.
43 with System.Multiprocessors;
44 with System.Tasking.Debug;
45 with System.Interrupt_Management;
46 with System.OS_Primitives;
47 with System.Task_Info;
49 pragma Warnings (Off);
53 with System.Soft_Links;
54 -- We use System.Soft_Links instead of System.Tasking.Initialization
55 -- because the later is a higher level package that we shouldn't depend on.
56 -- For example when using the restricted run time, it is replaced by
57 -- System.Tasking.Restricted.Stages.
59 package body System.Task_Primitives.Operations is
61 package SSL renames System.Soft_Links;
63 use System.Tasking.Debug;
66 use System.OS_Interface;
67 use System.Parameters;
68 use System.OS_Primitives;
74 -- The following are logically constants, but need to be initialized
77 Environment_Task_Id : Task_Id;
78 -- A variable to hold Task_Id for the environment task.
79 -- If we use this variable to get the Task_Id, we need the following
80 -- ATCB_Key only for non-Ada threads.
82 Unblocked_Signal_Mask : aliased sigset_t;
83 -- The set of signals that should unblocked in all tasks
85 ATCB_Key : aliased thread_key_t;
86 -- Key used to find the Ada Task_Id associated with a thread,
87 -- at least for C threads unknown to the Ada run-time system.
89 Single_RTS_Lock : aliased RTS_Lock;
90 -- This is a lock to allow only one thread of control in the RTS at
91 -- a time; it is used to execute in mutual exclusion from all other tasks.
92 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
94 Next_Serial_Number : Task_Serial_Number := 100;
95 -- We start at 100, to reserve some special values for
96 -- using in error checking.
97 -- The following are internal configuration constants needed.
99 Abort_Handler_Installed : Boolean := False;
100 -- True if a handler for the abort signal is installed
102 Null_Thread_Id : constant Thread_Id := Thread_Id'Last;
103 -- Constant to indicate that the thread identifier has not yet been
106 ----------------------
107 -- Priority Support --
108 ----------------------
110 Priority_Ceiling_Emulation : constant Boolean := True;
111 -- controls whether we emulate priority ceiling locking
113 -- To get a scheduling close to annex D requirements, we use the real-time
114 -- class provided for LWPs and map each task/thread to a specific and
115 -- unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
117 -- The real time class can only be set when the process has root
118 -- privileges, so in the other cases, we use the normal thread scheduling
119 -- and priority handling.
121 Using_Real_Time_Class : Boolean := False;
122 -- indicates whether the real time class is being used (i.e. the process
123 -- has root privileges).
125 Prio_Param : aliased struct_pcparms;
126 -- Hold priority info (Real_Time) initialized during the package
129 -----------------------------------
130 -- External Configuration Values --
131 -----------------------------------
133 Time_Slice_Val : Integer;
134 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
136 Locking_Policy : Character;
137 pragma Import (C, Locking_Policy, "__gl_locking_policy");
139 Dispatching_Policy : Character;
140 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
142 Foreign_Task_Elaborated : aliased Boolean := True;
143 -- Used to identified fake tasks (i.e., non-Ada Threads)
145 -----------------------
146 -- Local Subprograms --
147 -----------------------
149 function sysconf (name : System.OS_Interface.int) return processorid_t;
150 pragma Import (C, sysconf, "sysconf");
152 SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
155 (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
156 return processorid_t renames sysconf;
158 procedure Abort_Handler
160 Code : not null access siginfo_t;
161 Context : not null access ucontext_t);
162 -- Target-dependent binding of inter-thread Abort signal to
163 -- the raising of the Abort_Signal exception.
164 -- See also comments in 7staprop.adb
170 function Check_Initialize_Lock
172 Level : Lock_Level) return Boolean;
173 pragma Inline (Check_Initialize_Lock);
175 function Check_Lock (L : Lock_Ptr) return Boolean;
176 pragma Inline (Check_Lock);
178 function Record_Lock (L : Lock_Ptr) return Boolean;
179 pragma Inline (Record_Lock);
181 function Check_Sleep (Reason : Task_States) return Boolean;
182 pragma Inline (Check_Sleep);
184 function Record_Wakeup
186 Reason : Task_States) return Boolean;
187 pragma Inline (Record_Wakeup);
189 function Check_Wakeup
191 Reason : Task_States) return Boolean;
192 pragma Inline (Check_Wakeup);
194 function Check_Unlock (L : Lock_Ptr) return Boolean;
195 pragma Inline (Check_Unlock);
197 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
198 pragma Inline (Check_Finalize_Lock);
206 procedure Initialize (Environment_Task : Task_Id);
207 pragma Inline (Initialize);
208 -- Initialize various data needed by this package
210 function Is_Valid_Task return Boolean;
211 pragma Inline (Is_Valid_Task);
212 -- Does executing thread have a TCB?
214 procedure Set (Self_Id : Task_Id);
216 -- Set the self id for the current task
218 function Self return Task_Id;
219 pragma Inline (Self);
220 -- Return a pointer to the Ada Task Control Block of the calling task
224 package body Specific is separate;
225 -- The body of this package is target specific
227 ----------------------------------
228 -- ATCB allocation/deallocation --
229 ----------------------------------
231 package body ATCB_Allocation is separate;
232 -- The body of this package is shared across several targets
234 ---------------------------------
235 -- Support for foreign threads --
236 ---------------------------------
238 function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
239 -- Allocate and Initialize a new ATCB for the current Thread
241 function Register_Foreign_Thread
242 (Thread : Thread_Id) return Task_Id is separate;
248 Check_Count : Integer := 0;
249 Lock_Count : Integer := 0;
250 Unlock_Count : Integer := 0;
256 procedure Abort_Handler
258 Code : not null access siginfo_t;
259 Context : not null access ucontext_t)
261 pragma Unreferenced (Sig);
262 pragma Unreferenced (Code);
263 pragma Unreferenced (Context);
265 Self_ID : constant Task_Id := Self;
266 Old_Set : aliased sigset_t;
268 Result : Interfaces.C.int;
269 pragma Warnings (Off, Result);
272 -- It's not safe to raise an exception when using GCC ZCX mechanism.
273 -- Note that we still need to install a signal handler, since in some
274 -- cases (e.g. shutdown of the Server_Task in System.Interrupts) we
275 -- need to send the Abort signal to a task.
277 if ZCX_By_Default then
281 if Self_ID.Deferral_Level = 0
282 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
283 and then not Self_ID.Aborting
285 Self_ID.Aborting := True;
287 -- Make sure signals used for RTS internal purpose are unmasked
292 Unblocked_Signal_Mask'Unchecked_Access,
293 Old_Set'Unchecked_Access);
294 pragma Assert (Result = 0);
296 raise Standard'Abort_Signal;
304 -- The underlying thread system sets a guard page at the
305 -- bottom of a thread stack, so nothing is needed.
307 procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
308 pragma Unreferenced (T);
309 pragma Unreferenced (On);
318 function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
320 return T.Common.LL.Thread;
327 procedure Initialize (Environment_Task : ST.Task_Id) is
328 act : aliased struct_sigaction;
329 old_act : aliased struct_sigaction;
330 Tmp_Set : aliased sigset_t;
331 Result : Interfaces.C.int;
333 procedure Configure_Processors;
334 -- Processors configuration
335 -- The user can specify a processor which the program should run
336 -- on to emulate a single-processor system. This can be easily
337 -- done by setting environment variable GNAT_PROCESSOR to one of
340 -- -2 : use the default configuration (run the program on all
341 -- available processors) - this is the same as having
342 -- GNAT_PROCESSOR unset
343 -- -1 : let the RTS choose one processor and run the program on
345 -- 0 .. Last_Proc : run the program on the specified processor
347 -- Last_Proc is equal to the value of the system variable
348 -- _SC_NPROCESSORS_CONF, minus one.
350 procedure Configure_Processors is
351 Proc_Acc : constant System.OS_Lib.String_Access :=
352 System.OS_Lib.Getenv ("GNAT_PROCESSOR");
353 Proc : aliased processorid_t; -- User processor #
354 Last_Proc : processorid_t; -- Last processor #
357 if Proc_Acc.all'Length /= 0 then
359 -- Environment variable is defined
361 Last_Proc := Num_Procs - 1;
363 if Last_Proc /= -1 then
364 Proc := processorid_t'Value (Proc_Acc.all);
366 if Proc <= -2 or else Proc > Last_Proc then
368 -- Use the default configuration
374 -- Choose a processor
377 while Proc < Last_Proc loop
379 Result := p_online (Proc, PR_STATUS);
380 exit when Result = PR_ONLINE;
383 pragma Assert (Result = PR_ONLINE);
384 Result := processor_bind (P_PID, P_MYID, Proc, null);
385 pragma Assert (Result = 0);
388 -- Use user processor
390 Result := processor_bind (P_PID, P_MYID, Proc, null);
391 pragma Assert (Result = 0);
397 when Constraint_Error =>
399 -- Illegal environment variable GNAT_PROCESSOR - ignored
402 end Configure_Processors;
405 (Int : System.Interrupt_Management.Interrupt_ID) return Character;
406 pragma Import (C, State, "__gnat_get_interrupt_state");
407 -- Get interrupt state. Defined in a-init.c
408 -- The input argument is the interrupt number,
409 -- and the result is one of the following:
411 Default : constant Character := 's';
412 -- 'n' this interrupt not set by any Interrupt_State pragma
413 -- 'u' Interrupt_State pragma set state to User
414 -- 'r' Interrupt_State pragma set state to Runtime
415 -- 's' Interrupt_State pragma set state to System (use "default"
418 -- Start of processing for Initialize
421 Environment_Task_Id := Environment_Task;
423 Interrupt_Management.Initialize;
425 -- Prepare the set of signals that should unblocked in all tasks
427 Result := sigemptyset (Unblocked_Signal_Mask'Access);
428 pragma Assert (Result = 0);
430 for J in Interrupt_Management.Interrupt_ID loop
431 if System.Interrupt_Management.Keep_Unmasked (J) then
432 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
433 pragma Assert (Result = 0);
437 if Dispatching_Policy = 'F' then
439 Result : Interfaces.C.long;
440 Class_Info : aliased struct_pcinfo;
441 Secs, Nsecs : Interfaces.C.long;
444 -- If a pragma Time_Slice is specified, takes the value in account
446 if Time_Slice_Val > 0 then
448 -- Convert Time_Slice_Val (microseconds) to seconds/nanosecs
450 Secs := Interfaces.C.long (Time_Slice_Val / 1_000_000);
452 Interfaces.C.long ((Time_Slice_Val rem 1_000_000) * 1_000);
454 -- Otherwise, default to no time slicing (i.e run until blocked)
461 -- Get the real time class id
463 Class_Info.pc_clname (1) := 'R';
464 Class_Info.pc_clname (2) := 'T';
465 Class_Info.pc_clname (3) := ASCII.NUL;
467 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
470 -- Request the real time class
472 Prio_Param.pc_cid := Class_Info.pc_cid;
473 Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
474 Prio_Param.rt_tqsecs := Secs;
475 Prio_Param.rt_tqnsecs := Nsecs;
479 (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS, Prio_Param'Address);
481 Using_Real_Time_Class := Result /= -1;
485 Specific.Initialize (Environment_Task);
487 -- The following is done in Enter_Task, but this is too late for the
488 -- Environment Task, since we need to call Self in Check_Locks when
489 -- the run time is compiled with assertions on.
491 Specific.Set (Environment_Task);
493 -- Initialize the lock used to synchronize chain of all ATCBs
495 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
497 -- Make environment task known here because it doesn't go through
498 -- Activate_Tasks, which does it for all other tasks.
500 Known_Tasks (Known_Tasks'First) := Environment_Task;
501 Environment_Task.Known_Tasks_Index := Known_Tasks'First;
503 Enter_Task (Environment_Task);
505 Configure_Processors;
508 (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
510 -- Set sa_flags to SA_NODEFER so that during the handler execution
511 -- we do not change the Signal_Mask to be masked for the Abort_Signal
512 -- This is a temporary fix to the problem that the Signal_Mask is
513 -- not restored after the exception (longjmp) from the handler.
514 -- The right fix should be made in sigsetjmp so that we save
515 -- the Signal_Set and restore it after a longjmp.
516 -- In that case, this field should be changed back to 0. ???
520 act.sa_handler := Abort_Handler'Address;
521 Result := sigemptyset (Tmp_Set'Access);
522 pragma Assert (Result = 0);
523 act.sa_mask := Tmp_Set;
527 (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
528 act'Unchecked_Access,
529 old_act'Unchecked_Access);
530 pragma Assert (Result = 0);
531 Abort_Handler_Installed := True;
535 ---------------------
536 -- Initialize_Lock --
537 ---------------------
539 -- Note: mutexes and cond_variables needed per-task basis are initialized
540 -- in Initialize_TCB and the Storage_Error is handled. Other mutexes (such
541 -- as RTS_Lock, Memory_Lock...) used in RTS is initialized before any
542 -- status change of RTS. Therefore raising Storage_Error in the following
543 -- routines should be able to be handled safely.
545 procedure Initialize_Lock
546 (Prio : System.Any_Priority;
547 L : not null access Lock)
549 Result : Interfaces.C.int;
552 pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
554 if Priority_Ceiling_Emulation then
558 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
559 pragma Assert (Result = 0 or else Result = ENOMEM);
561 if Result = ENOMEM then
562 raise Storage_Error with "Failed to allocate a lock";
566 procedure Initialize_Lock
567 (L : not null access RTS_Lock;
570 Result : Interfaces.C.int;
574 (Check_Initialize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
575 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
576 pragma Assert (Result = 0 or else Result = ENOMEM);
578 if Result = ENOMEM then
579 raise Storage_Error with "Failed to allocate a lock";
587 procedure Finalize_Lock (L : not null access Lock) is
588 Result : Interfaces.C.int;
590 pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
591 Result := mutex_destroy (L.L'Access);
592 pragma Assert (Result = 0);
595 procedure Finalize_Lock (L : not null access RTS_Lock) is
596 Result : Interfaces.C.int;
598 pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
599 Result := mutex_destroy (L.L'Access);
600 pragma Assert (Result = 0);
608 (L : not null access Lock;
609 Ceiling_Violation : out Boolean)
611 Result : Interfaces.C.int;
614 pragma Assert (Check_Lock (Lock_Ptr (L)));
616 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
618 Self_Id : constant Task_Id := Self;
619 Saved_Priority : System.Any_Priority;
622 if Self_Id.Common.LL.Active_Priority > L.Ceiling then
623 Ceiling_Violation := True;
627 Saved_Priority := Self_Id.Common.LL.Active_Priority;
629 if Self_Id.Common.LL.Active_Priority < L.Ceiling then
630 Set_Priority (Self_Id, L.Ceiling);
633 Result := mutex_lock (L.L'Access);
634 pragma Assert (Result = 0);
635 Ceiling_Violation := False;
637 L.Saved_Priority := Saved_Priority;
641 Result := mutex_lock (L.L'Access);
642 pragma Assert (Result = 0);
643 Ceiling_Violation := False;
646 pragma Assert (Record_Lock (Lock_Ptr (L)));
650 (L : not null access RTS_Lock;
651 Global_Lock : Boolean := False)
653 Result : Interfaces.C.int;
655 if not Single_Lock or else Global_Lock then
656 pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
657 Result := mutex_lock (L.L'Access);
658 pragma Assert (Result = 0);
659 pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
663 procedure Write_Lock (T : Task_Id) is
664 Result : Interfaces.C.int;
666 if not Single_Lock then
667 pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
668 Result := mutex_lock (T.Common.LL.L.L'Access);
669 pragma Assert (Result = 0);
670 pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
679 (L : not null access Lock;
680 Ceiling_Violation : out Boolean) is
682 Write_Lock (L, Ceiling_Violation);
689 procedure Unlock (L : not null access Lock) is
690 Result : Interfaces.C.int;
693 pragma Assert (Check_Unlock (Lock_Ptr (L)));
695 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
697 Self_Id : constant Task_Id := Self;
700 Result := mutex_unlock (L.L'Access);
701 pragma Assert (Result = 0);
703 if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
704 Set_Priority (Self_Id, L.Saved_Priority);
708 Result := mutex_unlock (L.L'Access);
709 pragma Assert (Result = 0);
714 (L : not null access RTS_Lock;
715 Global_Lock : Boolean := False)
717 Result : Interfaces.C.int;
719 if not Single_Lock or else Global_Lock then
720 pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
721 Result := mutex_unlock (L.L'Access);
722 pragma Assert (Result = 0);
726 procedure Unlock (T : Task_Id) is
727 Result : Interfaces.C.int;
729 if not Single_Lock then
730 pragma Assert (Check_Unlock (To_Lock_Ptr (T.Common.LL.L'Access)));
731 Result := mutex_unlock (T.Common.LL.L.L'Access);
732 pragma Assert (Result = 0);
740 -- Dynamic priority ceilings are not supported by the underlying system
742 procedure Set_Ceiling
743 (L : not null access Lock;
744 Prio : System.Any_Priority)
746 pragma Unreferenced (L, Prio);
751 -- For the time delay implementation, we need to make sure we
752 -- achieve following criteria:
754 -- 1) We have to delay at least for the amount requested.
755 -- 2) We have to give up CPU even though the actual delay does not
756 -- result in blocking.
757 -- 3) Except for restricted run-time systems that do not support
758 -- ATC or task abort, the delay must be interrupted by the
759 -- abort_task operation.
760 -- 4) The implementation has to be efficient so that the delay overhead
761 -- is relatively cheap.
762 -- (1)-(3) are Ada requirements. Even though (2) is an Annex-D
763 -- requirement we still want to provide the effect in all cases.
764 -- The reason is that users may want to use short delays to implement
765 -- their own scheduling effect in the absence of language provided
766 -- scheduling policies.
768 ---------------------
769 -- Monotonic_Clock --
770 ---------------------
772 function Monotonic_Clock return Duration is
773 TS : aliased timespec;
774 Result : Interfaces.C.int;
776 Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
777 pragma Assert (Result = 0);
778 return To_Duration (TS);
785 function RT_Resolution return Duration is
794 procedure Yield (Do_Yield : Boolean := True) is
797 System.OS_Interface.thr_yield;
805 function Self return Task_Id renames Specific.Self;
811 procedure Set_Priority
813 Prio : System.Any_Priority;
814 Loss_Of_Inheritance : Boolean := False)
816 pragma Unreferenced (Loss_Of_Inheritance);
818 Result : Interfaces.C.int;
819 pragma Unreferenced (Result);
821 Param : aliased struct_pcparms;
826 T.Common.Current_Priority := Prio;
828 if Priority_Ceiling_Emulation then
829 T.Common.LL.Active_Priority := Prio;
832 if Using_Real_Time_Class then
833 Param.pc_cid := Prio_Param.pc_cid;
834 Param.rt_pri := pri_t (Prio);
835 Param.rt_tqsecs := Prio_Param.rt_tqsecs;
836 Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
838 Result := Interfaces.C.int (
839 priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
843 if T.Common.Task_Info /= null
844 and then not T.Common.Task_Info.Bound_To_LWP
846 -- The task is not bound to a LWP, so use thr_setprio
849 thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
852 -- The task is bound to a LWP, use priocntl
864 function Get_Priority (T : Task_Id) return System.Any_Priority is
866 return T.Common.Current_Priority;
873 procedure Enter_Task (Self_ID : Task_Id) is
875 Self_ID.Common.LL.Thread := thr_self;
876 Self_ID.Common.LL.LWP := lwp_self;
878 Set_Task_Affinity (Self_ID);
879 Specific.Set (Self_ID);
881 -- We need the above code even if we do direct fetch of Task_Id in Self
882 -- for the main task on Sun, x86 Solaris and for gcc 2.7.2.
889 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
891 -----------------------------
892 -- Register_Foreign_Thread --
893 -----------------------------
895 function Register_Foreign_Thread return Task_Id is
897 if Is_Valid_Task then
900 return Register_Foreign_Thread (thr_self);
902 end Register_Foreign_Thread;
908 procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
909 Result : Interfaces.C.int := 0;
912 -- Give the task a unique serial number
914 Self_ID.Serial_Number := Next_Serial_Number;
915 Next_Serial_Number := Next_Serial_Number + 1;
916 pragma Assert (Next_Serial_Number /= 0);
918 Self_ID.Common.LL.Thread := Null_Thread_Id;
920 if not Single_Lock then
923 (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
924 Self_ID.Common.LL.L.Level :=
925 Private_Task_Serial_Number (Self_ID.Serial_Number);
926 pragma Assert (Result = 0 or else Result = ENOMEM);
930 Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
931 pragma Assert (Result = 0 or else Result = ENOMEM);
937 if not Single_Lock then
938 Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
939 pragma Assert (Result = 0);
950 procedure Create_Task
952 Wrapper : System.Address;
953 Stack_Size : System.Parameters.Size_Type;
954 Priority : System.Any_Priority;
955 Succeeded : out Boolean)
957 pragma Unreferenced (Priority);
959 Result : Interfaces.C.int;
960 Adjusted_Stack_Size : Interfaces.C.size_t;
961 Opts : Interfaces.C.int := THR_DETACHED;
963 Page_Size : constant System.Parameters.Size_Type := 4096;
964 -- This constant is for reserving extra space at the
965 -- end of the stack, which can be used by the stack
966 -- checking as guard page. The idea is that we need
967 -- to have at least Stack_Size bytes available for
970 use System.Task_Info;
971 use type System.Multiprocessors.CPU_Range;
974 -- Check whether both Dispatching_Domain and CPU are specified for the
975 -- task, and the CPU value is not contained within the range of
976 -- processors for the domain.
978 if T.Common.Domain /= null
979 and then T.Common.Base_CPU /= System.Multiprocessors.Not_A_Specific_CPU
981 (T.Common.Base_CPU not in T.Common.Domain'Range
982 or else not T.Common.Domain (T.Common.Base_CPU))
988 Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size + Page_Size);
990 -- Since the initial signal mask of a thread is inherited from the
991 -- creator, and the Environment task has all its signals masked, we
992 -- do not need to manipulate caller's signal mask at this point.
993 -- All tasks in RTS will have All_Tasks_Mask initially.
995 if T.Common.Task_Info /= null then
996 if T.Common.Task_Info.New_LWP then
997 Opts := Opts + THR_NEW_LWP;
1000 if T.Common.Task_Info.Bound_To_LWP then
1001 Opts := Opts + THR_BOUND;
1005 Opts := THR_DETACHED + THR_BOUND;
1010 (System.Null_Address,
1011 Adjusted_Stack_Size,
1012 Thread_Body_Access (Wrapper),
1015 T.Common.LL.Thread'Access);
1017 Succeeded := Result = 0;
1020 or else Result = ENOMEM
1021 or else Result = EAGAIN);
1028 procedure Finalize_TCB (T : Task_Id) is
1029 Result : Interfaces.C.int;
1032 T.Common.LL.Thread := Null_Thread_Id;
1034 if not Single_Lock then
1035 Result := mutex_destroy (T.Common.LL.L.L'Access);
1036 pragma Assert (Result = 0);
1039 Result := cond_destroy (T.Common.LL.CV'Access);
1040 pragma Assert (Result = 0);
1042 if T.Known_Tasks_Index /= -1 then
1043 Known_Tasks (T.Known_Tasks_Index) := null;
1046 ATCB_Allocation.Free_ATCB (T);
1053 -- This procedure must be called with abort deferred. It can no longer
1054 -- call Self or access the current task's ATCB, since the ATCB has been
1057 procedure Exit_Task is
1059 Specific.Set (null);
1066 procedure Abort_Task (T : Task_Id) is
1067 Result : Interfaces.C.int;
1069 if Abort_Handler_Installed then
1070 pragma Assert (T /= Self);
1073 (T.Common.LL.Thread,
1074 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1075 pragma Assert (Result = 0);
1085 Reason : Task_States)
1087 Result : Interfaces.C.int;
1090 pragma Assert (Check_Sleep (Reason));
1095 (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1099 (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1103 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1104 pragma Assert (Result = 0 or else Result = EINTR);
1107 -- Note that we are relying heavily here on GNAT representing
1108 -- Calendar.Time, System.Real_Time.Time, Duration,
1109 -- System.Real_Time.Time_Span in the same way, i.e., as a 64-bit count of
1112 -- This allows us to always pass the timeout value as a Duration
1115 -- We are taking liberties here with the semantics of the delays. That is,
1116 -- we make no distinction between delays on the Calendar clock and delays
1117 -- on the Real_Time clock. That is technically incorrect, if the Calendar
1118 -- clock happens to be reset or adjusted. To solve this defect will require
1119 -- modification to the compiler interface, so that it can pass through more
1120 -- information, to tell us here which clock to use!
1122 -- cond_timedwait will return if any of the following happens:
1123 -- 1) some other task did cond_signal on this condition variable
1124 -- In this case, the return value is 0
1125 -- 2) the call just returned, for no good reason
1126 -- This is called a "spurious wakeup".
1127 -- In this case, the return value may also be 0.
1128 -- 3) the time delay expires
1129 -- In this case, the return value is ETIME
1130 -- 4) this task received a signal, which was handled by some
1131 -- handler procedure, and now the thread is resuming execution
1132 -- UNIX calls this an "interrupted" system call.
1133 -- In this case, the return value is EINTR
1135 -- If the cond_timedwait returns 0 or EINTR, it is still possible that the
1136 -- time has actually expired, and by chance a signal or cond_signal
1137 -- occurred at around the same time.
1139 -- We have also observed that on some OS's the value ETIME will be
1140 -- returned, but the clock will show that the full delay has not yet
1143 -- For these reasons, we need to check the clock after return from
1144 -- cond_timedwait. If the time has expired, we will set Timedout = True.
1146 -- This check might be omitted for systems on which the cond_timedwait()
1147 -- never returns early or wakes up spuriously.
1149 -- Annex D requires that completion of a delay cause the task to go to the
1150 -- end of its priority queue, regardless of whether the task actually was
1151 -- suspended by the delay. Since cond_timedwait does not do this on
1152 -- Solaris, we add a call to thr_yield at the end. We might do this at the
1153 -- beginning, instead, but then the round-robin effect would not be the
1154 -- same; the delayed task would be ahead of other tasks of the same
1155 -- priority that awoke while it was sleeping.
1157 -- For Timed_Sleep, we are expecting possible cond_signals to indicate
1158 -- other events (e.g., completion of a RV or completion of the abortable
1159 -- part of an async. select), we want to always return if interrupted. The
1160 -- caller will be responsible for checking the task state to see whether
1161 -- the wakeup was spurious, and to go back to sleep again in that case. We
1162 -- don't need to check for pending abort or priority change on the way in
1163 -- our out; that is the caller's responsibility.
1165 -- For Timed_Delay, we are not expecting any cond_signals or other
1166 -- interruptions, except for priority changes and aborts. Therefore, we
1167 -- don't want to return unless the delay has actually expired, or the call
1168 -- has been aborted. In this case, since we want to implement the entire
1169 -- delay statement semantics, we do need to check for pending abort and
1170 -- priority changes. We can quietly handle priority changes inside the
1171 -- procedure, since there is no entry-queue reordering involved.
1177 procedure Timed_Sleep
1180 Mode : ST.Delay_Modes;
1181 Reason : System.Tasking.Task_States;
1182 Timedout : out Boolean;
1183 Yielded : out Boolean)
1185 Base_Time : constant Duration := Monotonic_Clock;
1186 Check_Time : Duration := Base_Time;
1187 Abs_Time : Duration;
1188 Request : aliased timespec;
1189 Result : Interfaces.C.int;
1192 pragma Assert (Check_Sleep (Reason));
1198 then Duration'Min (Time, Max_Sensible_Delay) + Check_Time
1199 else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
1201 if Abs_Time > Check_Time then
1202 Request := To_Timespec (Abs_Time);
1204 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1209 (Self_ID.Common.LL.CV'Access,
1210 Single_RTS_Lock.L'Access, Request'Access);
1214 (Self_ID.Common.LL.CV'Access,
1215 Self_ID.Common.LL.L.L'Access, Request'Access);
1220 Check_Time := Monotonic_Clock;
1221 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1223 if Result = 0 or Result = EINTR then
1225 -- Somebody may have called Wakeup for us
1231 pragma Assert (Result = ETIME);
1236 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1243 procedure Timed_Delay
1246 Mode : ST.Delay_Modes)
1248 Base_Time : constant Duration := Monotonic_Clock;
1249 Check_Time : Duration := Base_Time;
1250 Abs_Time : Duration;
1251 Request : aliased timespec;
1252 Result : Interfaces.C.int;
1253 Yielded : Boolean := False;
1260 Write_Lock (Self_ID);
1264 then Time + Check_Time
1265 else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
1267 if Abs_Time > Check_Time then
1268 Request := To_Timespec (Abs_Time);
1269 Self_ID.Common.State := Delay_Sleep;
1271 pragma Assert (Check_Sleep (Delay_Sleep));
1274 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1279 (Self_ID.Common.LL.CV'Access,
1280 Single_RTS_Lock.L'Access,
1285 (Self_ID.Common.LL.CV'Access,
1286 Self_ID.Common.LL.L.L'Access,
1292 Check_Time := Monotonic_Clock;
1293 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1297 Result = ETIME or else
1303 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1305 Self_ID.Common.State := Runnable;
1325 Reason : Task_States)
1327 Result : Interfaces.C.int;
1329 pragma Assert (Check_Wakeup (T, Reason));
1330 Result := cond_signal (T.Common.LL.CV'Access);
1331 pragma Assert (Result = 0);
1334 ---------------------------
1335 -- Check_Initialize_Lock --
1336 ---------------------------
1338 -- The following code is intended to check some of the invariant assertions
1339 -- related to lock usage, on which we depend.
1341 function Check_Initialize_Lock
1343 Level : Lock_Level) return Boolean
1345 Self_ID : constant Task_Id := Self;
1348 -- Check that caller is abort-deferred
1350 if Self_ID.Deferral_Level = 0 then
1354 -- Check that the lock is not yet initialized
1356 if L.Level /= 0 then
1360 L.Level := Lock_Level'Pos (Level) + 1;
1362 end Check_Initialize_Lock;
1368 function Check_Lock (L : Lock_Ptr) return Boolean is
1369 Self_ID : constant Task_Id := Self;
1373 -- Check that the argument is not null
1379 -- Check that L is not frozen
1385 -- Check that caller is abort-deferred
1387 if Self_ID.Deferral_Level = 0 then
1391 -- Check that caller is not holding this lock already
1393 if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1401 -- Check that TCB lock order rules are satisfied
1403 P := Self_ID.Common.LL.Locks;
1405 if P.Level >= L.Level
1406 and then (P.Level > 2 or else L.Level > 2)
1419 function Record_Lock (L : Lock_Ptr) return Boolean is
1420 Self_ID : constant Task_Id := Self;
1424 Lock_Count := Lock_Count + 1;
1426 -- There should be no owner for this lock at this point
1428 if L.Owner /= null then
1434 L.Owner := To_Owner_ID (To_Address (Self_ID));
1440 -- Check that TCB lock order rules are satisfied
1442 P := Self_ID.Common.LL.Locks;
1448 Self_ID.Common.LL.Locking := null;
1449 Self_ID.Common.LL.Locks := L;
1457 function Check_Sleep (Reason : Task_States) return Boolean is
1458 pragma Unreferenced (Reason);
1460 Self_ID : constant Task_Id := Self;
1464 -- Check that caller is abort-deferred
1466 if Self_ID.Deferral_Level = 0 then
1474 -- Check that caller is holding own lock, on top of list
1476 if Self_ID.Common.LL.Locks /=
1477 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1482 -- Check that TCB lock order rules are satisfied
1484 if Self_ID.Common.LL.Locks.Next /= null then
1488 Self_ID.Common.LL.L.Owner := null;
1489 P := Self_ID.Common.LL.Locks;
1490 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1499 function Record_Wakeup
1501 Reason : Task_States) return Boolean
1503 pragma Unreferenced (Reason);
1505 Self_ID : constant Task_Id := Self;
1511 L.Owner := To_Owner_ID (To_Address (Self_ID));
1517 -- Check that TCB lock order rules are satisfied
1519 P := Self_ID.Common.LL.Locks;
1525 Self_ID.Common.LL.Locking := null;
1526 Self_ID.Common.LL.Locks := L;
1534 function Check_Wakeup
1536 Reason : Task_States) return Boolean
1538 Self_ID : constant Task_Id := Self;
1541 -- Is caller holding T's lock?
1543 if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1547 -- Are reasons for wakeup and sleep consistent?
1549 if T.Common.State /= Reason then
1560 function Check_Unlock (L : Lock_Ptr) return Boolean is
1561 Self_ID : constant Task_Id := Self;
1565 Unlock_Count := Unlock_Count + 1;
1571 if L.Buddy /= null then
1575 -- Magic constant 4???
1578 Check_Count := Unlock_Count;
1581 -- Magic constant 1000???
1583 if Unlock_Count - Check_Count > 1000 then
1584 Check_Count := Unlock_Count;
1587 -- Check that caller is abort-deferred
1589 if Self_ID.Deferral_Level = 0 then
1593 -- Check that caller is holding this lock, on top of list
1595 if Self_ID.Common.LL.Locks /= L then
1599 -- Record there is no owner now
1602 P := Self_ID.Common.LL.Locks;
1603 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1608 --------------------
1609 -- Check_Finalize --
1610 --------------------
1612 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1613 Self_ID : constant Task_Id := Self;
1616 -- Check that caller is abort-deferred
1618 if Self_ID.Deferral_Level = 0 then
1622 -- Check that no one is holding this lock
1624 if L.Owner /= null then
1630 end Check_Finalize_Lock;
1636 procedure Initialize (S : in out Suspension_Object) is
1637 Result : Interfaces.C.int;
1640 -- Initialize internal state (always to zero (RM D.10(6)))
1645 -- Initialize internal mutex
1647 Result := mutex_init (S.L'Access, USYNC_THREAD, System.Null_Address);
1648 pragma Assert (Result = 0 or else Result = ENOMEM);
1650 if Result = ENOMEM then
1651 raise Storage_Error with "Failed to allocate a lock";
1654 -- Initialize internal condition variable
1656 Result := cond_init (S.CV'Access, USYNC_THREAD, 0);
1657 pragma Assert (Result = 0 or else Result = ENOMEM);
1660 Result := mutex_destroy (S.L'Access);
1661 pragma Assert (Result = 0);
1663 if Result = ENOMEM then
1664 raise Storage_Error;
1673 procedure Finalize (S : in out Suspension_Object) is
1674 Result : Interfaces.C.int;
1677 -- Destroy internal mutex
1679 Result := mutex_destroy (S.L'Access);
1680 pragma Assert (Result = 0);
1682 -- Destroy internal condition variable
1684 Result := cond_destroy (S.CV'Access);
1685 pragma Assert (Result = 0);
1692 function Current_State (S : Suspension_Object) return Boolean is
1694 -- We do not want to use lock on this read operation. State is marked
1695 -- as Atomic so that we ensure that the value retrieved is correct.
1704 procedure Set_False (S : in out Suspension_Object) is
1705 Result : Interfaces.C.int;
1708 SSL.Abort_Defer.all;
1710 Result := mutex_lock (S.L'Access);
1711 pragma Assert (Result = 0);
1715 Result := mutex_unlock (S.L'Access);
1716 pragma Assert (Result = 0);
1718 SSL.Abort_Undefer.all;
1725 procedure Set_True (S : in out Suspension_Object) is
1726 Result : Interfaces.C.int;
1729 SSL.Abort_Defer.all;
1731 Result := mutex_lock (S.L'Access);
1732 pragma Assert (Result = 0);
1734 -- If there is already a task waiting on this suspension object then
1735 -- we resume it, leaving the state of the suspension object to False,
1736 -- as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1737 -- the state to True.
1743 Result := cond_signal (S.CV'Access);
1744 pragma Assert (Result = 0);
1750 Result := mutex_unlock (S.L'Access);
1751 pragma Assert (Result = 0);
1753 SSL.Abort_Undefer.all;
1756 ------------------------
1757 -- Suspend_Until_True --
1758 ------------------------
1760 procedure Suspend_Until_True (S : in out Suspension_Object) is
1761 Result : Interfaces.C.int;
1764 SSL.Abort_Defer.all;
1766 Result := mutex_lock (S.L'Access);
1767 pragma Assert (Result = 0);
1771 -- Program_Error must be raised upon calling Suspend_Until_True
1772 -- if another task is already waiting on that suspension object
1775 Result := mutex_unlock (S.L'Access);
1776 pragma Assert (Result = 0);
1778 SSL.Abort_Undefer.all;
1780 raise Program_Error;
1783 -- Suspend the task if the state is False. Otherwise, the task
1784 -- continues its execution, and the state of the suspension object
1785 -- is set to False (ARM D.10 par. 9).
1793 -- Loop in case pthread_cond_wait returns earlier than expected
1794 -- (e.g. in case of EINTR caused by a signal).
1796 Result := cond_wait (S.CV'Access, S.L'Access);
1797 pragma Assert (Result = 0 or else Result = EINTR);
1799 exit when not S.Waiting;
1803 Result := mutex_unlock (S.L'Access);
1804 pragma Assert (Result = 0);
1806 SSL.Abort_Undefer.all;
1808 end Suspend_Until_True;
1814 function Check_Exit (Self_ID : Task_Id) return Boolean is
1816 -- Check that caller is just holding Global_Task_Lock and no other locks
1818 if Self_ID.Common.LL.Locks = null then
1822 -- 2 = Global_Task_Level
1824 if Self_ID.Common.LL.Locks.Level /= 2 then
1828 if Self_ID.Common.LL.Locks.Next /= null then
1832 -- Check that caller is abort-deferred
1834 if Self_ID.Deferral_Level = 0 then
1841 --------------------
1842 -- Check_No_Locks --
1843 --------------------
1845 function Check_No_Locks (Self_ID : Task_Id) return Boolean is
1847 return Self_ID.Common.LL.Locks = null;
1850 ----------------------
1851 -- Environment_Task --
1852 ----------------------
1854 function Environment_Task return Task_Id is
1856 return Environment_Task_Id;
1857 end Environment_Task;
1863 procedure Lock_RTS is
1865 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1872 procedure Unlock_RTS is
1874 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1881 function Suspend_Task
1883 Thread_Self : Thread_Id) return Boolean
1886 if T.Common.LL.Thread /= Thread_Self then
1887 return thr_suspend (T.Common.LL.Thread) = 0;
1897 function Resume_Task
1899 Thread_Self : Thread_Id) return Boolean
1902 if T.Common.LL.Thread /= Thread_Self then
1903 return thr_continue (T.Common.LL.Thread) = 0;
1909 --------------------
1910 -- Stop_All_Tasks --
1911 --------------------
1913 procedure Stop_All_Tasks is
1922 function Stop_Task (T : ST.Task_Id) return Boolean is
1923 pragma Unreferenced (T);
1932 function Continue_Task (T : ST.Task_Id) return Boolean is
1933 pragma Unreferenced (T);
1938 -----------------------
1939 -- Set_Task_Affinity --
1940 -----------------------
1942 procedure Set_Task_Affinity (T : ST.Task_Id) is
1943 Result : Interfaces.C.int;
1944 Proc : processorid_t; -- User processor #
1945 Last_Proc : processorid_t; -- Last processor #
1947 use System.Task_Info;
1948 use type System.Multiprocessors.CPU_Range;
1951 -- Do nothing if the underlying thread has not yet been created. If the
1952 -- thread has not yet been created then the proper affinity will be set
1953 -- during its creation.
1955 if T.Common.LL.Thread = Null_Thread_Id then
1960 elsif T.Common.Base_CPU /=
1961 System.Multiprocessors.Not_A_Specific_CPU
1963 -- The CPU numbering in pragma CPU starts at 1 while the subprogram
1964 -- to set the affinity starts at 0, therefore we must substract 1.
1968 (P_LWPID, id_t (T.Common.LL.LWP),
1969 processorid_t (T.Common.Base_CPU) - 1, null);
1970 pragma Assert (Result = 0);
1974 elsif T.Common.Task_Info /= null then
1975 if T.Common.Task_Info.New_LWP
1976 and then T.Common.Task_Info.CPU /= CPU_UNCHANGED
1978 Last_Proc := Num_Procs - 1;
1980 if T.Common.Task_Info.CPU = ANY_CPU then
1984 while Proc < Last_Proc loop
1985 Result := p_online (Proc, PR_STATUS);
1986 exit when Result = PR_ONLINE;
1992 (P_LWPID, id_t (T.Common.LL.LWP), Proc, null);
1993 pragma Assert (Result = 0);
1996 -- Use specified processor
1998 if T.Common.Task_Info.CPU < 0
1999 or else T.Common.Task_Info.CPU > Last_Proc
2001 raise Invalid_CPU_Number;
2006 (P_LWPID, id_t (T.Common.LL.LWP),
2007 T.Common.Task_Info.CPU, null);
2008 pragma Assert (Result = 0);
2012 -- Handle dispatching domains
2014 elsif T.Common.Domain /= null
2015 and then (T.Common.Domain /= ST.System_Domain
2016 or else T.Common.Domain.all /=
2017 (Multiprocessors.CPU'First ..
2018 Multiprocessors.Number_Of_CPUs => True))
2021 CPU_Set : aliased psetid_t;
2025 Result := pset_create (CPU_Set'Access);
2026 pragma Assert (Result = 0);
2028 -- Set the affinity to all the processors belonging to the
2029 -- dispatching domain.
2031 for Proc in T.Common.Domain'Range loop
2033 -- The Ada CPU numbering starts at 1 while the subprogram to
2034 -- set the affinity starts at 0, therefore we must substract 1.
2036 if T.Common.Domain (Proc) then
2038 pset_assign (CPU_Set, processorid_t (Proc) - 1, null);
2039 pragma Assert (Result = 0);
2044 pset_bind (CPU_Set, P_LWPID, id_t (T.Common.LL.LWP), null);
2045 pragma Assert (Result = 0);
2048 end Set_Task_Affinity;
2050 end System.Task_Primitives.Operations;