1 ------------------------------------------------------------------------------
3 -- GNU ADA 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-2004, Free Software Foundation, Inc. --
11 -- GNARL is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 2, or (at your option) any later ver- --
14 -- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNARL; see file COPYING. If not, write --
19 -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
20 -- MA 02111-1307, USA. --
22 -- As a special exception, if other files instantiate generics from this --
23 -- unit, or you link this unit with other files to produce an executable, --
24 -- this unit does not by itself cause the resulting executable to be --
25 -- covered by the GNU General Public License. This exception does not --
26 -- however invalidate any other reasons why the executable file might be --
27 -- covered by the GNU Public License. --
29 -- GNARL was developed by the GNARL team at Florida State University. --
30 -- Extensive contributions were provided by Ada Core Technologies, Inc. --
32 ------------------------------------------------------------------------------
34 -- This is a Solaris (native) version of this package
36 -- This package contains all the GNULL primitives that interface directly
37 -- with the underlying OS.
40 -- Turn off polling, we do not want ATC polling to take place during
41 -- tasking operations. It causes infinite loops and other problems.
43 with System.Tasking.Debug;
44 -- used for Known_Tasks
47 -- used for Raise_Exception
50 -- used for String_Access, Getenv
56 with System.Interrupt_Management;
57 -- used for Keep_Unmasked
58 -- Abort_Task_Interrupt
61 with System.Interrupt_Management.Operations;
62 -- used for Set_Interrupt_Mask
64 pragma Elaborate_All (System.Interrupt_Management.Operations);
66 with System.Parameters;
70 -- used for Ada_Task_Control_Block
72 -- ATCB components and types
74 with System.Task_Info;
75 -- to initialize Task_Info for a C thread, in function Self
77 with System.Soft_Links;
78 -- used for Defer/Undefer_Abort
79 -- to initialize TSD for a C thread, in function Self
81 -- Note that we do not use System.Tasking.Initialization directly since
82 -- this is a higher level package that we shouldn't depend on. For example
83 -- when using the restricted run time, it is replaced by
84 -- System.Tasking.Restricted.Initialization
86 with System.OS_Primitives;
87 -- used for Delay_Modes
89 with Unchecked_Deallocation;
91 package body System.Task_Primitives.Operations is
93 use System.Tasking.Debug;
96 use System.OS_Interface;
97 use System.Parameters;
99 use System.OS_Primitives;
101 package SSL renames System.Soft_Links;
107 -- The following are logically constants, but need to be initialized
110 Environment_Task_ID : Task_ID;
111 -- A variable to hold Task_ID for the environment task.
112 -- If we use this variable to get the Task_ID, we need the following
113 -- ATCB_Key only for non-Ada threads.
115 Unblocked_Signal_Mask : aliased sigset_t;
116 -- The set of signals that should unblocked in all tasks
118 ATCB_Key : aliased thread_key_t;
119 -- Key used to find the Ada Task_ID associated with a thread,
120 -- at least for C threads unknown to the Ada run-time system.
122 Single_RTS_Lock : aliased RTS_Lock;
123 -- This is a lock to allow only one thread of control in the RTS at
124 -- a time; it is used to execute in mutual exclusion from all other tasks.
125 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
127 Next_Serial_Number : Task_Serial_Number := 100;
128 -- We start at 100, to reserve some special values for
129 -- using in error checking.
130 -- The following are internal configuration constants needed.
132 ----------------------
133 -- Priority Support --
134 ----------------------
136 Priority_Ceiling_Emulation : constant Boolean := True;
137 -- controls whether we emulate priority ceiling locking
139 -- To get a scheduling close to annex D requirements, we use the real-time
140 -- class provided for LWP's and map each task/thread to a specific and
141 -- unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
143 -- The real time class can only be set when the process has root
144 -- priviledges, so in the other cases, we use the normal thread scheduling
145 -- and priority handling.
147 Using_Real_Time_Class : Boolean := False;
148 -- indicates wether the real time class is being used (i.e the process
149 -- has root priviledges).
151 Prio_Param : aliased struct_pcparms;
152 -- Hold priority info (Real_Time) initialized during the package
155 -----------------------------------
156 -- External Configuration Values --
157 -----------------------------------
159 Time_Slice_Val : Interfaces.C.long;
160 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
162 Locking_Policy : Character;
163 pragma Import (C, Locking_Policy, "__gl_locking_policy");
165 Dispatching_Policy : Character;
166 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
168 Foreign_Task_Elaborated : aliased Boolean := True;
169 -- Used to identified fake tasks (i.e., non-Ada Threads).
171 -----------------------
172 -- Local Subprograms --
173 -----------------------
175 function sysconf (name : System.OS_Interface.int) return processorid_t;
176 pragma Import (C, sysconf, "sysconf");
178 SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
181 (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
182 return processorid_t renames sysconf;
184 procedure Abort_Handler
186 Code : access siginfo_t;
187 Context : access ucontext_t);
188 -- Target-dependent binding of inter-thread Abort signal to
189 -- the raising of the Abort_Signal exception.
190 -- See also comments in 7staprop.adb
196 function Check_Initialize_Lock
198 Level : Lock_Level) return Boolean;
199 pragma Inline (Check_Initialize_Lock);
201 function Check_Lock (L : Lock_Ptr) return Boolean;
202 pragma Inline (Check_Lock);
204 function Record_Lock (L : Lock_Ptr) return Boolean;
205 pragma Inline (Record_Lock);
207 function Check_Sleep (Reason : Task_States) return Boolean;
208 pragma Inline (Check_Sleep);
210 function Record_Wakeup
212 Reason : Task_States) return Boolean;
213 pragma Inline (Record_Wakeup);
215 function Check_Wakeup
217 Reason : Task_States) return Boolean;
218 pragma Inline (Check_Wakeup);
220 function Check_Unlock (L : Lock_Ptr) return Boolean;
221 pragma Inline (Check_Unlock);
223 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
224 pragma Inline (Check_Finalize_Lock);
232 procedure Initialize (Environment_Task : Task_ID);
233 pragma Inline (Initialize);
234 -- Initialize various data needed by this package.
236 function Is_Valid_Task return Boolean;
237 pragma Inline (Is_Valid_Task);
238 -- Does executing thread have a TCB?
240 procedure Set (Self_Id : Task_ID);
242 -- Set the self id for the current task.
244 function Self return Task_ID;
245 pragma Inline (Self);
246 -- Return a pointer to the Ada Task Control Block of the calling task.
250 package body Specific is separate;
251 -- The body of this package is target specific.
253 ---------------------------------
254 -- Support for foreign threads --
255 ---------------------------------
257 function Register_Foreign_Thread (Thread : Thread_Id) return Task_ID;
258 -- Allocate and Initialize a new ATCB for the current Thread.
260 function Register_Foreign_Thread
261 (Thread : Thread_Id) return Task_ID is separate;
267 Check_Count : Integer := 0;
268 Lock_Count : Integer := 0;
269 Unlock_Count : Integer := 0;
275 procedure Abort_Handler
277 Code : access siginfo_t;
278 Context : access ucontext_t)
280 pragma Unreferenced (Sig);
281 pragma Unreferenced (Code);
282 pragma Unreferenced (Context);
284 Self_ID : constant Task_ID := Self;
285 Old_Set : aliased sigset_t;
287 Result : Interfaces.C.int;
288 pragma Unreferenced (Result);
291 -- It is not safe to raise an exception when using ZCX and the GCC
292 -- exception handling mechanism.
294 if ZCX_By_Default and then GCC_ZCX_Support then
298 if Self_ID.Deferral_Level = 0
299 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
300 and then not Self_ID.Aborting
302 Self_ID.Aborting := True;
304 -- Make sure signals used for RTS internal purpose are unmasked
306 Result := thr_sigsetmask (SIG_UNBLOCK,
307 Unblocked_Signal_Mask'Unchecked_Access, Old_Set'Unchecked_Access);
308 pragma Assert (Result = 0);
310 raise Standard'Abort_Signal;
318 -- The underlying thread system sets a guard page at the
319 -- bottom of a thread stack, so nothing is needed.
321 procedure Stack_Guard (T : ST.Task_ID; On : Boolean) is
322 pragma Unreferenced (T);
323 pragma Unreferenced (On);
333 function Get_Thread_Id (T : ST.Task_ID) return OSI.Thread_Id is
335 return T.Common.LL.Thread;
342 procedure Initialize (Environment_Task : ST.Task_ID) is
343 act : aliased struct_sigaction;
344 old_act : aliased struct_sigaction;
345 Tmp_Set : aliased sigset_t;
346 Result : Interfaces.C.int;
348 procedure Configure_Processors;
349 -- Processors configuration
350 -- The user can specify a processor which the program should run
351 -- on to emulate a single-processor system. This can be easily
352 -- done by setting environment variable GNAT_PROCESSOR to one of
355 -- -2 : use the default configuration (run the program on all
356 -- available processors) - this is the same as having
357 -- GNAT_PROCESSOR unset
358 -- -1 : let the RTS choose one processor and run the program on
360 -- 0 .. Last_Proc : run the program on the specified processor
362 -- Last_Proc is equal to the value of the system variable
363 -- _SC_NPROCESSORS_CONF, minus one.
365 procedure Configure_Processors is
366 Proc_Acc : constant GNAT.OS_Lib.String_Access :=
367 GNAT.OS_Lib.Getenv ("GNAT_PROCESSOR");
368 Proc : aliased processorid_t; -- User processor #
369 Last_Proc : processorid_t; -- Last processor #
372 if Proc_Acc.all'Length /= 0 then
373 -- Environment variable is defined
375 Last_Proc := Num_Procs - 1;
377 if Last_Proc /= -1 then
378 Proc := processorid_t'Value (Proc_Acc.all);
380 if Proc <= -2 or else Proc > Last_Proc then
381 -- Use the default configuration
384 -- Choose a processor
388 while Proc < Last_Proc loop
390 Result := p_online (Proc, PR_STATUS);
391 exit when Result = PR_ONLINE;
394 pragma Assert (Result = PR_ONLINE);
395 Result := processor_bind (P_PID, P_MYID, Proc, null);
396 pragma Assert (Result = 0);
399 -- Use user processor
401 Result := processor_bind (P_PID, P_MYID, Proc, null);
402 pragma Assert (Result = 0);
408 when Constraint_Error =>
410 -- Illegal environment variable GNAT_PROCESSOR - ignored
413 end Configure_Processors;
415 function State (Int : System.Interrupt_Management.Interrupt_ID)
417 pragma Import (C, State, "__gnat_get_interrupt_state");
418 -- Get interrupt state. Defined in a-init.c
419 -- The input argument is the interrupt number,
420 -- and the result is one of the following:
422 Default : constant Character := 's';
423 -- 'n' this interrupt not set by any Interrupt_State pragma
424 -- 'u' Interrupt_State pragma set state to User
425 -- 'r' Interrupt_State pragma set state to Runtime
426 -- 's' Interrupt_State pragma set state to System (use "default"
429 -- Start of processing for Initialize
432 Environment_Task_ID := Environment_Task;
434 -- This is done in Enter_Task, but this is too late for the
435 -- Environment Task, since we need to call Self in Check_Locks when
436 -- the run time is compiled with assertions on.
438 Specific.Initialize (Environment_Task);
440 -- Initialize the lock used to synchronize chain of all ATCBs.
442 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
444 Enter_Task (Environment_Task);
446 -- Install the abort-signal handler
448 if State (System.Interrupt_Management.Abort_Task_Interrupt)
451 -- Set sa_flags to SA_NODEFER so that during the handler execution
452 -- we do not change the Signal_Mask to be masked for the Abort_Signal
453 -- This is a temporary fix to the problem that the Signal_Mask is
454 -- not restored after the exception (longjmp) from the handler.
455 -- The right fix should be made in sigsetjmp so that we save
456 -- the Signal_Set and restore it after a longjmp.
457 -- In that case, this field should be changed back to 0. ???
461 act.sa_handler := Abort_Handler'Address;
462 Result := sigemptyset (Tmp_Set'Access);
463 pragma Assert (Result = 0);
464 act.sa_mask := Tmp_Set;
468 Signal (System.Interrupt_Management.Abort_Task_Interrupt),
469 act'Unchecked_Access,
470 old_act'Unchecked_Access);
471 pragma Assert (Result = 0);
474 Configure_Processors;
477 ---------------------
478 -- Initialize_Lock --
479 ---------------------
481 -- Note: mutexes and cond_variables needed per-task basis are
482 -- initialized in Initialize_TCB and the Storage_Error is
483 -- handled. Other mutexes (such as RTS_Lock, Memory_Lock...)
484 -- used in RTS is initialized before any status change of RTS.
485 -- Therefore rasing Storage_Error in the following routines
486 -- should be able to be handled safely.
488 procedure Initialize_Lock
489 (Prio : System.Any_Priority;
492 Result : Interfaces.C.int;
495 pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
497 if Priority_Ceiling_Emulation then
501 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
502 pragma Assert (Result = 0 or else Result = ENOMEM);
504 if Result = ENOMEM then
505 Raise_Exception (Storage_Error'Identity, "Failed to allocate a lock");
509 procedure Initialize_Lock
510 (L : access RTS_Lock;
513 Result : Interfaces.C.int;
516 pragma Assert (Check_Initialize_Lock
517 (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
518 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
519 pragma Assert (Result = 0 or else Result = ENOMEM);
521 if Result = ENOMEM then
522 Raise_Exception (Storage_Error'Identity, "Failed to allocate a lock");
530 procedure Finalize_Lock (L : access Lock) is
531 Result : Interfaces.C.int;
534 pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
535 Result := mutex_destroy (L.L'Access);
536 pragma Assert (Result = 0);
539 procedure Finalize_Lock (L : access RTS_Lock) is
540 Result : Interfaces.C.int;
543 pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
544 Result := mutex_destroy (L.L'Access);
545 pragma Assert (Result = 0);
552 procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
553 Result : Interfaces.C.int;
556 pragma Assert (Check_Lock (Lock_Ptr (L)));
558 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
560 Self_Id : constant Task_ID := Self;
561 Saved_Priority : System.Any_Priority;
564 if Self_Id.Common.LL.Active_Priority > L.Ceiling then
565 Ceiling_Violation := True;
569 Saved_Priority := Self_Id.Common.LL.Active_Priority;
571 if Self_Id.Common.LL.Active_Priority < L.Ceiling then
572 Set_Priority (Self_Id, L.Ceiling);
575 Result := mutex_lock (L.L'Access);
576 pragma Assert (Result = 0);
577 Ceiling_Violation := False;
579 L.Saved_Priority := Saved_Priority;
583 Result := mutex_lock (L.L'Access);
584 pragma Assert (Result = 0);
585 Ceiling_Violation := False;
588 pragma Assert (Record_Lock (Lock_Ptr (L)));
592 (L : access RTS_Lock;
593 Global_Lock : Boolean := False)
595 Result : Interfaces.C.int;
598 if not Single_Lock or else Global_Lock then
599 pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
600 Result := mutex_lock (L.L'Access);
601 pragma Assert (Result = 0);
602 pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
606 procedure Write_Lock (T : Task_ID) is
607 Result : Interfaces.C.int;
610 if not Single_Lock then
611 pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
612 Result := mutex_lock (T.Common.LL.L.L'Access);
613 pragma Assert (Result = 0);
614 pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
622 procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
624 Write_Lock (L, Ceiling_Violation);
631 procedure Unlock (L : access Lock) is
632 Result : Interfaces.C.int;
635 pragma Assert (Check_Unlock (Lock_Ptr (L)));
637 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
639 Self_Id : constant Task_ID := Self;
642 Result := mutex_unlock (L.L'Access);
643 pragma Assert (Result = 0);
645 if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
646 Set_Priority (Self_Id, L.Saved_Priority);
650 Result := mutex_unlock (L.L'Access);
651 pragma Assert (Result = 0);
655 procedure Unlock (L : access RTS_Lock; Global_Lock : Boolean := False) is
656 Result : Interfaces.C.int;
659 if not Single_Lock or else Global_Lock then
660 pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
661 Result := mutex_unlock (L.L'Access);
662 pragma Assert (Result = 0);
666 procedure Unlock (T : Task_ID) is
667 Result : Interfaces.C.int;
670 if not Single_Lock then
671 pragma Assert (Check_Unlock (To_Lock_Ptr (T.Common.LL.L'Access)));
672 Result := mutex_unlock (T.Common.LL.L.L'Access);
673 pragma Assert (Result = 0);
677 -- For the time delay implementation, we need to make sure we
678 -- achieve following criteria:
680 -- 1) We have to delay at least for the amount requested.
681 -- 2) We have to give up CPU even though the actual delay does not
682 -- result in blocking.
683 -- 3) Except for restricted run-time systems that do not support
684 -- ATC or task abort, the delay must be interrupted by the
685 -- abort_task operation.
686 -- 4) The implementation has to be efficient so that the delay overhead
687 -- is relatively cheap.
688 -- (1)-(3) are Ada requirements. Even though (2) is an Annex-D
689 -- requirement we still want to provide the effect in all cases.
690 -- The reason is that users may want to use short delays to implement
691 -- their own scheduling effect in the absence of language provided
692 -- scheduling policies.
694 ---------------------
695 -- Monotonic_Clock --
696 ---------------------
698 function Monotonic_Clock return Duration is
699 TS : aliased timespec;
700 Result : Interfaces.C.int;
703 Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
704 pragma Assert (Result = 0);
705 return To_Duration (TS);
712 function RT_Resolution return Duration is
721 procedure Yield (Do_Yield : Boolean := True) is
724 System.OS_Interface.thr_yield;
732 function Self return Task_ID renames Specific.Self;
738 procedure Set_Priority
740 Prio : System.Any_Priority;
741 Loss_Of_Inheritance : Boolean := False)
743 pragma Unreferenced (Loss_Of_Inheritance);
745 Result : Interfaces.C.int;
746 pragma Unreferenced (Result);
748 Param : aliased struct_pcparms;
753 T.Common.Current_Priority := Prio;
755 if Priority_Ceiling_Emulation then
756 T.Common.LL.Active_Priority := Prio;
759 if Using_Real_Time_Class then
760 Param.pc_cid := Prio_Param.pc_cid;
761 Param.rt_pri := pri_t (Prio);
762 Param.rt_tqsecs := Prio_Param.rt_tqsecs;
763 Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
765 Result := Interfaces.C.int (
766 priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
770 if T.Common.Task_Info /= null
771 and then not T.Common.Task_Info.Bound_To_LWP
773 -- The task is not bound to a LWP, so use thr_setprio
776 thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
780 -- The task is bound to a LWP, use priocntl
792 function Get_Priority (T : Task_ID) return System.Any_Priority is
794 return T.Common.Current_Priority;
801 procedure Enter_Task (Self_ID : Task_ID) is
802 Result : Interfaces.C.int;
803 Proc : processorid_t; -- User processor #
804 Last_Proc : processorid_t; -- Last processor #
806 use System.Task_Info;
808 Self_ID.Common.LL.Thread := thr_self;
810 Self_ID.Common.LL.LWP := lwp_self;
812 if Self_ID.Common.Task_Info /= null then
813 if Self_ID.Common.Task_Info.New_LWP
814 and then Self_ID.Common.Task_Info.CPU /= CPU_UNCHANGED
816 Last_Proc := Num_Procs - 1;
818 if Self_ID.Common.Task_Info.CPU = ANY_CPU then
822 while Proc < Last_Proc loop
823 Result := p_online (Proc, PR_STATUS);
824 exit when Result = PR_ONLINE;
828 Result := processor_bind (P_LWPID, P_MYID, Proc, null);
829 pragma Assert (Result = 0);
832 -- Use specified processor
834 if Self_ID.Common.Task_Info.CPU < 0
835 or else Self_ID.Common.Task_Info.CPU > Last_Proc
837 raise Invalid_CPU_Number;
840 Result := processor_bind
841 (P_LWPID, P_MYID, Self_ID.Common.Task_Info.CPU, null);
842 pragma Assert (Result = 0);
847 Specific.Set (Self_ID);
849 -- We need the above code even if we do direct fetch of Task_ID in Self
850 -- for the main task on Sun, x86 Solaris and for gcc 2.7.2.
854 for J in Known_Tasks'Range loop
855 if Known_Tasks (J) = null then
856 Known_Tasks (J) := Self_ID;
857 Self_ID.Known_Tasks_Index := J;
869 function New_ATCB (Entry_Num : Task_Entry_Index) return Task_ID is
871 return new Ada_Task_Control_Block (Entry_Num);
878 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
880 -----------------------------
881 -- Register_Foreign_Thread --
882 -----------------------------
884 function Register_Foreign_Thread return Task_ID is
886 if Is_Valid_Task then
889 return Register_Foreign_Thread (thr_self);
891 end Register_Foreign_Thread;
897 procedure Initialize_TCB (Self_ID : Task_ID; Succeeded : out Boolean) is
898 Result : Interfaces.C.int := 0;
901 -- Give the task a unique serial number.
903 Self_ID.Serial_Number := Next_Serial_Number;
904 Next_Serial_Number := Next_Serial_Number + 1;
905 pragma Assert (Next_Serial_Number /= 0);
907 Self_ID.Common.LL.Thread := To_thread_t (-1);
909 if not Single_Lock then
911 (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
912 Self_ID.Common.LL.L.Level :=
913 Private_Task_Serial_Number (Self_ID.Serial_Number);
914 pragma Assert (Result = 0 or else Result = ENOMEM);
918 Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
919 pragma Assert (Result = 0 or else Result = ENOMEM);
925 if not Single_Lock then
926 Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
927 pragma Assert (Result = 0);
938 procedure Create_Task
940 Wrapper : System.Address;
941 Stack_Size : System.Parameters.Size_Type;
942 Priority : System.Any_Priority;
943 Succeeded : out Boolean)
945 pragma Unreferenced (Priority);
947 Result : Interfaces.C.int;
948 Adjusted_Stack_Size : Interfaces.C.size_t;
949 Opts : Interfaces.C.int := THR_DETACHED;
951 Page_Size : constant System.Parameters.Size_Type := 4096;
952 -- This constant is for reserving extra space at the
953 -- end of the stack, which can be used by the stack
954 -- checking as guard page. The idea is that we need
955 -- to have at least Stack_Size bytes available for
958 use System.Task_Info;
961 if Stack_Size = System.Parameters.Unspecified_Size then
962 Adjusted_Stack_Size :=
963 Interfaces.C.size_t (Default_Stack_Size + Page_Size);
965 elsif Stack_Size < Minimum_Stack_Size then
966 Adjusted_Stack_Size :=
967 Interfaces.C.size_t (Minimum_Stack_Size + Page_Size);
970 Adjusted_Stack_Size :=
971 Interfaces.C.size_t (Stack_Size + Page_Size);
974 -- Since the initial signal mask of a thread is inherited from the
975 -- creator, and the Environment task has all its signals masked, we
976 -- do not need to manipulate caller's signal mask at this point.
977 -- All tasks in RTS will have All_Tasks_Mask initially.
979 if T.Common.Task_Info /= null then
980 if T.Common.Task_Info.New_LWP then
981 Opts := Opts + THR_NEW_LWP;
984 if T.Common.Task_Info.Bound_To_LWP then
985 Opts := Opts + THR_BOUND;
989 Opts := THR_DETACHED + THR_BOUND;
993 (System.Null_Address,
995 Thread_Body_Access (Wrapper),
998 T.Common.LL.Thread'Access);
1000 Succeeded := Result = 0;
1003 or else Result = ENOMEM
1004 or else Result = EAGAIN);
1011 procedure Finalize_TCB (T : Task_ID) is
1012 Result : Interfaces.C.int;
1014 Is_Self : constant Boolean := T = Self;
1016 procedure Free is new
1017 Unchecked_Deallocation (Ada_Task_Control_Block, Task_ID);
1020 T.Common.LL.Thread := To_thread_t (0);
1022 if not Single_Lock then
1023 Result := mutex_destroy (T.Common.LL.L.L'Access);
1024 pragma Assert (Result = 0);
1027 Result := cond_destroy (T.Common.LL.CV'Access);
1028 pragma Assert (Result = 0);
1030 if T.Known_Tasks_Index /= -1 then
1031 Known_Tasks (T.Known_Tasks_Index) := null;
1037 Specific.Set (null);
1045 -- This procedure must be called with abort deferred.
1046 -- It can no longer call Self or access
1047 -- the current task's ATCB, since the ATCB has been deallocated.
1049 procedure Exit_Task is
1051 Specific.Set (null);
1058 procedure Abort_Task (T : Task_ID) is
1059 Result : Interfaces.C.int;
1061 pragma Assert (T /= Self);
1063 Result := thr_kill (T.Common.LL.Thread,
1064 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1067 pragma Assert (Result = 0);
1076 Reason : Task_States)
1078 Result : Interfaces.C.int;
1081 pragma Assert (Check_Sleep (Reason));
1083 if Dynamic_Priority_Support
1084 and then Self_ID.Pending_Priority_Change
1086 Self_ID.Pending_Priority_Change := False;
1087 Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1088 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1093 (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1096 (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1099 pragma Assert (Record_Wakeup
1100 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1101 pragma Assert (Result = 0 or else Result = EINTR);
1104 -- Note that we are relying heaviliy here on the GNAT feature
1105 -- that Calendar.Time, System.Real_Time.Time, Duration, and
1106 -- System.Real_Time.Time_Span are all represented in the same
1107 -- way, i.e., as a 64-bit count of nanoseconds.
1109 -- This allows us to always pass the timeout value as a Duration.
1112 -- We are taking liberties here with the semantics of the delays.
1113 -- That is, we make no distinction between delays on the Calendar clock
1114 -- and delays on the Real_Time clock. That is technically incorrect, if
1115 -- the Calendar clock happens to be reset or adjusted.
1116 -- To solve this defect will require modification to the compiler
1117 -- interface, so that it can pass through more information, to tell
1118 -- us here which clock to use!
1120 -- cond_timedwait will return if any of the following happens:
1121 -- 1) some other task did cond_signal on this condition variable
1122 -- In this case, the return value is 0
1123 -- 2) the call just returned, for no good reason
1124 -- This is called a "spurious wakeup".
1125 -- In this case, the return value may also be 0.
1126 -- 3) the time delay expires
1127 -- In this case, the return value is ETIME
1128 -- 4) this task received a signal, which was handled by some
1129 -- handler procedure, and now the thread is resuming execution
1130 -- UNIX calls this an "interrupted" system call.
1131 -- In this case, the return value is EINTR
1133 -- If the cond_timedwait returns 0 or EINTR, it is still
1134 -- possible that the time has actually expired, and by chance
1135 -- a signal or cond_signal occurred at around the same time.
1137 -- We have also observed that on some OS's the value ETIME
1138 -- will be returned, but the clock will show that the full delay
1139 -- has not yet expired.
1141 -- For these reasons, we need to check the clock after return
1142 -- from cond_timedwait. If the time has expired, we will set
1145 -- This check might be omitted for systems on which the
1146 -- cond_timedwait() never returns early or wakes up spuriously.
1148 -- Annex D requires that completion of a delay cause the task
1149 -- to go to the end of its priority queue, regardless of whether
1150 -- the task actually was suspended by the delay. Since
1151 -- cond_timedwait does not do this on Solaris, we add a call
1152 -- to thr_yield at the end. We might do this at the beginning,
1153 -- instead, but then the round-robin effect would not be the
1154 -- same; the delayed task would be ahead of other tasks of the
1155 -- same priority that awoke while it was sleeping.
1157 -- For Timed_Sleep, we are expecting possible cond_signals
1158 -- to indicate other events (e.g., completion of a RV or
1159 -- completion of the abortable part of an async. select),
1160 -- we want to always return if interrupted. The caller will
1161 -- be responsible for checking the task state to see whether
1162 -- the wakeup was spurious, and to go back to sleep again
1163 -- in that case. We don't need to check for pending abort
1164 -- or priority change on the way in our out; that is the
1165 -- caller's responsibility.
1167 -- For Timed_Delay, we are not expecting any cond_signals or
1168 -- other interruptions, except for priority changes and aborts.
1169 -- Therefore, we don't want to return unless the delay has
1170 -- actually expired, or the call has been aborted. In this
1171 -- case, since we want to implement the entire delay statement
1172 -- semantics, we do need to check for pending abort and priority
1173 -- changes. We can quietly handle priority changes inside the
1174 -- procedure, since there is no entry-queue reordering involved.
1180 procedure Timed_Sleep
1183 Mode : ST.Delay_Modes;
1184 Reason : System.Tasking.Task_States;
1185 Timedout : out Boolean;
1186 Yielded : out Boolean)
1188 Check_Time : constant Duration := Monotonic_Clock;
1189 Abs_Time : Duration;
1190 Request : aliased timespec;
1191 Result : Interfaces.C.int;
1194 pragma Assert (Check_Sleep (Reason));
1198 if Mode = Relative then
1199 Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
1201 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1204 if Abs_Time > Check_Time then
1205 Request := To_Timespec (Abs_Time);
1208 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
1209 or else (Dynamic_Priority_Support and then
1210 Self_ID.Pending_Priority_Change);
1213 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1214 Single_RTS_Lock.L'Access, Request'Access);
1216 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1217 Self_ID.Common.LL.L.L'Access, Request'Access);
1222 exit when Abs_Time <= Monotonic_Clock;
1224 if Result = 0 or Result = EINTR then
1226 -- Somebody may have called Wakeup for us
1232 pragma Assert (Result = ETIME);
1236 pragma Assert (Record_Wakeup
1237 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1244 procedure Timed_Delay
1247 Mode : ST.Delay_Modes)
1249 Check_Time : constant Duration := Monotonic_Clock;
1250 Abs_Time : Duration;
1251 Request : aliased timespec;
1252 Result : Interfaces.C.int;
1253 Yielded : Boolean := False;
1256 -- Only the little window between deferring abort and
1257 -- locking Self_ID is the reason we need to
1258 -- check for pending abort and priority change below!
1260 SSL.Abort_Defer.all;
1266 Write_Lock (Self_ID);
1268 if Mode = Relative then
1269 Abs_Time := Time + Check_Time;
1271 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1274 if Abs_Time > Check_Time then
1275 Request := To_Timespec (Abs_Time);
1276 Self_ID.Common.State := Delay_Sleep;
1278 pragma Assert (Check_Sleep (Delay_Sleep));
1281 if Dynamic_Priority_Support and then
1282 Self_ID.Pending_Priority_Change then
1283 Self_ID.Pending_Priority_Change := False;
1284 Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1285 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1288 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1291 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1292 Single_RTS_Lock.L'Access, Request'Access);
1294 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1295 Self_ID.Common.LL.L.L'Access, Request'Access);
1300 exit when Abs_Time <= Monotonic_Clock;
1302 pragma Assert (Result = 0 or else
1303 Result = ETIME or else
1307 pragma Assert (Record_Wakeup
1308 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1310 Self_ID.Common.State := Runnable;
1323 SSL.Abort_Undefer.all;
1332 Reason : Task_States)
1334 Result : Interfaces.C.int;
1337 pragma Assert (Check_Wakeup (T, Reason));
1338 Result := cond_signal (T.Common.LL.CV'Access);
1339 pragma Assert (Result = 0);
1342 ---------------------------
1343 -- Check_Initialize_Lock --
1344 ---------------------------
1346 -- The following code is intended to check some of the invariant
1347 -- assertions related to lock usage, on which we depend.
1349 function Check_Initialize_Lock
1351 Level : Lock_Level) return Boolean
1353 Self_ID : constant Task_ID := Self;
1356 -- Check that caller is abort-deferred
1358 if Self_ID.Deferral_Level <= 0 then
1362 -- Check that the lock is not yet initialized
1364 if L.Level /= 0 then
1368 L.Level := Lock_Level'Pos (Level) + 1;
1370 end Check_Initialize_Lock;
1376 function Check_Lock (L : Lock_Ptr) return Boolean is
1377 Self_ID : constant Task_ID := Self;
1381 -- Check that the argument is not null
1387 -- Check that L is not frozen
1393 -- Check that caller is abort-deferred
1395 if Self_ID.Deferral_Level <= 0 then
1399 -- Check that caller is not holding this lock already
1401 if L.Owner = To_Owner_ID (To_Address (Self_ID)) then
1409 -- Check that TCB lock order rules are satisfied
1411 P := Self_ID.Common.LL.Locks;
1413 if P.Level >= L.Level
1414 and then (P.Level > 2 or else L.Level > 2)
1427 function Record_Lock (L : Lock_Ptr) return Boolean is
1428 Self_ID : constant Task_ID := Self;
1432 Lock_Count := Lock_Count + 1;
1434 -- There should be no owner for this lock at this point
1436 if L.Owner /= null then
1442 L.Owner := To_Owner_ID (To_Address (Self_ID));
1448 -- Check that TCB lock order rules are satisfied
1450 P := Self_ID.Common.LL.Locks;
1456 Self_ID.Common.LL.Locking := null;
1457 Self_ID.Common.LL.Locks := L;
1465 function Check_Sleep (Reason : Task_States) return Boolean is
1466 pragma Unreferenced (Reason);
1468 Self_ID : constant Task_ID := Self;
1472 -- Check that caller is abort-deferred
1474 if Self_ID.Deferral_Level <= 0 then
1482 -- Check that caller is holding own lock, on top of list
1484 if Self_ID.Common.LL.Locks /=
1485 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1490 -- Check that TCB lock order rules are satisfied
1492 if Self_ID.Common.LL.Locks.Next /= null then
1496 Self_ID.Common.LL.L.Owner := null;
1497 P := Self_ID.Common.LL.Locks;
1498 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1507 function Record_Wakeup
1509 Reason : Task_States) return Boolean
1511 pragma Unreferenced (Reason);
1513 Self_ID : constant Task_ID := Self;
1519 L.Owner := To_Owner_ID (To_Address (Self_ID));
1525 -- Check that TCB lock order rules are satisfied
1527 P := Self_ID.Common.LL.Locks;
1533 Self_ID.Common.LL.Locking := null;
1534 Self_ID.Common.LL.Locks := L;
1542 function Check_Wakeup
1544 Reason : Task_States) return Boolean
1546 Self_ID : constant Task_ID := Self;
1549 -- Is caller holding T's lock?
1551 if T.Common.LL.L.Owner /= To_Owner_ID (To_Address (Self_ID)) then
1555 -- Are reasons for wakeup and sleep consistent?
1557 if T.Common.State /= Reason then
1568 function Check_Unlock (L : Lock_Ptr) return Boolean is
1569 Self_ID : constant Task_ID := Self;
1573 Unlock_Count := Unlock_Count + 1;
1579 if L.Buddy /= null then
1584 Check_Count := Unlock_Count;
1587 if Unlock_Count - Check_Count > 1000 then
1588 Check_Count := Unlock_Count;
1591 -- Check that caller is abort-deferred
1593 if Self_ID.Deferral_Level <= 0 then
1597 -- Check that caller is holding this lock, on top of list
1599 if Self_ID.Common.LL.Locks /= L then
1603 -- Record there is no owner now
1606 P := Self_ID.Common.LL.Locks;
1607 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1612 --------------------
1613 -- Check_Finalize --
1614 --------------------
1616 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1617 Self_ID : constant Task_ID := Self;
1620 -- Check that caller is abort-deferred
1622 if Self_ID.Deferral_Level <= 0 then
1626 -- Check that no one is holding this lock
1628 if L.Owner /= null then
1634 end Check_Finalize_Lock;
1640 function Check_Exit (Self_ID : Task_ID) return Boolean is
1642 -- Check that caller is just holding Global_Task_Lock
1643 -- and no other locks
1645 if Self_ID.Common.LL.Locks = null then
1649 -- 2 = Global_Task_Level
1651 if Self_ID.Common.LL.Locks.Level /= 2 then
1655 if Self_ID.Common.LL.Locks.Next /= null then
1659 -- Check that caller is abort-deferred
1661 if Self_ID.Deferral_Level <= 0 then
1668 --------------------
1669 -- Check_No_Locks --
1670 --------------------
1672 function Check_No_Locks (Self_ID : Task_ID) return Boolean is
1674 return Self_ID.Common.LL.Locks = null;
1677 ----------------------
1678 -- Environment_Task --
1679 ----------------------
1681 function Environment_Task return Task_ID is
1683 return Environment_Task_ID;
1684 end Environment_Task;
1690 procedure Lock_RTS is
1692 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1699 procedure Unlock_RTS is
1701 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1708 function Suspend_Task
1710 Thread_Self : Thread_Id) return Boolean
1713 if T.Common.LL.Thread /= Thread_Self then
1714 return thr_suspend (T.Common.LL.Thread) = 0;
1724 function Resume_Task
1726 Thread_Self : Thread_Id) return Boolean
1729 if T.Common.LL.Thread /= Thread_Self then
1730 return thr_continue (T.Common.LL.Thread) = 0;
1736 -- Package elaboration
1740 Result : Interfaces.C.int;
1743 -- Mask Environment task for all signals. The original mask of the
1744 -- Environment task will be recovered by Interrupt_Server task
1745 -- during the elaboration of s-interr.adb.
1747 System.Interrupt_Management.Operations.Set_Interrupt_Mask
1748 (System.Interrupt_Management.Operations.All_Tasks_Mask'Access);
1750 -- Prepare the set of signals that should unblocked in all tasks
1752 Result := sigemptyset (Unblocked_Signal_Mask'Access);
1753 pragma Assert (Result = 0);
1755 for J in Interrupt_Management.Interrupt_ID loop
1756 if System.Interrupt_Management.Keep_Unmasked (J) then
1757 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1758 pragma Assert (Result = 0);
1762 -- We need the following code to support automatic creation of fake
1763 -- ATCB's for C threads that call the Ada run-time system, even if
1764 -- we use a faster way of getting Self for real Ada tasks.
1766 Result := thr_keycreate (ATCB_Key'Access, System.Null_Address);
1767 pragma Assert (Result = 0);
1770 if Dispatching_Policy = 'F' then
1772 Result : Interfaces.C.long;
1773 Class_Info : aliased struct_pcinfo;
1774 Secs, Nsecs : Interfaces.C.long;
1777 -- If a pragma Time_Slice is specified, takes the value in account.
1779 if Time_Slice_Val > 0 then
1780 -- Convert Time_Slice_Val (microseconds) into seconds and
1783 Secs := Time_Slice_Val / 1_000_000;
1784 Nsecs := (Time_Slice_Val rem 1_000_000) * 1_000;
1786 -- Otherwise, default to no time slicing (i.e run until blocked)
1793 -- Get the real time class id.
1795 Class_Info.pc_clname (1) := 'R';
1796 Class_Info.pc_clname (2) := 'T';
1797 Class_Info.pc_clname (3) := ASCII.NUL;
1799 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
1800 Class_Info'Address);
1802 -- Request the real time class
1804 Prio_Param.pc_cid := Class_Info.pc_cid;
1805 Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
1806 Prio_Param.rt_tqsecs := Secs;
1807 Prio_Param.rt_tqnsecs := Nsecs;
1809 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS,
1810 Prio_Param'Address);
1812 Using_Real_Time_Class := Result /= -1;
1815 end System.Task_Primitives.Operations;