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-2010, 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.Multiprocessors;
46 with System.Tasking.Debug;
47 with System.Interrupt_Management;
48 with System.OS_Primitives;
49 with System.Task_Info;
51 pragma Warnings (Off);
55 with System.Soft_Links;
56 -- We use System.Soft_Links instead of System.Tasking.Initialization
57 -- because the later is a higher level package that we shouldn't depend on.
58 -- For example when using the restricted run time, it is replaced by
59 -- System.Tasking.Restricted.Stages.
61 package body System.Task_Primitives.Operations is
63 package SSL renames System.Soft_Links;
65 use System.Tasking.Debug;
68 use System.OS_Interface;
69 use System.Parameters;
70 use System.OS_Primitives;
76 -- The following are logically constants, but need to be initialized
79 Environment_Task_Id : Task_Id;
80 -- A variable to hold Task_Id for the environment task.
81 -- If we use this variable to get the Task_Id, we need the following
82 -- ATCB_Key only for non-Ada threads.
84 Unblocked_Signal_Mask : aliased sigset_t;
85 -- The set of signals that should unblocked in all tasks
87 ATCB_Key : aliased thread_key_t;
88 -- Key used to find the Ada Task_Id associated with a thread,
89 -- at least for C threads unknown to the Ada run-time system.
91 Single_RTS_Lock : aliased RTS_Lock;
92 -- This is a lock to allow only one thread of control in the RTS at
93 -- a time; it is used to execute in mutual exclusion from all other tasks.
94 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
96 Next_Serial_Number : Task_Serial_Number := 100;
97 -- We start at 100, to reserve some special values for
98 -- using in error checking.
99 -- The following are internal configuration constants needed.
101 Abort_Handler_Installed : Boolean := False;
102 -- True if a handler for the abort signal is installed
104 ----------------------
105 -- Priority Support --
106 ----------------------
108 Priority_Ceiling_Emulation : constant Boolean := True;
109 -- controls whether we emulate priority ceiling locking
111 -- To get a scheduling close to annex D requirements, we use the real-time
112 -- class provided for LWPs and map each task/thread to a specific and
113 -- unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
115 -- The real time class can only be set when the process has root
116 -- privileges, so in the other cases, we use the normal thread scheduling
117 -- and priority handling.
119 Using_Real_Time_Class : Boolean := False;
120 -- indicates whether the real time class is being used (i.e. the process
121 -- has root privileges).
123 Prio_Param : aliased struct_pcparms;
124 -- Hold priority info (Real_Time) initialized during the package
127 -----------------------------------
128 -- External Configuration Values --
129 -----------------------------------
131 Time_Slice_Val : Integer;
132 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
134 Locking_Policy : Character;
135 pragma Import (C, Locking_Policy, "__gl_locking_policy");
137 Dispatching_Policy : Character;
138 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
140 Foreign_Task_Elaborated : aliased Boolean := True;
141 -- Used to identified fake tasks (i.e., non-Ada Threads)
143 -----------------------
144 -- Local Subprograms --
145 -----------------------
147 function sysconf (name : System.OS_Interface.int) return processorid_t;
148 pragma Import (C, sysconf, "sysconf");
150 SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
153 (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
154 return processorid_t renames sysconf;
156 procedure Abort_Handler
158 Code : not null access siginfo_t;
159 Context : not null access ucontext_t);
160 -- Target-dependent binding of inter-thread Abort signal to
161 -- the raising of the Abort_Signal exception.
162 -- See also comments in 7staprop.adb
168 function Check_Initialize_Lock
170 Level : Lock_Level) return Boolean;
171 pragma Inline (Check_Initialize_Lock);
173 function Check_Lock (L : Lock_Ptr) return Boolean;
174 pragma Inline (Check_Lock);
176 function Record_Lock (L : Lock_Ptr) return Boolean;
177 pragma Inline (Record_Lock);
179 function Check_Sleep (Reason : Task_States) return Boolean;
180 pragma Inline (Check_Sleep);
182 function Record_Wakeup
184 Reason : Task_States) return Boolean;
185 pragma Inline (Record_Wakeup);
187 function Check_Wakeup
189 Reason : Task_States) return Boolean;
190 pragma Inline (Check_Wakeup);
192 function Check_Unlock (L : Lock_Ptr) return Boolean;
193 pragma Inline (Check_Unlock);
195 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
196 pragma Inline (Check_Finalize_Lock);
204 procedure Initialize (Environment_Task : Task_Id);
205 pragma Inline (Initialize);
206 -- Initialize various data needed by this package
208 function Is_Valid_Task return Boolean;
209 pragma Inline (Is_Valid_Task);
210 -- Does executing thread have a TCB?
212 procedure Set (Self_Id : Task_Id);
214 -- Set the self id for the current task
216 function Self return Task_Id;
217 pragma Inline (Self);
218 -- Return a pointer to the Ada Task Control Block of the calling task
222 package body Specific is separate;
223 -- The body of this package is target specific
225 ---------------------------------
226 -- Support for foreign threads --
227 ---------------------------------
229 function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
230 -- Allocate and Initialize a new ATCB for the current Thread
232 function Register_Foreign_Thread
233 (Thread : Thread_Id) return Task_Id is separate;
239 Check_Count : Integer := 0;
240 Lock_Count : Integer := 0;
241 Unlock_Count : Integer := 0;
247 procedure Abort_Handler
249 Code : not null access siginfo_t;
250 Context : not null access ucontext_t)
252 pragma Unreferenced (Sig);
253 pragma Unreferenced (Code);
254 pragma Unreferenced (Context);
256 Self_ID : constant Task_Id := Self;
257 Old_Set : aliased sigset_t;
259 Result : Interfaces.C.int;
260 pragma Warnings (Off, Result);
263 -- It's not safe to raise an exception when using GCC ZCX mechanism.
264 -- Note that we still need to install a signal handler, since in some
265 -- cases (e.g. shutdown of the Server_Task in System.Interrupts) we
266 -- need to send the Abort signal to a task.
268 if ZCX_By_Default and then GCC_ZCX_Support then
272 if Self_ID.Deferral_Level = 0
273 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
274 and then not Self_ID.Aborting
276 Self_ID.Aborting := True;
278 -- Make sure signals used for RTS internal purpose are unmasked
283 Unblocked_Signal_Mask'Unchecked_Access,
284 Old_Set'Unchecked_Access);
285 pragma Assert (Result = 0);
287 raise Standard'Abort_Signal;
295 -- The underlying thread system sets a guard page at the
296 -- bottom of a thread stack, so nothing is needed.
298 procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
299 pragma Unreferenced (T);
300 pragma Unreferenced (On);
309 function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
311 return T.Common.LL.Thread;
318 procedure Initialize (Environment_Task : ST.Task_Id) is
319 act : aliased struct_sigaction;
320 old_act : aliased struct_sigaction;
321 Tmp_Set : aliased sigset_t;
322 Result : Interfaces.C.int;
324 procedure Configure_Processors;
325 -- Processors configuration
326 -- The user can specify a processor which the program should run
327 -- on to emulate a single-processor system. This can be easily
328 -- done by setting environment variable GNAT_PROCESSOR to one of
331 -- -2 : use the default configuration (run the program on all
332 -- available processors) - this is the same as having
333 -- GNAT_PROCESSOR unset
334 -- -1 : let the RTS choose one processor and run the program on
336 -- 0 .. Last_Proc : run the program on the specified processor
338 -- Last_Proc is equal to the value of the system variable
339 -- _SC_NPROCESSORS_CONF, minus one.
341 procedure Configure_Processors is
342 Proc_Acc : constant System.OS_Lib.String_Access :=
343 System.OS_Lib.Getenv ("GNAT_PROCESSOR");
344 Proc : aliased processorid_t; -- User processor #
345 Last_Proc : processorid_t; -- Last processor #
348 if Proc_Acc.all'Length /= 0 then
350 -- Environment variable is defined
352 Last_Proc := Num_Procs - 1;
354 if Last_Proc /= -1 then
355 Proc := processorid_t'Value (Proc_Acc.all);
357 if Proc <= -2 or else Proc > Last_Proc then
359 -- Use the default configuration
365 -- Choose a processor
368 while Proc < Last_Proc loop
370 Result := p_online (Proc, PR_STATUS);
371 exit when Result = PR_ONLINE;
374 pragma Assert (Result = PR_ONLINE);
375 Result := processor_bind (P_PID, P_MYID, Proc, null);
376 pragma Assert (Result = 0);
379 -- Use user processor
381 Result := processor_bind (P_PID, P_MYID, Proc, null);
382 pragma Assert (Result = 0);
388 when Constraint_Error =>
390 -- Illegal environment variable GNAT_PROCESSOR - ignored
393 end Configure_Processors;
396 (Int : System.Interrupt_Management.Interrupt_ID) return Character;
397 pragma Import (C, State, "__gnat_get_interrupt_state");
398 -- Get interrupt state. Defined in a-init.c
399 -- The input argument is the interrupt number,
400 -- and the result is one of the following:
402 Default : constant Character := 's';
403 -- 'n' this interrupt not set by any Interrupt_State pragma
404 -- 'u' Interrupt_State pragma set state to User
405 -- 'r' Interrupt_State pragma set state to Runtime
406 -- 's' Interrupt_State pragma set state to System (use "default"
409 -- Start of processing for Initialize
412 Environment_Task_Id := Environment_Task;
414 Interrupt_Management.Initialize;
416 -- Prepare the set of signals that should unblocked in all tasks
418 Result := sigemptyset (Unblocked_Signal_Mask'Access);
419 pragma Assert (Result = 0);
421 for J in Interrupt_Management.Interrupt_ID loop
422 if System.Interrupt_Management.Keep_Unmasked (J) then
423 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
424 pragma Assert (Result = 0);
428 if Dispatching_Policy = 'F' then
430 Result : Interfaces.C.long;
431 Class_Info : aliased struct_pcinfo;
432 Secs, Nsecs : Interfaces.C.long;
435 -- If a pragma Time_Slice is specified, takes the value in account
437 if Time_Slice_Val > 0 then
439 -- Convert Time_Slice_Val (microseconds) to seconds/nanosecs
441 Secs := Interfaces.C.long (Time_Slice_Val / 1_000_000);
443 Interfaces.C.long ((Time_Slice_Val rem 1_000_000) * 1_000);
445 -- Otherwise, default to no time slicing (i.e run until blocked)
452 -- Get the real time class id
454 Class_Info.pc_clname (1) := 'R';
455 Class_Info.pc_clname (2) := 'T';
456 Class_Info.pc_clname (3) := ASCII.NUL;
458 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
461 -- Request the real time class
463 Prio_Param.pc_cid := Class_Info.pc_cid;
464 Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
465 Prio_Param.rt_tqsecs := Secs;
466 Prio_Param.rt_tqnsecs := Nsecs;
470 (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS, Prio_Param'Address);
472 Using_Real_Time_Class := Result /= -1;
476 Specific.Initialize (Environment_Task);
478 -- The following is done in Enter_Task, but this is too late for the
479 -- Environment Task, since we need to call Self in Check_Locks when
480 -- the run time is compiled with assertions on.
482 Specific.Set (Environment_Task);
484 -- Initialize the lock used to synchronize chain of all ATCBs
486 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
488 -- Make environment task known here because it doesn't go through
489 -- Activate_Tasks, which does it for all other tasks.
491 Known_Tasks (Known_Tasks'First) := Environment_Task;
492 Environment_Task.Known_Tasks_Index := Known_Tasks'First;
494 Enter_Task (Environment_Task);
496 Configure_Processors;
499 (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
501 -- Set sa_flags to SA_NODEFER so that during the handler execution
502 -- we do not change the Signal_Mask to be masked for the Abort_Signal
503 -- This is a temporary fix to the problem that the Signal_Mask is
504 -- not restored after the exception (longjmp) from the handler.
505 -- The right fix should be made in sigsetjmp so that we save
506 -- the Signal_Set and restore it after a longjmp.
507 -- In that case, this field should be changed back to 0. ???
511 act.sa_handler := Abort_Handler'Address;
512 Result := sigemptyset (Tmp_Set'Access);
513 pragma Assert (Result = 0);
514 act.sa_mask := Tmp_Set;
518 (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
519 act'Unchecked_Access,
520 old_act'Unchecked_Access);
521 pragma Assert (Result = 0);
522 Abort_Handler_Installed := True;
526 ---------------------
527 -- Initialize_Lock --
528 ---------------------
530 -- Note: mutexes and cond_variables needed per-task basis are initialized
531 -- in Initialize_TCB and the Storage_Error is handled. Other mutexes (such
532 -- as RTS_Lock, Memory_Lock...) used in RTS is initialized before any
533 -- status change of RTS. Therefore raising Storage_Error in the following
534 -- routines should be able to be handled safely.
536 procedure Initialize_Lock
537 (Prio : System.Any_Priority;
538 L : not null access Lock)
540 Result : Interfaces.C.int;
543 pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
545 if Priority_Ceiling_Emulation then
549 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
550 pragma Assert (Result = 0 or else Result = ENOMEM);
552 if Result = ENOMEM then
553 raise Storage_Error with "Failed to allocate a lock";
557 procedure Initialize_Lock
558 (L : not null access RTS_Lock;
561 Result : Interfaces.C.int;
565 (Check_Initialize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
566 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
567 pragma Assert (Result = 0 or else Result = ENOMEM);
569 if Result = ENOMEM then
570 raise Storage_Error with "Failed to allocate a lock";
578 procedure Finalize_Lock (L : not null access Lock) is
579 Result : Interfaces.C.int;
581 pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
582 Result := mutex_destroy (L.L'Access);
583 pragma Assert (Result = 0);
586 procedure Finalize_Lock (L : not null access RTS_Lock) is
587 Result : Interfaces.C.int;
589 pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
590 Result := mutex_destroy (L.L'Access);
591 pragma Assert (Result = 0);
599 (L : not null access Lock;
600 Ceiling_Violation : out Boolean)
602 Result : Interfaces.C.int;
605 pragma Assert (Check_Lock (Lock_Ptr (L)));
607 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
609 Self_Id : constant Task_Id := Self;
610 Saved_Priority : System.Any_Priority;
613 if Self_Id.Common.LL.Active_Priority > L.Ceiling then
614 Ceiling_Violation := True;
618 Saved_Priority := Self_Id.Common.LL.Active_Priority;
620 if Self_Id.Common.LL.Active_Priority < L.Ceiling then
621 Set_Priority (Self_Id, L.Ceiling);
624 Result := mutex_lock (L.L'Access);
625 pragma Assert (Result = 0);
626 Ceiling_Violation := False;
628 L.Saved_Priority := Saved_Priority;
632 Result := mutex_lock (L.L'Access);
633 pragma Assert (Result = 0);
634 Ceiling_Violation := False;
637 pragma Assert (Record_Lock (Lock_Ptr (L)));
641 (L : not null access RTS_Lock;
642 Global_Lock : Boolean := False)
644 Result : Interfaces.C.int;
646 if not Single_Lock or else Global_Lock then
647 pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
648 Result := mutex_lock (L.L'Access);
649 pragma Assert (Result = 0);
650 pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
654 procedure Write_Lock (T : Task_Id) is
655 Result : Interfaces.C.int;
657 if not Single_Lock then
658 pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
659 Result := mutex_lock (T.Common.LL.L.L'Access);
660 pragma Assert (Result = 0);
661 pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
670 (L : not null access Lock;
671 Ceiling_Violation : out Boolean) is
673 Write_Lock (L, Ceiling_Violation);
680 procedure Unlock (L : not null access Lock) is
681 Result : Interfaces.C.int;
684 pragma Assert (Check_Unlock (Lock_Ptr (L)));
686 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
688 Self_Id : constant Task_Id := Self;
691 Result := mutex_unlock (L.L'Access);
692 pragma Assert (Result = 0);
694 if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
695 Set_Priority (Self_Id, L.Saved_Priority);
699 Result := mutex_unlock (L.L'Access);
700 pragma Assert (Result = 0);
705 (L : not null access RTS_Lock;
706 Global_Lock : Boolean := False)
708 Result : Interfaces.C.int;
710 if not Single_Lock or else Global_Lock then
711 pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
712 Result := mutex_unlock (L.L'Access);
713 pragma Assert (Result = 0);
717 procedure Unlock (T : Task_Id) is
718 Result : Interfaces.C.int;
720 if not Single_Lock then
721 pragma Assert (Check_Unlock (To_Lock_Ptr (T.Common.LL.L'Access)));
722 Result := mutex_unlock (T.Common.LL.L.L'Access);
723 pragma Assert (Result = 0);
731 -- Dynamic priority ceilings are not supported by the underlying system
733 procedure Set_Ceiling
734 (L : not null access Lock;
735 Prio : System.Any_Priority)
737 pragma Unreferenced (L, Prio);
742 -- For the time delay implementation, we need to make sure we
743 -- achieve following criteria:
745 -- 1) We have to delay at least for the amount requested.
746 -- 2) We have to give up CPU even though the actual delay does not
747 -- result in blocking.
748 -- 3) Except for restricted run-time systems that do not support
749 -- ATC or task abort, the delay must be interrupted by the
750 -- abort_task operation.
751 -- 4) The implementation has to be efficient so that the delay overhead
752 -- is relatively cheap.
753 -- (1)-(3) are Ada requirements. Even though (2) is an Annex-D
754 -- requirement we still want to provide the effect in all cases.
755 -- The reason is that users may want to use short delays to implement
756 -- their own scheduling effect in the absence of language provided
757 -- scheduling policies.
759 ---------------------
760 -- Monotonic_Clock --
761 ---------------------
763 function Monotonic_Clock return Duration is
764 TS : aliased timespec;
765 Result : Interfaces.C.int;
767 Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
768 pragma Assert (Result = 0);
769 return To_Duration (TS);
776 function RT_Resolution return Duration is
785 procedure Yield (Do_Yield : Boolean := True) is
788 System.OS_Interface.thr_yield;
796 function Self return Task_Id renames Specific.Self;
802 procedure Set_Priority
804 Prio : System.Any_Priority;
805 Loss_Of_Inheritance : Boolean := False)
807 pragma Unreferenced (Loss_Of_Inheritance);
809 Result : Interfaces.C.int;
810 pragma Unreferenced (Result);
812 Param : aliased struct_pcparms;
817 T.Common.Current_Priority := Prio;
819 if Priority_Ceiling_Emulation then
820 T.Common.LL.Active_Priority := Prio;
823 if Using_Real_Time_Class then
824 Param.pc_cid := Prio_Param.pc_cid;
825 Param.rt_pri := pri_t (Prio);
826 Param.rt_tqsecs := Prio_Param.rt_tqsecs;
827 Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
829 Result := Interfaces.C.int (
830 priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
834 if T.Common.Task_Info /= null
835 and then not T.Common.Task_Info.Bound_To_LWP
837 -- The task is not bound to a LWP, so use thr_setprio
840 thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
843 -- The task is bound to a LWP, use priocntl
855 function Get_Priority (T : Task_Id) return System.Any_Priority is
857 return T.Common.Current_Priority;
864 procedure Enter_Task (Self_ID : Task_Id) is
865 Result : Interfaces.C.int;
866 Proc : processorid_t; -- User processor #
867 Last_Proc : processorid_t; -- Last processor #
869 use System.Task_Info;
870 use type System.Multiprocessors.CPU_Range;
873 Self_ID.Common.LL.Thread := thr_self;
875 Self_ID.Common.LL.LWP := lwp_self;
879 if Self_ID.Common.Base_CPU /=
880 System.Multiprocessors.Not_A_Specific_CPU
882 -- The CPU numbering in pragma CPU starts at 1 while the subprogram
883 -- to set the affinity starts at 0, therefore we must subtract 1.
887 (P_LWPID, P_MYID, processorid_t (Self_ID.Common.Base_CPU) - 1,
889 pragma Assert (Result = 0);
893 elsif Self_ID.Common.Task_Info /= null then
894 if Self_ID.Common.Task_Info.New_LWP
895 and then Self_ID.Common.Task_Info.CPU /= CPU_UNCHANGED
897 Last_Proc := Num_Procs - 1;
899 if Self_ID.Common.Task_Info.CPU = ANY_CPU then
902 while Proc < Last_Proc loop
903 Result := p_online (Proc, PR_STATUS);
904 exit when Result = PR_ONLINE;
908 Result := processor_bind (P_LWPID, P_MYID, Proc, null);
909 pragma Assert (Result = 0);
912 -- Use specified processor
914 if Self_ID.Common.Task_Info.CPU < 0
915 or else Self_ID.Common.Task_Info.CPU > Last_Proc
917 raise Invalid_CPU_Number;
922 (P_LWPID, P_MYID, Self_ID.Common.Task_Info.CPU, null);
923 pragma Assert (Result = 0);
928 Specific.Set (Self_ID);
930 -- We need the above code even if we do direct fetch of Task_Id in Self
931 -- for the main task on Sun, x86 Solaris and for gcc 2.7.2.
938 function New_ATCB (Entry_Num : Task_Entry_Index) return Task_Id is
940 return new Ada_Task_Control_Block (Entry_Num);
947 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
949 -----------------------------
950 -- Register_Foreign_Thread --
951 -----------------------------
953 function Register_Foreign_Thread return Task_Id is
955 if Is_Valid_Task then
958 return Register_Foreign_Thread (thr_self);
960 end Register_Foreign_Thread;
966 procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
967 Result : Interfaces.C.int := 0;
970 -- Give the task a unique serial number
972 Self_ID.Serial_Number := Next_Serial_Number;
973 Next_Serial_Number := Next_Serial_Number + 1;
974 pragma Assert (Next_Serial_Number /= 0);
976 Self_ID.Common.LL.Thread := To_thread_t (-1);
978 if not Single_Lock then
981 (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
982 Self_ID.Common.LL.L.Level :=
983 Private_Task_Serial_Number (Self_ID.Serial_Number);
984 pragma Assert (Result = 0 or else Result = ENOMEM);
988 Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
989 pragma Assert (Result = 0 or else Result = ENOMEM);
995 if not Single_Lock then
996 Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
997 pragma Assert (Result = 0);
1008 procedure Create_Task
1010 Wrapper : System.Address;
1011 Stack_Size : System.Parameters.Size_Type;
1012 Priority : System.Any_Priority;
1013 Succeeded : out Boolean)
1015 pragma Unreferenced (Priority);
1017 Result : Interfaces.C.int;
1018 Adjusted_Stack_Size : Interfaces.C.size_t;
1019 Opts : Interfaces.C.int := THR_DETACHED;
1021 Page_Size : constant System.Parameters.Size_Type := 4096;
1022 -- This constant is for reserving extra space at the
1023 -- end of the stack, which can be used by the stack
1024 -- checking as guard page. The idea is that we need
1025 -- to have at least Stack_Size bytes available for
1028 use System.Task_Info;
1031 Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size + Page_Size);
1033 -- Since the initial signal mask of a thread is inherited from the
1034 -- creator, and the Environment task has all its signals masked, we
1035 -- do not need to manipulate caller's signal mask at this point.
1036 -- All tasks in RTS will have All_Tasks_Mask initially.
1038 if T.Common.Task_Info /= null then
1039 if T.Common.Task_Info.New_LWP then
1040 Opts := Opts + THR_NEW_LWP;
1043 if T.Common.Task_Info.Bound_To_LWP then
1044 Opts := Opts + THR_BOUND;
1048 Opts := THR_DETACHED + THR_BOUND;
1053 (System.Null_Address,
1054 Adjusted_Stack_Size,
1055 Thread_Body_Access (Wrapper),
1058 T.Common.LL.Thread'Access);
1060 Succeeded := Result = 0;
1063 or else Result = ENOMEM
1064 or else Result = EAGAIN);
1071 procedure Finalize_TCB (T : Task_Id) is
1072 Result : Interfaces.C.int;
1074 Is_Self : constant Boolean := T = Self;
1076 procedure Free is new
1077 Ada.Unchecked_Deallocation (Ada_Task_Control_Block, Task_Id);
1080 T.Common.LL.Thread := To_thread_t (0);
1082 if not Single_Lock then
1083 Result := mutex_destroy (T.Common.LL.L.L'Access);
1084 pragma Assert (Result = 0);
1087 Result := cond_destroy (T.Common.LL.CV'Access);
1088 pragma Assert (Result = 0);
1090 if T.Known_Tasks_Index /= -1 then
1091 Known_Tasks (T.Known_Tasks_Index) := null;
1097 Specific.Set (null);
1105 -- This procedure must be called with abort deferred. It can no longer
1106 -- call Self or access the current task's ATCB, since the ATCB has been
1109 procedure Exit_Task is
1111 Specific.Set (null);
1118 procedure Abort_Task (T : Task_Id) is
1119 Result : Interfaces.C.int;
1121 if Abort_Handler_Installed then
1122 pragma Assert (T /= Self);
1125 (T.Common.LL.Thread,
1126 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1127 pragma Assert (Result = 0);
1137 Reason : Task_States)
1139 Result : Interfaces.C.int;
1142 pragma Assert (Check_Sleep (Reason));
1147 (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1151 (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1155 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1156 pragma Assert (Result = 0 or else Result = EINTR);
1159 -- Note that we are relying heavily here on GNAT representing
1160 -- Calendar.Time, System.Real_Time.Time, Duration,
1161 -- System.Real_Time.Time_Span in the same way, i.e., as a 64-bit count of
1164 -- This allows us to always pass the timeout value as a Duration
1167 -- We are taking liberties here with the semantics of the delays. That is,
1168 -- we make no distinction between delays on the Calendar clock and delays
1169 -- on the Real_Time clock. That is technically incorrect, if the Calendar
1170 -- clock happens to be reset or adjusted. To solve this defect will require
1171 -- modification to the compiler interface, so that it can pass through more
1172 -- information, to tell us here which clock to use!
1174 -- cond_timedwait will return if any of the following happens:
1175 -- 1) some other task did cond_signal on this condition variable
1176 -- In this case, the return value is 0
1177 -- 2) the call just returned, for no good reason
1178 -- This is called a "spurious wakeup".
1179 -- In this case, the return value may also be 0.
1180 -- 3) the time delay expires
1181 -- In this case, the return value is ETIME
1182 -- 4) this task received a signal, which was handled by some
1183 -- handler procedure, and now the thread is resuming execution
1184 -- UNIX calls this an "interrupted" system call.
1185 -- In this case, the return value is EINTR
1187 -- If the cond_timedwait returns 0 or EINTR, it is still possible that the
1188 -- time has actually expired, and by chance a signal or cond_signal
1189 -- occurred at around the same time.
1191 -- We have also observed that on some OS's the value ETIME will be
1192 -- returned, but the clock will show that the full delay has not yet
1195 -- For these reasons, we need to check the clock after return from
1196 -- cond_timedwait. If the time has expired, we will set Timedout = True.
1198 -- This check might be omitted for systems on which the cond_timedwait()
1199 -- never returns early or wakes up spuriously.
1201 -- Annex D requires that completion of a delay cause the task to go to the
1202 -- end of its priority queue, regardless of whether the task actually was
1203 -- suspended by the delay. Since cond_timedwait does not do this on
1204 -- Solaris, we add a call to thr_yield at the end. We might do this at the
1205 -- beginning, instead, but then the round-robin effect would not be the
1206 -- same; the delayed task would be ahead of other tasks of the same
1207 -- priority that awoke while it was sleeping.
1209 -- For Timed_Sleep, we are expecting possible cond_signals to indicate
1210 -- other events (e.g., completion of a RV or completion of the abortable
1211 -- part of an async. select), we want to always return if interrupted. The
1212 -- caller will be responsible for checking the task state to see whether
1213 -- the wakeup was spurious, and to go back to sleep again in that case. We
1214 -- don't need to check for pending abort or priority change on the way in
1215 -- our out; that is the caller's responsibility.
1217 -- For Timed_Delay, we are not expecting any cond_signals or other
1218 -- interruptions, except for priority changes and aborts. Therefore, we
1219 -- don't want to return unless the delay has actually expired, or the call
1220 -- has been aborted. In this case, since we want to implement the entire
1221 -- delay statement semantics, we do need to check for pending abort and
1222 -- priority changes. We can quietly handle priority changes inside the
1223 -- procedure, since there is no entry-queue reordering involved.
1229 procedure Timed_Sleep
1232 Mode : ST.Delay_Modes;
1233 Reason : System.Tasking.Task_States;
1234 Timedout : out Boolean;
1235 Yielded : out Boolean)
1237 Base_Time : constant Duration := Monotonic_Clock;
1238 Check_Time : Duration := Base_Time;
1239 Abs_Time : Duration;
1240 Request : aliased timespec;
1241 Result : Interfaces.C.int;
1244 pragma Assert (Check_Sleep (Reason));
1250 then Duration'Min (Time, Max_Sensible_Delay) + Check_Time
1251 else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
1253 if Abs_Time > Check_Time then
1254 Request := To_Timespec (Abs_Time);
1256 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1261 (Self_ID.Common.LL.CV'Access,
1262 Single_RTS_Lock.L'Access, Request'Access);
1266 (Self_ID.Common.LL.CV'Access,
1267 Self_ID.Common.LL.L.L'Access, Request'Access);
1272 Check_Time := Monotonic_Clock;
1273 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1275 if Result = 0 or Result = EINTR then
1277 -- Somebody may have called Wakeup for us
1283 pragma Assert (Result = ETIME);
1288 (Record_Wakeup (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1295 procedure Timed_Delay
1298 Mode : ST.Delay_Modes)
1300 Base_Time : constant Duration := Monotonic_Clock;
1301 Check_Time : Duration := Base_Time;
1302 Abs_Time : Duration;
1303 Request : aliased timespec;
1304 Result : Interfaces.C.int;
1305 Yielded : Boolean := False;
1312 Write_Lock (Self_ID);
1316 then Time + Check_Time
1317 else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
1319 if Abs_Time > Check_Time then
1320 Request := To_Timespec (Abs_Time);
1321 Self_ID.Common.State := Delay_Sleep;
1323 pragma Assert (Check_Sleep (Delay_Sleep));
1326 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1331 (Self_ID.Common.LL.CV'Access,
1332 Single_RTS_Lock.L'Access,
1337 (Self_ID.Common.LL.CV'Access,
1338 Self_ID.Common.LL.L.L'Access,
1344 Check_Time := Monotonic_Clock;
1345 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
1349 Result = ETIME or else
1355 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1357 Self_ID.Common.State := Runnable;
1377 Reason : Task_States)
1379 Result : Interfaces.C.int;
1381 pragma Assert (Check_Wakeup (T, Reason));
1382 Result := cond_signal (T.Common.LL.CV'Access);
1383 pragma Assert (Result = 0);
1386 ---------------------------
1387 -- Check_Initialize_Lock --
1388 ---------------------------
1390 -- The following code is intended to check some of the invariant assertions
1391 -- related to lock usage, on which we depend.
1393 function Check_Initialize_Lock
1395 Level : Lock_Level) return Boolean
1397 Self_ID : constant Task_Id := Self;
1400 -- Check that caller is abort-deferred
1402 if Self_ID.Deferral_Level = 0 then
1406 -- Check that the lock is not yet initialized
1408 if L.Level /= 0 then
1412 L.Level := Lock_Level'Pos (Level) + 1;
1414 end Check_Initialize_Lock;
1420 function Check_Lock (L : Lock_Ptr) return Boolean is
1421 Self_ID : constant Task_Id := Self;
1425 -- Check that the argument is not null
1431 -- Check that L is not frozen
1437 -- Check that caller is abort-deferred
1439 if Self_ID.Deferral_Level = 0 then
1443 -- Check that caller is not holding this lock already
1445 if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1453 -- Check that TCB lock order rules are satisfied
1455 P := Self_ID.Common.LL.Locks;
1457 if P.Level >= L.Level
1458 and then (P.Level > 2 or else L.Level > 2)
1471 function Record_Lock (L : Lock_Ptr) return Boolean is
1472 Self_ID : constant Task_Id := Self;
1476 Lock_Count := Lock_Count + 1;
1478 -- There should be no owner for this lock at this point
1480 if L.Owner /= null then
1486 L.Owner := To_Owner_ID (To_Address (Self_ID));
1492 -- Check that TCB lock order rules are satisfied
1494 P := Self_ID.Common.LL.Locks;
1500 Self_ID.Common.LL.Locking := null;
1501 Self_ID.Common.LL.Locks := L;
1509 function Check_Sleep (Reason : Task_States) return Boolean is
1510 pragma Unreferenced (Reason);
1512 Self_ID : constant Task_Id := Self;
1516 -- Check that caller is abort-deferred
1518 if Self_ID.Deferral_Level = 0 then
1526 -- Check that caller is holding own lock, on top of list
1528 if Self_ID.Common.LL.Locks /=
1529 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1534 -- Check that TCB lock order rules are satisfied
1536 if Self_ID.Common.LL.Locks.Next /= null then
1540 Self_ID.Common.LL.L.Owner := null;
1541 P := Self_ID.Common.LL.Locks;
1542 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1551 function Record_Wakeup
1553 Reason : Task_States) return Boolean
1555 pragma Unreferenced (Reason);
1557 Self_ID : constant Task_Id := Self;
1563 L.Owner := To_Owner_ID (To_Address (Self_ID));
1569 -- Check that TCB lock order rules are satisfied
1571 P := Self_ID.Common.LL.Locks;
1577 Self_ID.Common.LL.Locking := null;
1578 Self_ID.Common.LL.Locks := L;
1586 function Check_Wakeup
1588 Reason : Task_States) return Boolean
1590 Self_ID : constant Task_Id := Self;
1593 -- Is caller holding T's lock?
1595 if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1599 -- Are reasons for wakeup and sleep consistent?
1601 if T.Common.State /= Reason then
1612 function Check_Unlock (L : Lock_Ptr) return Boolean is
1613 Self_ID : constant Task_Id := Self;
1617 Unlock_Count := Unlock_Count + 1;
1623 if L.Buddy /= null then
1627 -- Magic constant 4???
1630 Check_Count := Unlock_Count;
1633 -- Magic constant 1000???
1635 if Unlock_Count - Check_Count > 1000 then
1636 Check_Count := Unlock_Count;
1639 -- Check that caller is abort-deferred
1641 if Self_ID.Deferral_Level = 0 then
1645 -- Check that caller is holding this lock, on top of list
1647 if Self_ID.Common.LL.Locks /= L then
1651 -- Record there is no owner now
1654 P := Self_ID.Common.LL.Locks;
1655 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1660 --------------------
1661 -- Check_Finalize --
1662 --------------------
1664 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1665 Self_ID : constant Task_Id := Self;
1668 -- Check that caller is abort-deferred
1670 if Self_ID.Deferral_Level = 0 then
1674 -- Check that no one is holding this lock
1676 if L.Owner /= null then
1682 end Check_Finalize_Lock;
1688 procedure Initialize (S : in out Suspension_Object) is
1689 Result : Interfaces.C.int;
1692 -- Initialize internal state (always to zero (RM D.10(6)))
1697 -- Initialize internal mutex
1699 Result := mutex_init (S.L'Access, USYNC_THREAD, System.Null_Address);
1700 pragma Assert (Result = 0 or else Result = ENOMEM);
1702 if Result = ENOMEM then
1703 raise Storage_Error with "Failed to allocate a lock";
1706 -- Initialize internal condition variable
1708 Result := cond_init (S.CV'Access, USYNC_THREAD, 0);
1709 pragma Assert (Result = 0 or else Result = ENOMEM);
1712 Result := mutex_destroy (S.L'Access);
1713 pragma Assert (Result = 0);
1715 if Result = ENOMEM then
1716 raise Storage_Error;
1725 procedure Finalize (S : in out Suspension_Object) is
1726 Result : Interfaces.C.int;
1729 -- Destroy internal mutex
1731 Result := mutex_destroy (S.L'Access);
1732 pragma Assert (Result = 0);
1734 -- Destroy internal condition variable
1736 Result := cond_destroy (S.CV'Access);
1737 pragma Assert (Result = 0);
1744 function Current_State (S : Suspension_Object) return Boolean is
1746 -- We do not want to use lock on this read operation. State is marked
1747 -- as Atomic so that we ensure that the value retrieved is correct.
1756 procedure Set_False (S : in out Suspension_Object) is
1757 Result : Interfaces.C.int;
1760 SSL.Abort_Defer.all;
1762 Result := mutex_lock (S.L'Access);
1763 pragma Assert (Result = 0);
1767 Result := mutex_unlock (S.L'Access);
1768 pragma Assert (Result = 0);
1770 SSL.Abort_Undefer.all;
1777 procedure Set_True (S : in out Suspension_Object) is
1778 Result : Interfaces.C.int;
1781 SSL.Abort_Defer.all;
1783 Result := mutex_lock (S.L'Access);
1784 pragma Assert (Result = 0);
1786 -- If there is already a task waiting on this suspension object then
1787 -- we resume it, leaving the state of the suspension object to False,
1788 -- as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1789 -- the state to True.
1795 Result := cond_signal (S.CV'Access);
1796 pragma Assert (Result = 0);
1802 Result := mutex_unlock (S.L'Access);
1803 pragma Assert (Result = 0);
1805 SSL.Abort_Undefer.all;
1808 ------------------------
1809 -- Suspend_Until_True --
1810 ------------------------
1812 procedure Suspend_Until_True (S : in out Suspension_Object) is
1813 Result : Interfaces.C.int;
1816 SSL.Abort_Defer.all;
1818 Result := mutex_lock (S.L'Access);
1819 pragma Assert (Result = 0);
1823 -- Program_Error must be raised upon calling Suspend_Until_True
1824 -- if another task is already waiting on that suspension object
1827 Result := mutex_unlock (S.L'Access);
1828 pragma Assert (Result = 0);
1830 SSL.Abort_Undefer.all;
1832 raise Program_Error;
1835 -- Suspend the task if the state is False. Otherwise, the task
1836 -- continues its execution, and the state of the suspension object
1837 -- is set to False (ARM D.10 par. 9).
1845 -- Loop in case pthread_cond_wait returns earlier than expected
1846 -- (e.g. in case of EINTR caused by a signal).
1848 Result := cond_wait (S.CV'Access, S.L'Access);
1849 pragma Assert (Result = 0 or else Result = EINTR);
1851 exit when not S.Waiting;
1855 Result := mutex_unlock (S.L'Access);
1856 pragma Assert (Result = 0);
1858 SSL.Abort_Undefer.all;
1860 end Suspend_Until_True;
1866 function Check_Exit (Self_ID : Task_Id) return Boolean is
1868 -- Check that caller is just holding Global_Task_Lock and no other locks
1870 if Self_ID.Common.LL.Locks = null then
1874 -- 2 = Global_Task_Level
1876 if Self_ID.Common.LL.Locks.Level /= 2 then
1880 if Self_ID.Common.LL.Locks.Next /= null then
1884 -- Check that caller is abort-deferred
1886 if Self_ID.Deferral_Level = 0 then
1893 --------------------
1894 -- Check_No_Locks --
1895 --------------------
1897 function Check_No_Locks (Self_ID : Task_Id) return Boolean is
1899 return Self_ID.Common.LL.Locks = null;
1902 ----------------------
1903 -- Environment_Task --
1904 ----------------------
1906 function Environment_Task return Task_Id is
1908 return Environment_Task_Id;
1909 end Environment_Task;
1915 procedure Lock_RTS is
1917 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1924 procedure Unlock_RTS is
1926 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1933 function Suspend_Task
1935 Thread_Self : Thread_Id) return Boolean
1938 if T.Common.LL.Thread /= Thread_Self then
1939 return thr_suspend (T.Common.LL.Thread) = 0;
1949 function Resume_Task
1951 Thread_Self : Thread_Id) return Boolean
1954 if T.Common.LL.Thread /= Thread_Self then
1955 return thr_continue (T.Common.LL.Thread) = 0;
1961 --------------------
1962 -- Stop_All_Tasks --
1963 --------------------
1965 procedure Stop_All_Tasks is
1974 function Stop_Task (T : ST.Task_Id) return Boolean is
1975 pragma Unreferenced (T);
1984 function Continue_Task (T : ST.Task_Id) return Boolean is
1985 pragma Unreferenced (T);
1990 end System.Task_Primitives.Operations;