PR middle-end/61455
[official-gcc.git] / gcc / ada / s-taprop-posix.adb
blob8aff965d53ea18b5d1453019cb2bfe9c94539fd9
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT 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-2013, 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 POSIX-like version of this package
34 -- This package contains all the GNULL primitives that interface directly with
35 -- the underlying OS.
37 -- Note: this file can only be used for POSIX compliant systems that implement
38 -- SCHED_FIFO and Ceiling Locking correctly.
40 -- For configurations where SCHED_FIFO and priority ceiling are not a
41 -- requirement, this file can also be used (e.g AiX threads)
43 pragma Polling (Off);
44 -- Turn off polling, we do not want ATC polling to take place during tasking
45 -- operations. It causes infinite loops and other problems.
47 with Ada.Unchecked_Conversion;
49 with Interfaces.C;
51 with System.Tasking.Debug;
52 with System.Interrupt_Management;
53 with System.OS_Constants;
54 with System.OS_Primitives;
55 with System.Task_Info;
57 with System.Soft_Links;
58 -- We use System.Soft_Links instead of System.Tasking.Initialization
59 -- because the later is a higher level package that we shouldn't depend on.
60 -- For example when using the restricted run time, it is replaced by
61 -- System.Tasking.Restricted.Stages.
63 package body System.Task_Primitives.Operations is
65 package OSC renames System.OS_Constants;
66 package SSL renames System.Soft_Links;
68 use System.Tasking.Debug;
69 use System.Tasking;
70 use Interfaces.C;
71 use System.OS_Interface;
72 use System.Parameters;
73 use System.OS_Primitives;
75 ----------------
76 -- Local Data --
77 ----------------
79 -- The followings are logically constants, but need to be initialized
80 -- at run time.
82 Single_RTS_Lock : aliased RTS_Lock;
83 -- This is a lock to allow only one thread of control in the RTS at
84 -- a time; it is used to execute in mutual exclusion from all other tasks.
85 -- Used mainly in Single_Lock mode, but also to protect All_Tasks_List
87 Environment_Task_Id : Task_Id;
88 -- A variable to hold Task_Id for the environment task
90 Locking_Policy : Character;
91 pragma Import (C, Locking_Policy, "__gl_locking_policy");
92 -- Value of the pragma Locking_Policy:
93 -- 'C' for Ceiling_Locking
94 -- 'I' for Inherit_Locking
95 -- ' ' for none.
97 Unblocked_Signal_Mask : aliased sigset_t;
98 -- The set of signals that should unblocked in all tasks
100 -- The followings are internal configuration constants needed
102 Next_Serial_Number : Task_Serial_Number := 100;
103 -- We start at 100, to reserve some special values for
104 -- using in error checking.
106 Time_Slice_Val : Integer;
107 pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
109 Dispatching_Policy : Character;
110 pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
112 Foreign_Task_Elaborated : aliased Boolean := True;
113 -- Used to identified fake tasks (i.e., non-Ada Threads)
115 Use_Alternate_Stack : constant Boolean := Alternate_Stack_Size /= 0;
116 -- Whether to use an alternate signal stack for stack overflows
118 Abort_Handler_Installed : Boolean := False;
119 -- True if a handler for the abort signal is installed
121 --------------------
122 -- Local Packages --
123 --------------------
125 package Specific is
127 procedure Initialize (Environment_Task : Task_Id);
128 pragma Inline (Initialize);
129 -- Initialize various data needed by this package
131 function Is_Valid_Task return Boolean;
132 pragma Inline (Is_Valid_Task);
133 -- Does executing thread have a TCB?
135 procedure Set (Self_Id : Task_Id);
136 pragma Inline (Set);
137 -- Set the self id for the current task
139 function Self return Task_Id;
140 pragma Inline (Self);
141 -- Return a pointer to the Ada Task Control Block of the calling task
143 end Specific;
145 package body Specific is separate;
146 -- The body of this package is target specific
148 ----------------------------------
149 -- ATCB allocation/deallocation --
150 ----------------------------------
152 package body ATCB_Allocation is separate;
153 -- The body of this package is shared across several targets
155 ---------------------------------
156 -- Support for foreign threads --
157 ---------------------------------
159 function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id;
160 -- Allocate and Initialize a new ATCB for the current Thread
162 function Register_Foreign_Thread
163 (Thread : Thread_Id) return Task_Id is separate;
165 -----------------------
166 -- Local Subprograms --
167 -----------------------
169 procedure Abort_Handler (Sig : Signal);
170 -- Signal handler used to implement asynchronous abort.
171 -- See also comment before body, below.
173 function To_Address is
174 new Ada.Unchecked_Conversion (Task_Id, System.Address);
176 function GNAT_pthread_condattr_setup
177 (attr : access pthread_condattr_t) return int;
178 pragma Import (C,
179 GNAT_pthread_condattr_setup, "__gnat_pthread_condattr_setup");
181 procedure Compute_Deadline
182 (Time : Duration;
183 Mode : ST.Delay_Modes;
184 Check_Time : out Duration;
185 Abs_Time : out Duration;
186 Rel_Time : out Duration);
187 -- Helper for Timed_Sleep and Timed_Delay: given a deadline specified by
188 -- Time and Mode, compute the current clock reading (Check_Time), and the
189 -- target absolute and relative clock readings (Abs_Time, Rel_Time). The
190 -- epoch for Time depends on Mode; the epoch for Check_Time and Abs_Time
191 -- is always that of CLOCK_RT_Ada.
193 -------------------
194 -- Abort_Handler --
195 -------------------
197 -- Target-dependent binding of inter-thread Abort signal to the raising of
198 -- the Abort_Signal exception.
200 -- The technical issues and alternatives here are essentially the
201 -- same as for raising exceptions in response to other signals
202 -- (e.g. Storage_Error). See code and comments in the package body
203 -- System.Interrupt_Management.
205 -- Some implementations may not allow an exception to be propagated out of
206 -- a handler, and others might leave the signal or interrupt that invoked
207 -- this handler masked after the exceptional return to the application
208 -- code.
210 -- GNAT exceptions are originally implemented using setjmp()/longjmp(). On
211 -- most UNIX systems, this will allow transfer out of a signal handler,
212 -- which is usually the only mechanism available for implementing
213 -- asynchronous handlers of this kind. However, some systems do not
214 -- restore the signal mask on longjmp(), leaving the abort signal masked.
216 procedure Abort_Handler (Sig : Signal) is
217 pragma Unreferenced (Sig);
219 T : constant Task_Id := Self;
220 Old_Set : aliased sigset_t;
222 Result : Interfaces.C.int;
223 pragma Warnings (Off, Result);
225 begin
226 -- It's not safe to raise an exception when using GCC ZCX mechanism.
227 -- Note that we still need to install a signal handler, since in some
228 -- cases (e.g. shutdown of the Server_Task in System.Interrupts) we
229 -- need to send the Abort signal to a task.
231 if ZCX_By_Default then
232 return;
233 end if;
235 if T.Deferral_Level = 0
236 and then T.Pending_ATC_Level < T.ATC_Nesting_Level and then
237 not T.Aborting
238 then
239 T.Aborting := True;
241 -- Make sure signals used for RTS internal purpose are unmasked
243 Result := pthread_sigmask (SIG_UNBLOCK,
244 Unblocked_Signal_Mask'Access, Old_Set'Access);
245 pragma Assert (Result = 0);
247 raise Standard'Abort_Signal;
248 end if;
249 end Abort_Handler;
251 ----------------------
252 -- Compute_Deadline --
253 ----------------------
255 procedure Compute_Deadline
256 (Time : Duration;
257 Mode : ST.Delay_Modes;
258 Check_Time : out Duration;
259 Abs_Time : out Duration;
260 Rel_Time : out Duration)
262 begin
263 Check_Time := Monotonic_Clock;
265 -- Relative deadline
267 if Mode = Relative then
268 Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
270 if Relative_Timed_Wait then
271 Rel_Time := Duration'Min (Max_Sensible_Delay, Time);
272 end if;
274 pragma Warnings (Off);
275 -- Comparison "OSC.CLOCK_RT_Ada = OSC.CLOCK_REALTIME" is compile
276 -- time known.
278 -- Absolute deadline specified using the tasking clock (CLOCK_RT_Ada)
280 elsif Mode = Absolute_RT
281 or else OSC.CLOCK_RT_Ada = OSC.CLOCK_REALTIME
282 then
283 pragma Warnings (On);
284 Abs_Time := Duration'Min (Check_Time + Max_Sensible_Delay, Time);
286 if Relative_Timed_Wait then
287 Rel_Time := Duration'Min (Max_Sensible_Delay, Time - Check_Time);
288 end if;
290 -- Absolute deadline specified using the calendar clock, in the
291 -- case where it is not the same as the tasking clock: compensate for
292 -- difference between clock epochs (Base_Time - Base_Cal_Time).
294 else
295 declare
296 Cal_Check_Time : constant Duration :=
297 OS_Primitives.Monotonic_Clock;
298 RT_Time : constant Duration :=
299 Time + Check_Time - Cal_Check_Time;
300 begin
301 Abs_Time :=
302 Duration'Min (Check_Time + Max_Sensible_Delay, RT_Time);
304 if Relative_Timed_Wait then
305 Rel_Time :=
306 Duration'Min (Max_Sensible_Delay, RT_Time - Check_Time);
307 end if;
308 end;
309 end if;
310 end Compute_Deadline;
312 -----------------
313 -- Stack_Guard --
314 -----------------
316 procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
317 Stack_Base : constant Address := Get_Stack_Base (T.Common.LL.Thread);
318 Guard_Page_Address : Address;
320 Res : Interfaces.C.int;
322 begin
323 if Stack_Base_Available then
325 -- Compute the guard page address
327 Guard_Page_Address :=
328 Stack_Base - (Stack_Base mod Get_Page_Size) + Get_Page_Size;
330 Res :=
331 mprotect (Guard_Page_Address, Get_Page_Size,
332 prot => (if On then PROT_ON else PROT_OFF));
333 pragma Assert (Res = 0);
334 end if;
335 end Stack_Guard;
337 --------------------
338 -- Get_Thread_Id --
339 --------------------
341 function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
342 begin
343 return T.Common.LL.Thread;
344 end Get_Thread_Id;
346 ----------
347 -- Self --
348 ----------
350 function Self return Task_Id renames Specific.Self;
352 ---------------------
353 -- Initialize_Lock --
354 ---------------------
356 -- Note: mutexes and cond_variables needed per-task basis are
357 -- initialized in Initialize_TCB and the Storage_Error is
358 -- handled. Other mutexes (such as RTS_Lock, Memory_Lock...)
359 -- used in RTS is initialized before any status change of RTS.
360 -- Therefore raising Storage_Error in the following routines
361 -- should be able to be handled safely.
363 procedure Initialize_Lock
364 (Prio : System.Any_Priority;
365 L : not null access Lock)
367 Attributes : aliased pthread_mutexattr_t;
368 Result : Interfaces.C.int;
370 begin
371 Result := pthread_mutexattr_init (Attributes'Access);
372 pragma Assert (Result = 0 or else Result = ENOMEM);
374 if Result = ENOMEM then
375 raise Storage_Error;
376 end if;
378 if Locking_Policy = 'C' then
379 Result := pthread_mutexattr_setprotocol
380 (Attributes'Access, PTHREAD_PRIO_PROTECT);
381 pragma Assert (Result = 0);
383 Result := pthread_mutexattr_setprioceiling
384 (Attributes'Access, Interfaces.C.int (Prio));
385 pragma Assert (Result = 0);
387 elsif Locking_Policy = 'I' then
388 Result := pthread_mutexattr_setprotocol
389 (Attributes'Access, PTHREAD_PRIO_INHERIT);
390 pragma Assert (Result = 0);
391 end if;
393 Result := pthread_mutex_init (L.WO'Access, Attributes'Access);
394 pragma Assert (Result = 0 or else Result = ENOMEM);
396 if Result = ENOMEM then
397 Result := pthread_mutexattr_destroy (Attributes'Access);
398 raise Storage_Error;
399 end if;
401 Result := pthread_mutexattr_destroy (Attributes'Access);
402 pragma Assert (Result = 0);
403 end Initialize_Lock;
405 procedure Initialize_Lock
406 (L : not null access RTS_Lock; Level : Lock_Level)
408 pragma Unreferenced (Level);
410 Attributes : aliased pthread_mutexattr_t;
411 Result : Interfaces.C.int;
413 begin
414 Result := pthread_mutexattr_init (Attributes'Access);
415 pragma Assert (Result = 0 or else Result = ENOMEM);
417 if Result = ENOMEM then
418 raise Storage_Error;
419 end if;
421 if Locking_Policy = 'C' then
422 Result := pthread_mutexattr_setprotocol
423 (Attributes'Access, PTHREAD_PRIO_PROTECT);
424 pragma Assert (Result = 0);
426 Result := pthread_mutexattr_setprioceiling
427 (Attributes'Access, Interfaces.C.int (System.Any_Priority'Last));
428 pragma Assert (Result = 0);
430 elsif Locking_Policy = 'I' then
431 Result := pthread_mutexattr_setprotocol
432 (Attributes'Access, PTHREAD_PRIO_INHERIT);
433 pragma Assert (Result = 0);
434 end if;
436 Result := pthread_mutex_init (L, Attributes'Access);
437 pragma Assert (Result = 0 or else Result = ENOMEM);
439 if Result = ENOMEM then
440 Result := pthread_mutexattr_destroy (Attributes'Access);
441 raise Storage_Error;
442 end if;
444 Result := pthread_mutexattr_destroy (Attributes'Access);
445 pragma Assert (Result = 0);
446 end Initialize_Lock;
448 -------------------
449 -- Finalize_Lock --
450 -------------------
452 procedure Finalize_Lock (L : not null access Lock) is
453 Result : Interfaces.C.int;
454 begin
455 Result := pthread_mutex_destroy (L.WO'Access);
456 pragma Assert (Result = 0);
457 end Finalize_Lock;
459 procedure Finalize_Lock (L : not null access RTS_Lock) is
460 Result : Interfaces.C.int;
461 begin
462 Result := pthread_mutex_destroy (L);
463 pragma Assert (Result = 0);
464 end Finalize_Lock;
466 ----------------
467 -- Write_Lock --
468 ----------------
470 procedure Write_Lock
471 (L : not null access Lock; Ceiling_Violation : out Boolean)
473 Result : Interfaces.C.int;
475 begin
476 Result := pthread_mutex_lock (L.WO'Access);
478 -- Assume that the cause of EINVAL is a priority ceiling violation
480 Ceiling_Violation := (Result = EINVAL);
481 pragma Assert (Result = 0 or else Result = EINVAL);
482 end Write_Lock;
484 procedure Write_Lock
485 (L : not null access RTS_Lock;
486 Global_Lock : Boolean := False)
488 Result : Interfaces.C.int;
489 begin
490 if not Single_Lock or else Global_Lock then
491 Result := pthread_mutex_lock (L);
492 pragma Assert (Result = 0);
493 end if;
494 end Write_Lock;
496 procedure Write_Lock (T : Task_Id) is
497 Result : Interfaces.C.int;
498 begin
499 if not Single_Lock then
500 Result := pthread_mutex_lock (T.Common.LL.L'Access);
501 pragma Assert (Result = 0);
502 end if;
503 end Write_Lock;
505 ---------------
506 -- Read_Lock --
507 ---------------
509 procedure Read_Lock
510 (L : not null access Lock; Ceiling_Violation : out Boolean) is
511 begin
512 Write_Lock (L, Ceiling_Violation);
513 end Read_Lock;
515 ------------
516 -- Unlock --
517 ------------
519 procedure Unlock (L : not null access Lock) is
520 Result : Interfaces.C.int;
521 begin
522 Result := pthread_mutex_unlock (L.WO'Access);
523 pragma Assert (Result = 0);
524 end Unlock;
526 procedure Unlock
527 (L : not null access RTS_Lock; Global_Lock : Boolean := False)
529 Result : Interfaces.C.int;
530 begin
531 if not Single_Lock or else Global_Lock then
532 Result := pthread_mutex_unlock (L);
533 pragma Assert (Result = 0);
534 end if;
535 end Unlock;
537 procedure Unlock (T : Task_Id) is
538 Result : Interfaces.C.int;
539 begin
540 if not Single_Lock then
541 Result := pthread_mutex_unlock (T.Common.LL.L'Access);
542 pragma Assert (Result = 0);
543 end if;
544 end Unlock;
546 -----------------
547 -- Set_Ceiling --
548 -----------------
550 -- Dynamic priority ceilings are not supported by the underlying system
552 procedure Set_Ceiling
553 (L : not null access Lock;
554 Prio : System.Any_Priority)
556 pragma Unreferenced (L, Prio);
557 begin
558 null;
559 end Set_Ceiling;
561 -----------
562 -- Sleep --
563 -----------
565 procedure Sleep
566 (Self_ID : Task_Id;
567 Reason : System.Tasking.Task_States)
569 pragma Unreferenced (Reason);
571 Result : Interfaces.C.int;
573 begin
574 Result :=
575 pthread_cond_wait
576 (cond => Self_ID.Common.LL.CV'Access,
577 mutex => (if Single_Lock
578 then Single_RTS_Lock'Access
579 else Self_ID.Common.LL.L'Access));
581 -- EINTR is not considered a failure
583 pragma Assert (Result = 0 or else Result = EINTR);
584 end Sleep;
586 -----------------
587 -- Timed_Sleep --
588 -----------------
590 -- This is for use within the run-time system, so abort is
591 -- assumed to be already deferred, and the caller should be
592 -- holding its own ATCB lock.
594 procedure Timed_Sleep
595 (Self_ID : Task_Id;
596 Time : Duration;
597 Mode : ST.Delay_Modes;
598 Reason : Task_States;
599 Timedout : out Boolean;
600 Yielded : out Boolean)
602 pragma Unreferenced (Reason);
604 Base_Time : Duration;
605 Check_Time : Duration;
606 Abs_Time : Duration;
607 Rel_Time : Duration;
609 Request : aliased timespec;
610 Result : Interfaces.C.int;
612 begin
613 Timedout := True;
614 Yielded := False;
616 Compute_Deadline
617 (Time => Time,
618 Mode => Mode,
619 Check_Time => Check_Time,
620 Abs_Time => Abs_Time,
621 Rel_Time => Rel_Time);
622 Base_Time := Check_Time;
624 if Abs_Time > Check_Time then
625 Request :=
626 To_Timespec (if Relative_Timed_Wait then Rel_Time else Abs_Time);
628 loop
629 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
631 Result :=
632 pthread_cond_timedwait
633 (cond => Self_ID.Common.LL.CV'Access,
634 mutex => (if Single_Lock
635 then Single_RTS_Lock'Access
636 else Self_ID.Common.LL.L'Access),
637 abstime => Request'Access);
639 Check_Time := Monotonic_Clock;
640 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
642 if Result = 0 or Result = EINTR then
644 -- Somebody may have called Wakeup for us
646 Timedout := False;
647 exit;
648 end if;
650 pragma Assert (Result = ETIMEDOUT);
651 end loop;
652 end if;
653 end Timed_Sleep;
655 -----------------
656 -- Timed_Delay --
657 -----------------
659 -- This is for use in implementing delay statements, so we assume the
660 -- caller is abort-deferred but is holding no locks.
662 procedure Timed_Delay
663 (Self_ID : Task_Id;
664 Time : Duration;
665 Mode : ST.Delay_Modes)
667 Base_Time : Duration;
668 Check_Time : Duration;
669 Abs_Time : Duration;
670 Rel_Time : Duration;
671 Request : aliased timespec;
673 Result : Interfaces.C.int;
674 pragma Warnings (Off, Result);
676 begin
677 if Single_Lock then
678 Lock_RTS;
679 end if;
681 Write_Lock (Self_ID);
683 Compute_Deadline
684 (Time => Time,
685 Mode => Mode,
686 Check_Time => Check_Time,
687 Abs_Time => Abs_Time,
688 Rel_Time => Rel_Time);
689 Base_Time := Check_Time;
691 if Abs_Time > Check_Time then
692 Request :=
693 To_Timespec (if Relative_Timed_Wait then Rel_Time else Abs_Time);
694 Self_ID.Common.State := Delay_Sleep;
696 loop
697 exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
699 Result :=
700 pthread_cond_timedwait
701 (cond => Self_ID.Common.LL.CV'Access,
702 mutex => (if Single_Lock
703 then Single_RTS_Lock'Access
704 else Self_ID.Common.LL.L'Access),
705 abstime => Request'Access);
707 Check_Time := Monotonic_Clock;
708 exit when Abs_Time <= Check_Time or else Check_Time < Base_Time;
710 pragma Assert (Result = 0
711 or else Result = ETIMEDOUT
712 or else Result = EINTR);
713 end loop;
715 Self_ID.Common.State := Runnable;
716 end if;
718 Unlock (Self_ID);
720 if Single_Lock then
721 Unlock_RTS;
722 end if;
724 Result := sched_yield;
725 end Timed_Delay;
727 ---------------------
728 -- Monotonic_Clock --
729 ---------------------
731 function Monotonic_Clock return Duration is
732 TS : aliased timespec;
733 Result : Interfaces.C.int;
734 begin
735 Result := clock_gettime
736 (clock_id => OSC.CLOCK_RT_Ada, tp => TS'Unchecked_Access);
737 pragma Assert (Result = 0);
738 return To_Duration (TS);
739 end Monotonic_Clock;
741 -------------------
742 -- RT_Resolution --
743 -------------------
745 function RT_Resolution return Duration is
746 begin
747 return 10#1.0#E-6;
748 end RT_Resolution;
750 ------------
751 -- Wakeup --
752 ------------
754 procedure Wakeup (T : Task_Id; Reason : System.Tasking.Task_States) is
755 pragma Unreferenced (Reason);
756 Result : Interfaces.C.int;
757 begin
758 Result := pthread_cond_signal (T.Common.LL.CV'Access);
759 pragma Assert (Result = 0);
760 end Wakeup;
762 -----------
763 -- Yield --
764 -----------
766 procedure Yield (Do_Yield : Boolean := True) is
767 Result : Interfaces.C.int;
768 pragma Unreferenced (Result);
769 begin
770 if Do_Yield then
771 Result := sched_yield;
772 end if;
773 end Yield;
775 ------------------
776 -- Set_Priority --
777 ------------------
779 procedure Set_Priority
780 (T : Task_Id;
781 Prio : System.Any_Priority;
782 Loss_Of_Inheritance : Boolean := False)
784 pragma Unreferenced (Loss_Of_Inheritance);
786 Result : Interfaces.C.int;
787 Param : aliased struct_sched_param;
789 function Get_Policy (Prio : System.Any_Priority) return Character;
790 pragma Import (C, Get_Policy, "__gnat_get_specific_dispatching");
791 -- Get priority specific dispatching policy
793 Priority_Specific_Policy : constant Character := Get_Policy (Prio);
794 -- Upper case first character of the policy name corresponding to the
795 -- task as set by a Priority_Specific_Dispatching pragma.
797 begin
798 T.Common.Current_Priority := Prio;
799 Param.sched_priority := To_Target_Priority (Prio);
801 if Time_Slice_Supported
802 and then (Dispatching_Policy = 'R'
803 or else Priority_Specific_Policy = 'R'
804 or else Time_Slice_Val > 0)
805 then
806 Result := pthread_setschedparam
807 (T.Common.LL.Thread, SCHED_RR, Param'Access);
809 elsif Dispatching_Policy = 'F'
810 or else Priority_Specific_Policy = 'F'
811 or else Time_Slice_Val = 0
812 then
813 Result := pthread_setschedparam
814 (T.Common.LL.Thread, SCHED_FIFO, Param'Access);
816 else
817 Result := pthread_setschedparam
818 (T.Common.LL.Thread, SCHED_OTHER, Param'Access);
819 end if;
821 pragma Assert (Result = 0);
822 end Set_Priority;
824 ------------------
825 -- Get_Priority --
826 ------------------
828 function Get_Priority (T : Task_Id) return System.Any_Priority is
829 begin
830 return T.Common.Current_Priority;
831 end Get_Priority;
833 ----------------
834 -- Enter_Task --
835 ----------------
837 procedure Enter_Task (Self_ID : Task_Id) is
838 begin
839 Self_ID.Common.LL.Thread := pthread_self;
840 Self_ID.Common.LL.LWP := lwp_self;
842 Specific.Set (Self_ID);
844 if Use_Alternate_Stack then
845 declare
846 Stack : aliased stack_t;
847 Result : Interfaces.C.int;
848 begin
849 Stack.ss_sp := Self_ID.Common.Task_Alternate_Stack;
850 Stack.ss_size := Alternate_Stack_Size;
851 Stack.ss_flags := 0;
852 Result := sigaltstack (Stack'Access, null);
853 pragma Assert (Result = 0);
854 end;
855 end if;
856 end Enter_Task;
858 -------------------
859 -- Is_Valid_Task --
860 -------------------
862 function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
864 -----------------------------
865 -- Register_Foreign_Thread --
866 -----------------------------
868 function Register_Foreign_Thread return Task_Id is
869 begin
870 if Is_Valid_Task then
871 return Self;
872 else
873 return Register_Foreign_Thread (pthread_self);
874 end if;
875 end Register_Foreign_Thread;
877 --------------------
878 -- Initialize_TCB --
879 --------------------
881 procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
882 Mutex_Attr : aliased pthread_mutexattr_t;
883 Result : Interfaces.C.int;
884 Cond_Attr : aliased pthread_condattr_t;
886 begin
887 -- Give the task a unique serial number
889 Self_ID.Serial_Number := Next_Serial_Number;
890 Next_Serial_Number := Next_Serial_Number + 1;
891 pragma Assert (Next_Serial_Number /= 0);
893 if not Single_Lock then
894 Result := pthread_mutexattr_init (Mutex_Attr'Access);
895 pragma Assert (Result = 0 or else Result = ENOMEM);
897 if Result = 0 then
898 if Locking_Policy = 'C' then
899 Result :=
900 pthread_mutexattr_setprotocol
901 (Mutex_Attr'Access,
902 PTHREAD_PRIO_PROTECT);
903 pragma Assert (Result = 0);
905 Result :=
906 pthread_mutexattr_setprioceiling
907 (Mutex_Attr'Access,
908 Interfaces.C.int (System.Any_Priority'Last));
909 pragma Assert (Result = 0);
911 elsif Locking_Policy = 'I' then
912 Result :=
913 pthread_mutexattr_setprotocol
914 (Mutex_Attr'Access,
915 PTHREAD_PRIO_INHERIT);
916 pragma Assert (Result = 0);
917 end if;
919 Result :=
920 pthread_mutex_init
921 (Self_ID.Common.LL.L'Access,
922 Mutex_Attr'Access);
923 pragma Assert (Result = 0 or else Result = ENOMEM);
924 end if;
926 if Result /= 0 then
927 Succeeded := False;
928 return;
929 end if;
931 Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
932 pragma Assert (Result = 0);
933 end if;
935 Result := pthread_condattr_init (Cond_Attr'Access);
936 pragma Assert (Result = 0 or else Result = ENOMEM);
938 if Result = 0 then
939 Result := GNAT_pthread_condattr_setup (Cond_Attr'Access);
940 pragma Assert (Result = 0);
942 Result :=
943 pthread_cond_init
944 (Self_ID.Common.LL.CV'Access, Cond_Attr'Access);
945 pragma Assert (Result = 0 or else Result = ENOMEM);
946 end if;
948 if Result = 0 then
949 Succeeded := True;
950 else
951 if not Single_Lock then
952 Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access);
953 pragma Assert (Result = 0);
954 end if;
956 Succeeded := False;
957 end if;
959 Result := pthread_condattr_destroy (Cond_Attr'Access);
960 pragma Assert (Result = 0);
961 end Initialize_TCB;
963 -----------------
964 -- Create_Task --
965 -----------------
967 procedure Create_Task
968 (T : Task_Id;
969 Wrapper : System.Address;
970 Stack_Size : System.Parameters.Size_Type;
971 Priority : System.Any_Priority;
972 Succeeded : out Boolean)
974 Attributes : aliased pthread_attr_t;
975 Adjusted_Stack_Size : Interfaces.C.size_t;
976 Page_Size : constant Interfaces.C.size_t := Get_Page_Size;
977 Result : Interfaces.C.int;
979 function Thread_Body_Access is new
980 Ada.Unchecked_Conversion (System.Address, Thread_Body);
982 use System.Task_Info;
984 begin
985 Adjusted_Stack_Size :=
986 Interfaces.C.size_t (Stack_Size + Alternate_Stack_Size);
988 if Stack_Base_Available then
990 -- If Stack Checking is supported then allocate 2 additional pages:
992 -- In the worst case, stack is allocated at something like
993 -- N * Get_Page_Size - epsilon, we need to add the size for 2 pages
994 -- to be sure the effective stack size is greater than what
995 -- has been asked.
997 Adjusted_Stack_Size := Adjusted_Stack_Size + 2 * Page_Size;
998 end if;
1000 -- Round stack size as this is required by some OSes (Darwin)
1002 Adjusted_Stack_Size := Adjusted_Stack_Size + Page_Size - 1;
1003 Adjusted_Stack_Size :=
1004 Adjusted_Stack_Size - Adjusted_Stack_Size mod Page_Size;
1006 Result := pthread_attr_init (Attributes'Access);
1007 pragma Assert (Result = 0 or else Result = ENOMEM);
1009 if Result /= 0 then
1010 Succeeded := False;
1011 return;
1012 end if;
1014 Result :=
1015 pthread_attr_setdetachstate
1016 (Attributes'Access, PTHREAD_CREATE_DETACHED);
1017 pragma Assert (Result = 0);
1019 Result :=
1020 pthread_attr_setstacksize
1021 (Attributes'Access, Adjusted_Stack_Size);
1022 pragma Assert (Result = 0);
1024 if T.Common.Task_Info /= Default_Scope then
1025 case T.Common.Task_Info is
1026 when System.Task_Info.Process_Scope =>
1027 Result :=
1028 pthread_attr_setscope
1029 (Attributes'Access, PTHREAD_SCOPE_PROCESS);
1031 when System.Task_Info.System_Scope =>
1032 Result :=
1033 pthread_attr_setscope
1034 (Attributes'Access, PTHREAD_SCOPE_SYSTEM);
1036 when System.Task_Info.Default_Scope =>
1037 Result := 0;
1038 end case;
1040 pragma Assert (Result = 0);
1041 end if;
1043 -- Since the initial signal mask of a thread is inherited from the
1044 -- creator, and the Environment task has all its signals masked, we
1045 -- do not need to manipulate caller's signal mask at this point.
1046 -- All tasks in RTS will have All_Tasks_Mask initially.
1048 -- Note: the use of Unrestricted_Access in the following call is needed
1049 -- because otherwise we have an error of getting a access-to-volatile
1050 -- value which points to a non-volatile object. But in this case it is
1051 -- safe to do this, since we know we have no problems with aliasing and
1052 -- Unrestricted_Access bypasses this check.
1054 Result := pthread_create
1055 (T.Common.LL.Thread'Unrestricted_Access,
1056 Attributes'Access,
1057 Thread_Body_Access (Wrapper),
1058 To_Address (T));
1059 pragma Assert (Result = 0 or else Result = EAGAIN);
1061 Succeeded := Result = 0;
1063 Result := pthread_attr_destroy (Attributes'Access);
1064 pragma Assert (Result = 0);
1066 if Succeeded then
1067 Set_Priority (T, Priority);
1068 end if;
1069 end Create_Task;
1071 ------------------
1072 -- Finalize_TCB --
1073 ------------------
1075 procedure Finalize_TCB (T : Task_Id) is
1076 Result : Interfaces.C.int;
1078 begin
1079 if not Single_Lock then
1080 Result := pthread_mutex_destroy (T.Common.LL.L'Access);
1081 pragma Assert (Result = 0);
1082 end if;
1084 Result := pthread_cond_destroy (T.Common.LL.CV'Access);
1085 pragma Assert (Result = 0);
1087 if T.Known_Tasks_Index /= -1 then
1088 Known_Tasks (T.Known_Tasks_Index) := null;
1089 end if;
1091 ATCB_Allocation.Free_ATCB (T);
1092 end Finalize_TCB;
1094 ---------------
1095 -- Exit_Task --
1096 ---------------
1098 procedure Exit_Task is
1099 begin
1100 -- Mark this task as unknown, so that if Self is called, it won't
1101 -- return a dangling pointer.
1103 Specific.Set (null);
1104 end Exit_Task;
1106 ----------------
1107 -- Abort_Task --
1108 ----------------
1110 procedure Abort_Task (T : Task_Id) is
1111 Result : Interfaces.C.int;
1112 begin
1113 if Abort_Handler_Installed then
1114 Result :=
1115 pthread_kill
1116 (T.Common.LL.Thread,
1117 Signal (System.Interrupt_Management.Abort_Task_Interrupt));
1118 pragma Assert (Result = 0);
1119 end if;
1120 end Abort_Task;
1122 ----------------
1123 -- Initialize --
1124 ----------------
1126 procedure Initialize (S : in out Suspension_Object) is
1127 Mutex_Attr : aliased pthread_mutexattr_t;
1128 Cond_Attr : aliased pthread_condattr_t;
1129 Result : Interfaces.C.int;
1131 begin
1132 -- Initialize internal state (always to False (RM D.10 (6)))
1134 S.State := False;
1135 S.Waiting := False;
1137 -- Initialize internal mutex
1139 Result := pthread_mutexattr_init (Mutex_Attr'Access);
1140 pragma Assert (Result = 0 or else Result = ENOMEM);
1142 if Result = ENOMEM then
1143 raise Storage_Error;
1144 end if;
1146 Result := pthread_mutex_init (S.L'Access, Mutex_Attr'Access);
1147 pragma Assert (Result = 0 or else Result = ENOMEM);
1149 if Result = ENOMEM then
1150 Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
1151 pragma Assert (Result = 0);
1153 raise Storage_Error;
1154 end if;
1156 Result := pthread_mutexattr_destroy (Mutex_Attr'Access);
1157 pragma Assert (Result = 0);
1159 -- Initialize internal condition variable
1161 Result := pthread_condattr_init (Cond_Attr'Access);
1162 pragma Assert (Result = 0 or else Result = ENOMEM);
1164 if Result /= 0 then
1165 Result := pthread_mutex_destroy (S.L'Access);
1166 pragma Assert (Result = 0);
1168 -- Storage_Error is propagated as intended if the allocation of the
1169 -- underlying OS entities fails.
1171 raise Storage_Error;
1173 else
1174 Result := GNAT_pthread_condattr_setup (Cond_Attr'Access);
1175 pragma Assert (Result = 0);
1176 end if;
1178 Result := pthread_cond_init (S.CV'Access, Cond_Attr'Access);
1179 pragma Assert (Result = 0 or else Result = ENOMEM);
1181 if Result /= 0 then
1182 Result := pthread_mutex_destroy (S.L'Access);
1183 pragma Assert (Result = 0);
1185 Result := pthread_condattr_destroy (Cond_Attr'Access);
1186 pragma Assert (Result = 0);
1188 -- Storage_Error is propagated as intended if the allocation of the
1189 -- underlying OS entities fails.
1191 raise Storage_Error;
1192 end if;
1194 Result := pthread_condattr_destroy (Cond_Attr'Access);
1195 pragma Assert (Result = 0);
1196 end Initialize;
1198 --------------
1199 -- Finalize --
1200 --------------
1202 procedure Finalize (S : in out Suspension_Object) is
1203 Result : Interfaces.C.int;
1205 begin
1206 -- Destroy internal mutex
1208 Result := pthread_mutex_destroy (S.L'Access);
1209 pragma Assert (Result = 0);
1211 -- Destroy internal condition variable
1213 Result := pthread_cond_destroy (S.CV'Access);
1214 pragma Assert (Result = 0);
1215 end Finalize;
1217 -------------------
1218 -- Current_State --
1219 -------------------
1221 function Current_State (S : Suspension_Object) return Boolean is
1222 begin
1223 -- We do not want to use lock on this read operation. State is marked
1224 -- as Atomic so that we ensure that the value retrieved is correct.
1226 return S.State;
1227 end Current_State;
1229 ---------------
1230 -- Set_False --
1231 ---------------
1233 procedure Set_False (S : in out Suspension_Object) is
1234 Result : Interfaces.C.int;
1236 begin
1237 SSL.Abort_Defer.all;
1239 Result := pthread_mutex_lock (S.L'Access);
1240 pragma Assert (Result = 0);
1242 S.State := False;
1244 Result := pthread_mutex_unlock (S.L'Access);
1245 pragma Assert (Result = 0);
1247 SSL.Abort_Undefer.all;
1248 end Set_False;
1250 --------------
1251 -- Set_True --
1252 --------------
1254 procedure Set_True (S : in out Suspension_Object) is
1255 Result : Interfaces.C.int;
1257 begin
1258 SSL.Abort_Defer.all;
1260 Result := pthread_mutex_lock (S.L'Access);
1261 pragma Assert (Result = 0);
1263 -- If there is already a task waiting on this suspension object then
1264 -- we resume it, leaving the state of the suspension object to False,
1265 -- as it is specified in (RM D.10(9)). Otherwise, it just leaves
1266 -- the state to True.
1268 if S.Waiting then
1269 S.Waiting := False;
1270 S.State := False;
1272 Result := pthread_cond_signal (S.CV'Access);
1273 pragma Assert (Result = 0);
1275 else
1276 S.State := True;
1277 end if;
1279 Result := pthread_mutex_unlock (S.L'Access);
1280 pragma Assert (Result = 0);
1282 SSL.Abort_Undefer.all;
1283 end Set_True;
1285 ------------------------
1286 -- Suspend_Until_True --
1287 ------------------------
1289 procedure Suspend_Until_True (S : in out Suspension_Object) is
1290 Result : Interfaces.C.int;
1292 begin
1293 SSL.Abort_Defer.all;
1295 Result := pthread_mutex_lock (S.L'Access);
1296 pragma Assert (Result = 0);
1298 if S.Waiting then
1300 -- Program_Error must be raised upon calling Suspend_Until_True
1301 -- if another task is already waiting on that suspension object
1302 -- (RM D.10(10)).
1304 Result := pthread_mutex_unlock (S.L'Access);
1305 pragma Assert (Result = 0);
1307 SSL.Abort_Undefer.all;
1309 raise Program_Error;
1311 else
1312 -- Suspend the task if the state is False. Otherwise, the task
1313 -- continues its execution, and the state of the suspension object
1314 -- is set to False (ARM D.10 par. 9).
1316 if S.State then
1317 S.State := False;
1318 else
1319 S.Waiting := True;
1321 loop
1322 -- Loop in case pthread_cond_wait returns earlier than expected
1323 -- (e.g. in case of EINTR caused by a signal).
1325 Result := pthread_cond_wait (S.CV'Access, S.L'Access);
1326 pragma Assert (Result = 0 or else Result = EINTR);
1328 exit when not S.Waiting;
1329 end loop;
1330 end if;
1332 Result := pthread_mutex_unlock (S.L'Access);
1333 pragma Assert (Result = 0);
1335 SSL.Abort_Undefer.all;
1336 end if;
1337 end Suspend_Until_True;
1339 ----------------
1340 -- Check_Exit --
1341 ----------------
1343 -- Dummy version
1345 function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
1346 pragma Unreferenced (Self_ID);
1347 begin
1348 return True;
1349 end Check_Exit;
1351 --------------------
1352 -- Check_No_Locks --
1353 --------------------
1355 function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
1356 pragma Unreferenced (Self_ID);
1357 begin
1358 return True;
1359 end Check_No_Locks;
1361 ----------------------
1362 -- Environment_Task --
1363 ----------------------
1365 function Environment_Task return Task_Id is
1366 begin
1367 return Environment_Task_Id;
1368 end Environment_Task;
1370 --------------
1371 -- Lock_RTS --
1372 --------------
1374 procedure Lock_RTS is
1375 begin
1376 Write_Lock (Single_RTS_Lock'Access, Global_Lock => True);
1377 end Lock_RTS;
1379 ----------------
1380 -- Unlock_RTS --
1381 ----------------
1383 procedure Unlock_RTS is
1384 begin
1385 Unlock (Single_RTS_Lock'Access, Global_Lock => True);
1386 end Unlock_RTS;
1388 ------------------
1389 -- Suspend_Task --
1390 ------------------
1392 function Suspend_Task
1393 (T : ST.Task_Id;
1394 Thread_Self : Thread_Id) return Boolean
1396 pragma Unreferenced (T, Thread_Self);
1397 begin
1398 return False;
1399 end Suspend_Task;
1401 -----------------
1402 -- Resume_Task --
1403 -----------------
1405 function Resume_Task
1406 (T : ST.Task_Id;
1407 Thread_Self : Thread_Id) return Boolean
1409 pragma Unreferenced (T, Thread_Self);
1410 begin
1411 return False;
1412 end Resume_Task;
1414 --------------------
1415 -- Stop_All_Tasks --
1416 --------------------
1418 procedure Stop_All_Tasks is
1419 begin
1420 null;
1421 end Stop_All_Tasks;
1423 ---------------
1424 -- Stop_Task --
1425 ---------------
1427 function Stop_Task (T : ST.Task_Id) return Boolean is
1428 pragma Unreferenced (T);
1429 begin
1430 return False;
1431 end Stop_Task;
1433 -------------------
1434 -- Continue_Task --
1435 -------------------
1437 function Continue_Task (T : ST.Task_Id) return Boolean is
1438 pragma Unreferenced (T);
1439 begin
1440 return False;
1441 end Continue_Task;
1443 ----------------
1444 -- Initialize --
1445 ----------------
1447 procedure Initialize (Environment_Task : Task_Id) is
1448 act : aliased struct_sigaction;
1449 old_act : aliased struct_sigaction;
1450 Tmp_Set : aliased sigset_t;
1451 Result : Interfaces.C.int;
1453 function State
1454 (Int : System.Interrupt_Management.Interrupt_ID) return Character;
1455 pragma Import (C, State, "__gnat_get_interrupt_state");
1456 -- Get interrupt state. Defined in a-init.c
1457 -- The input argument is the interrupt number,
1458 -- and the result is one of the following:
1460 Default : constant Character := 's';
1461 -- 'n' this interrupt not set by any Interrupt_State pragma
1462 -- 'u' Interrupt_State pragma set state to User
1463 -- 'r' Interrupt_State pragma set state to Runtime
1464 -- 's' Interrupt_State pragma set state to System (use "default"
1465 -- system handler)
1467 begin
1468 Environment_Task_Id := Environment_Task;
1470 Interrupt_Management.Initialize;
1472 -- Prepare the set of signals that should unblocked in all tasks
1474 Result := sigemptyset (Unblocked_Signal_Mask'Access);
1475 pragma Assert (Result = 0);
1477 for J in Interrupt_Management.Interrupt_ID loop
1478 if System.Interrupt_Management.Keep_Unmasked (J) then
1479 Result := sigaddset (Unblocked_Signal_Mask'Access, Signal (J));
1480 pragma Assert (Result = 0);
1481 end if;
1482 end loop;
1484 -- Initialize the lock used to synchronize chain of all ATCBs
1486 Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
1488 Specific.Initialize (Environment_Task);
1490 if Use_Alternate_Stack then
1491 Environment_Task.Common.Task_Alternate_Stack :=
1492 Alternate_Stack'Address;
1493 end if;
1495 -- Make environment task known here because it doesn't go through
1496 -- Activate_Tasks, which does it for all other tasks.
1498 Known_Tasks (Known_Tasks'First) := Environment_Task;
1499 Environment_Task.Known_Tasks_Index := Known_Tasks'First;
1501 Enter_Task (Environment_Task);
1503 if State
1504 (System.Interrupt_Management.Abort_Task_Interrupt) /= Default
1505 then
1506 act.sa_flags := 0;
1507 act.sa_handler := Abort_Handler'Address;
1509 Result := sigemptyset (Tmp_Set'Access);
1510 pragma Assert (Result = 0);
1511 act.sa_mask := Tmp_Set;
1513 Result :=
1514 sigaction
1515 (Signal (System.Interrupt_Management.Abort_Task_Interrupt),
1516 act'Unchecked_Access,
1517 old_act'Unchecked_Access);
1518 pragma Assert (Result = 0);
1519 Abort_Handler_Installed := True;
1520 end if;
1521 end Initialize;
1523 -----------------------
1524 -- Set_Task_Affinity --
1525 -----------------------
1527 procedure Set_Task_Affinity (T : ST.Task_Id) is
1528 pragma Unreferenced (T);
1530 begin
1531 -- Setting task affinity is not supported by the underlying system
1533 null;
1534 end Set_Task_Affinity;
1536 end System.Task_Primitives.Operations;