2015-05-05 Yvan Roux <yvan.roux@linaro.org>
[official-gcc.git] / gcc / ada / s-taprop-linux.adb
bloba43133a9dee4a760ba3284ededb690001022a43c
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS --
4 -- --
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 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2014, Free Software Foundation, Inc. --
10 -- --
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. --
17 -- --
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. --
21 -- --
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/>. --
26 -- --
27 -- GNARL was developed by the GNARL team at Florida State University. --
28 -- Extensive contributions were provided by Ada Core Technologies, Inc. --
29 -- --
30 ------------------------------------------------------------------------------
32 -- This is a GNU/Linux (GNU/LinuxThreads) version of this package
34 -- This package contains all the GNULL primitives that interface directly with
35 -- the underlying OS.
37 pragma Polling (Off);
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 Interfaces.C;
42 with Interfaces.C.Extensions;
44 with System.Task_Info;
45 with System.Tasking.Debug;
46 with System.Interrupt_Management;
47 with System.OS_Constants;
48 with System.OS_Primitives;
49 with System.Stack_Checking.Operations;
50 with System.Multiprocessors;
52 with System.Soft_Links;
53 -- We use System.Soft_Links instead of System.Tasking.Initialization
54 -- because the later is a higher level package that we shouldn't depend on.
55 -- For example when using the restricted run time, it is replaced by
56 -- System.Tasking.Restricted.Stages.
58 package body System.Task_Primitives.Operations is
60 package OSC renames System.OS_Constants;
61 package SSL renames System.Soft_Links;
62 package SC renames System.Stack_Checking.Operations;
64 use System.Tasking.Debug;
65 use System.Tasking;
66 use Interfaces.C;
67 use Interfaces.C.Extensions;
68 use System.OS_Interface;
69 use System.Parameters;
70 use System.OS_Primitives;
71 use System.Task_Info;
73 ----------------
74 -- Local Data --
75 ----------------
77 -- The followings are logically constants, but need to be initialized
78 -- at run time.
80 Single_RTS_Lock : aliased RTS_Lock;
81 -- This is a lock to allow only one thread of control in the RTS at
82 -- a time; it is used to execute in mutual exclusion from all other tasks.
83 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
85 Environment_Task_Id : Task_Id;
86 -- A variable to hold Task_Id for the environment task
88 Unblocked_Signal_Mask : aliased sigset_t;
89 -- The set of signals that should be unblocked in all tasks
91 -- The followings are internal configuration constants needed
93 Next_Serial_Number : Task_Serial_Number := 100;
94 -- We start at 100 (reserve some special values for using in error checks)
96 Time_Slice_Val : Integer;
97 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
99 Dispatching_Policy : Character;
100 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
102 Locking_Policy : Character;
103 pragma Import (C, Locking_Policy, "__gl_locking_policy");
105 Foreign_Task_Elaborated : aliased Boolean := True;
106 -- Used to identified fake tasks (i.e., non-Ada Threads)
108 Use_Alternate_Stack : constant Boolean := Alternate_Stack_Size /= 0;
109 -- Whether to use an alternate signal stack for stack overflows
111 Abort_Handler_Installed : Boolean := False;
112 -- True if a handler for the abort signal is installed
114 Null_Thread_Id : constant pthread_t := pthread_t'Last;
115 -- Constant to indicate that the thread identifier has not yet been
116 -- initialized.
118 --------------------
119 -- Local Packages --
120 --------------------
122 package Specific is
124 procedure Initialize (Environment_Task : Task_Id);
125 pragma Inline (Initialize);
126 -- Initialize various data needed by this package
128 function Is_Valid_Task return Boolean;
129 pragma Inline (Is_Valid_Task);
130 -- Does executing thread have a TCB?
132 procedure Set (Self_Id : Task_Id);
133 pragma Inline (Set);
134 -- Set the self id for the current task
136 function Self return Task_Id;
137 pragma Inline (Self);
138 -- Return a pointer to the Ada Task Control Block of the calling task
140 end Specific;
142 package body Specific is separate;
143 -- The body of this package is target specific
145 ----------------------------------
146 -- ATCB allocation/deallocation --
147 ----------------------------------
149 package body ATCB_Allocation is separate;
150 -- The body of this package is shared across several targets
152 ---------------------------------
153 -- Support for foreign threads --
154 ---------------------------------
156 function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
157 -- Allocate and Initialize a new ATCB for the current Thread
159 function Register_Foreign_Thread
160 (Thread : Thread_Id) return Task_Id is separate;
162 -----------------------
163 -- Local Subprograms --
164 -----------------------
166 procedure Abort_Handler (signo : Signal);
168 -------------------
169 -- Abort_Handler --
170 -------------------
172 procedure Abort_Handler (signo : Signal) is
173 pragma Unreferenced (signo);
175 Self_Id : constant Task_Id := Self;
176 Result : Interfaces.C.int;
177 Old_Set : aliased sigset_t;
179 begin
180 -- It's not safe to raise an exception when using GCC ZCX mechanism.
181 -- Note that we still need to install a signal handler, since in some
182 -- cases (e.g. shutdown of the Server_Task in System.Interrupts) we
183 -- need to send the Abort signal to a task.
185 if ZCX_By_Default then
186 return;
187 end if;
189 if Self_Id.Deferral_Level = 0
190 and then Self_Id.Pending_ATC_Level < Self_Id.ATC_Nesting_Level
191 and then not Self_Id.Aborting
192 then
193 Self_Id.Aborting := True;
195 -- Make sure signals used for RTS internal purpose are unmasked
197 Result :=
198 pthread_sigmask
199 (SIG_UNBLOCK,
200 Unblocked_Signal_Mask'Access,
201 Old_Set'Access);
202 pragma Assert (Result = 0);
204 raise Standard'Abort_Signal;
205 end if;
206 end Abort_Handler;
208 --------------
209 -- Lock_RTS --
210 --------------
212 procedure Lock_RTS is
213 begin
214 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
215 end Lock_RTS;
217 ----------------
218 -- Unlock_RTS --
219 ----------------
221 procedure Unlock_RTS is
222 begin
223 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
224 end Unlock_RTS;
226 -----------------
227 -- Stack_Guard --
228 -----------------
230 -- The underlying thread system extends the memory (up to 2MB) when needed
232 procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
233 pragma Unreferenced (T);
234 pragma Unreferenced (On);
235 begin
236 null;
237 end Stack_Guard;
239 --------------------
240 -- Get_Thread_Id --
241 --------------------
243 function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
244 begin
245 return T.Common.LL.Thread;
246 end Get_Thread_Id;
248 ----------
249 -- Self --
250 ----------
252 function Self return Task_Id renames Specific.Self;
254 ---------------------
255 -- Initialize_Lock --
256 ---------------------
258 -- Note: mutexes and cond_variables needed per-task basis are initialized
259 -- in Initialize_TCB and the Storage_Error is handled. Other mutexes (such
260 -- as RTS_Lock, Memory_Lock...) used in RTS is initialized before any
261 -- status change of RTS. Therefore raising Storage_Error in the following
262 -- routines should be able to be handled safely.
264 procedure Initialize_Lock
265 (Prio : System.Any_Priority;
266 L : not null access Lock)
268 pragma Unreferenced (Prio);
270 begin
271 if Locking_Policy = 'R' then
272 declare
273 RWlock_Attr : aliased pthread_rwlockattr_t;
274 Result : Interfaces.C.int;
276 begin
277 -- Set the rwlock to prefer writer to avoid writers starvation
279 Result := pthread_rwlockattr_init (RWlock_Attr'Access);
280 pragma Assert (Result = 0);
282 Result := pthread_rwlockattr_setkind_np
283 (RWlock_Attr'Access,
284 PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
285 pragma Assert (Result = 0);
287 Result := pthread_rwlock_init (L.RW'Access, RWlock_Attr'Access);
289 pragma Assert (Result = 0 or else Result = ENOMEM);
291 if Result = ENOMEM then
292 raise Storage_Error with "Failed to allocate a lock";
293 end if;
294 end;
296 else
297 declare
298 Result : Interfaces.C.int;
300 begin
301 Result := pthread_mutex_init (L.WO'Access, null);
303 pragma Assert (Result = 0 or else Result = ENOMEM);
305 if Result = ENOMEM then
306 raise Storage_Error with "Failed to allocate a lock";
307 end if;
308 end;
309 end if;
310 end Initialize_Lock;
312 procedure Initialize_Lock
313 (L : not null access RTS_Lock;
314 Level : Lock_Level)
316 pragma Unreferenced (Level);
318 Result : Interfaces.C.int;
320 begin
321 Result := pthread_mutex_init (L, null);
323 pragma Assert (Result = 0 or else Result = ENOMEM);
325 if Result = ENOMEM then
326 raise Storage_Error;
327 end if;
328 end Initialize_Lock;
330 -------------------
331 -- Finalize_Lock --
332 -------------------
334 procedure Finalize_Lock (L : not null access Lock) is
335 Result : Interfaces.C.int;
336 begin
337 if Locking_Policy = 'R' then
338 Result := pthread_rwlock_destroy (L.RW'Access);
339 else
340 Result := pthread_mutex_destroy (L.WO'Access);
341 end if;
342 pragma Assert (Result = 0);
343 end Finalize_Lock;
345 procedure Finalize_Lock (L : not null access RTS_Lock) is
346 Result : Interfaces.C.int;
347 begin
348 Result := pthread_mutex_destroy (L);
349 pragma Assert (Result = 0);
350 end Finalize_Lock;
352 ----------------
353 -- Write_Lock --
354 ----------------
356 procedure Write_Lock
357 (L : not null access Lock;
358 Ceiling_Violation : out Boolean)
360 Result : Interfaces.C.int;
361 begin
362 if Locking_Policy = 'R' then
363 Result := pthread_rwlock_wrlock (L.RW'Access);
364 else
365 Result := pthread_mutex_lock (L.WO'Access);
366 end if;
368 Ceiling_Violation := Result = EINVAL;
370 -- Assume the cause of EINVAL is a priority ceiling violation
372 pragma Assert (Result = 0 or else Result = EINVAL);
373 end Write_Lock;
375 procedure Write_Lock
376 (L : not null access RTS_Lock;
377 Global_Lock : Boolean := False)
379 Result : Interfaces.C.int;
380 begin
381 if not Single_Lock or else Global_Lock then
382 Result := pthread_mutex_lock (L);
383 pragma Assert (Result = 0);
384 end if;
385 end Write_Lock;
387 procedure Write_Lock (T : Task_Id) is
388 Result : Interfaces.C.int;
389 begin
390 if not Single_Lock then
391 Result := pthread_mutex_lock (T.Common.LL.L'Access);
392 pragma Assert (Result = 0);
393 end if;
394 end Write_Lock;
396 ---------------
397 -- Read_Lock --
398 ---------------
400 procedure Read_Lock
401 (L : not null access Lock;
402 Ceiling_Violation : out Boolean)
404 Result : Interfaces.C.int;
405 begin
406 if Locking_Policy = 'R' then
407 Result := pthread_rwlock_rdlock (L.RW'Access);
408 else
409 Result := pthread_mutex_lock (L.WO'Access);
410 end if;
412 Ceiling_Violation := Result = EINVAL;
414 -- Assume the cause of EINVAL is a priority ceiling violation
416 pragma Assert (Result = 0 or else Result = EINVAL);
417 end Read_Lock;
419 ------------
420 -- Unlock --
421 ------------
423 procedure Unlock (L : not null access Lock) is
424 Result : Interfaces.C.int;
425 begin
426 if Locking_Policy = 'R' then
427 Result := pthread_rwlock_unlock (L.RW'Access);
428 else
429 Result := pthread_mutex_unlock (L.WO'Access);
430 end if;
431 pragma Assert (Result = 0);
432 end Unlock;
434 procedure Unlock
435 (L : not null access RTS_Lock;
436 Global_Lock : Boolean := False)
438 Result : Interfaces.C.int;
439 begin
440 if not Single_Lock or else Global_Lock then
441 Result := pthread_mutex_unlock (L);
442 pragma Assert (Result = 0);
443 end if;
444 end Unlock;
446 procedure Unlock (T : Task_Id) is
447 Result : Interfaces.C.int;
448 begin
449 if not Single_Lock then
450 Result := pthread_mutex_unlock (T.Common.LL.L'Access);
451 pragma Assert (Result = 0);
452 end if;
453 end Unlock;
455 -----------------
456 -- Set_Ceiling --
457 -----------------
459 -- Dynamic priority ceilings are not supported by the underlying system
461 procedure Set_Ceiling
462 (L : not null access Lock;
463 Prio : System.Any_Priority)
465 pragma Unreferenced (L, Prio);
466 begin
467 null;
468 end Set_Ceiling;
470 -----------
471 -- Sleep --
472 -----------
474 procedure Sleep
475 (Self_ID : Task_Id;
476 Reason : System.Tasking.Task_States)
478 pragma Unreferenced (Reason);
480 Result : Interfaces.C.int;
482 begin
483 pragma Assert (Self_ID = Self);
485 Result :=
486 pthread_cond_wait
487 (cond => Self_ID.Common.LL.CV'Access,
488 mutex => (if Single_Lock
489 then Single_RTS_Lock'Access
490 else Self_ID.Common.LL.L'Access));
492 -- EINTR is not considered a failure
494 pragma Assert (Result = 0 or else Result = EINTR);
495 end Sleep;
497 -----------------
498 -- Timed_Sleep --
499 -----------------
501 -- This is for use within the run-time system, so abort is
502 -- assumed to be already deferred, and the caller should be
503 -- holding its own ATCB lock.
505 procedure Timed_Sleep
506 (Self_ID : Task_Id;
507 Time : Duration;
508 Mode : ST.Delay_Modes;
509 Reason : System.Tasking.Task_States;
510 Timedout : out Boolean;
511 Yielded : out Boolean)
513 pragma Unreferenced (Reason);
515 Base_Time : constant Duration := Monotonic_Clock;
516 Check_Time : Duration := Base_Time;
517 Abs_Time : Duration;
518 Request : aliased timespec;
519 Result : Interfaces.C.int;
521 begin
522 Timedout := True;
523 Yielded := False;
525 Abs_Time :=
526 (if Mode = Relative
527 then Duration'Min (Time, Max_Sensible_Delay) + Check_Time
528 else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
530 if Abs_Time > Check_Time then
531 Request := To_Timespec (Abs_Time);
533 loop
534 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
536 Result :=
537 pthread_cond_timedwait
538 (cond => Self_ID.Common.LL.CV'Access,
539 mutex => (if Single_Lock
540 then Single_RTS_Lock'Access
541 else Self_ID.Common.LL.L'Access),
542 abstime => Request'Access);
544 Check_Time := Monotonic_Clock;
545 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
547 if Result = 0 or else Result = EINTR then
549 -- Somebody may have called Wakeup for us
551 Timedout := False;
552 exit;
553 end if;
555 pragma Assert (Result = ETIMEDOUT);
556 end loop;
557 end if;
558 end Timed_Sleep;
560 -----------------
561 -- Timed_Delay --
562 -----------------
564 -- This is for use in implementing delay statements, so we assume the
565 -- caller is abort-deferred but is holding no locks.
567 procedure Timed_Delay
568 (Self_ID : Task_Id;
569 Time : Duration;
570 Mode : ST.Delay_Modes)
572 Base_Time : constant Duration := Monotonic_Clock;
573 Check_Time : Duration := Base_Time;
574 Abs_Time : Duration;
575 Request : aliased timespec;
577 Result : Interfaces.C.int;
578 pragma Warnings (Off, Result);
580 begin
581 if Single_Lock then
582 Lock_RTS;
583 end if;
585 Write_Lock (Self_ID);
587 Abs_Time :=
588 (if Mode = Relative
589 then Time + Check_Time
590 else Duration'Min (Check_Time + Max_Sensible_Delay, Time));
592 if Abs_Time > Check_Time then
593 Request := To_Timespec (Abs_Time);
594 Self_ID.Common.State := Delay_Sleep;
596 loop
597 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
599 Result :=
600 pthread_cond_timedwait
601 (cond => Self_ID.Common.LL.CV'Access,
602 mutex => (if Single_Lock
603 then Single_RTS_Lock'Access
604 else Self_ID.Common.LL.L'Access),
605 abstime => Request'Access);
607 Check_Time := Monotonic_Clock;
608 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
610 pragma Assert (Result = 0 or else
611 Result = ETIMEDOUT or else
612 Result = EINTR);
613 end loop;
615 Self_ID.Common.State := Runnable;
616 end if;
618 Unlock (Self_ID);
620 if Single_Lock then
621 Unlock_RTS;
622 end if;
624 Result := sched_yield;
625 end Timed_Delay;
627 ---------------------
628 -- Monotonic_Clock --
629 ---------------------
631 function Monotonic_Clock return Duration is
632 use Interfaces;
634 procedure timeval_to_duration
635 (T : not null access timeval;
636 sec : not null access C.Extensions.long_long;
637 usec : not null access C.long);
638 pragma Import (C, timeval_to_duration, "__gnat_timeval_to_duration");
640 Micro : constant := 10**6;
641 sec : aliased C.Extensions.long_long;
642 usec : aliased C.long;
643 TV : aliased timeval;
644 Result : int;
646 function gettimeofday
647 (Tv : access timeval;
648 Tz : System.Address := System.Null_Address) return int;
649 pragma Import (C, gettimeofday, "gettimeofday");
651 begin
652 Result := gettimeofday (TV'Access, System.Null_Address);
653 pragma Assert (Result = 0);
654 timeval_to_duration (TV'Access, sec'Access, usec'Access);
655 return Duration (sec) + Duration (usec) / Micro;
656 end Monotonic_Clock;
658 -------------------
659 -- RT_Resolution --
660 -------------------
662 function RT_Resolution return Duration is
663 TS : aliased timespec;
664 Result : int;
666 begin
667 Result := clock_getres (OSC.CLOCK_REALTIME, TS'Unchecked_Access);
668 pragma Assert (Result = 0);
670 return To_Duration (TS);
671 end RT_Resolution;
673 ------------
674 -- Wakeup --
675 ------------
677 procedure Wakeup (T : Task_Id; Reason : System.Tasking.Task_States) is
678 pragma Unreferenced (Reason);
679 Result : Interfaces.C.int;
680 begin
681 Result := pthread_cond_signal (T.Common.LL.CV'Access);
682 pragma Assert (Result = 0);
683 end Wakeup;
685 -----------
686 -- Yield --
687 -----------
689 procedure Yield (Do_Yield : Boolean := True) is
690 Result : Interfaces.C.int;
691 pragma Unreferenced (Result);
692 begin
693 if Do_Yield then
694 Result := sched_yield;
695 end if;
696 end Yield;
698 ------------------
699 -- Set_Priority --
700 ------------------
702 procedure Set_Priority
703 (T : Task_Id;
704 Prio : System.Any_Priority;
705 Loss_Of_Inheritance : Boolean := False)
707 pragma Unreferenced (Loss_Of_Inheritance);
709 Result : Interfaces.C.int;
710 Param : aliased struct_sched_param;
712 function Get_Policy (Prio : System.Any_Priority) return Character;
713 pragma Import (C, Get_Policy, "__gnat_get_specific_dispatching");
714 -- Get priority specific dispatching policy
716 Priority_Specific_Policy : constant Character := Get_Policy (Prio);
717 -- Upper case first character of the policy name corresponding to the
718 -- task as set by a Priority_Specific_Dispatching pragma.
720 begin
721 T.Common.Current_Priority := Prio;
723 -- Priorities are 1 .. 99 on GNU/Linux, so we map 0 .. 98 to 1 .. 99
725 Param.sched_priority := Interfaces.C.int (Prio) + 1;
727 if Dispatching_Policy = 'R'
728 or else Priority_Specific_Policy = 'R'
729 or else Time_Slice_Val > 0
730 then
731 Result :=
732 pthread_setschedparam
733 (T.Common.LL.Thread, SCHED_RR, Param'Access);
735 elsif Dispatching_Policy = 'F'
736 or else Priority_Specific_Policy = 'F'
737 or else Time_Slice_Val = 0
738 then
739 Result :=
740 pthread_setschedparam
741 (T.Common.LL.Thread, SCHED_FIFO, Param'Access);
743 else
744 Param.sched_priority := 0;
745 Result :=
746 pthread_setschedparam
747 (T.Common.LL.Thread,
748 SCHED_OTHER, Param'Access);
749 end if;
751 pragma Assert (Result = 0 or else Result = EPERM);
752 end Set_Priority;
754 ------------------
755 -- Get_Priority --
756 ------------------
758 function Get_Priority (T : Task_Id) return System.Any_Priority is
759 begin
760 return T.Common.Current_Priority;
761 end Get_Priority;
763 ----------------
764 -- Enter_Task --
765 ----------------
767 procedure Enter_Task (Self_ID : Task_Id) is
768 begin
769 if Self_ID.Common.Task_Info /= null
770 and then Self_ID.Common.Task_Info.CPU_Affinity = No_CPU
771 then
772 raise Invalid_CPU_Number;
773 end if;
775 Self_ID.Common.LL.Thread := pthread_self;
776 Self_ID.Common.LL.LWP := lwp_self;
778 if Self_ID.Common.Task_Image_Len > 0 then
779 declare
780 Task_Name : String (1 .. Parameters.Max_Task_Image_Length + 1);
781 Result : int;
783 begin
784 -- Set thread name to ease debugging
786 Task_Name (1 .. Self_ID.Common.Task_Image_Len) :=
787 Self_ID.Common.Task_Image (1 .. Self_ID.Common.Task_Image_Len);
788 Task_Name (Self_ID.Common.Task_Image_Len + 1) := ASCII.NUL;
790 Result := prctl (PR_SET_NAME, unsigned_long (Task_Name'Address));
791 pragma Assert (Result = 0);
792 end;
793 end if;
795 Specific.Set (Self_ID);
797 if Use_Alternate_Stack
798 and then Self_ID.Common.Task_Alternate_Stack /= Null_Address
799 then
800 declare
801 Stack : aliased stack_t;
802 Result : Interfaces.C.int;
803 begin
804 Stack.ss_sp := Self_ID.Common.Task_Alternate_Stack;
805 Stack.ss_size := Alternate_Stack_Size;
806 Stack.ss_flags := 0;
807 Result := sigaltstack (Stack'Access, null);
808 pragma Assert (Result = 0);
809 end;
810 end if;
811 end Enter_Task;
813 -------------------
814 -- Is_Valid_Task --
815 -------------------
817 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
819 -----------------------------
820 -- Register_Foreign_Thread --
821 -----------------------------
823 function Register_Foreign_Thread return Task_Id is
824 begin
825 if Is_Valid_Task then
826 return Self;
827 else
828 return Register_Foreign_Thread (pthread_self);
829 end if;
830 end Register_Foreign_Thread;
832 --------------------
833 -- Initialize_TCB --
834 --------------------
836 procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
837 Cond_Attr : aliased pthread_condattr_t;
838 Result : Interfaces.C.int;
840 begin
841 -- Give the task a unique serial number
843 Self_ID.Serial_Number := Next_Serial_Number;
844 Next_Serial_Number := Next_Serial_Number + 1;
845 pragma Assert (Next_Serial_Number /= 0);
847 Self_ID.Common.LL.Thread := Null_Thread_Id;
849 if not Single_Lock then
850 Result :=
851 pthread_mutex_init (Self_ID.Common.LL.L'Access, null);
852 pragma Assert (Result = 0 or else Result = ENOMEM);
854 if Result /= 0 then
855 Succeeded := False;
856 return;
857 end if;
858 end if;
860 Result := pthread_condattr_init (Cond_Attr'Access);
861 pragma Assert (Result = 0);
863 Result :=
864 pthread_cond_init (Self_ID.Common.LL.CV'Access, Cond_Attr'Access);
865 pragma Assert (Result = 0 or else Result = ENOMEM);
867 if Result = 0 then
868 Succeeded := True;
869 else
870 if not Single_Lock then
871 Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access);
872 pragma Assert (Result = 0);
873 end if;
875 Succeeded := False;
876 end if;
877 end Initialize_TCB;
879 -----------------
880 -- Create_Task --
881 -----------------
883 procedure Create_Task
884 (T : Task_Id;
885 Wrapper : System.Address;
886 Stack_Size : System.Parameters.Size_Type;
887 Priority : System.Any_Priority;
888 Succeeded : out Boolean)
890 Attributes : aliased pthread_attr_t;
891 Adjusted_Stack_Size : Interfaces.C.size_t;
892 Result : Interfaces.C.int;
894 use type System.Multiprocessors.CPU_Range;
896 begin
897 -- Check whether both Dispatching_Domain and CPU are specified for
898 -- the task, and the CPU value is not contained within the range of
899 -- processors for the domain.
901 if T.Common.Domain /= null
902 and then T.Common.Base_CPU /= System.Multiprocessors.Not_A_Specific_CPU
903 and then
904 (T.Common.Base_CPU not in T.Common.Domain'Range
905 or else not T.Common.Domain (T.Common.Base_CPU))
906 then
907 Succeeded := False;
908 return;
909 end if;
911 Adjusted_Stack_Size :=
912 Interfaces.C.size_t (Stack_Size + Alternate_Stack_Size);
914 Result := pthread_attr_init (Attributes'Access);
915 pragma Assert (Result = 0 or else Result = ENOMEM);
917 if Result /= 0 then
918 Succeeded := False;
919 return;
920 end if;
922 Result :=
923 pthread_attr_setstacksize (Attributes'Access, Adjusted_Stack_Size);
924 pragma Assert (Result = 0);
926 Result :=
927 pthread_attr_setdetachstate
928 (Attributes'Access, PTHREAD_CREATE_DETACHED);
929 pragma Assert (Result = 0);
931 -- Set the required attributes for the creation of the thread
933 -- Note: Previously, we called pthread_setaffinity_np (after thread
934 -- creation but before thread activation) to set the affinity but it was
935 -- not behaving as expected. Setting the required attributes for the
936 -- creation of the thread works correctly and it is more appropriate.
938 -- Do nothing if required support not provided by the operating system
940 if pthread_attr_setaffinity_np'Address = System.Null_Address then
941 null;
943 -- Support is available
945 elsif T.Common.Base_CPU /= System.Multiprocessors.Not_A_Specific_CPU then
946 declare
947 CPUs : constant size_t :=
948 Interfaces.C.size_t
949 (System.Multiprocessors.Number_Of_CPUs);
950 CPU_Set : constant cpu_set_t_ptr := CPU_ALLOC (CPUs);
951 Size : constant size_t := CPU_ALLOC_SIZE (CPUs);
953 begin
954 CPU_ZERO (Size, CPU_Set);
955 System.OS_Interface.CPU_SET
956 (int (T.Common.Base_CPU), Size, CPU_Set);
957 Result :=
958 pthread_attr_setaffinity_np (Attributes'Access, Size, CPU_Set);
959 pragma Assert (Result = 0);
961 CPU_FREE (CPU_Set);
962 end;
964 -- Handle Task_Info
966 elsif T.Common.Task_Info /= null then
967 Result :=
968 pthread_attr_setaffinity_np
969 (Attributes'Access,
970 CPU_SETSIZE / 8,
971 T.Common.Task_Info.CPU_Affinity'Access);
972 pragma Assert (Result = 0);
974 -- Handle dispatching domains
976 -- To avoid changing CPU affinities when not needed, we set the
977 -- affinity only when assigning to a domain other than the default
978 -- one, or when the default one has been modified.
980 elsif T.Common.Domain /= null and then
981 (T.Common.Domain /= ST.System_Domain
982 or else T.Common.Domain.all /=
983 (Multiprocessors.CPU'First ..
984 Multiprocessors.Number_Of_CPUs => True))
985 then
986 declare
987 CPUs : constant size_t :=
988 Interfaces.C.size_t
989 (System.Multiprocessors.Number_Of_CPUs);
990 CPU_Set : constant cpu_set_t_ptr := CPU_ALLOC (CPUs);
991 Size : constant size_t := CPU_ALLOC_SIZE (CPUs);
993 begin
994 CPU_ZERO (Size, CPU_Set);
996 -- Set the affinity to all the processors belonging to the
997 -- dispatching domain.
999 for Proc in T.Common.Domain'Range loop
1000 if T.Common.Domain (Proc) then
1001 System.OS_Interface.CPU_SET (int (Proc), Size, CPU_Set);
1002 end if;
1003 end loop;
1005 Result :=
1006 pthread_attr_setaffinity_np (Attributes'Access, Size, CPU_Set);
1007 pragma Assert (Result = 0);
1009 CPU_FREE (CPU_Set);
1010 end;
1011 end if;
1013 -- Since the initial signal mask of a thread is inherited from the
1014 -- creator, and the Environment task has all its signals masked, we
1015 -- do not need to manipulate caller's signal mask at this point.
1016 -- All tasks in RTS will have All_Tasks_Mask initially.
1018 -- Note: the use of Unrestricted_Access in the following call is needed
1019 -- because otherwise we have an error of getting a access-to-volatile
1020 -- value which points to a non-volatile object. But in this case it is
1021 -- safe to do this, since we know we have no problems with aliasing and
1022 -- Unrestricted_Access bypasses this check.
1024 Result :=
1025 pthread_create
1026 (T.Common.LL.Thread'Unrestricted_Access,
1027 Attributes'Access,
1028 Thread_Body_Access (Wrapper),
1029 To_Address (T));
1031 pragma Assert
1032 (Result = 0 or else Result = EAGAIN or else Result = ENOMEM);
1034 if Result /= 0 then
1035 Succeeded := False;
1036 Result := pthread_attr_destroy (Attributes'Access);
1037 pragma Assert (Result = 0);
1038 return;
1039 end if;
1041 Succeeded := True;
1043 Result := pthread_attr_destroy (Attributes'Access);
1044 pragma Assert (Result = 0);
1046 Set_Priority (T, Priority);
1047 end Create_Task;
1049 ------------------
1050 -- Finalize_TCB --
1051 ------------------
1053 procedure Finalize_TCB (T : Task_Id) is
1054 Result : Interfaces.C.int;
1056 begin
1057 if not Single_Lock then
1058 Result := pthread_mutex_destroy (T.Common.LL.L'Access);
1059 pragma Assert (Result = 0);
1060 end if;
1062 Result := pthread_cond_destroy (T.Common.LL.CV'Access);
1063 pragma Assert (Result = 0);
1065 if T.Known_Tasks_Index /= -1 then
1066 Known_Tasks (T.Known_Tasks_Index) := null;
1067 end if;
1069 SC.Invalidate_Stack_Cache (T.Common.Compiler_Data.Pri_Stack_Info'Access);
1071 ATCB_Allocation.Free_ATCB (T);
1072 end Finalize_TCB;
1074 ---------------
1075 -- Exit_Task --
1076 ---------------
1078 procedure Exit_Task is
1079 begin
1080 Specific.Set (null);
1081 end Exit_Task;
1083 ----------------
1084 -- Abort_Task --
1085 ----------------
1087 procedure Abort_Task (T : Task_Id) is
1088 Result : Interfaces.C.int;
1090 ESRCH : constant := 3; -- No such process
1091 -- It can happen that T has already vanished, in which case pthread_kill
1092 -- returns ESRCH, so we don't consider that to be an error.
1094 begin
1095 if Abort_Handler_Installed then
1096 Result :=
1097 pthread_kill
1098 (T.Common.LL.Thread,
1099 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1100 pragma Assert (Result = 0 or else Result = ESRCH);
1101 end if;
1102 end Abort_Task;
1104 ----------------
1105 -- Initialize --
1106 ----------------
1108 procedure Initialize (S : in out Suspension_Object) is
1109 Result : Interfaces.C.int;
1111 begin
1112 -- Initialize internal state (always to False (RM D.10(6)))
1114 S.State := False;
1115 S.Waiting := False;
1117 -- Initialize internal mutex
1119 Result := pthread_mutex_init (S.L'Access, null);
1121 pragma Assert (Result = 0 or else Result = ENOMEM);
1123 if Result = ENOMEM then
1124 raise Storage_Error;
1125 end if;
1127 -- Initialize internal condition variable
1129 Result := pthread_cond_init (S.CV'Access, null);
1131 pragma Assert (Result = 0 or else Result = ENOMEM);
1133 if Result /= 0 then
1134 Result := pthread_mutex_destroy (S.L'Access);
1135 pragma Assert (Result = 0);
1137 if Result = ENOMEM then
1138 raise Storage_Error;
1139 end if;
1140 end if;
1141 end Initialize;
1143 --------------
1144 -- Finalize --
1145 --------------
1147 procedure Finalize (S : in out Suspension_Object) is
1148 Result : Interfaces.C.int;
1150 begin
1151 -- Destroy internal mutex
1153 Result := pthread_mutex_destroy (S.L'Access);
1154 pragma Assert (Result = 0);
1156 -- Destroy internal condition variable
1158 Result := pthread_cond_destroy (S.CV'Access);
1159 pragma Assert (Result = 0);
1160 end Finalize;
1162 -------------------
1163 -- Current_State --
1164 -------------------
1166 function Current_State (S : Suspension_Object) return Boolean is
1167 begin
1168 -- We do not want to use lock on this read operation. State is marked
1169 -- as Atomic so that we ensure that the value retrieved is correct.
1171 return S.State;
1172 end Current_State;
1174 ---------------
1175 -- Set_False --
1176 ---------------
1178 procedure Set_False (S : in out Suspension_Object) is
1179 Result : Interfaces.C.int;
1181 begin
1182 SSL.Abort_Defer.all;
1184 Result := pthread_mutex_lock (S.L'Access);
1185 pragma Assert (Result = 0);
1187 S.State := False;
1189 Result := pthread_mutex_unlock (S.L'Access);
1190 pragma Assert (Result = 0);
1192 SSL.Abort_Undefer.all;
1193 end Set_False;
1195 --------------
1196 -- Set_True --
1197 --------------
1199 procedure Set_True (S : in out Suspension_Object) is
1200 Result : Interfaces.C.int;
1202 begin
1203 SSL.Abort_Defer.all;
1205 Result := pthread_mutex_lock (S.L'Access);
1206 pragma Assert (Result = 0);
1208 -- If there is already a task waiting on this suspension object then
1209 -- we resume it, leaving the state of the suspension object to False,
1210 -- as it is specified in ARM D.10 par. 9. Otherwise, it just leaves
1211 -- the state to True.
1213 if S.Waiting then
1214 S.Waiting := False;
1215 S.State := False;
1217 Result := pthread_cond_signal (S.CV'Access);
1218 pragma Assert (Result = 0);
1220 else
1221 S.State := True;
1222 end if;
1224 Result := pthread_mutex_unlock (S.L'Access);
1225 pragma Assert (Result = 0);
1227 SSL.Abort_Undefer.all;
1228 end Set_True;
1230 ------------------------
1231 -- Suspend_Until_True --
1232 ------------------------
1234 procedure Suspend_Until_True (S : in out Suspension_Object) is
1235 Result : Interfaces.C.int;
1237 begin
1238 SSL.Abort_Defer.all;
1240 Result := pthread_mutex_lock (S.L'Access);
1241 pragma Assert (Result = 0);
1243 if S.Waiting then
1245 -- Program_Error must be raised upon calling Suspend_Until_True
1246 -- if another task is already waiting on that suspension object
1247 -- (RM D.10(10)).
1249 Result := pthread_mutex_unlock (S.L'Access);
1250 pragma Assert (Result = 0);
1252 SSL.Abort_Undefer.all;
1254 raise Program_Error;
1256 else
1257 -- Suspend the task if the state is False. Otherwise, the task
1258 -- continues its execution, and the state of the suspension object
1259 -- is set to False (ARM D.10 par. 9).
1261 if S.State then
1262 S.State := False;
1263 else
1264 S.Waiting := True;
1266 loop
1267 -- Loop in case pthread_cond_wait returns earlier than expected
1268 -- (e.g. in case of EINTR caused by a signal). This should not
1269 -- happen with the current Linux implementation of pthread, but
1270 -- POSIX does not guarantee it so this may change in future.
1272 Result := pthread_cond_wait (S.CV'Access, S.L'Access);
1273 pragma Assert (Result = 0 or else Result = EINTR);
1275 exit when not S.Waiting;
1276 end loop;
1277 end if;
1279 Result := pthread_mutex_unlock (S.L'Access);
1280 pragma Assert (Result = 0);
1282 SSL.Abort_Undefer.all;
1283 end if;
1284 end Suspend_Until_True;
1286 ----------------
1287 -- Check_Exit --
1288 ----------------
1290 -- Dummy version
1292 function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1293 pragma Unreferenced (Self_ID);
1294 begin
1295 return True;
1296 end Check_Exit;
1298 --------------------
1299 -- Check_No_Locks --
1300 --------------------
1302 function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1303 pragma Unreferenced (Self_ID);
1304 begin
1305 return True;
1306 end Check_No_Locks;
1308 ----------------------
1309 -- Environment_Task --
1310 ----------------------
1312 function Environment_Task return Task_Id is
1313 begin
1314 return Environment_Task_Id;
1315 end Environment_Task;
1317 ------------------
1318 -- Suspend_Task --
1319 ------------------
1321 function Suspend_Task
1322 (T : ST.Task_Id;
1323 Thread_Self : Thread_Id) return Boolean
1325 begin
1326 if T.Common.LL.Thread /= Thread_Self then
1327 return pthread_kill (T.Common.LL.Thread, SIGSTOP) = 0;
1328 else
1329 return True;
1330 end if;
1331 end Suspend_Task;
1333 -----------------
1334 -- Resume_Task --
1335 -----------------
1337 function Resume_Task
1338 (T : ST.Task_Id;
1339 Thread_Self : Thread_Id) return Boolean
1341 begin
1342 if T.Common.LL.Thread /= Thread_Self then
1343 return pthread_kill (T.Common.LL.Thread, SIGCONT) = 0;
1344 else
1345 return True;
1346 end if;
1347 end Resume_Task;
1349 --------------------
1350 -- Stop_All_Tasks --
1351 --------------------
1353 procedure Stop_All_Tasks is
1354 begin
1355 null;
1356 end Stop_All_Tasks;
1358 ---------------
1359 -- Stop_Task --
1360 ---------------
1362 function Stop_Task (T : ST.Task_Id) return Boolean is
1363 pragma Unreferenced (T);
1364 begin
1365 return False;
1366 end Stop_Task;
1368 -------------------
1369 -- Continue_Task --
1370 -------------------
1372 function Continue_Task (T : ST.Task_Id) return Boolean is
1373 pragma Unreferenced (T);
1374 begin
1375 return False;
1376 end Continue_Task;
1378 ----------------
1379 -- Initialize --
1380 ----------------
1382 procedure Initialize (Environment_Task : Task_Id) is
1383 act : aliased struct_sigaction;
1384 old_act : aliased struct_sigaction;
1385 Tmp_Set : aliased sigset_t;
1386 Result : Interfaces.C.int;
1387 -- Whether to use an alternate signal stack for stack overflows
1389 function State
1390 (Int : System.Interrupt_Management.Interrupt_ID) return Character;
1391 pragma Import (C, State, "__gnat_get_interrupt_state");
1392 -- Get interrupt state. Defined in a-init.c
1393 -- The input argument is the interrupt number,
1394 -- and the result is one of the following:
1396 Default : constant Character := 's';
1397 -- 'n' this interrupt not set by any Interrupt_State pragma
1398 -- 'u' Interrupt_State pragma set state to User
1399 -- 'r' Interrupt_State pragma set state to Runtime
1400 -- 's' Interrupt_State pragma set state to System (use "default"
1401 -- system handler)
1403 use type System.Multiprocessors.CPU_Range;
1405 begin
1406 Environment_Task_Id := Environment_Task;
1408 Interrupt_Management.Initialize;
1410 -- Prepare the set of signals that should be unblocked in all tasks
1412 Result := sigemptyset (Unblocked_Signal_Mask'Access);
1413 pragma Assert (Result = 0);
1415 for J in Interrupt_Management.Interrupt_ID loop
1416 if System.Interrupt_Management.Keep_Unmasked (J) then
1417 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1418 pragma Assert (Result = 0);
1419 end if;
1420 end loop;
1422 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1424 -- Initialize the global RTS lock
1426 Specific.Initialize (Environment_Task);
1428 if Use_Alternate_Stack then
1429 Environment_Task.Common.Task_Alternate_Stack :=
1430 Alternate_Stack'Address;
1431 end if;
1433 -- Make environment task known here because it doesn't go through
1434 -- Activate_Tasks, which does it for all other tasks.
1436 Known_Tasks (Known_Tasks'First) := Environment_Task;
1437 Environment_Task.Known_Tasks_Index := Known_Tasks'First;
1439 Enter_Task (Environment_Task);
1441 if State
1442 (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
1443 then
1444 act.sa_flags := 0;
1445 act.sa_handler := Abort_Handler'Address;
1447 Result := sigemptyset (Tmp_Set'Access);
1448 pragma Assert (Result = 0);
1449 act.sa_mask := Tmp_Set;
1451 Result :=
1452 sigaction
1453 (Signal (Interrupt_Management.Abort_Task_Interrupt),
1454 act'Unchecked_Access,
1455 old_act'Unchecked_Access);
1456 pragma Assert (Result = 0);
1457 Abort_Handler_Installed := True;
1458 end if;
1460 -- pragma CPU and dispatching domains for the environment task
1462 Set_Task_Affinity (Environment_Task);
1463 end Initialize;
1465 -----------------------
1466 -- Set_Task_Affinity --
1467 -----------------------
1469 procedure Set_Task_Affinity (T : ST.Task_Id) is
1470 use type System.Multiprocessors.CPU_Range;
1472 begin
1473 -- Do nothing if there is no support for setting affinities or the
1474 -- underlying thread has not yet been created. If the thread has not
1475 -- yet been created then the proper affinity will be set during its
1476 -- creation.
1478 if pthread_setaffinity_np'Address /= System.Null_Address
1479 and then T.Common.LL.Thread /= Null_Thread_Id
1480 then
1481 declare
1482 CPUs : constant size_t :=
1483 Interfaces.C.size_t
1484 (System.Multiprocessors.Number_Of_CPUs);
1485 CPU_Set : cpu_set_t_ptr := null;
1486 Size : constant size_t := CPU_ALLOC_SIZE (CPUs);
1488 Result : Interfaces.C.int;
1490 begin
1491 -- We look at the specific CPU (Base_CPU) first, then at the
1492 -- Task_Info field, and finally at the assigned dispatching
1493 -- domain, if any.
1495 if T.Common.Base_CPU /= Multiprocessors.Not_A_Specific_CPU then
1497 -- Set the affinity to an unique CPU
1499 CPU_Set := CPU_ALLOC (CPUs);
1500 System.OS_Interface.CPU_ZERO (Size, CPU_Set);
1501 System.OS_Interface.CPU_SET
1502 (int (T.Common.Base_CPU), Size, CPU_Set);
1504 -- Handle Task_Info
1506 elsif T.Common.Task_Info /= null then
1507 CPU_Set := T.Common.Task_Info.CPU_Affinity'Access;
1509 -- Handle dispatching domains
1511 elsif T.Common.Domain /= null and then
1512 (T.Common.Domain /= ST.System_Domain
1513 or else T.Common.Domain.all /=
1514 (Multiprocessors.CPU'First ..
1515 Multiprocessors.Number_Of_CPUs => True))
1516 then
1517 -- Set the affinity to all the processors belonging to the
1518 -- dispatching domain. To avoid changing CPU affinities when
1519 -- not needed, we set the affinity only when assigning to a
1520 -- domain other than the default one, or when the default one
1521 -- has been modified.
1523 CPU_Set := CPU_ALLOC (CPUs);
1524 System.OS_Interface.CPU_ZERO (Size, CPU_Set);
1526 for Proc in T.Common.Domain'Range loop
1527 if T.Common.Domain (Proc) then
1528 System.OS_Interface.CPU_SET (int (Proc), Size, CPU_Set);
1529 end if;
1530 end loop;
1531 end if;
1533 -- We set the new affinity if needed. Otherwise, the new task
1534 -- will inherit its creator's CPU affinity mask (according to
1535 -- the documentation of pthread_setaffinity_np), which is
1536 -- consistent with Ada's required semantics.
1538 if CPU_Set /= null then
1539 Result :=
1540 pthread_setaffinity_np (T.Common.LL.Thread, Size, CPU_Set);
1541 pragma Assert (Result = 0);
1543 CPU_FREE (CPU_Set);
1544 end if;
1545 end;
1546 end if;
1547 end Set_Task_Affinity;
1549 end System.Task_Primitives.Operations;