OSDN Git Service

2008-05-27 Thomas Quinot <quinot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / s-asthan-vms-alpha.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                        GNAT RUN-TIME COMPONENTS                          --
4 --                                                                          --
5 --                  S Y S T E M . A S T _ H A N D L I N G                   --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1996-2008, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT 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.  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.  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 GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, 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 -- GNAT was originally developed  by the GNAT team at  New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
31 --                                                                          --
32 ------------------------------------------------------------------------------
33
34 --  This is the OpenVMS/Alpha version
35
36 with System; use System;
37
38 with System.IO;
39
40 with System.Machine_Code;
41 with System.Parameters;
42 with System.Storage_Elements;
43
44 with System.Tasking;
45 with System.Tasking.Rendezvous;
46 with System.Tasking.Initialization;
47 with System.Tasking.Utilities;
48
49 with System.Task_Primitives;
50 with System.Task_Primitives.Operations;
51 with System.Task_Primitives.Operations.DEC;
52
53 --  with Ada.Finalization;
54 --  removed, because of problem with controlled attribute ???
55
56 with Ada.Task_Attributes;
57
58 with Ada.Exceptions; use Ada.Exceptions;
59
60 with Ada.Unchecked_Conversion;
61
62 package body System.AST_Handling is
63
64    package ATID renames Ada.Task_Identification;
65
66    package SP   renames System.Parameters;
67    package ST   renames System.Tasking;
68    package STR  renames System.Tasking.Rendezvous;
69    package STI  renames System.Tasking.Initialization;
70    package STU  renames System.Tasking.Utilities;
71
72    package SSE  renames System.Storage_Elements;
73    package STPO renames System.Task_Primitives.Operations;
74    package STPOD renames System.Task_Primitives.Operations.DEC;
75
76    AST_Lock : aliased System.Task_Primitives.RTS_Lock;
77    --  This is a global lock; it is used to execute in mutual exclusion
78    --  from all other AST tasks.  It is only used by Lock_AST and
79    --  Unlock_AST.
80
81    procedure Lock_AST (Self_ID : ST.Task_Id);
82    --  Locks out other AST tasks. Preceding a section of code by Lock_AST and
83    --  following it by Unlock_AST creates a critical region.
84
85    procedure Unlock_AST (Self_ID : ST.Task_Id);
86    --  Releases lock previously set by call to Lock_AST.
87    --  All nested locks must be released before other tasks competing for the
88    --  tasking lock are released.
89
90    --------------
91    -- Lock_AST --
92    --------------
93
94    procedure Lock_AST (Self_ID : ST.Task_Id) is
95    begin
96       STI.Defer_Abort_Nestable (Self_ID);
97       STPO.Write_Lock (AST_Lock'Access, Global_Lock => True);
98    end Lock_AST;
99
100    ----------------
101    -- Unlock_AST --
102    ----------------
103
104    procedure Unlock_AST (Self_ID : ST.Task_Id) is
105    begin
106       STPO.Unlock (AST_Lock'Access, Global_Lock => True);
107       STI.Undefer_Abort_Nestable (Self_ID);
108    end Unlock_AST;
109
110    ---------------------------------
111    -- AST_Handler Data Structures --
112    ---------------------------------
113
114    --  As noted in the private part of the spec of System.Aux_DEC, the
115    --  AST_Handler type is simply a pointer to a procedure that takes
116    --  a single 64bit parameter. The following is a local copy
117    --  of that definition.
118
119    --  We need our own copy because we need to get our hands on this
120    --  and we cannot see the private part of System.Aux_DEC. We don't
121    --  want to be a child of Aux_Dec because of complications resulting
122    --  from the use of pragma Extend_System. We will use unchecked
123    --  conversions between the two versions of the declarations.
124
125    type AST_Handler is access procedure (Param : Long_Integer);
126
127    --  However, this declaration is somewhat misleading, since the values
128    --  referenced by AST_Handler values (all produced in this package by
129    --  calls to Create_AST_Handler) are highly stylized.
130
131    --  The first point is that in VMS/Alpha, procedure pointers do not in
132    --  fact point to code, but rather to a 48-byte procedure descriptor.
133    --  So a value of type AST_Handler is in fact a pointer to one of these
134    --  48-byte descriptors.
135
136    type Descriptor_Type is new SSE.Storage_Array (1 .. 48);
137    for  Descriptor_Type'Alignment use Standard'Maximum_Alignment;
138    pragma Warnings (Off, Descriptor_Type);
139    --  Suppress harmless warnings about alignment.
140    --  Should explain why this warning is harmless ???
141
142    type Descriptor_Ref is access all Descriptor_Type;
143
144    --  Normally, there is only one such descriptor for a given procedure, but
145    --  it works fine to make a copy of the single allocated descriptor, and
146    --  use the copy itself, and we take advantage of this in the design here.
147    --  The idea is that AST_Handler values will all point to a record with the
148    --  following structure:
149
150    --  Note: When we say it works fine, there is one delicate point, which
151    --  is that the code for the AST procedure itself requires the original
152    --  descriptor address.  We handle this by saving the original descriptor
153    --  address in this structure and restoring in Process_AST.
154
155    type AST_Handler_Data is record
156       Descriptor              : Descriptor_Type;
157       Original_Descriptor_Ref : Descriptor_Ref;
158       Taskid                  : ATID.Task_Id;
159       Entryno                 : Natural;
160    end record;
161
162    type AST_Handler_Data_Ref is access all AST_Handler_Data;
163
164    function To_AST_Handler is new Ada.Unchecked_Conversion
165      (AST_Handler_Data_Ref, System.Aux_DEC.AST_Handler);
166
167    --  Each time Create_AST_Handler is called, a new value of this record
168    --  type is created, containing a copy of the procedure descriptor for
169    --  the routine used to handle all AST's (Process_AST), and the Task_Id
170    --  and entry number parameters identifying the task entry involved.
171
172    --  The AST_Handler value returned is a pointer to this record. Since
173    --  the record starts with the procedure descriptor, it can be used
174    --  by the system in the normal way to call the procedure. But now
175    --  when the procedure gets control, it can determine the address of
176    --  the procedure descriptor used to call it (since the ABI specifies
177    --  that this is left sitting in register r27 on entry), and then use
178    --  that address to retrieve the Task_Id and entry number so that it
179    --  knows on which entry to queue the AST request.
180
181    --  The next issue is where are these records placed. Since we intend
182    --  to pass pointers to these records to asynchronous system service
183    --  routines, they have to be on the heap, which means we have to worry
184    --  about when to allocate them and deallocate them.
185
186    --  We solve this problem by introducing a task attribute that points to
187    --  a vector, indexed by the entry number, of AST_Handler_Data records
188    --  for a given task. The pointer itself is a controlled object allowing
189    --  us to write a finalization routine that frees the referenced vector.
190
191    --  An entry in this vector is either initialized (Entryno non-zero) and
192    --  can be used for any subsequent reference to the same entry, or it is
193    --  unused, marked by the Entryno value being zero.
194
195    type AST_Handler_Vector is array (Natural range <>) of AST_Handler_Data;
196    type AST_Handler_Vector_Ref is access all AST_Handler_Vector;
197
198 --  type AST_Vector_Ptr is new Ada.Finalization.Controlled with record
199 --  removed due to problem with controlled attribute, consequence is that
200 --  we have a memory leak if a task that has AST attribute entries is
201 --  terminated. ???
202
203    type AST_Vector_Ptr is record
204       Vector : AST_Handler_Vector_Ref;
205    end record;
206
207    AST_Vector_Init : AST_Vector_Ptr;
208    --  Initial value, treated as constant, Vector will be null
209
210    package AST_Attribute is new Ada.Task_Attributes
211      (Attribute     => AST_Vector_Ptr,
212       Initial_Value => AST_Vector_Init);
213
214    use AST_Attribute;
215
216    -----------------------
217    -- AST Service Queue --
218    -----------------------
219
220    --  The following global data structures are used to queue pending
221    --  AST requests. When an AST is signalled, the AST service routine
222    --  Process_AST is called, and it makes an entry in this structure.
223
224    type AST_Instance is record
225       Taskid  : ATID.Task_Id;
226       Entryno : Natural;
227       Param   : Long_Integer;
228    end record;
229    --  The Taskid and Entryno indicate the entry on which this AST is to
230    --  be queued, and Param is the parameter provided from the AST itself.
231
232    AST_Service_Queue_Size  : constant := 256;
233    AST_Service_Queue_Limit : constant := 250;
234    type AST_Service_Queue_Index is mod AST_Service_Queue_Size;
235    --  Index used to refer to entries in the circular buffer which holds
236    --  active AST_Instance values. The upper bound reflects the maximum
237    --  number of AST instances that can be stored in the buffer. Since
238    --  these entries are immediately serviced by the high priority server
239    --  task that does the actual entry queuing, it is very unusual to have
240    --  any significant number of entries simultaneously queued.
241
242    AST_Service_Queue : array (AST_Service_Queue_Index) of AST_Instance;
243    pragma Volatile_Components (AST_Service_Queue);
244    --  The circular buffer used to store active AST requests
245
246    AST_Service_Queue_Put : AST_Service_Queue_Index := 0;
247    AST_Service_Queue_Get : AST_Service_Queue_Index := 0;
248    pragma Atomic (AST_Service_Queue_Put);
249    pragma Atomic (AST_Service_Queue_Get);
250    --  These two variables point to the next slots in the AST_Service_Queue
251    --  to be used for putting a new entry in and taking an entry out. This
252    --  is a circular buffer, so these pointers wrap around. If the two values
253    --  are equal the buffer is currently empty. The pointers are atomic to
254    --  ensure proper synchronization between the single producer (namely the
255    --  Process_AST procedure), and the single consumer (the AST_Service_Task).
256
257    --------------------------------
258    -- AST Server Task Structures --
259    --------------------------------
260
261    --  The basic approach is that when an AST comes in, a call is made to
262    --  the Process_AST procedure. It queues the request in the service queue
263    --  and then wakes up an AST server task to perform the actual call to the
264    --  required entry. We use this intermediate server task, since the AST
265    --  procedure itself cannot wait to return, and we need some caller for
266    --  the rendezvous so that we can use the normal rendezvous mechanism.
267
268    --  It would work to have only one AST server task, but then we would lose
269    --  all overlap in AST processing, and furthermore, we could get priority
270    --  inversion effects resulting in starvation of AST requests.
271
272    --  We therefore maintain a small pool of AST server tasks. We adjust
273    --  the size of the pool dynamically to reflect traffic, so that we have
274    --  a sufficient number of server tasks to avoid starvation.
275
276    Max_AST_Servers : constant Natural := 16;
277    --  Maximum number of AST server tasks that can be allocated
278
279    Num_AST_Servers : Natural := 0;
280    --  Number of AST server tasks currently active
281
282    Num_Waiting_AST_Servers : Natural := 0;
283    --  This is the number of AST server tasks that are either waiting for
284    --  work, or just about to go to sleep and wait for work.
285
286    Is_Waiting : array (1 .. Max_AST_Servers) of Boolean := (others => False);
287    --  An array of flags showing which AST server tasks are currently waiting
288
289    AST_Task_Ids : array (1 .. Max_AST_Servers) of ST.Task_Id;
290    --  Task Id's of allocated AST server tasks
291
292    task type AST_Server_Task (Num : Natural) is
293       pragma Priority (Priority'Last);
294    end AST_Server_Task;
295    --  Declaration for AST server task. This task has no entries, it is
296    --  controlled by sleep and wakeup calls at the task primitives level.
297
298    type AST_Server_Task_Ptr is access all AST_Server_Task;
299    --  Type used to allocate server tasks
300
301    -----------------------
302    -- Local Subprograms --
303    -----------------------
304
305    procedure Allocate_New_AST_Server;
306    --  Allocate an additional AST server task
307
308    procedure Process_AST (Param : Long_Integer);
309    --  This is the central routine for processing all AST's, it is referenced
310    --  as the code address of all created AST_Handler values. See detailed
311    --  description in body to understand how it works to have a single such
312    --  procedure for all AST's even though it does not get any indication of
313    --  the entry involved passed as an explicit parameter. The single explicit
314    --  parameter Param is the parameter passed by the system with the AST.
315
316    -----------------------------
317    -- Allocate_New_AST_Server --
318    -----------------------------
319
320    procedure Allocate_New_AST_Server is
321       Dummy : AST_Server_Task_Ptr;
322       pragma Unreferenced (Dummy);
323
324    begin
325       if Num_AST_Servers = Max_AST_Servers then
326          return;
327
328       else
329          --  Note: it is safe to increment Num_AST_Servers immediately, since
330          --  no one will try to activate this task until it indicates that it
331          --  is sleeping by setting its entry in Is_Waiting to True.
332
333          Num_AST_Servers := Num_AST_Servers + 1;
334          Dummy := new AST_Server_Task (Num_AST_Servers);
335       end if;
336    end Allocate_New_AST_Server;
337
338    ---------------------
339    -- AST_Server_Task --
340    ---------------------
341
342    task body AST_Server_Task is
343       Taskid  : ATID.Task_Id;
344       Entryno : Natural;
345       Param   : aliased Long_Integer;
346       Self_Id : constant ST.Task_Id := ST.Self;
347
348       pragma Volatile (Param);
349
350    begin
351       --  By making this task independent of master, when the environment
352       --  task is finalizing, the AST_Server_Task will be notified that it
353       --  should terminate.
354
355       STU.Make_Independent;
356
357       --  Record our task Id for access by Process_AST
358
359       AST_Task_Ids (Num) := Self_Id;
360
361       --  Note: this entire task operates with the main task lock set, except
362       --  when it is sleeping waiting for work, or busy doing a rendezvous
363       --  with an AST server. This lock protects the data structures that
364       --  are shared by multiple instances of the server task.
365
366       Lock_AST (Self_Id);
367
368       --  This is the main infinite loop of the task. We go to sleep and
369       --  wait to be woken up by Process_AST when there is some work to do.
370
371       loop
372          Num_Waiting_AST_Servers := Num_Waiting_AST_Servers + 1;
373
374          Unlock_AST (Self_Id);
375
376          STI.Defer_Abort (Self_Id);
377
378          if SP.Single_Lock then
379             STPO.Lock_RTS;
380          end if;
381
382          STPO.Write_Lock (Self_Id);
383
384          Is_Waiting (Num) := True;
385
386          Self_Id.Common.State := ST.AST_Server_Sleep;
387          STPO.Sleep (Self_Id, ST.AST_Server_Sleep);
388          Self_Id.Common.State := ST.Runnable;
389
390          STPO.Unlock (Self_Id);
391
392          if SP.Single_Lock then
393             STPO.Unlock_RTS;
394          end if;
395
396          --  If the process is finalizing, Undefer_Abort will simply end
397          --  this task.
398
399          STI.Undefer_Abort (Self_Id);
400
401          --  We are awake, there is something to do!
402
403          Lock_AST (Self_Id);
404          Num_Waiting_AST_Servers := Num_Waiting_AST_Servers - 1;
405
406          --  Loop here to service outstanding requests. We are always
407          --  locked on entry to this loop.
408
409          while AST_Service_Queue_Get /= AST_Service_Queue_Put loop
410             Taskid  := AST_Service_Queue (AST_Service_Queue_Get).Taskid;
411             Entryno := AST_Service_Queue (AST_Service_Queue_Get).Entryno;
412             Param   := AST_Service_Queue (AST_Service_Queue_Get).Param;
413
414             AST_Service_Queue_Get := AST_Service_Queue_Get + 1;
415
416             --  This is a manual expansion of the normal call simple code
417
418             declare
419                type AA is access all Long_Integer;
420                P : AA := Param'Unrestricted_Access;
421
422                function To_ST_Task_Id is new Ada.Unchecked_Conversion
423                  (ATID.Task_Id, ST.Task_Id);
424
425             begin
426                Unlock_AST (Self_Id);
427                STR.Call_Simple
428                  (Acceptor           => To_ST_Task_Id (Taskid),
429                   E                  => ST.Task_Entry_Index (Entryno),
430                   Uninterpreted_Data => P'Address);
431
432             exception
433                when E : others =>
434                   System.IO.Put_Line ("%Debugging event");
435                   System.IO.Put_Line (Exception_Name (E) &
436                     " raised when trying to deliver an AST.");
437
438                   if Exception_Message (E)'Length /= 0 then
439                      System.IO.Put_Line (Exception_Message (E));
440                   end if;
441
442                   System.IO.Put_Line ("Task type is " & "Receiver_Type");
443                   System.IO.Put_Line ("Task id is " & ATID.Image (Taskid));
444             end;
445
446             Lock_AST (Self_Id);
447          end loop;
448       end loop;
449    end AST_Server_Task;
450
451    ------------------------
452    -- Create_AST_Handler --
453    ------------------------
454
455    function Create_AST_Handler
456      (Taskid  : ATID.Task_Id;
457       Entryno : Natural) return System.Aux_DEC.AST_Handler
458    is
459       Attr_Ref : Attribute_Handle;
460
461       Process_AST_Ptr : constant AST_Handler := Process_AST'Access;
462       --  Reference to standard procedure descriptor for Process_AST
463
464       function To_Descriptor_Ref is new Ada.Unchecked_Conversion
465         (AST_Handler, Descriptor_Ref);
466
467       Original_Descriptor_Ref : constant Descriptor_Ref :=
468                                   To_Descriptor_Ref (Process_AST_Ptr);
469
470    begin
471       if ATID.Is_Terminated (Taskid) then
472          raise Program_Error;
473       end if;
474
475       Attr_Ref := Reference (Taskid);
476
477       --  Allocate another server if supply is getting low
478
479       if Num_Waiting_AST_Servers < 2 then
480          Allocate_New_AST_Server;
481       end if;
482
483       --  No point in creating more if we have zillions waiting to
484       --  be serviced.
485
486       while AST_Service_Queue_Put - AST_Service_Queue_Get
487          > AST_Service_Queue_Limit
488       loop
489          delay 0.01;
490       end loop;
491
492       --  If no AST vector allocated, or the one we have is too short, then
493       --  allocate one of right size and initialize all entries except the
494       --  one we will use to unused. Note that the assignment automatically
495       --  frees the old allocated table if there is one.
496
497       if Attr_Ref.Vector = null
498         or else Attr_Ref.Vector'Length < Entryno
499       then
500          Attr_Ref.Vector := new AST_Handler_Vector (1 .. Entryno);
501
502          for E in 1 .. Entryno loop
503             Attr_Ref.Vector (E).Descriptor :=
504               Original_Descriptor_Ref.all;
505             Attr_Ref.Vector (E).Original_Descriptor_Ref :=
506               Original_Descriptor_Ref;
507             Attr_Ref.Vector (E).Taskid  := Taskid;
508             Attr_Ref.Vector (E).Entryno := E;
509          end loop;
510       end if;
511
512       return To_AST_Handler (Attr_Ref.Vector (Entryno)'Unrestricted_Access);
513    end Create_AST_Handler;
514
515    ----------------------------
516    -- Expand_AST_Packet_Pool --
517    ----------------------------
518
519    procedure Expand_AST_Packet_Pool
520      (Requested_Packets : Natural;
521       Actual_Number     : out Natural;
522       Total_Number      : out Natural)
523    is
524       pragma Unreferenced (Requested_Packets);
525    begin
526       --  The AST implementation of GNAT does not permit dynamic expansion
527       --  of the pool, so we simply add no entries and return the total. If
528       --  it is necessary to expand the allocation, then this package body
529       --  must be recompiled with a larger value for AST_Service_Queue_Size.
530
531       Actual_Number := 0;
532       Total_Number := AST_Service_Queue_Size;
533    end Expand_AST_Packet_Pool;
534
535    -----------------
536    -- Process_AST --
537    -----------------
538
539    procedure Process_AST (Param : Long_Integer) is
540
541       Handler_Data_Ptr : AST_Handler_Data_Ref;
542       --  This variable is set to the address of the descriptor through
543       --  which Process_AST is called. Since the descriptor is part of
544       --  an AST_Handler value, this is also the address of this value,
545       --  from which we can obtain the task and entry number information.
546
547       function To_Address is new Ada.Unchecked_Conversion
548         (ST.Task_Id, System.Task_Primitives.Task_Address);
549
550    begin
551       System.Machine_Code.Asm
552         (Template => "addq $27,0,%0",
553          Outputs  => AST_Handler_Data_Ref'Asm_Output ("=r", Handler_Data_Ptr),
554          Volatile => True);
555
556       System.Machine_Code.Asm
557         (Template => "ldq $27,%0",
558          Inputs  => Descriptor_Ref'Asm_Input
559            ("m", Handler_Data_Ptr.Original_Descriptor_Ref),
560          Volatile => True);
561
562       AST_Service_Queue (AST_Service_Queue_Put) := AST_Instance'
563         (Taskid  => Handler_Data_Ptr.Taskid,
564          Entryno => Handler_Data_Ptr.Entryno,
565          Param   => Param);
566
567       --  OpenVMS Programming Concepts manual, chapter 8.2.3:
568       --  "Implicit synchronization can be achieved for data that is shared
569       --   for write by using only AST routines to write the data, since only
570       --   one AST can be running at any one time."
571
572       --  This subprogram runs at AST level so is guaranteed to be
573       --  called sequentially at a given access level.
574
575       AST_Service_Queue_Put := AST_Service_Queue_Put + 1;
576
577       --  Need to wake up processing task. If there is no waiting server
578       --  then we have temporarily run out, but things should still be
579       --  OK, since one of the active ones will eventually pick up the
580       --  service request queued in the AST_Service_Queue.
581
582       for J in 1 .. Num_AST_Servers loop
583          if Is_Waiting (J) then
584             Is_Waiting (J) := False;
585
586             --  Sleeps are handled by ASTs on VMS, so don't call Wakeup
587
588             STPOD.Interrupt_AST_Handler (To_Address (AST_Task_Ids (J)));
589             exit;
590          end if;
591       end loop;
592    end Process_AST;
593
594 begin
595    STPO.Initialize_Lock (AST_Lock'Access, STPO.Global_Task_Level);
596 end System.AST_Handling;