OSDN Git Service

New Language: Ada
[pf3gnuchains/gcc-fork.git] / gcc / ada / 5wtaprop.adb
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 --                             $Revision: 1.66 $
10 --                                                                          --
11 --         Copyright (C) 1992-2001, Free Software Foundation, Inc.          --
12 --                                                                          --
13 -- GNARL is free software; you can  redistribute it  and/or modify it under --
14 -- terms of the  GNU General Public License as published  by the Free Soft- --
15 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
16 -- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
17 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
18 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
19 -- for  more details.  You should have  received  a copy of the GNU General --
20 -- Public License  distributed with GNARL; see file COPYING.  If not, write --
21 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
22 -- MA 02111-1307, USA.                                                      --
23 --                                                                          --
24 -- As a special exception,  if other files  instantiate  generics from this --
25 -- unit, or you link  this unit with other files  to produce an executable, --
26 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
27 -- covered  by the  GNU  General  Public  License.  This exception does not --
28 -- however invalidate  any other reasons why  the executable file  might be --
29 -- covered by the  GNU Public License.                                      --
30 --                                                                          --
31 -- GNARL was developed by the GNARL team at Florida State University. It is --
32 -- now maintained by Ada Core Technologies Inc. in cooperation with Florida --
33 -- State University (http://www.gnat.com).                                  --
34 --                                                                          --
35 ------------------------------------------------------------------------------
36
37 --  This is a NT (native) version of this package.
38
39 --  This package contains all the GNULL primitives that interface directly
40 --  with the underlying OS.
41
42 pragma Polling (Off);
43 --  Turn off polling, we do not want ATC polling to take place during
44 --  tasking operations. It causes infinite loops and other problems.
45
46 with System.Tasking.Debug;
47 --  used for Known_Tasks
48
49 with Interfaces.C;
50 --  used for int
51 --           size_t
52
53 with Interfaces.C.Strings;
54 --  used for Null_Ptr
55
56 with System.OS_Interface;
57 --  used for various type, constant, and operations
58
59 with System.Parameters;
60 --  used for Size_Type
61
62 with System.Tasking;
63 --  used for Ada_Task_Control_Block
64 --           Task_ID
65
66 with System.Soft_Links;
67 --  used for Defer/Undefer_Abort
68 --       to initialize TSD for a C thread, in function Self
69
70 --  Note that we do not use System.Tasking.Initialization directly since
71 --  this is a higher level package that we shouldn't depend on. For example
72 --  when using the restricted run time, it is replaced by
73 --  System.Tasking.Restricted.Initialization
74
75 with System.OS_Primitives;
76 --  used for Delay_Modes
77
78 with System.Task_Info;
79 --  used for Unspecified_Task_Info
80
81 with Unchecked_Conversion;
82 with Unchecked_Deallocation;
83
84 package body System.Task_Primitives.Operations is
85
86    use System.Tasking.Debug;
87    use System.Tasking;
88    use Interfaces.C;
89    use Interfaces.C.Strings;
90    use System.OS_Interface;
91    use System.Parameters;
92    use System.OS_Primitives;
93
94    pragma Linker_Options ("-Xlinker --stack=0x800000,0x1000");
95
96    package SSL renames System.Soft_Links;
97
98    ------------------
99    --  Local Data  --
100    ------------------
101
102    Environment_Task_ID : Task_ID;
103    --  A variable to hold Task_ID for the environment task.
104
105    All_Tasks_L : aliased System.Task_Primitives.RTS_Lock;
106    --  See comments on locking rules in System.Tasking (spec).
107
108    Time_Slice_Val : Integer;
109    pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
110
111    Dispatching_Policy : Character;
112    pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
113
114    FIFO_Within_Priorities : constant Boolean := Dispatching_Policy = 'F';
115    --  Indicates whether FIFO_Within_Priorities is set.
116
117    ---------------------------------
118    --  Foreign Threads Detection  --
119    ---------------------------------
120
121    --  The following are used to allow the Self function to
122    --  automatically generate ATCB's for C threads that happen to call
123    --  Ada procedure, which in turn happen to call the Ada run-time system.
124
125    type Fake_ATCB;
126    type Fake_ATCB_Ptr is access Fake_ATCB;
127    type Fake_ATCB is record
128       Stack_Base : Interfaces.C.unsigned := 0;
129       --  A value of zero indicates the node is not in use.
130       Next       : Fake_ATCB_Ptr;
131       Real_ATCB  : aliased Ada_Task_Control_Block (0);
132    end record;
133
134    Fake_ATCB_List : Fake_ATCB_Ptr;
135    --  A linear linked list.
136    --  The list is protected by All_Tasks_L;
137    --  Nodes are added to this list from the front.
138    --  Once a node is added to this list, it is never removed.
139
140    Fake_Task_Elaborated : aliased Boolean := True;
141    --  Used to identified fake tasks (i.e., non-Ada Threads).
142
143    Next_Fake_ATCB : Fake_ATCB_Ptr;
144    --  Used to allocate one Fake_ATCB in advance. See comment in New_Fake_ATCB
145
146    ---------------------------------
147    --  Support for New_Fake_ATCB  --
148    ---------------------------------
149
150    function New_Fake_ATCB return Task_ID;
151    --  Allocate and Initialize a new ATCB. This code can safely be called from
152    --  a foreign thread, as it doesn't access implicitely or explicitely
153    --  "self" before having initialized the new ATCB.
154
155    ------------------------------------
156    -- The thread local storage index --
157    ------------------------------------
158
159    TlsIndex : DWORD;
160    pragma Export (Ada, TlsIndex);
161    --  To ensure that this variable won't be local to this package, since
162    --  in some cases, inlining forces this variable to be global anyway.
163
164    ----------------------------------
165    -- Utility Conversion Functions --
166    ----------------------------------
167
168    function To_Task_Id is new Unchecked_Conversion (System.Address, Task_ID);
169
170    function To_Address is new Unchecked_Conversion (Task_ID, System.Address);
171
172    -------------------
173    -- New_Fake_ATCB --
174    -------------------
175
176    function New_Fake_ATCB return Task_ID is
177       Self_ID   : Task_ID;
178       P, Q      : Fake_ATCB_Ptr;
179       Succeeded : Boolean;
180       Res       : BOOL;
181
182    begin
183       --  This section is ticklish.
184       --  We dare not call anything that might require an ATCB, until
185       --  we have the new ATCB in place.
186
187       Write_Lock (All_Tasks_L'Access);
188       Q := null;
189       P := Fake_ATCB_List;
190
191       while P /= null loop
192          if P.Stack_Base = 0 then
193             Q := P;
194          end if;
195
196          P := P.Next;
197       end loop;
198
199       if Q = null then
200
201          --  Create a new ATCB with zero entries.
202
203          Self_ID := Next_Fake_ATCB.Real_ATCB'Access;
204          Next_Fake_ATCB.Stack_Base := 1;
205          Next_Fake_ATCB.Next := Fake_ATCB_List;
206          Fake_ATCB_List := Next_Fake_ATCB;
207          Next_Fake_ATCB := null;
208
209       else
210          --  Reuse an existing fake ATCB.
211
212          Self_ID := Q.Real_ATCB'Access;
213          Q.Stack_Base := 1;
214       end if;
215
216       --  Record this as the Task_ID for the current thread.
217
218       Self_ID.Common.LL.Thread := GetCurrentThread;
219
220       Res := TlsSetValue (TlsIndex, To_Address (Self_ID));
221       pragma Assert (Res = True);
222
223       --  Do the standard initializations
224
225       System.Tasking.Initialize_ATCB
226         (Self_ID, null, Null_Address, Null_Task, Fake_Task_Elaborated'Access,
227          System.Priority'First, Task_Info.Unspecified_Task_Info, 0, Self_ID,
228          Succeeded);
229       pragma Assert (Succeeded);
230
231       --  Finally, it is safe to use an allocator in this thread.
232
233       if Next_Fake_ATCB = null then
234          Next_Fake_ATCB := new Fake_ATCB;
235       end if;
236
237       Self_ID.Master_of_Task := 0;
238       Self_ID.Master_Within := Self_ID.Master_of_Task + 1;
239
240       for L in Self_ID.Entry_Calls'Range loop
241          Self_ID.Entry_Calls (L).Self := Self_ID;
242          Self_ID.Entry_Calls (L).Level := L;
243       end loop;
244
245       Self_ID.Common.State := Runnable;
246       Self_ID.Awake_Count := 1;
247
248       --  Since this is not an ordinary Ada task, we will start out undeferred
249
250       Self_ID.Deferral_Level := 0;
251
252       System.Soft_Links.Create_TSD (Self_ID.Common.Compiler_Data);
253
254       --  ????
255       --  The following call is commented out to avoid dependence on
256       --  the System.Tasking.Initialization package.
257       --  It seems that if we want Ada.Task_Attributes to work correctly
258       --  for C threads we will need to raise the visibility of this soft
259       --  link to System.Soft_Links.
260       --  We are putting that off until this new functionality is otherwise
261       --  stable.
262       --  System.Tasking.Initialization.Initialize_Attributes_Link.all (T);
263
264       --  Must not unlock until Next_ATCB is again allocated.
265
266       Unlock (All_Tasks_L'Access);
267       return Self_ID;
268    end New_Fake_ATCB;
269
270    ----------------------------------
271    -- Condition Variable Functions --
272    ----------------------------------
273
274    procedure Initialize_Cond (Cond : access Condition_Variable);
275    --  Initialize given condition variable Cond
276
277    procedure Finalize_Cond (Cond : access Condition_Variable);
278    --  Finalize given condition variable Cond.
279
280    procedure Cond_Signal (Cond : access Condition_Variable);
281    --  Signal condition variable Cond
282
283    procedure Cond_Wait
284      (Cond : access Condition_Variable;
285       L    : access RTS_Lock);
286    --  Wait on conditional variable Cond, using lock L
287
288    procedure Cond_Timed_Wait
289      (Cond      : access Condition_Variable;
290       L         : access RTS_Lock;
291       Rel_Time  : Duration;
292       Timed_Out : out Boolean;
293       Status    : out Integer);
294    --  Do timed wait on condition variable Cond using lock L. The duration
295    --  of the timed wait is given by Rel_Time. When the condition is
296    --  signalled, Timed_Out shows whether or not a time out occurred.
297    --  Status shows whether Cond_Timed_Wait completed successfully.
298
299    ---------------------
300    -- Initialize_Cond --
301    ---------------------
302
303    procedure Initialize_Cond (Cond : access Condition_Variable) is
304       hEvent : HANDLE;
305
306    begin
307       hEvent := CreateEvent (null, True, False, Null_Ptr);
308       pragma Assert (hEvent /= 0);
309       Cond.all := Condition_Variable (hEvent);
310    end Initialize_Cond;
311
312    -------------------
313    -- Finalize_Cond --
314    -------------------
315
316    --  No such problem here, DosCloseEventSem has been derived.
317    --  What does such refer to in above comment???
318
319    procedure Finalize_Cond (Cond : access Condition_Variable) is
320       Result : BOOL;
321
322    begin
323       Result := CloseHandle (HANDLE (Cond.all));
324       pragma Assert (Result = True);
325    end Finalize_Cond;
326
327    -----------------
328    -- Cond_Signal --
329    -----------------
330
331    procedure Cond_Signal (Cond : access Condition_Variable) is
332       Result : BOOL;
333
334    begin
335       Result := SetEvent (HANDLE (Cond.all));
336       pragma Assert (Result = True);
337    end Cond_Signal;
338
339    ---------------
340    -- Cond_Wait --
341    ---------------
342
343    --  Pre-assertion: Cond is posted
344    --                 L is locked.
345
346    --  Post-assertion: Cond is posted
347    --                  L is locked.
348
349    procedure Cond_Wait
350      (Cond : access Condition_Variable;
351       L    : access RTS_Lock)
352    is
353       Result      : DWORD;
354       Result_Bool : BOOL;
355
356    begin
357       --  Must reset Cond BEFORE L is unlocked.
358
359       Result_Bool := ResetEvent (HANDLE (Cond.all));
360       pragma Assert (Result_Bool = True);
361       Unlock (L);
362
363       --  No problem if we are interrupted here: if the condition is signaled,
364       --  WaitForSingleObject will simply not block
365
366       Result := WaitForSingleObject (HANDLE (Cond.all), Wait_Infinite);
367       pragma Assert (Result = 0);
368
369       Write_Lock (L);
370    end Cond_Wait;
371
372    ---------------------
373    -- Cond_Timed_Wait --
374    ---------------------
375
376    --  Pre-assertion: Cond is posted
377    --                 L is locked.
378
379    --  Post-assertion: Cond is posted
380    --                  L is locked.
381
382    procedure Cond_Timed_Wait
383      (Cond      : access Condition_Variable;
384       L         : access RTS_Lock;
385       Rel_Time  : Duration;
386       Timed_Out : out Boolean;
387       Status    : out Integer)
388    is
389       Time_Out : DWORD;
390       Result   : BOOL;
391
392       Int_Rel_Time : DWORD;
393       Wait_Result  : DWORD;
394
395    begin
396       --  Must reset Cond BEFORE L is unlocked.
397
398       Result := ResetEvent (HANDLE (Cond.all));
399       pragma Assert (Result = True);
400       Unlock (L);
401
402       --  No problem if we are interrupted here: if the condition is signaled,
403       --  WaitForSingleObject will simply not block
404
405       if Rel_Time <= 0.0 then
406          Timed_Out := True;
407       else
408          Int_Rel_Time := DWORD (Rel_Time);
409          Time_Out := Int_Rel_Time * 1000 +
410                      DWORD ((Rel_Time - Duration (Int_Rel_Time)) * 1000.0);
411          Wait_Result := WaitForSingleObject (HANDLE (Cond.all), Time_Out);
412
413          if Wait_Result = WAIT_TIMEOUT then
414             Timed_Out := True;
415             Wait_Result := 0;
416          else
417             Timed_Out := False;
418          end if;
419       end if;
420
421       Write_Lock (L);
422
423       --  Ensure post-condition
424
425       if Timed_Out then
426          Result := SetEvent (HANDLE (Cond.all));
427          pragma Assert (Result = True);
428       end if;
429
430       Status := Integer (Wait_Result);
431    end Cond_Timed_Wait;
432
433    ------------------
434    -- Stack_Guard  --
435    ------------------
436
437    --  The underlying thread system sets a guard page at the
438    --  bottom of a thread stack, so nothing is needed.
439    --  ??? Check the comment above
440
441    procedure Stack_Guard (T : ST.Task_ID; On : Boolean) is
442    begin
443       null;
444    end Stack_Guard;
445
446    --------------------
447    -- Get_Thread_Id  --
448    --------------------
449
450    function Get_Thread_Id (T : ST.Task_ID) return OSI.Thread_Id is
451    begin
452       return T.Common.LL.Thread;
453    end Get_Thread_Id;
454
455    ----------
456    -- Self --
457    ----------
458
459    function Self return Task_ID is
460       Self_Id : Task_ID;
461
462    begin
463       Self_Id := To_Task_Id (TlsGetValue (TlsIndex));
464
465       if Self_Id = null then
466          return New_Fake_ATCB;
467       end if;
468
469       return Self_Id;
470    end Self;
471
472    ---------------------
473    -- Initialize_Lock --
474    ---------------------
475
476    --  Note: mutexes and cond_variables needed per-task basis are
477    --  initialized in Intialize_TCB and the Storage_Error is handled.
478    --  Other mutexes (such as All_Tasks_Lock, Memory_Lock...) used in
479    --  the RTS is initialized before any status change of RTS.
480    --  Therefore raising Storage_Error in the following routines
481    --  should be able to be handled safely.
482
483    procedure Initialize_Lock
484      (Prio : System.Any_Priority;
485       L    : access Lock) is
486    begin
487       InitializeCriticalSection (L.Mutex'Access);
488       L.Owner_Priority := 0;
489       L.Priority := Prio;
490    end Initialize_Lock;
491
492    procedure Initialize_Lock (L : access RTS_Lock; Level : Lock_Level) is
493    begin
494       InitializeCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
495    end Initialize_Lock;
496
497    -------------------
498    -- Finalize_Lock --
499    -------------------
500
501    procedure Finalize_Lock (L : access Lock) is
502    begin
503       DeleteCriticalSection (L.Mutex'Access);
504    end Finalize_Lock;
505
506    procedure Finalize_Lock (L : access RTS_Lock) is
507    begin
508       DeleteCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
509    end Finalize_Lock;
510
511    ----------------
512    -- Write_Lock --
513    ----------------
514
515    procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
516    begin
517       L.Owner_Priority := Get_Priority (Self);
518
519       if L.Priority < L.Owner_Priority then
520          Ceiling_Violation := True;
521          return;
522       end if;
523
524       EnterCriticalSection (L.Mutex'Access);
525
526       Ceiling_Violation := False;
527    end Write_Lock;
528
529    procedure Write_Lock (L : access RTS_Lock) is
530    begin
531       EnterCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
532    end Write_Lock;
533
534    procedure Write_Lock (T : Task_ID) is
535    begin
536       EnterCriticalSection
537         (CRITICAL_SECTION (T.Common.LL.L)'Unrestricted_Access);
538    end Write_Lock;
539
540    ---------------
541    -- Read_Lock --
542    ---------------
543
544    procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is
545    begin
546       Write_Lock (L, Ceiling_Violation);
547    end Read_Lock;
548
549    ------------
550    -- Unlock --
551    ------------
552
553    procedure Unlock (L : access Lock) is
554    begin
555       LeaveCriticalSection (L.Mutex'Access);
556    end Unlock;
557
558    procedure Unlock (L : access RTS_Lock) is
559    begin
560       LeaveCriticalSection (CRITICAL_SECTION (L.all)'Unrestricted_Access);
561    end Unlock;
562
563    procedure Unlock (T : Task_ID) is
564    begin
565       LeaveCriticalSection
566         (CRITICAL_SECTION (T.Common.LL.L)'Unrestricted_Access);
567    end Unlock;
568
569    -----------
570    -- Sleep --
571    -----------
572
573    procedure Sleep
574      (Self_ID : Task_ID;
575       Reason  : System.Tasking.Task_States) is
576    begin
577       pragma Assert (Self_ID = Self);
578
579       Cond_Wait (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access);
580
581       if Self_ID.Deferral_Level = 0
582         and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
583       then
584          Unlock (Self_ID);
585          raise Standard'Abort_Signal;
586       end if;
587    end Sleep;
588
589    -----------------
590    -- Timed_Sleep --
591    -----------------
592
593    --  This is for use within the run-time system, so abort is
594    --  assumed to be already deferred, and the caller should be
595    --  holding its own ATCB lock.
596
597    procedure Timed_Sleep
598      (Self_ID  : Task_ID;
599       Time     : Duration;
600       Mode     : ST.Delay_Modes;
601       Reason   : System.Tasking.Task_States;
602       Timedout : out Boolean;
603       Yielded  : out Boolean)
604    is
605       Check_Time : constant Duration := Monotonic_Clock;
606       Rel_Time   : Duration;
607       Abs_Time   : Duration;
608       Result     : Integer;
609
610       Local_Timedout : Boolean;
611
612    begin
613       Timedout := True;
614       Yielded := False;
615
616       if Mode = Relative then
617          Rel_Time := Time;
618          Abs_Time := Duration'Min (Time, Max_Sensible_Delay) + Check_Time;
619       else
620          Rel_Time := Time - Check_Time;
621          Abs_Time := Time;
622       end if;
623
624       if Rel_Time > 0.0 then
625          loop
626             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
627               or else Self_ID.Pending_Priority_Change;
628
629             Cond_Timed_Wait (Self_ID.Common.LL.CV'Access,
630               Self_ID.Common.LL.L'Access, Rel_Time, Local_Timedout, Result);
631
632             exit when Abs_Time <= Monotonic_Clock;
633
634             if not Local_Timedout then
635                --  somebody may have called Wakeup for us
636                Timedout := False;
637                exit;
638             end if;
639
640             Rel_Time := Abs_Time - Monotonic_Clock;
641          end loop;
642       end if;
643    end Timed_Sleep;
644
645    -----------------
646    -- Timed_Delay --
647    -----------------
648
649    procedure Timed_Delay
650      (Self_ID  : Task_ID;
651       Time     : Duration;
652       Mode     : ST.Delay_Modes)
653    is
654       Check_Time : constant Duration := Monotonic_Clock;
655       Rel_Time   : Duration;
656       Abs_Time   : Duration;
657       Result     : Integer;
658       Timedout   : Boolean;
659
660    begin
661       --  Only the little window between deferring abort and
662       --  locking Self_ID is the reason we need to
663       --  check for pending abort and priority change below! :(
664
665       SSL.Abort_Defer.all;
666       Write_Lock (Self_ID);
667
668       if Mode = Relative then
669          Rel_Time := Time;
670          Abs_Time := Time + Check_Time;
671       else
672          Rel_Time := Time - Check_Time;
673          Abs_Time := Time;
674       end if;
675
676       if Rel_Time > 0.0 then
677          Self_ID.Common.State := Delay_Sleep;
678
679          loop
680             if Self_ID.Pending_Priority_Change then
681                Self_ID.Pending_Priority_Change := False;
682                Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority;
683                Set_Priority (Self_ID, Self_ID.Common.Base_Priority);
684             end if;
685
686             exit when Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
687
688             Cond_Timed_Wait (Self_ID.Common.LL.CV'Access,
689               Self_ID.Common.LL.L'Access, Rel_Time, Timedout, Result);
690
691             exit when Abs_Time <= Monotonic_Clock;
692
693             Rel_Time := Abs_Time - Monotonic_Clock;
694          end loop;
695
696          Self_ID.Common.State := Runnable;
697       end if;
698
699       Unlock (Self_ID);
700       Yield;
701       SSL.Abort_Undefer.all;
702    end Timed_Delay;
703
704    ------------
705    -- Wakeup --
706    ------------
707
708    procedure Wakeup (T : Task_ID; Reason : System.Tasking.Task_States) is
709    begin
710       Cond_Signal (T.Common.LL.CV'Access);
711    end Wakeup;
712
713    -----------
714    -- Yield --
715    -----------
716
717    procedure Yield (Do_Yield : Boolean := True) is
718    begin
719       if Do_Yield then
720          Sleep (0);
721       end if;
722    end Yield;
723
724    ------------------
725    -- Set_Priority --
726    ------------------
727
728    type Prio_Array_Type is array (System.Any_Priority) of Integer;
729    pragma Atomic_Components (Prio_Array_Type);
730
731    Prio_Array : Prio_Array_Type;
732    --  Global array containing the id of the currently running task for
733    --  each priority.
734    --
735    --  Note: we assume that we are on a single processor with run-til-blocked
736    --  scheduling.
737
738    procedure Set_Priority
739      (T : Task_ID;
740       Prio : System.Any_Priority;
741       Loss_Of_Inheritance : Boolean := False)
742    is
743       Res        : BOOL;
744       Array_Item : Integer;
745
746    begin
747       Res := SetThreadPriority
748         (T.Common.LL.Thread, Interfaces.C.int (Underlying_Priorities (Prio)));
749       pragma Assert (Res = True);
750
751       --  ??? Work around a bug in NT 4.0 SP3 scheduler
752       --  It looks like when a task with Thread_Priority_Idle (using RT class)
753       --  never reaches its time slice (e.g by doing multiple and simple RV,
754       --  see CXD8002), the scheduler never gives higher priority task a
755       --  chance to run.
756       --  Note that this works fine on NT 4.0 SP1
757
758       if Time_Slice_Val = 0
759         and then Underlying_Priorities (Prio) = Thread_Priority_Idle
760         and then Loss_Of_Inheritance
761       then
762          Sleep (20);
763       end if;
764
765       if FIFO_Within_Priorities then
766
767          --  Annex D requirement [RM D.2.2 par. 9]:
768          --    If the task drops its priority due to the loss of inherited
769          --    priority, it is added at the head of the ready queue for its
770          --    new active priority.
771
772          if Loss_Of_Inheritance
773            and then Prio < T.Common.Current_Priority
774          then
775             Array_Item := Prio_Array (T.Common.Base_Priority) + 1;
776             Prio_Array (T.Common.Base_Priority) := Array_Item;
777
778             loop
779                --  Let some processes a chance to arrive
780
781                Yield;
782
783                --  Then wait for our turn to proceed
784
785                exit when Array_Item = Prio_Array (T.Common.Base_Priority)
786                  or else Prio_Array (T.Common.Base_Priority) = 1;
787             end loop;
788
789             Prio_Array (T.Common.Base_Priority) :=
790               Prio_Array (T.Common.Base_Priority) - 1;
791          end if;
792       end if;
793
794       T.Common.Current_Priority := Prio;
795    end Set_Priority;
796
797    ------------------
798    -- Get_Priority --
799    ------------------
800
801    function Get_Priority (T : Task_ID) return System.Any_Priority is
802    begin
803       return T.Common.Current_Priority;
804    end Get_Priority;
805
806    ----------------
807    -- Enter_Task --
808    ----------------
809
810    --  There were two paths were we needed to call Enter_Task :
811    --  1) from System.Task_Primitives.Operations.Initialize
812    --  2) from System.Tasking.Stages.Task_Wrapper
813    --
814    --  The thread initialisation has to be done only for the first case.
815    --
816    --  This is because the GetCurrentThread NT call does not return the
817    --  real thread handler but only a "pseudo" one. It is not possible to
818    --  release the thread handle and free the system ressources from this
819    --  "pseudo" handle. So we really want to keep the real thread handle
820    --  set in System.Task_Primitives.Operations.Create_Task during the
821    --  thread creation.
822
823    procedure Enter_Task (Self_ID : Task_ID) is
824       procedure Init_Float;
825       pragma Import (C, Init_Float, "__gnat_init_float");
826       --  Properly initializes the FPU for x86 systems.
827
828       Succeeded : BOOL;
829
830    begin
831       Succeeded := TlsSetValue (TlsIndex, To_Address (Self_ID));
832       pragma Assert (Succeeded = True);
833       Init_Float;
834
835       Self_ID.Common.LL.Thread_Id := GetCurrentThreadId;
836
837       Lock_All_Tasks_List;
838
839       for J in Known_Tasks'Range loop
840          if Known_Tasks (J) = null then
841             Known_Tasks (J) := Self_ID;
842             Self_ID.Known_Tasks_Index := J;
843             exit;
844          end if;
845       end loop;
846
847       Unlock_All_Tasks_List;
848    end Enter_Task;
849
850    --------------
851    -- New_ATCB --
852    --------------
853
854    function New_ATCB (Entry_Num : Task_Entry_Index) return Task_ID is
855    begin
856       return new Ada_Task_Control_Block (Entry_Num);
857    end New_ATCB;
858
859    ----------------------
860    --  Initialize_TCB  --
861    ----------------------
862
863    procedure Initialize_TCB (Self_ID : Task_ID; Succeeded : out Boolean) is
864    begin
865       Initialize_Cond (Self_ID.Common.LL.CV'Access);
866       Initialize_Lock (Self_ID.Common.LL.L'Access, ATCB_Level);
867       Succeeded := True;
868    end Initialize_TCB;
869
870    -----------------
871    -- Create_Task --
872    -----------------
873
874    procedure Create_Task
875      (T          : Task_ID;
876       Wrapper    : System.Address;
877       Stack_Size : System.Parameters.Size_Type;
878       Priority   : System.Any_Priority;
879       Succeeded  : out Boolean)
880    is
881       hTask          : HANDLE;
882       TaskId         : aliased DWORD;
883
884       --  ??? The fact that we can't use PVOID because the compiler
885       --  gives a "PVOID is not visible" error is a GNAT bug.
886       --  The strange thing is that the file compiles fine during a regular
887       --  build.
888
889       pTaskParameter : System.OS_Interface.PVOID;
890       dwStackSize    : DWORD;
891       Result         : DWORD;
892       Entry_Point    : PTHREAD_START_ROUTINE;
893
894       function To_PTHREAD_START_ROUTINE is new
895         Unchecked_Conversion (System.Address, PTHREAD_START_ROUTINE);
896
897    begin
898       pTaskParameter := To_Address (T);
899
900       if Stack_Size = Unspecified_Size then
901          dwStackSize := DWORD (Default_Stack_Size);
902
903       elsif Stack_Size < Minimum_Stack_Size then
904          dwStackSize := DWORD (Minimum_Stack_Size);
905
906       else
907          dwStackSize := DWORD (Stack_Size);
908       end if;
909
910       Entry_Point := To_PTHREAD_START_ROUTINE (Wrapper);
911
912       hTask := CreateThread
913          (null,
914           dwStackSize,
915           Entry_Point,
916           pTaskParameter,
917           DWORD (Create_Suspended),
918           TaskId'Unchecked_Access);
919
920       --  Step 1: Create the thread in blocked mode
921
922       if hTask = 0 then
923          raise Storage_Error;
924       end if;
925
926       --  Step 2: set its TCB
927
928       T.Common.LL.Thread := hTask;
929
930       --  Step 3: set its priority (child has inherited priority from parent)
931
932       Set_Priority (T, Priority);
933
934       --  Step 4: Now, start it for good:
935
936       Result := ResumeThread (hTask);
937       pragma Assert (Result = 1);
938
939       Succeeded := Result = 1;
940    end Create_Task;
941
942    ------------------
943    -- Finalize_TCB --
944    ------------------
945
946    procedure Finalize_TCB (T : Task_ID) is
947       Self_ID   : Task_ID := T;
948       Result    : DWORD;
949       Succeeded : BOOL;
950
951       procedure Free is new
952         Unchecked_Deallocation (Ada_Task_Control_Block, Task_ID);
953
954    begin
955       Finalize_Lock (T.Common.LL.L'Access);
956       Finalize_Cond (T.Common.LL.CV'Access);
957
958       if T.Known_Tasks_Index /= -1 then
959          Known_Tasks (T.Known_Tasks_Index) := null;
960       end if;
961
962       --  Wait for the thread to terminate then close it. this is needed
963       --  to release system ressources.
964
965       Result := WaitForSingleObject (T.Common.LL.Thread, Wait_Infinite);
966       pragma Assert (Result /= WAIT_FAILED);
967       Succeeded := CloseHandle (T.Common.LL.Thread);
968       pragma Assert (Succeeded = True);
969
970       Free (Self_ID);
971    end Finalize_TCB;
972
973    ---------------
974    -- Exit_Task --
975    ---------------
976
977    procedure Exit_Task is
978    begin
979       ExitThread (0);
980    end Exit_Task;
981
982    ----------------
983    -- Abort_Task --
984    ----------------
985
986    procedure Abort_Task (T : Task_ID) is
987    begin
988       null;
989    end Abort_Task;
990
991    ----------------------
992    -- Environment_Task --
993    ----------------------
994
995    function Environment_Task return Task_ID is
996    begin
997       return Environment_Task_ID;
998    end Environment_Task;
999
1000    -------------------------
1001    -- Lock_All_Tasks_List --
1002    -------------------------
1003
1004    procedure Lock_All_Tasks_List is
1005    begin
1006       Write_Lock (All_Tasks_L'Access);
1007    end Lock_All_Tasks_List;
1008
1009    ---------------------------
1010    -- Unlock_All_Tasks_List --
1011    ---------------------------
1012
1013    procedure Unlock_All_Tasks_List is
1014    begin
1015       Unlock (All_Tasks_L'Access);
1016    end Unlock_All_Tasks_List;
1017
1018    ----------------
1019    -- Initialize --
1020    ----------------
1021
1022    procedure Initialize (Environment_Task : Task_ID) is
1023       Res : BOOL;
1024    begin
1025       Environment_Task_ID := Environment_Task;
1026
1027       if Time_Slice_Val = 0 or else FIFO_Within_Priorities then
1028          Res := OS_Interface.SetPriorityClass
1029            (GetCurrentProcess, Realtime_Priority_Class);
1030       end if;
1031
1032       TlsIndex := TlsAlloc;
1033
1034       --  Initialize the lock used to synchronize chain of all ATCBs.
1035
1036       Initialize_Lock (All_Tasks_L'Access, All_Tasks_Level);
1037
1038       Environment_Task.Common.LL.Thread := GetCurrentThread;
1039       Enter_Task (Environment_Task);
1040
1041       --  Create a free ATCB for use on the Fake_ATCB_List
1042
1043       Next_Fake_ATCB := new Fake_ATCB;
1044    end Initialize;
1045
1046    ---------------------
1047    -- Monotonic_Clock --
1048    ---------------------
1049
1050    function Monotonic_Clock return Duration
1051      renames System.OS_Primitives.Monotonic_Clock;
1052
1053    -------------------
1054    -- RT_Resolution --
1055    -------------------
1056
1057    function RT_Resolution return Duration is
1058    begin
1059       return 0.000_001; --  1 micro-second
1060    end RT_Resolution;
1061
1062    ----------------
1063    -- Check_Exit --
1064    ----------------
1065
1066    --  Dummy versions.  The only currently working versions is for solaris
1067    --  (native).
1068
1069    function Check_Exit (Self_ID : ST.Task_ID) return Boolean is
1070    begin
1071       return True;
1072    end Check_Exit;
1073
1074    --------------------
1075    -- Check_No_Locks --
1076    --------------------
1077
1078    function Check_No_Locks (Self_ID : ST.Task_ID) return Boolean is
1079    begin
1080       return True;
1081    end Check_No_Locks;
1082
1083    ------------------
1084    -- Suspend_Task --
1085    ------------------
1086
1087    function Suspend_Task
1088      (T           : ST.Task_ID;
1089       Thread_Self : Thread_Id) return Boolean is
1090    begin
1091       if T.Common.LL.Thread /= Thread_Self then
1092          return SuspendThread (T.Common.LL.Thread) = NO_ERROR;
1093       else
1094          return True;
1095       end if;
1096    end Suspend_Task;
1097
1098    -----------------
1099    -- Resume_Task --
1100    -----------------
1101
1102    function Resume_Task
1103      (T           : ST.Task_ID;
1104       Thread_Self : Thread_Id) return Boolean is
1105    begin
1106       if T.Common.LL.Thread /= Thread_Self then
1107          return ResumeThread (T.Common.LL.Thread) = NO_ERROR;
1108       else
1109          return True;
1110       end if;
1111    end Resume_Task;
1112
1113 end System.Task_Primitives.Operations;