OSDN Git Service

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