summaryrefslogtreecommitdiff
path: root/gcc/m2/gm2-libs-coroutines/TimerHandler.mod
blob: 1285873486d6a22d8c22d0a1f7fc6c4df6886bb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
(* TimerHandler.mod provides a simple timer handler for the Executive.

Copyright (C) 2002-2023 Free Software Foundation, Inc.
Contributed by Gaius Mulley <gaius.mulley@southwales.ac.uk>.

This file is part of GNU Modula-2.

GNU Modula-2 is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.

GNU Modula-2 is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.

You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
<http://www.gnu.org/licenses/>.  *)

IMPLEMENTATION MODULE TimerHandler[MAX(PROTECTION)] ;


FROM COROUTINES IMPORT PROTECTION ;
FROM SysStorage IMPORT ALLOCATE ;
FROM NumberIO IMPORT CardToStr ;
FROM Debug IMPORT Halt, DebugString ;
FROM KeyBoardLEDs IMPORT SwitchScroll ;
FROM RTint IMPORT ReArmTimeVector, GetTimeVector, InitTimeVector ;
FROM Executive IMPORT DESCRIPTOR, Suspend, Resume, GetCurrentProcess,
                      WaitForIO, InitProcess, RotateRunQueue,
                      ProcessName, Ps ;

CONST
   MaxQuantum     =     4 ;   (* Maximum ticks a process may consume    *)
                              (* before being rescheduled.              *)
   BaseTicks      = 1000000 ; (* Max resolution of clock ticks per sec  *)
   TimerStackSize = 100000H ; (* Reasonable sized stack for a process   *)
   Debugging      =  FALSE ;  (* Do you want lots of debugging info?    *)
   EnableLED      =  FALSE ;  (* Should the scroll LED be pulsed?       *)

TYPE
   EVENT = POINTER TO RECORD
                         EventQ      : Queue ;
                         WhichQ      : QueueType ;
                         Process     : DESCRIPTOR ;
                         NoOfTicks   : CARDINAL ;
                         WasCancelled: BOOLEAN ;
                      END ;

   (* the queue types are either:

      active queue which has a list of outstanding events
      dead queue which is essentially the free list
      solo which is no queue and the event is in limbo
   *)

   QueueType = (active, dead, solo) ;

   Queue  = RECORD
               Right,
               Left : EVENT ;
            END ;

VAR
   TotalTicks    : CARDINAL ;   (* System up time tick count            *)
   CurrentQuanta : CARDINAL ;   (* Currentprocess time quanta allowance *)
   ActiveQueue,                 (* Queue of outstanding timer requests  *)
   DeadQueue     : EVENT ;      (* Free list of events.                 *)


(*
   GetTicks - returns the number of ticks since boottime.
*)

PROCEDURE GetTicks () : CARDINAL ;
VAR
   ToOldState : PROTECTION ;
   CopyOfTicks: CARDINAL ;
BEGIN
(*   ToOldState := TurnInterrupts(MAX(PROTECTION)) ;      (* disable interrupts *) *)
   CopyOfTicks := TotalTicks ;
(*   ToOldState := TurnInterrupts(ToOldState) ;         (* restore interrupts *) *)
   RETURN( CopyOfTicks )
END GetTicks ;


(*
   Sleep - suspends the current process for a time, t.
           The time is measured in ticks.
*)

PROCEDURE Sleep (t: CARDINAL) ;
VAR
   ToOldState: PROTECTION ;
   e         : EVENT ;
BEGIN
(* ToOldState := TurnInterrupts(MAX(PROTECTION)) ;               (* disable interrupts *) *)
   e := ArmEvent (t) ;
   IF WaitOn (e)
   THEN
   END ;
(* ToOldState := TurnInterrupts(ToOldState)          (* restore interrupts *) *)
END Sleep ;


(*
   More lower system calls to the timer procedures follow,
   they are necessary to allow handling multiple events.
*)


(*
   ArmEvent - initializes an event, e, to occur at time, t.
              The time, t, is measured in ticks.
              The event is NOT placed onto the event queue.
*)

PROCEDURE ArmEvent (t: CARDINAL) : EVENT ;
VAR
   e         : EVENT ;
   ToOldState: PROTECTION ;
   Ticks     : CARDINAL ;
BEGIN
(* ToOldState := TurnInterrupts(MAX(PROTECTION)) ;                (* disable interrupts *) *)
   e := CreateSolo() ;

   (* your code needs to go here *)
   WITH e^ DO                                                                       (* remove for student *)
      InitQueue(EventQ) ;           (* not on a queue yet                   *)      (* remove for student *)
      WhichQ       := solo ;        (* and set the queue state accordingly  *)      (* remove for student *)
      Process      := NIL ;         (* no process waiting event yet         *)      (* remove for student *)
      NoOfTicks    := t ;           (* absolute number of ticks             *)      (* remove for student *)
      WasCancelled := FALSE ;       (* has not been cancelled               *)      (* remove for student *)
   END ;                                                                            (* remove for student *)

(* ToOldState := TurnInterrupts(ToOldState) ;         (* restore interrupts *) *)
   RETURN( e )
END ArmEvent ;


(*
   WaitOn - places event, e, onto the event queue and then the calling
            process suspends. It is resumed up by either the event
            expiring or the event, e, being cancelled.
            TRUE is returned if the event was cancelled
            FALSE is returned if the event expires.
            The event, e, is always assigned to NIL when the function
            finishes.
*)

PROCEDURE WaitOn (VAR e: EVENT) : BOOLEAN ;
VAR
   ToOldState: PROTECTION ;
   Cancelled : BOOLEAN ;
BEGIN
(* ToOldState := TurnInterrupts(MAX(PROTECTION)) ;                (* disable interrupts *) *)
   IF e=NIL
   THEN
      Halt ('event should never be NIL',
            __FILE__, __FUNCTION__, __LINE__)
   ELSE
      WITH e^ DO
         (* we will just check to see whether someone has cancelled this    *)
         (* event before it ever got to the queue...                        *)
         IF NOT WasCancelled
         THEN
            (* right so it wasn't cancelled. Lets place it on the queue and *)
            (* go to sleep.                                                 *)
            Process := GetCurrentProcess() ;  (* so we know who is waiting  *)
            OnActiveQueue(e) ;                (* add to the queue and then  *)

            IF Debugging
            THEN
               DisplayActive ;  (* debugging *)
            END ;

            Suspend                           (* wait for Resume (we sleep) *)
         END ;
         (* At this point we have either been cancelled or not. We must     *)
         (* check the event again as we might have been sleeping (Suspend)  *)
         Cancelled := WasCancelled
      END
   END ;
   OnDeadQueue(e) ;              (* now it is safe to throw this event away *)
   e := NIL ;
(* ToOldState := TurnInterrupts(ToOldState) ;         (* restore interrupts *) *)
   RETURN Cancelled
END WaitOn ;


(*
   Cancel - cancels the event, e, on the event queue and makes
            the appropriate process runnable again.
            TRUE is returned if the event was cancelled and
            FALSE is returned is the event was not found or
                  no process was waiting on this event.
*)

PROCEDURE Cancel (e: EVENT) : BOOLEAN ;
VAR
   ToOldState: PROTECTION ;
   Cancelled : BOOLEAN ;
   Private   : DESCRIPTOR ;
BEGIN
(* ToOldState := TurnInterrupts(MAX(PROTECTION)) ;                (* disable interrupts *) *)
   IF IsOnActiveQueue(e)
   THEN
      WITH e^ DO
         Cancelled := NOT WasCancelled ;
         IF WasCancelled
         THEN
            Halt ('inconsistancy event has been cancelled and it is on queue',
                  __FILE__, __FUNCTION__, __LINE__)
         END ;
         OnSoloQueue(e) ;
         WasCancelled := TRUE ;
         IF Process#NIL                (* double check that it has not     *)
                                       (* already been cancelled           *)
         THEN
            Private := Process ;       (* we use our own Private variable  *)
            Process := NIL ;           (* as we need to set Process to NIL *)
            Process := Resume(Private) (* before we Resume. Otherwise      *)
                                       (* there is the possibility that it *)
                                       (* might be reused before we := NIL *)
                                       (* (because when we touch Resume    *)
                                       (* another process could run and..) *)
         END
      END
   ELSE
      Cancelled := FALSE
   END ;
(* ToOldState := TurnInterrupts(ToOldState) ;         (* restore interrupts *) *)
   RETURN( Cancelled )
END Cancel ;


(*
   ReArmEvent - removes an event, e, from the event queue. A new time
                is given to this event and it is then re-inserted onto the
                event queue in the correct place.
                TRUE is returned if this occurred
                FALSE is returned if the event was not found.
*)

PROCEDURE ReArmEvent (e: EVENT; t: CARDINAL) : BOOLEAN ;
VAR
   ToOldState: PROTECTION ;
   ReArmed   : BOOLEAN ;
BEGIN
(* ToOldState := TurnInterrupts(MAX(PROTECTION)) ;                (* disable interrupts *) *)
   WITH e^ DO
      IF WasCancelled
      THEN
         ReArmed := FALSE
      ELSIF IsOnActiveQueue(e) OR IsOnSoloQueue(e)
      THEN
         ReArmed := TRUE ;
         OnSoloQueue(e) ;                             (* remove from queue  *)
         NoOfTicks := t ;                             (* give it a new time *)
         OnActiveQueue(e)                             (* back on queue      *)
      ELSE
         Halt ('ReArm should not be asked to ReArm a dead event',
               __FILE__, __FUNCTION__, __LINE__)
      END
   END ;
(* ToOldState := TurnInterrupts(ToOldState) ;         (* restore interrupts *) *)
   RETURN( ReArmed )
END ReArmEvent ;


(*
   StartClock - ticks is milli seconds.
*)

PROCEDURE StartClock (vec: CARDINAL; ticks: CARDINAL) ;
BEGIN
   ReArmTimeVector (vec, ticks MOD BaseTicks, ticks DIV BaseTicks)
END StartClock ;


(*
   LoadClock - returns the number of milli seconds.
*)

PROCEDURE LoadClock (vec: CARDINAL) : CARDINAL ;
VAR
   micro, secs: CARDINAL ;
BEGIN
   GetTimeVector (vec, micro, secs) ;
   RETURN secs * BaseTicks + micro
END LoadClock ;


(*
   Timer  - is a process which serves the clock interrupt.
            Its function is fourfold:

            (i)   to maintain the timer event queue
            (ii)  to give some fairness to processes via round robin scheduling
            (iii) to keep a count of the total ticks so far  (time of day)
            (iv)  provide a heartbeat sign of life via the scroll lock LED
*)

PROCEDURE Timer ;
VAR
   CurrentCount: CARDINAL ;
   ToOldState  : PROTECTION ;
   ScrollLED   : BOOLEAN ;
   TimerIntNo  : CARDINAL ;
   r           : INTEGER ;
BEGIN
(* ToOldState := TurnInterrupts(MAX(PROTECTION)) ; *)
   ScrollLED := FALSE ;
   TimerIntNo := InitTimeVector ((BaseTicks DIV TicksPerSecond) MOD BaseTicks,
                                 (BaseTicks DIV TicksPerSecond) DIV BaseTicks,
                                 MAX (PROTECTION)) ;
   LOOP
      WaitForIO (TimerIntNo) ;

      (* Get current clock count *)
      CurrentCount := (* LoadClock(TimerIntNo) ; *) 0 ;
      (* Now compenstate for lost ticks *)
      StartClock (TimerIntNo, CurrentCount + (BaseTicks DIV TicksPerSecond)) ;

      INC (TotalTicks) ;                                     (* (iii) *)
      IF EnableLED
      THEN
         (* now pulse scroll LED *)
         IF (TotalTicks MOD TicksPerSecond) = 0
         THEN
            ScrollLED := NOT ScrollLED ;
            (* r := printf("<scroll %d>", TotalTicks); *)
            SwitchScroll(ScrollLED)                          (* (iv)  *)
         END
      END ;
      IF (TotalTicks MOD MaxQuantum) = 0
      THEN
         RotateRunQueue                                      (* (ii)  *)
      END ;

      CheckActiveQueue                                       (* (i)   *)
   END
END Timer ;


(*
   CheckActiveQueue - purpose is:

                      (i)   to remove all events which have expired
                      (ii)  resume all processes waiting on these events
                      (iii) decrement the first event with a non zero NoOfTicks
*)

PROCEDURE CheckActiveQueue ;
VAR
   e      : EVENT ;
   Private: DESCRIPTOR ;
BEGIN
   IF Debugging
   THEN
      DebugString('inside CheckActiveQueue\n') ;
      DisplayActive
   END ;
   WHILE (ActiveQueue#NIL) AND (ActiveQueue^.NoOfTicks=0) DO    (* (i)  *)
      e := ActiveQueue ;
      OnSoloQueue(e) ;
      (* note we do not put it onto the dead queue. The process
         waiting for the event will place, e, onto the dead queue *)
      WITH e^ DO
         IF (NOT WasCancelled) AND (Process#NIL)
         THEN
            Private := Process ;    (* we use our own Private variable  *)
            Process := NIL ;        (* as we might context switch in    *)
            Process := Resume(Private) ;  (* resume.               (ii) *)
            IF Debugging
            THEN
               Ps
            END
         END
      END
   END ;
   IF ActiveQueue#NIL
   THEN
      DEC(ActiveQueue^.NoOfTicks)                              (* (iii) *)
   END ;
   IF Debugging
   THEN
      DebugString('after CheckActiveQueue\n') ;
      DisplayActive
   END ;
END CheckActiveQueue ;


(*
   CreateSolo - create a new event. It does this by either getting an event from
                the dead queue or (if the dead queue is empty) an event is created
                by using NEW.
*)

PROCEDURE CreateSolo () : EVENT ;
VAR
   e: EVENT ;
BEGIN
   IF DeadQueue=NIL
   THEN
      NEW(e)
   ELSE
      e := DeadQueue ;
      SubFrom(DeadQueue, e)
   END ;
   e^.WhichQ := solo ;
   RETURN( e )
END CreateSolo ;


(*
   RemoveFromDead - removes event, e, from the dead queue.
*)

PROCEDURE RemoveFromDead (e: EVENT) ;
BEGIN
   SubFrom(DeadQueue, e)
END RemoveFromDead ;


(*
   OnDeadQueue - places an event onto the dead queue.
*)

PROCEDURE OnDeadQueue (e: EVENT) ;
BEGIN
   IF e#NIL
   THEN
      OnSoloQueue(e) ;                   (* put on solo queue first       *)
      AddTo(DeadQueue, e) ;              (* now safe to put on dead queue *)
      e^.WhichQ := dead
   END
END OnDeadQueue ;


(*
   OnSoloQueue - places an event onto the solo queue.
*)

PROCEDURE OnSoloQueue (e: EVENT) ;
BEGIN
   IF e#NIL
   THEN
      IF IsOnActiveQueue(e)
      THEN
         RemoveFromActive(e)
      ELSIF IsOnDeadQueue(e)
      THEN
         RemoveFromDead(e)
      END ;
      e^.WhichQ := solo
   END
END OnSoloQueue ;


(*
   OnActiveQueue - places an event onto the active queue.
*)

PROCEDURE OnActiveQueue (e: EVENT) ;
BEGIN
   IF e#NIL
   THEN
      IF IsOnDeadQueue(e)
      THEN
         Halt ('illegal state change',
               __FILE__, __FUNCTION__, __LINE__)
      ELSIF IsOnSoloQueue(e)
      THEN
         RelativeAddToActive(e) ;
         e^.WhichQ := active
      END
   END
END OnActiveQueue ;


(*
   IsOnSoloQueue - returns TRUE if event, e, is on the solo queue.
*)

PROCEDURE IsOnSoloQueue (e: EVENT) : BOOLEAN ;
BEGIN
   RETURN( (e#NIL) AND (e^.WhichQ=solo) )
END IsOnSoloQueue ;


(*
   IsOnDeadQueue - returns TRUE if event, e, is on the dead queue.
*)

PROCEDURE IsOnDeadQueue (e: EVENT) : BOOLEAN ;
BEGIN
   RETURN( (e#NIL) AND (e^.WhichQ=dead) )
END IsOnDeadQueue ;


(*
   IsOnActiveQueue - returns TRUE if event, e, is on the active queue.
*)

PROCEDURE IsOnActiveQueue (e: EVENT) : BOOLEAN ;
BEGIN
   RETURN( (e#NIL) AND (e^.WhichQ=active) )
END IsOnActiveQueue ;


(*
   RemoveFromActive - removes an event, e, from the active queue.
*)

PROCEDURE RemoveFromActive (e: EVENT) ;
BEGIN
   IF ActiveQueue=e
   THEN
      SubFrom(ActiveQueue, e) ;
      (* providing that the ActiveQueue is non empty we need to
         modify first event ticks as we have removed the first event, e. *)
      IF ActiveQueue#NIL
      THEN
         INC(ActiveQueue^.NoOfTicks, e^.NoOfTicks)
      END
   ELSE
      (* providing that event, e, is not the last event on the list then
         update the next event by the time of, e. *)
      IF e^.EventQ.Right#ActiveQueue
      THEN
         INC(e^.EventQ.Right^.NoOfTicks, e^.NoOfTicks)
      END ;
      SubFrom(ActiveQueue, e)
   END
END RemoveFromActive ;


(*
   InsertBefore - insert an event, new, on a circular event queue BEFORE
                  event, pos.
*)

PROCEDURE InsertBefore (VAR Head: EVENT; pos, new: EVENT) ;
BEGIN
   IF Head=NIL
   THEN
      (* empty queue *)
      Head := new ;
      new^.EventQ.Right := new ;
      new^.EventQ.Left := new
   ELSIF Head=pos
   THEN
      (* insert before the first element on the queue *)
      new^.EventQ.Right := pos ;
      new^.EventQ.Left := pos^.EventQ.Left ;
      pos^.EventQ.Left^.EventQ.Right := new ;
      pos^.EventQ.Left := new ;
      Head := new
   ELSE
      (* insert before any other element *)
      new^.EventQ.Right := pos ;
      new^.EventQ.Left := pos^.EventQ.Left ;
      pos^.EventQ.Left^.EventQ.Right := new ;
      pos^.EventQ.Left := new
   END
END InsertBefore ;


(*
   InsertAfter - place an event, new, AFTER the event pos on any circular event queue.
*)

PROCEDURE InsertAfter (pos, new: EVENT) ;
BEGIN
   new^.EventQ.Right := pos^.EventQ.Right ;
   new^.EventQ.Left := pos ;
   pos^.EventQ.Right^.EventQ.Left := new ;
   pos^.EventQ.Right := new
END InsertAfter ;


(*
   RelativeAddToActive - the active event queue is an ordered queue of
                         relative time events.
                         The event, e, is inserted at the appropriate
                         position in the queue. The event, e, enters
                         this routine with an absolute NoOfTicks field which
                         is then used to work out the relative position
                         of the event. After the position is found then
                         the absolute NoOfTicks field is altered to a
                         relative value and inserted on the queue.
*)

PROCEDURE RelativeAddToActive (e: EVENT) ;
VAR
   t  : EVENT ;
   sum: CARDINAL ;
BEGIN
   IF ActiveQueue = NIL
   THEN
      (* simple as the queue is empty (relative=absolute) *)
      InsertBefore (ActiveQueue, ActiveQueue, e)
   ELSE
      (* at the end of the while loop sum will contain the total of all
         events up to but not including, t.
         If the value of sum is <  e^.NoOfTicks then e must be placed at the end
                                >= e^.NoOfTicks then e needs to be placed in the middle
      *)

      sum := ActiveQueue^.NoOfTicks ;
      t := ActiveQueue^.EventQ.Right ;      (* second event *)
      WHILE (sum < e^.NoOfTicks) AND (t # ActiveQueue) DO
         INC (sum, t^.NoOfTicks) ;
         t := t^.EventQ.Right
      END ;
      IF sum < e^.NoOfTicks
      THEN
         (* e will occur after all the current ActiveQueue has expired therefore
            we must add it to the end of the ActiveQueue. *)
         DEC (e^.NoOfTicks, sum) ;
         InsertAfter (ActiveQueue^.EventQ.Left, e)
      ELSE
         (* as sum >= e^.NoOfTicks we know that e is scheduled to occur
            in the middle of the queue but before t^.Left
         *)
         DEC (e^.NoOfTicks, sum-t^.EventQ.Left^.NoOfTicks) ;
         InsertBefore (ActiveQueue, t^.EventQ.Left, e)
      END ;
      (* the first event after e must have its relative NoOfTicks altered *)
      IF e^.EventQ.Right # ActiveQueue
      THEN
         DEC (e^.EventQ.Right^.NoOfTicks, e^.NoOfTicks)
      END
   END
END RelativeAddToActive ;


(*
   AddTo - adds an event to a specified queue.
*)

PROCEDURE AddTo (VAR Head: EVENT; e: EVENT) ;
BEGIN
   IF Head=NIL
   THEN
      Head := e ;
      e^.EventQ.Left := e ;
      e^.EventQ.Right := e
   ELSE
      e^.EventQ.Right := Head ;
      e^.EventQ.Left := Head^.EventQ.Left ;
      Head^.EventQ.Left^.EventQ.Right := e ;
      Head^.EventQ.Left := e
   END
END AddTo ;


(*
   SubFrom - removes an event from a queue.
*)

PROCEDURE SubFrom (VAR Head: EVENT; e: EVENT) ;
BEGIN
   IF (e^.EventQ.Left = Head) AND (e = Head)
   THEN
      Head := NIL
   ELSE
      IF Head = e
      THEN
         Head := Head^.EventQ.Right
      END ;
      e^.EventQ.Left^.EventQ.Right := e^.EventQ.Right ;
      e^.EventQ.Right^.EventQ.Left := e^.EventQ.Left
   END
END SubFrom ;


(*
   DisplayActive - display the active queue.
*)

PROCEDURE DisplayActive ;
VAR
   e: EVENT ;
BEGIN
   e := ActiveQueue ;
   IF e#NIL
   THEN
      REPEAT
         DisplayEvent(e) ;
         e := e^.EventQ.Right
      UNTIL e=ActiveQueue
   END
END DisplayActive ;


(*
   DisplayEvent - display a single event, e.
*)

PROCEDURE DisplayEvent (e: EVENT) ;
VAR
   a: ARRAY [0..20] OF CHAR ;
BEGIN
   WITH e^ DO
      CardToStr(NoOfTicks, 6, a) ;
      DebugString(a) ;
      DebugString('  process (') ;
      IF Process=NIL
      THEN
         DebugString('is NIL') ;
      ELSE
         ProcessName(Process)
      END ;
      DebugString(')') ;
      IF WasCancelled
      THEN
         DebugString('  has been cancelled')
      END
   END ;
   DebugString('\n')
END DisplayEvent ;


(*
   InitQueue -
*)

PROCEDURE InitQueue (VAR q: Queue) ;
BEGIN
   q.Right := NIL ;
   q.Left  := NIL
END InitQueue ;


(*
   Init - starts the timer process and initializes some queues.
*)

PROCEDURE Init ;
VAR
   d: DESCRIPTOR ;
BEGIN
   TotalTicks := 0 ;
   CurrentQuanta := 0 ;
   ActiveQueue := NIL ;
   DeadQueue := NIL ;
   d := Resume(InitProcess(Timer, TimerStackSize, 'Timer'))
END Init ;


BEGIN
   Init
END TimerHandler.