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-2003, 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_Conversion;
90 with Unchecked_Deallocation;
92 package body System.Task_Primitives.Operations is
94 use System.Tasking.Debug;
97 use System.OS_Interface;
98 use System.Parameters;
100 use System.OS_Primitives;
102 package SSL renames System.Soft_Links;
108 -- The following are logically constants, but need to be initialized
111 Environment_Task_ID : Task_ID;
112 -- A variable to hold Task_ID for the environment task.
113 -- If we use this variable to get the Task_ID, we need the following
114 -- ATCB_Key only for non-Ada threads.
116 Unblocked_Signal_Mask : aliased sigset_t;
117 -- The set of signals that should unblocked in all tasks
119 ATCB_Key : aliased thread_key_t;
120 -- Key used to find the Ada Task_ID associated with a thread,
121 -- at least for C threads unknown to the Ada run-time system.
123 Single_RTS_Lock : aliased RTS_Lock;
124 -- This is a lock to allow only one thread of control in the RTS at
125 -- a time; it is used to execute in mutual exclusion from all other tasks.
126 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
128 Next_Serial_Number : Task_Serial_Number := 100;
129 -- We start at 100, to reserve some special values for
130 -- using in error checking.
131 -- The following are internal configuration constants needed.
133 ----------------------
134 -- Priority Support --
135 ----------------------
137 Priority_Ceiling_Emulation : constant Boolean := True;
138 -- controls whether we emulate priority ceiling locking
140 -- To get a scheduling close to annex D requirements, we use the real-time
141 -- class provided for LWP's and map each task/thread to a specific and
142 -- unique LWP (there is 1 thread per LWP, and 1 LWP per thread).
144 -- The real time class can only be set when the process has root
145 -- priviledges, so in the other cases, we use the normal thread scheduling
146 -- and priority handling.
148 Using_Real_Time_Class : Boolean := False;
149 -- indicates wether the real time class is being used (i.e the process
150 -- has root priviledges).
152 Prio_Param : aliased struct_pcparms;
153 -- Hold priority info (Real_Time) initialized during the package
156 -----------------------------------
157 -- External Configuration Values --
158 -----------------------------------
160 Time_Slice_Val : Interfaces.C.long;
161 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
163 Locking_Policy : Character;
164 pragma Import (C, Locking_Policy, "__gl_locking_policy");
166 Dispatching_Policy : Character;
167 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
169 Foreign_Task_Elaborated : aliased Boolean := True;
170 -- Used to identified fake tasks (i.e., non-Ada Threads).
172 -----------------------
173 -- Local Subprograms --
174 -----------------------
176 function sysconf (name : System.OS_Interface.int)
177 return processorid_t;
178 pragma Import (C, sysconf, "sysconf");
180 SC_NPROCESSORS_CONF : constant System.OS_Interface.int := 14;
182 function Num_Procs (name : System.OS_Interface.int := SC_NPROCESSORS_CONF)
183 return processorid_t renames sysconf;
185 procedure Abort_Handler
187 Code : access siginfo_t;
188 Context : access ucontext_t);
189 -- Target-dependent binding of inter-thread Abort signal to
190 -- the raising of the Abort_Signal exception.
191 -- See also comments in 7staprop.adb
193 function To_thread_t is new Unchecked_Conversion
194 (Integer, System.OS_Interface.thread_t);
196 function To_Task_ID is new Unchecked_Conversion (System.Address, Task_ID);
198 function To_Address is new Unchecked_Conversion (Task_ID, System.Address);
200 function Thread_Body_Access is
201 new Unchecked_Conversion (System.Address, Thread_Body);
207 function Check_Initialize_Lock (L : Lock_Ptr; Level : Lock_Level)
209 pragma Inline (Check_Initialize_Lock);
211 function Check_Lock (L : Lock_Ptr) return Boolean;
212 pragma Inline (Check_Lock);
214 function Record_Lock (L : Lock_Ptr) return Boolean;
215 pragma Inline (Record_Lock);
217 function Check_Sleep (Reason : Task_States) return Boolean;
218 pragma Inline (Check_Sleep);
220 function Record_Wakeup
222 Reason : Task_States) return Boolean;
223 pragma Inline (Record_Wakeup);
225 function Check_Wakeup
227 Reason : Task_States) return Boolean;
228 pragma Inline (Check_Wakeup);
230 function Check_Unlock (L : Lock_Ptr) return Boolean;
231 pragma Inline (Check_Lock);
233 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean;
234 pragma Inline (Check_Finalize_Lock);
242 procedure Initialize (Environment_Task : Task_ID);
243 pragma Inline (Initialize);
244 -- Initialize various data needed by this package.
246 function Is_Valid_Task return Boolean;
247 pragma Inline (Is_Valid_Task);
248 -- Does executing thread have a TCB?
250 procedure Set (Self_Id : Task_ID);
252 -- Set the self id for the current task.
254 function Self return Task_ID;
255 pragma Inline (Self);
256 -- Return a pointer to the Ada Task Control Block of the calling task.
260 package body Specific is separate;
261 -- The body of this package is target specific.
263 ---------------------------------
264 -- Support for foreign threads --
265 ---------------------------------
267 function Register_Foreign_Thread (Thread : Thread_Id) return Task_ID;
268 -- Allocate and Initialize a new ATCB for the current Thread.
270 function Register_Foreign_Thread
271 (Thread : Thread_Id) return Task_ID is separate;
277 Check_Count : Integer := 0;
279 Lock_Count : Integer := 0;
280 Unlock_Count : Integer := 0;
282 function To_Lock_Ptr is
283 new Unchecked_Conversion (RTS_Lock_Ptr, Lock_Ptr);
284 function To_Task_ID is
285 new Unchecked_Conversion (Owner_ID, Task_ID);
286 function To_Owner_ID is
287 new Unchecked_Conversion (Task_ID, Owner_ID);
293 procedure Abort_Handler
295 Code : access siginfo_t;
296 Context : access ucontext_t)
298 pragma Unreferenced (Sig);
299 pragma Unreferenced (Code);
300 pragma Unreferenced (Context);
302 Self_ID : Task_ID := Self;
303 Result : Interfaces.C.int;
304 Old_Set : aliased sigset_t;
307 -- It is not safe to raise an exception when using ZCX and the GCC
308 -- exception handling mechanism.
310 if ZCX_By_Default and then GCC_ZCX_Support then
314 if Self_ID.Deferral_Level = 0
315 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
316 and then not Self_ID.Aborting
318 Self_ID.Aborting := True;
320 -- Make sure signals used for RTS internal purpose are unmasked
322 Result := thr_sigsetmask (SIG_UNBLOCK,
323 Unblocked_Signal_Mask'Unchecked_Access, Old_Set'Unchecked_Access);
324 pragma Assert (Result = 0);
326 raise Standard'Abort_Signal;
334 -- The underlying thread system sets a guard page at the
335 -- bottom of a thread stack, so nothing is needed.
337 procedure Stack_Guard (T : ST.Task_ID; On : Boolean) is
338 pragma Unreferenced (T);
339 pragma Unreferenced (On);
349 function Get_Thread_Id (T : ST.Task_ID) return OSI.Thread_Id is
351 return T.Common.LL.Thread;
358 procedure Initialize (Environment_Task : ST.Task_ID) is
359 act : aliased struct_sigaction;
360 old_act : aliased struct_sigaction;
361 Tmp_Set : aliased sigset_t;
362 Result : Interfaces.C.int;
364 procedure Configure_Processors;
365 -- Processors configuration
366 -- The user can specify a processor which the program should run
367 -- on to emulate a single-processor system. This can be easily
368 -- done by setting environment variable GNAT_PROCESSOR to one of
371 -- -2 : use the default configuration (run the program on all
372 -- available processors) - this is the same as having
373 -- GNAT_PROCESSOR unset
374 -- -1 : let the RTS choose one processor and run the program on
376 -- 0 .. Last_Proc : run the program on the specified processor
378 -- Last_Proc is equal to the value of the system variable
379 -- _SC_NPROCESSORS_CONF, minus one.
381 procedure Configure_Processors is
382 Proc_Acc : constant GNAT.OS_Lib.String_Access :=
383 GNAT.OS_Lib.Getenv ("GNAT_PROCESSOR");
384 Proc : aliased processorid_t; -- User processor #
385 Last_Proc : processorid_t; -- Last processor #
388 if Proc_Acc.all'Length /= 0 then
389 -- Environment variable is defined
391 Last_Proc := Num_Procs - 1;
393 if Last_Proc /= -1 then
394 Proc := processorid_t'Value (Proc_Acc.all);
396 if Proc <= -2 or else Proc > Last_Proc then
397 -- Use the default configuration
400 -- Choose a processor
404 while Proc < Last_Proc loop
406 Result := p_online (Proc, PR_STATUS);
407 exit when Result = PR_ONLINE;
410 pragma Assert (Result = PR_ONLINE);
411 Result := processor_bind (P_PID, P_MYID, Proc, null);
412 pragma Assert (Result = 0);
415 -- Use user processor
417 Result := processor_bind (P_PID, P_MYID, Proc, null);
418 pragma Assert (Result = 0);
424 when Constraint_Error =>
426 -- Illegal environment variable GNAT_PROCESSOR - ignored
429 end Configure_Processors;
431 function State (Int : System.Interrupt_Management.Interrupt_ID)
433 pragma Import (C, State, "__gnat_get_interrupt_state");
434 -- Get interrupt state. Defined in a-init.c
435 -- The input argument is the interrupt number,
436 -- and the result is one of the following:
438 Default : constant Character := 's';
439 -- 'n' this interrupt not set by any Interrupt_State pragma
440 -- 'u' Interrupt_State pragma set state to User
441 -- 'r' Interrupt_State pragma set state to Runtime
442 -- 's' Interrupt_State pragma set state to System (use "default"
445 -- Start of processing for Initialize
448 Environment_Task_ID := Environment_Task;
450 -- This is done in Enter_Task, but this is too late for the
451 -- Environment Task, since we need to call Self in Check_Locks when
452 -- the run time is compiled with assertions on.
454 Specific.Initialize (Environment_Task);
456 -- Initialize the lock used to synchronize chain of all ATCBs.
458 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
460 Enter_Task (Environment_Task);
462 -- Install the abort-signal handler
464 if State (System.Interrupt_Management.Abort_Task_Interrupt)
467 -- Set sa_flags to SA_NODEFER so that during the handler execution
468 -- we do not change the Signal_Mask to be masked for the Abort_Signal
469 -- This is a temporary fix to the problem that the Signal_Mask is
470 -- not restored after the exception (longjmp) from the handler.
471 -- The right fix should be made in sigsetjmp so that we save
472 -- the Signal_Set and restore it after a longjmp.
473 -- In that case, this field should be changed back to 0. ???
477 act.sa_handler := Abort_Handler'Address;
478 Result := sigemptyset (Tmp_Set'Access);
479 pragma Assert (Result = 0);
480 act.sa_mask := Tmp_Set;
484 Signal (System.Interrupt_Management.Abort_Task_Interrupt),
485 act'Unchecked_Access,
486 old_act'Unchecked_Access);
487 pragma Assert (Result = 0);
490 Configure_Processors;
493 ---------------------
494 -- Initialize_Lock --
495 ---------------------
497 -- Note: mutexes and cond_variables needed per-task basis are
498 -- initialized in Initialize_TCB and the Storage_Error is
499 -- handled. Other mutexes (such as RTS_Lock, Memory_Lock...)
500 -- used in RTS is initialized before any status change of RTS.
501 -- Therefore rasing Storage_Error in the following routines
502 -- should be able to be handled safely.
504 procedure Initialize_Lock
505 (Prio : System.Any_Priority;
508 Result : Interfaces.C.int;
511 pragma Assert (Check_Initialize_Lock (Lock_Ptr (L), PO_Level));
513 if Priority_Ceiling_Emulation then
517 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
518 pragma Assert (Result = 0 or else Result = ENOMEM);
520 if Result = ENOMEM then
521 Raise_Exception (Storage_Error'Identity, "Failed to allocate a lock");
525 procedure Initialize_Lock
526 (L : access RTS_Lock;
529 Result : Interfaces.C.int;
532 pragma Assert (Check_Initialize_Lock
533 (To_Lock_Ptr (RTS_Lock_Ptr (L)), Level));
534 Result := mutex_init (L.L'Access, USYNC_THREAD, System.Null_Address);
535 pragma Assert (Result = 0 or else Result = ENOMEM);
537 if Result = ENOMEM then
538 Raise_Exception (Storage_Error'Identity, "Failed to allocate a lock");
546 procedure Finalize_Lock (L : access Lock) is
547 Result : Interfaces.C.int;
550 pragma Assert (Check_Finalize_Lock (Lock_Ptr (L)));
551 Result := mutex_destroy (L.L'Access);
552 pragma Assert (Result = 0);
555 procedure Finalize_Lock (L : access RTS_Lock) is
556 Result : Interfaces.C.int;
559 pragma Assert (Check_Finalize_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
560 Result := mutex_destroy (L.L'Access);
561 pragma Assert (Result = 0);
568 procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
569 Result : Interfaces.C.int;
572 pragma Assert (Check_Lock (Lock_Ptr (L)));
574 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
576 Self_Id : constant Task_ID := Self;
577 Saved_Priority : System.Any_Priority;
580 if Self_Id.Common.LL.Active_Priority > L.Ceiling then
581 Ceiling_Violation := True;
585 Saved_Priority := Self_Id.Common.LL.Active_Priority;
587 if Self_Id.Common.LL.Active_Priority < L.Ceiling then
588 Set_Priority (Self_Id, L.Ceiling);
591 Result := mutex_lock (L.L'Access);
592 pragma Assert (Result = 0);
593 Ceiling_Violation := False;
595 L.Saved_Priority := Saved_Priority;
599 Result := mutex_lock (L.L'Access);
600 pragma Assert (Result = 0);
601 Ceiling_Violation := False;
604 pragma Assert (Record_Lock (Lock_Ptr (L)));
608 (L : access RTS_Lock;
609 Global_Lock : Boolean := False)
611 Result : Interfaces.C.int;
614 if not Single_Lock or else Global_Lock then
615 pragma Assert (Check_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
616 Result := mutex_lock (L.L'Access);
617 pragma Assert (Result = 0);
618 pragma Assert (Record_Lock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
622 procedure Write_Lock (T : Task_ID) is
623 Result : Interfaces.C.int;
626 if not Single_Lock then
627 pragma Assert (Check_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
628 Result := mutex_lock (T.Common.LL.L.L'Access);
629 pragma Assert (Result = 0);
630 pragma Assert (Record_Lock (To_Lock_Ptr (T.Common.LL.L'Access)));
638 procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
640 Write_Lock (L, Ceiling_Violation);
647 procedure Unlock (L : access Lock) is
648 Result : Interfaces.C.int;
651 pragma Assert (Check_Unlock (Lock_Ptr (L)));
653 if Priority_Ceiling_Emulation and then Locking_Policy = 'C' then
655 Self_Id : constant Task_ID := Self;
658 Result := mutex_unlock (L.L'Access);
659 pragma Assert (Result = 0);
661 if Self_Id.Common.LL.Active_Priority > L.Saved_Priority then
662 Set_Priority (Self_Id, L.Saved_Priority);
666 Result := mutex_unlock (L.L'Access);
667 pragma Assert (Result = 0);
671 procedure Unlock (L : access RTS_Lock; Global_Lock : Boolean := False) is
672 Result : Interfaces.C.int;
675 if not Single_Lock or else Global_Lock then
676 pragma Assert (Check_Unlock (To_Lock_Ptr (RTS_Lock_Ptr (L))));
677 Result := mutex_unlock (L.L'Access);
678 pragma Assert (Result = 0);
682 procedure Unlock (T : Task_ID) is
683 Result : Interfaces.C.int;
686 if not Single_Lock then
687 pragma Assert (Check_Unlock (To_Lock_Ptr (T.Common.LL.L'Access)));
688 Result := mutex_unlock (T.Common.LL.L.L'Access);
689 pragma Assert (Result = 0);
693 -- For the time delay implementation, we need to make sure we
694 -- achieve following criteria:
696 -- 1) We have to delay at least for the amount requested.
697 -- 2) We have to give up CPU even though the actual delay does not
698 -- result in blocking.
699 -- 3) Except for restricted run-time systems that do not support
700 -- ATC or task abort, the delay must be interrupted by the
701 -- abort_task operation.
702 -- 4) The implementation has to be efficient so that the delay overhead
703 -- is relatively cheap.
704 -- (1)-(3) are Ada requirements. Even though (2) is an Annex-D
705 -- requirement we still want to provide the effect in all cases.
706 -- The reason is that users may want to use short delays to implement
707 -- their own scheduling effect in the absence of language provided
708 -- scheduling policies.
710 ---------------------
711 -- Monotonic_Clock --
712 ---------------------
714 function Monotonic_Clock return Duration is
715 TS : aliased timespec;
716 Result : Interfaces.C.int;
719 Result := clock_gettime (CLOCK_REALTIME, TS'Unchecked_Access);
720 pragma Assert (Result = 0);
721 return To_Duration (TS);
728 function RT_Resolution return Duration is
737 procedure Yield (Do_Yield : Boolean := True) is
740 System.OS_Interface.thr_yield;
748 function Self return Task_ID renames Specific.Self;
754 procedure Set_Priority
756 Prio : System.Any_Priority;
757 Loss_Of_Inheritance : Boolean := False)
759 pragma Unreferenced (Loss_Of_Inheritance);
761 Result : Interfaces.C.int;
762 Param : aliased struct_pcparms;
767 T.Common.Current_Priority := Prio;
769 if Priority_Ceiling_Emulation then
770 T.Common.LL.Active_Priority := Prio;
773 if Using_Real_Time_Class then
774 Param.pc_cid := Prio_Param.pc_cid;
775 Param.rt_pri := pri_t (Prio);
776 Param.rt_tqsecs := Prio_Param.rt_tqsecs;
777 Param.rt_tqnsecs := Prio_Param.rt_tqnsecs;
779 Result := Interfaces.C.int (
780 priocntl (PC_VERSION, P_LWPID, T.Common.LL.LWP, PC_SETPARMS,
784 if T.Common.Task_Info /= null
785 and then not T.Common.Task_Info.Bound_To_LWP
787 -- The task is not bound to a LWP, so use thr_setprio
790 thr_setprio (T.Common.LL.Thread, Interfaces.C.int (Prio));
794 -- The task is bound to a LWP, use priocntl
806 function Get_Priority (T : Task_ID) return System.Any_Priority is
808 return T.Common.Current_Priority;
815 procedure Enter_Task (Self_ID : Task_ID) is
816 Result : Interfaces.C.int;
817 Proc : processorid_t; -- User processor #
818 Last_Proc : processorid_t; -- Last processor #
820 use System.Task_Info;
822 Self_ID.Common.LL.Thread := thr_self;
824 Self_ID.Common.LL.LWP := lwp_self;
826 if Self_ID.Common.Task_Info /= null then
827 if Self_ID.Common.Task_Info.New_LWP
828 and then Self_ID.Common.Task_Info.CPU /= CPU_UNCHANGED
830 Last_Proc := Num_Procs - 1;
832 if Self_ID.Common.Task_Info.CPU = ANY_CPU then
836 while Proc < Last_Proc loop
837 Result := p_online (Proc, PR_STATUS);
838 exit when Result = PR_ONLINE;
842 Result := processor_bind (P_LWPID, P_MYID, Proc, null);
843 pragma Assert (Result = 0);
846 -- Use specified processor
848 if Self_ID.Common.Task_Info.CPU < 0
849 or else Self_ID.Common.Task_Info.CPU > Last_Proc
851 raise Invalid_CPU_Number;
854 Result := processor_bind
855 (P_LWPID, P_MYID, Self_ID.Common.Task_Info.CPU, null);
856 pragma Assert (Result = 0);
861 Specific.Set (Self_ID);
863 -- We need the above code even if we do direct fetch of Task_ID in Self
864 -- for the main task on Sun, x86 Solaris and for gcc 2.7.2.
868 for J in Known_Tasks'Range loop
869 if Known_Tasks (J) = null then
870 Known_Tasks (J) := Self_ID;
871 Self_ID.Known_Tasks_Index := J;
883 function New_ATCB (Entry_Num : Task_Entry_Index) return Task_ID is
885 return new Ada_Task_Control_Block (Entry_Num);
892 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
894 -----------------------------
895 -- Register_Foreign_Thread --
896 -----------------------------
898 function Register_Foreign_Thread return Task_ID is
901 if Is_Valid_Task then
904 return Register_Foreign_Thread (thr_self);
906 end Register_Foreign_Thread;
912 procedure Initialize_TCB (Self_ID : Task_ID; Succeeded : out Boolean) is
913 Result : Interfaces.C.int := 0;
916 -- Give the task a unique serial number.
918 Self_ID.Serial_Number := Next_Serial_Number;
919 Next_Serial_Number := Next_Serial_Number + 1;
920 pragma Assert (Next_Serial_Number /= 0);
922 Self_ID.Common.LL.Thread := To_thread_t (-1);
924 if not Single_Lock then
926 (Self_ID.Common.LL.L.L'Access, USYNC_THREAD, System.Null_Address);
927 Self_ID.Common.LL.L.Level :=
928 Private_Task_Serial_Number (Self_ID.Serial_Number);
929 pragma Assert (Result = 0 or else Result = ENOMEM);
933 Result := cond_init (Self_ID.Common.LL.CV'Access, USYNC_THREAD, 0);
934 pragma Assert (Result = 0 or else Result = ENOMEM);
940 if not Single_Lock then
941 Result := mutex_destroy (Self_ID.Common.LL.L.L'Access);
942 pragma Assert (Result = 0);
953 procedure Create_Task
955 Wrapper : System.Address;
956 Stack_Size : System.Parameters.Size_Type;
957 Priority : System.Any_Priority;
958 Succeeded : out Boolean)
960 pragma Unreferenced (Priority);
962 Result : Interfaces.C.int;
963 Adjusted_Stack_Size : Interfaces.C.size_t;
964 Opts : Interfaces.C.int := THR_DETACHED;
966 Page_Size : constant System.Parameters.Size_Type := 4096;
967 -- This constant is for reserving extra space at the
968 -- end of the stack, which can be used by the stack
969 -- checking as guard page. The idea is that we need
970 -- to have at least Stack_Size bytes available for
973 use System.Task_Info;
976 if Stack_Size = System.Parameters.Unspecified_Size then
977 Adjusted_Stack_Size :=
978 Interfaces.C.size_t (Default_Stack_Size + Page_Size);
980 elsif Stack_Size < Minimum_Stack_Size then
981 Adjusted_Stack_Size :=
982 Interfaces.C.size_t (Minimum_Stack_Size + Page_Size);
985 Adjusted_Stack_Size :=
986 Interfaces.C.size_t (Stack_Size + Page_Size);
989 -- Since the initial signal mask of a thread is inherited from the
990 -- creator, and the Environment task has all its signals masked, we
991 -- do not need to manipulate caller's signal mask at this point.
992 -- All tasks in RTS will have All_Tasks_Mask initially.
994 if T.Common.Task_Info /= null then
995 if T.Common.Task_Info.New_LWP then
996 Opts := Opts + THR_NEW_LWP;
999 if T.Common.Task_Info.Bound_To_LWP then
1000 Opts := Opts + THR_BOUND;
1004 Opts := THR_DETACHED + THR_BOUND;
1007 Result := thr_create
1008 (System.Null_Address,
1009 Adjusted_Stack_Size,
1010 Thread_Body_Access (Wrapper),
1013 T.Common.LL.Thread'Access);
1015 Succeeded := Result = 0;
1018 or else Result = ENOMEM
1019 or else Result = EAGAIN);
1026 procedure Finalize_TCB (T : Task_ID) is
1027 Result : Interfaces.C.int;
1029 Is_Self : constant Boolean := T = Self;
1031 procedure Free is new
1032 Unchecked_Deallocation (Ada_Task_Control_Block, Task_ID);
1035 T.Common.LL.Thread := To_thread_t (0);
1037 if not Single_Lock then
1038 Result := mutex_destroy (T.Common.LL.L.L'Access);
1039 pragma Assert (Result = 0);
1042 Result := cond_destroy (T.Common.LL.CV'Access);
1043 pragma Assert (Result = 0);
1045 if T.Known_Tasks_Index /= -1 then
1046 Known_Tasks (T.Known_Tasks_Index) := null;
1052 Specific.Set (null);
1061 -- This procedure must be called with abort deferred.
1062 -- It can no longer call Self or access
1063 -- the current task's ATCB, since the ATCB has been deallocated.
1065 procedure Exit_Task is
1067 Specific.Set (null);
1074 procedure Abort_Task (T : Task_ID) is
1075 Result : Interfaces.C.int;
1077 pragma Assert (T /= Self);
1079 Result := thr_kill (T.Common.LL.Thread,
1080 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1083 pragma Assert (Result = 0);
1092 Reason : Task_States)
1094 Result : Interfaces.C.int;
1097 pragma Assert (Check_Sleep (Reason));
1099 if Dynamic_Priority_Support
1100 and then Self_ID.Pending_Priority_Change
1102 Self_ID.Pending_Priority_Change := False;
1103 Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1104 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1109 (Self_ID.Common.LL.CV'Access, Single_RTS_Lock.L'Access);
1112 (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L.L'Access);
1115 pragma Assert (Record_Wakeup
1116 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1117 pragma Assert (Result = 0 or else Result = EINTR);
1120 -- Note that we are relying heaviliy here on the GNAT feature
1121 -- that Calendar.Time, System.Real_Time.Time, Duration, and
1122 -- System.Real_Time.Time_Span are all represented in the same
1123 -- way, i.e., as a 64-bit count of nanoseconds.
1125 -- This allows us to always pass the timeout value as a Duration.
1128 -- We are taking liberties here with the semantics of the delays.
1129 -- That is, we make no distinction between delays on the Calendar clock
1130 -- and delays on the Real_Time clock. That is technically incorrect, if
1131 -- the Calendar clock happens to be reset or adjusted.
1132 -- To solve this defect will require modification to the compiler
1133 -- interface, so that it can pass through more information, to tell
1134 -- us here which clock to use!
1136 -- cond_timedwait will return if any of the following happens:
1137 -- 1) some other task did cond_signal on this condition variable
1138 -- In this case, the return value is 0
1139 -- 2) the call just returned, for no good reason
1140 -- This is called a "spurious wakeup".
1141 -- In this case, the return value may also be 0.
1142 -- 3) the time delay expires
1143 -- In this case, the return value is ETIME
1144 -- 4) this task received a signal, which was handled by some
1145 -- handler procedure, and now the thread is resuming execution
1146 -- UNIX calls this an "interrupted" system call.
1147 -- In this case, the return value is EINTR
1149 -- If the cond_timedwait returns 0 or EINTR, it is still
1150 -- possible that the time has actually expired, and by chance
1151 -- a signal or cond_signal occurred at around the same time.
1153 -- We have also observed that on some OS's the value ETIME
1154 -- will be returned, but the clock will show that the full delay
1155 -- has not yet expired.
1157 -- For these reasons, we need to check the clock after return
1158 -- from cond_timedwait. If the time has expired, we will set
1161 -- This check might be omitted for systems on which the
1162 -- cond_timedwait() never returns early or wakes up spuriously.
1164 -- Annex D requires that completion of a delay cause the task
1165 -- to go to the end of its priority queue, regardless of whether
1166 -- the task actually was suspended by the delay. Since
1167 -- cond_timedwait does not do this on Solaris, we add a call
1168 -- to thr_yield at the end. We might do this at the beginning,
1169 -- instead, but then the round-robin effect would not be the
1170 -- same; the delayed task would be ahead of other tasks of the
1171 -- same priority that awoke while it was sleeping.
1173 -- For Timed_Sleep, we are expecting possible cond_signals
1174 -- to indicate other events (e.g., completion of a RV or
1175 -- completion of the abortable part of an async. select),
1176 -- we want to always return if interrupted. The caller will
1177 -- be responsible for checking the task state to see whether
1178 -- the wakeup was spurious, and to go back to sleep again
1179 -- in that case. We don't need to check for pending abort
1180 -- or priority change on the way in our out; that is the
1181 -- caller's responsibility.
1183 -- For Timed_Delay, we are not expecting any cond_signals or
1184 -- other interruptions, except for priority changes and aborts.
1185 -- Therefore, we don't want to return unless the delay has
1186 -- actually expired, or the call has been aborted. In this
1187 -- case, since we want to implement the entire delay statement
1188 -- semantics, we do need to check for pending abort and priority
1189 -- changes. We can quietly handle priority changes inside the
1190 -- procedure, since there is no entry-queue reordering involved.
1196 procedure Timed_Sleep
1199 Mode : ST.Delay_Modes;
1200 Reason : System.Tasking.Task_States;
1201 Timedout : out Boolean;
1202 Yielded : out Boolean)
1204 Check_Time : constant Duration := Monotonic_Clock;
1205 Abs_Time : Duration;
1206 Request : aliased timespec;
1207 Result : Interfaces.C.int;
1210 pragma Assert (Check_Sleep (Reason));
1214 if Mode = Relative then
1215 Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
1217 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1220 if Abs_Time > Check_Time then
1221 Request := To_Timespec (Abs_Time);
1224 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
1225 or else (Dynamic_Priority_Support and then
1226 Self_ID.Pending_Priority_Change);
1229 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1230 Single_RTS_Lock.L'Access, Request'Access);
1232 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1233 Self_ID.Common.LL.L.L'Access, Request'Access);
1238 exit when Abs_Time <= Monotonic_Clock;
1240 if Result = 0 or Result = EINTR then
1242 -- Somebody may have called Wakeup for us
1248 pragma Assert (Result = ETIME);
1252 pragma Assert (Record_Wakeup
1253 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Reason));
1260 procedure Timed_Delay
1263 Mode : ST.Delay_Modes)
1265 Check_Time : constant Duration := Monotonic_Clock;
1266 Abs_Time : Duration;
1267 Request : aliased timespec;
1268 Result : Interfaces.C.int;
1269 Yielded : Boolean := False;
1272 -- Only the little window between deferring abort and
1273 -- locking Self_ID is the reason we need to
1274 -- check for pending abort and priority change below!
1276 SSL.Abort_Defer.all;
1282 Write_Lock (Self_ID);
1284 if Mode = Relative then
1285 Abs_Time := Time + Check_Time;
1287 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
1290 if Abs_Time > Check_Time then
1291 Request := To_Timespec (Abs_Time);
1292 Self_ID.Common.State := Delay_Sleep;
1294 pragma Assert (Check_Sleep (Delay_Sleep));
1297 if Dynamic_Priority_Support and then
1298 Self_ID.Pending_Priority_Change then
1299 Self_ID.Pending_Priority_Change := False;
1300 Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
1301 Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
1304 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
1307 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1308 Single_RTS_Lock.L'Access, Request'Access);
1310 Result := cond_timedwait (Self_ID.Common.LL.CV'Access,
1311 Self_ID.Common.LL.L.L'Access, Request'Access);
1316 exit when Abs_Time <= Monotonic_Clock;
1318 pragma Assert (Result = 0 or else
1319 Result = ETIME or else
1323 pragma Assert (Record_Wakeup
1324 (To_Lock_Ptr (Self_ID.Common.LL.L'Access), Delay_Sleep));
1326 Self_ID.Common.State := Runnable;
1339 SSL.Abort_Undefer.all;
1348 Reason : Task_States)
1350 Result : Interfaces.C.int;
1353 pragma Assert (Check_Wakeup (T, Reason));
1354 Result := cond_signal (T.Common.LL.CV'Access);
1355 pragma Assert (Result = 0);
1358 ---------------------------
1359 -- Check_Initialize_Lock --
1360 ---------------------------
1362 -- The following code is intended to check some of the invariant
1363 -- assertions related to lock usage, on which we depend.
1365 function Check_Initialize_Lock
1370 Self_ID : constant Task_ID := Self;
1373 -- Check that caller is abort-deferred
1375 if Self_ID.Deferral_Level <= 0 then
1379 -- Check that the lock is not yet initialized
1381 if L.Level /= 0 then
1385 L.Level := Lock_Level'Pos (Level) + 1;
1387 end Check_Initialize_Lock;
1393 function Check_Lock (L : Lock_Ptr) return Boolean is
1394 Self_ID : constant Task_ID := Self;
1398 -- Check that the argument is not null
1404 -- Check that L is not frozen
1410 -- Check that caller is abort-deferred
1412 if Self_ID.Deferral_Level <= 0 then
1416 -- Check that caller is not holding this lock already
1418 if L.Owner = To_Owner_ID (Self_ID) then
1426 -- Check that TCB lock order rules are satisfied
1428 P := Self_ID.Common.LL.Locks;
1430 if P.Level >= L.Level
1431 and then (P.Level > 2 or else L.Level > 2)
1444 function Record_Lock (L : Lock_Ptr) return Boolean is
1445 Self_ID : Task_ID := Self;
1449 Lock_Count := Lock_Count + 1;
1451 -- There should be no owner for this lock at this point
1453 if L.Owner /= null then
1459 L.Owner := To_Owner_ID (Self_ID);
1465 -- Check that TCB lock order rules are satisfied
1467 P := Self_ID.Common.LL.Locks;
1473 Self_ID.Common.LL.Locking := null;
1474 Self_ID.Common.LL.Locks := L;
1482 function Check_Sleep (Reason : Task_States) return Boolean is
1483 pragma Unreferenced (Reason);
1485 Self_ID : Task_ID := Self;
1489 -- Check that caller is abort-deferred
1491 if Self_ID.Deferral_Level <= 0 then
1499 -- Check that caller is holding own lock, on top of list
1501 if Self_ID.Common.LL.Locks /=
1502 To_Lock_Ptr (Self_ID.Common.LL.L'Access)
1507 -- Check that TCB lock order rules are satisfied
1509 if Self_ID.Common.LL.Locks.Next /= null then
1513 Self_ID.Common.LL.L.Owner := null;
1514 P := Self_ID.Common.LL.Locks;
1515 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1524 function Record_Wakeup
1526 Reason : Task_States)
1529 pragma Unreferenced (Reason);
1531 Self_ID : Task_ID := Self;
1537 L.Owner := To_Owner_ID (Self_ID);
1543 -- Check that TCB lock order rules are satisfied
1545 P := Self_ID.Common.LL.Locks;
1551 Self_ID.Common.LL.Locking := null;
1552 Self_ID.Common.LL.Locks := L;
1560 function Check_Wakeup
1562 Reason : Task_States)
1565 Self_ID : constant Task_ID := Self;
1568 -- Is caller holding T's lock?
1570 if T.Common.LL.L.Owner /= To_Owner_ID (Self_ID) then
1574 -- Are reasons for wakeup and sleep consistent?
1576 if T.Common.State /= Reason then
1587 function Check_Unlock (L : Lock_Ptr) return Boolean is
1588 Self_ID : Task_ID := Self;
1592 Unlock_Count := Unlock_Count + 1;
1598 if L.Buddy /= null then
1603 Check_Count := Unlock_Count;
1606 if Unlock_Count - Check_Count > 1000 then
1607 Check_Count := Unlock_Count;
1608 Old_Owner := To_Task_ID (Single_RTS_Lock.Owner);
1611 -- Check that caller is abort-deferred
1613 if Self_ID.Deferral_Level <= 0 then
1617 -- Check that caller is holding this lock, on top of list
1619 if Self_ID.Common.LL.Locks /= L then
1623 -- Record there is no owner now
1626 P := Self_ID.Common.LL.Locks;
1627 Self_ID.Common.LL.Locks := Self_ID.Common.LL.Locks.Next;
1632 --------------------
1633 -- Check_Finalize --
1634 --------------------
1636 function Check_Finalize_Lock (L : Lock_Ptr) return Boolean is
1637 Self_ID : constant Task_ID := Self;
1640 -- Check that caller is abort-deferred
1642 if Self_ID.Deferral_Level <= 0 then
1646 -- Check that no one is holding this lock
1648 if L.Owner /= null then
1654 end Check_Finalize_Lock;
1660 function Check_Exit (Self_ID : Task_ID) return Boolean is
1662 -- Check that caller is just holding Global_Task_Lock
1663 -- and no other locks
1665 if Self_ID.Common.LL.Locks = null then
1669 -- 2 = Global_Task_Level
1671 if Self_ID.Common.LL.Locks.Level /= 2 then
1675 if Self_ID.Common.LL.Locks.Next /= null then
1679 -- Check that caller is abort-deferred
1681 if Self_ID.Deferral_Level <= 0 then
1688 --------------------
1689 -- Check_No_Locks --
1690 --------------------
1692 function Check_No_Locks (Self_ID : Task_ID) return Boolean is
1694 return Self_ID.Common.LL.Locks = null;
1697 ----------------------
1698 -- Environment_Task --
1699 ----------------------
1701 function Environment_Task return Task_ID is
1703 return Environment_Task_ID;
1704 end Environment_Task;
1710 procedure Lock_RTS is
1712 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1719 procedure Unlock_RTS is
1721 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1728 function Suspend_Task
1730 Thread_Self : Thread_Id)
1734 if T.Common.LL.Thread /= Thread_Self then
1735 return thr_suspend (T.Common.LL.Thread) = 0;
1745 function Resume_Task
1747 Thread_Self : Thread_Id)
1751 if T.Common.LL.Thread /= Thread_Self then
1752 return thr_continue (T.Common.LL.Thread) = 0;
1758 -- Package elaboration
1762 Result : Interfaces.C.int;
1765 -- Mask Environment task for all signals. The original mask of the
1766 -- Environment task will be recovered by Interrupt_Server task
1767 -- during the elaboration of s-interr.adb.
1769 System.Interrupt_Management.Operations.Set_Interrupt_Mask
1770 (System.Interrupt_Management.Operations.All_Tasks_Mask'Access);
1772 -- Prepare the set of signals that should unblocked in all tasks
1774 Result := sigemptyset (Unblocked_Signal_Mask'Access);
1775 pragma Assert (Result = 0);
1777 for J in Interrupt_Management.Interrupt_ID loop
1778 if System.Interrupt_Management.Keep_Unmasked (J) then
1779 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1780 pragma Assert (Result = 0);
1784 -- We need the following code to support automatic creation of fake
1785 -- ATCB's for C threads that call the Ada run-time system, even if
1786 -- we use a faster way of getting Self for real Ada tasks.
1788 Result := thr_keycreate (ATCB_Key'Access, System.Null_Address);
1789 pragma Assert (Result = 0);
1792 if Dispatching_Policy = 'F' then
1794 Result : Interfaces.C.long;
1795 Class_Info : aliased struct_pcinfo;
1796 Secs, Nsecs : Interfaces.C.long;
1799 -- If a pragma Time_Slice is specified, takes the value in account.
1801 if Time_Slice_Val > 0 then
1802 -- Convert Time_Slice_Val (microseconds) into seconds and
1805 Secs := Time_Slice_Val / 1_000_000;
1806 Nsecs := (Time_Slice_Val rem 1_000_000) * 1_000;
1808 -- Otherwise, default to no time slicing (i.e run until blocked)
1815 -- Get the real time class id.
1817 Class_Info.pc_clname (1) := 'R';
1818 Class_Info.pc_clname (2) := 'T';
1819 Class_Info.pc_clname (3) := ASCII.NUL;
1821 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_GETCID,
1822 Class_Info'Address);
1824 -- Request the real time class
1826 Prio_Param.pc_cid := Class_Info.pc_cid;
1827 Prio_Param.rt_pri := pri_t (Class_Info.rt_maxpri);
1828 Prio_Param.rt_tqsecs := Secs;
1829 Prio_Param.rt_tqnsecs := Nsecs;
1831 Result := priocntl (PC_VERSION, P_LWPID, P_MYID, PC_SETPARMS,
1832 Prio_Param'Address);
1834 Using_Real_Time_Class := Result /= -1;
1837 end System.Task_Primitives.Operations;