File: time.c

package info (click to toggle)
swi-prolog 5.6.58-2
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 73,288 kB
  • ctags: 42,973
  • sloc: ansic: 273,575; perl: 193,068; cpp: 8,361; sh: 5,329; java: 5,136; makefile: 5,048; yacc: 843; xml: 77; csh: 16; awk: 14; sed: 12
file content (1045 lines) | stat: -rw-r--r-- 22,801 bytes parent folder | download
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
/*  $Id$

    Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        wielemak@science.uva.nl
    WWW:           http://www.swi-prolog.org
    Copyright (C): 1985-2007, University of Amsterdam

    This program 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 2
    of the License, or (at your option) any later version.

    This program 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.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    As a special exception, if you link this library with other files,
    compiled with a Free Software compiler, to produce an executable, this
    library does not by itself cause the resulting executable to be covered
    by the GNU General Public License. This exception does not however
    invalidate any other reasons why the executable file might be covered by
    the GNU General Public License.
*/

#define O_DEBUG 1			/* provides time:time_debug(+Level) */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <SWI-Stream.h>
#include <SWI-Prolog.h>
#include <error.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <math.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include <string.h>
#include <errno.h>
#include <assert.h>

#ifdef _REENTRANT
#include <pthread.h>
#endif

#ifdef __WINDOWS__
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The __WINDOWS__ port uses the multimedia timers.   This  module must be linked
with winmm.lib
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#include <windows.h>
#include <sys/timeb.h>
#if (_MSC_VER < 1400) 
typedef DWORD DWORD_PTR;
#endif

#ifndef SIGALRM
#define SIGALRM 14
#endif

/* Seems to be there
struct timeval
{ long tv_usec;
  long tv_sec;
};
*/

struct timezone
{ int zone;
};

static int
gettimeofday(struct timeval *tv, struct timezone *tz)
{ struct timeb tb;

  ftime(&tb);
  tv->tv_sec  = (long)tb.time;
  tv->tv_usec = tb.millitm * 1000;

  return 0;
}


#else /*__WINDOWS__*/

#ifdef _REENTRANT
#define SHARED_TABLE 1
#endif

#include <time.h>
#include <sys/time.h>

#endif /*__WINDOWS__*/

#ifdef O_DEBUG
static int debuglevel = 0;
#define DEBUG(n, g) if ( debuglevel >= n ) g

static foreign_t
pl_time_debug(term_t n)
{ return PL_get_integer(n, &debuglevel);
}


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
glibc defines backtrace() and friends to  print the calling context. For
debugging this is just great,  as   the  problem  generally appear after
generating an exception.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

#ifdef HAVE_EXECINFO_H
#define BACKTRACE 1

#if BACKTRACE
#include <execinfo.h>
#include <string.h>

static void
print_trace (void)
{ void *array[100];
  size_t size;
  char **strings;
  size_t i;
     
  size = backtrace(array, sizeof(array)/sizeof(void *));
  strings = backtrace_symbols(array, size);
     
#ifdef _REENTRANT
  Sdprintf("on_alarm() Prolog-context [thread %d]:\n", PL_thread_self());
#else
  Sdprintf("on_alarm() Prolog-context:\n");
#endif
  PL_action(PL_ACTION_BACKTRACE, 3);

  Sdprintf("on_alarm() C-context:\n");
  
  for(i = 0; i < size; i++)
  { if ( !strstr(strings[i], "checkData") )
      Sdprintf("\t[%d] %s\n", i, strings[i]);
  }
       
  free(strings);
}
#endif /*BACKTRACE*/
#endif /*HAVE_EXECINFO_H*/
#else /*O_DEBUG*/
#define DEBUG(n, g) ((void)0)
#endif /*O_DEBUG*/

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This module defines support for timing during execution. Most of this is
highly system dependent.

Design
======

The module contains three implementations:

	* Windows
	The Windows versions is based on multimedia timer objects.
	
	* Unix setitimer (single threaded)
	This implementation uses setitimer() and SIGALRM.  Whenever
	something is changed, re_schedule() is called to set the
	alarm clock for the next wakeup.

	* Unix scheduler thread
	This implementation uses a table shared between all threads and
	a thread that waits for the next signal to be send using
	pthread_cond_timedwait().  The signal SIGALRM is then delivered
	using pthread_kill() to the scheduled thread.

This module keeps a double-linked  list   of  `scheduled events' that is
tagged with and annotated using  the   absolute  time  it should happen.
These  times  are  represented  using   the  struct  timeval,  providing
microsecond   resolution.   If   the     SHARED_TABLE    version   (Unix
multithreaded), there is one table for all  events. In the other designs
each thread has its own table.

The  signal  handler  uses  the  PL_SIGSYNC    option  to  be  scheduled
synchronous with the Prolog activity  and   eb  able to throw exceptions
(the most common alarm activity).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static void	on_alarm(int sig);

static module_t	   MODULE_user;
static atom_t	   ATOM_remove;
static atom_t	   ATOM_install;
static atom_t	   ATOM_done;
static atom_t	   ATOM_next;
static atom_t	   ATOM_scheduled;
static functor_t   FUNCTOR_module2;
static functor_t   FUNCTOR_alarm1;
static functor_t   FUNCTOR_alarm4;
static predicate_t PREDICATE_call1;

#define EV_MAGIC	1920299187	/* Random magic number */

#define EV_DONE		0x0001		/* Handled this one */
#define EV_REMOVE	0x0002		/* Automatically remove */
#define EV_FIRED	0x0004		/* Windows: got this one */
#define EV_NOINSTALL	0x0008		/* Only allocate; do not install */

typedef struct event
{ record_t	 goal;			/* Thing to call */
  module_t	 module;		/* Module to call in */
  struct event  *next;			/* linked list for current */
  struct event  *previous;		/* idem */
  unsigned long  flags;			/* misc flags */
  long		 magic;			/* validate magic */
  double	 time;			/* Specified time */
  struct timeval at;			/* Time to deliver */
#ifdef SHARED_TABLE
  pthread_t	 thread_id;		/* Thread to call in */
#ifdef O_DEBUG
  int		 pl_thread_id;		/* Prolog thread ID */
#endif
#endif
#ifdef __WINDOWS__
  UINT		 mmid;			/* MultiMedia timer id */
  DWORD		 tid;			/* thread-id of Prolog thread */
#endif
} event, *Event;

typedef void (*handler_t)(int);

typedef struct
{ Event first;				/* first in list */
  Event scheduled;			/* The one we scheduled for */
} schedule;

#ifdef SHARED_TABLE
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond   = PTHREAD_COND_INITIALIZER;
static int scheduler_running = FALSE;	/* is scheduler running? */
static pthread_t scheduler;		/* thread id of scheduler */

#define LOCK()   pthread_mutex_lock(&mutex);
#define UNLOCK() pthread_mutex_unlock(&mutex);
#else
#define LOCK()   (void)0
#define UNLOCK() (void)0
#endif /*SHARED_TABLE*/

#if defined(_REENTRANT) && !defined(SHARED_TABLE)

static pthread_key_t key;

static schedule *
TheSchedule()
{ schedule *s;

  if ( !(s=pthread_getspecific(key)) )
  { s = PL_malloc(sizeof(schedule));
    memset(s, 0, sizeof(*s));
    pthread_setspecific(key, s);
  }

  return s;
}

static void
free_schedule(void *closure)
{ schedule *s = closure;

  PL_free(s);
}

#else /*defined(_REENTRANT) && !defined(SHARED_TABLE)*/

static schedule the_schedule;		/* the schedule */
#define TheSchedule() (&the_schedule)	/* current schedule */

#endif  /*defined(_REENTRANT) && !defined(SHARED_TABLE)*/

int signal_function_set = FALSE;	/* signal function is set */
static handler_t signal_function;	/* Current signal function */

static void uninstallEvent(Event ev);

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Allocate the event, maintaining a time-sorted list of scheduled events.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static Event
allocEvent(struct timeval *at)
{ Event ev = malloc(sizeof(*ev));

  if ( !ev )
  { pl_error(NULL, 0, NULL, ERR_ERRNO, errno);
    return NULL;
  }

  memset(ev, 0, sizeof(*ev));
  ev->at = *at;
  ev->magic = EV_MAGIC;

  return ev;
}


static void
insertEvent(Event ev)
{ schedule *sched = TheSchedule();
  Event e;

  DEBUG(1, Sdprintf("insertEvent(%d.%06d)\n", ev->at.tv_sec, ev->at.tv_usec));

  for(e = sched->first; e; e = e->next)
  { struct timeval d;

    d.tv_sec  = ev->at.tv_sec  - e->at.tv_sec;
    d.tv_usec = ev->at.tv_usec - e->at.tv_usec;
    if ( d.tv_usec < 0 )
    { d.tv_sec--;
      d.tv_usec += 1000000;
    }

    if ( d.tv_sec < 0 )			/* new must be before e */
    { ev->next = e;
      ev->previous = e->previous;
      if ( e->previous )
	e->previous->next = ev;
      e->previous = ev;

      if ( sched->first == e )		/* allocated as first */
	sched->first = ev;

      return;
    } else
    { if ( e->next )
	continue;

      ev->previous = e;			/* end of the list */
      e->next = ev;

      return;
    }
  }

  sched->first = ev;
}


static void
freeEvent(Event ev)
{ schedule *sched = TheSchedule();

  if ( sched->scheduled == ev )
    sched->scheduled = NULL;

  if ( ev->previous )
    ev->previous->next = ev->next;
  else
    sched->first = ev->next;

  if ( ev->next )
    ev->next->previous = ev->previous;

  if ( ev->goal )
    PL_erase(ev->goal);

  ev->magic = 0;

  free(ev);
}


#ifndef SHARED_TABLE
static void
callEvent(Event ev)
{ term_t goal = PL_new_term_ref();

  ev->flags |= EV_DONE;
    
  PL_recorded(ev->goal, goal);
  PL_call_predicate(ev->module,
		    PL_Q_PASS_EXCEPTION,
		    PREDICATE_call1,
		    goal);
}
#endif


static void
cleanupHandler()
{ 
#ifndef __WINDOWS__
  struct itimerval v;

  DEBUG(1, Sdprintf("Removed timer\n"));
  memset(&v, 0, sizeof(v));
  setitimer(ITIMER_REAL, &v, NULL);	/* restore? */
#endif

  if ( signal_function_set )
  { signal_function_set = FALSE;
    PL_signal(SIGALRM, signal_function);
  }
}


static void
installHandler()
{ if ( !signal_function_set )
  { signal_function = PL_signal(SIGALRM|PL_SIGSYNC, on_alarm);
    signal_function_set = TRUE;
  }
}


static void
cleanup()
{ Event ev, next;
  schedule *sched = TheSchedule();

  for(ev=sched->first; ev; ev = next)
  { next = ev->next;
    uninstallEvent(ev);
  }

  cleanupHandler();
}


#ifdef __WINDOWS__

static void
on_alarm(int sig)
{ Event ev, next;

  for(ev=TheSchedule()->first; ev; ev = next)
  { assert(ev->magic == EV_MAGIC);

    if ( ev->flags & EV_FIRED )
    { ev->flags &= ~EV_FIRED;

      callEvent(ev);
      ev->mmid = 0;			/* TIME_ONESHOT */

      next = ev->next;
      if ( ev->flags & EV_REMOVE )
	freeEvent(ev);
    } else
      next = ev->next;
  }
}


static void CALLBACK
callTimer(UINT id, UINT msg, DWORD_PTR dwuser, DWORD_PTR dw1, DWORD_PTR dw2)
{ Event ev = (Event)dwuser;

  ev->flags |= EV_FIRED;
  PL_w32thread_raise(ev->tid, SIGALRM);
}


static int
installEvent(Event ev)
{ MMRESULT rval;

  insertEvent(ev);

  rval = timeSetEvent((int)(ev->time*1000),
		      50,			/* resolution (milliseconds) */
		      callTimer,
		      (DWORD)ev,
		      TIME_ONESHOT);

  if ( rval )
  { ev->tid = GetCurrentThreadId();
    ev->mmid = rval;

    return TRUE;
  }
    
  return pl_error(NULL, 0, NULL, ERR_RESOURCE, "no_timers");
}


static void
uninstallEvent(Event ev)
{ if ( TheSchedule()->scheduled == ev )
    ev->flags |= EV_DONE;

  if ( ev->mmid )
  { timeKillEvent(ev->mmid);
    ev->mmid = 0;
  }

  freeEvent(ev);
}


#else /*__WINDOWS__*/

#ifdef SHARED_TABLE

static Event
nextEvent(schedule *sched)
{ Event ev;

  for(ev=sched->first; ev; ev = ev->next)
  { if ( ev->flags & (EV_DONE|EV_FIRED) )
      continue;

    return ev;
  }

  return NULL;
}


static void *
alarm_loop(void * closure)
{ schedule *sched = TheSchedule();

  pthread_mutex_lock(&mutex);		/* for condition variable */

  for(;;)
  { Event ev = nextEvent(sched);

    if ( ev )
    { struct timespec timeout;
      int rc;

      timeout.tv_sec  = ev->at.tv_sec;
      timeout.tv_nsec = ev->at.tv_usec*1000;

      DEBUG(1, Sdprintf("Waiting ...\n"));
      rc = pthread_cond_timedwait(&cond, &mutex, &timeout);

      switch( rc )
      { case ETIMEDOUT:
	  DEBUG(1, Sdprintf("Signalling %d (= %d) ...\n",
			    ev->pl_thread_id, ev->thread_id));
	  sched->scheduled = ev;
	  ev->flags |= EV_FIRED;
	  pthread_kill(ev->thread_id, SIGALRM);
	  break;
	case 0:
	case EINTR:
	  continue;
	default:
	  Sdprintf("alarm/4: pthread_cond_timedwait(): %s\n", strerror(rc));
      }
    } else
    { int rc = pthread_cond_wait(&cond, &mutex);

      if ( rc == EINTR )
	continue;
    }
  }

  return NULL;
}


static void
on_alarm(int sig)
{ Event ev;
  schedule *sched = TheSchedule();
  pthread_t self = pthread_self();
  term_t goal = 0;
  module_t module = NULL;

  DEBUG(1, Sdprintf("Signal received in %d (= %d)\n",
		    PL_thread_self(), self));
#ifdef BACKTRACE
  DEBUG(10, print_trace());
#endif

  LOCK();
  for(ev = sched->first; ev; ev=ev->next)
  { assert(ev->magic == EV_MAGIC);

    if ( (ev->flags & EV_FIRED) &&
	 pthread_equal(self, ev->thread_id) )
    { ev->flags &= ~EV_FIRED;

      DEBUG(1, Sdprintf("Calling event\n"));
      ev->flags |= EV_DONE;
      module = ev->module;
      goal = PL_new_term_ref();
      PL_recorded(ev->goal, goal);

      if ( ev->flags & EV_REMOVE )
	freeEvent(ev);
      break;
    }
  }
  UNLOCK();

  if ( goal )
  { PL_call_predicate(module,
		      PL_Q_PASS_EXCEPTION,
		      PREDICATE_call1,
		      goal);
  }
}


static int
installEvent(Event ev)
{ LOCK();

  ev->thread_id = pthread_self();
#ifdef O_DEBUG
  ev->pl_thread_id = PL_thread_self();
#endif

  if ( !scheduler_running )
  { pthread_attr_t attr;
    int rc;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_attr_setstacksize(&attr, 1024);

    if ( (rc=pthread_create(&scheduler, &attr, alarm_loop, NULL)) )
      return pl_error("alarm", 4, "Failed to start schedule thread",
		      ERR_ERRNO, rc);
    pthread_attr_destroy(&attr);

    DEBUG(1, Sdprintf("Started scheduler thread\n"));
    scheduler_running = TRUE;
  }

  insertEvent(ev);
  pthread_cond_signal(&cond);
  UNLOCK();

  return TRUE;
}


static void
uninstallEvent(Event ev)
{ LOCK();
  if ( TheSchedule()->scheduled == ev )
    ev->flags |= EV_DONE;
  freeEvent(ev);
  pthread_cond_signal(&cond);
  UNLOCK();
}


#else /*SHARED_TABLE*/

static void
re_schedule()
{ struct itimerval v;
  Event ev;
  schedule *sched = TheSchedule();
  
  for(ev=sched->first; ev; ev = ev->next)
  { struct timeval now;
    struct timeval left;

    if ( ev->flags & EV_DONE )
      continue;

    gettimeofday(&now, NULL);
    left.tv_sec  = ev->at.tv_sec  - now.tv_sec;
    left.tv_usec = ev->at.tv_usec - now.tv_usec;
    if ( left.tv_usec < 0 )
    { left.tv_sec--;
      left.tv_usec += 1000000;
    }

    if ( left.tv_sec < 0 ||
	 (left.tv_sec == 0 && left.tv_usec == 0) )
    { DEBUG(1, Sdprintf("Passed\n"));

      callEvent(ev);		/* Time has passed.  What about exceptions? */

      continue;		
    }

    sched->scheduled = ev;	/* This is the scheduled one */
    DEBUG(1, Sdprintf("Scheduled for %d.%06d\n", ev->at.tv_sec, ev->at.tv_usec));

    v.it_value            = left;
    v.it_interval.tv_sec  = 0;
    v.it_interval.tv_usec = 0;

    setitimer(ITIMER_REAL, &v, NULL);	/* Store old? */

    return;
  }
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This one is  asynchronously  called  from   the  hook  registered  using
PL_signal(). Throwing an exception is normally   safe,  but some foreign
code might not leave the  system   unstable  after resulting long_jmp().
This should all nicely be protected,  but   most  likely  this isn't the
case.

The alternative is to delay the signal to a safe place using PL_raise();
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static void
on_alarm(int sig)
{ Event ev;
  schedule *sched = TheSchedule();

#ifdef BACKTRACE
  DEBUG(10, print_trace());
#endif

  if ( (ev=sched->scheduled) )
  { assert(ev->magic == EV_MAGIC);
    sched->scheduled = NULL;

    callEvent(ev);

    if ( ev->flags & EV_REMOVE )
      freeEvent(ev);
  }

  re_schedule();
}


static int
installEvent(Event ev)
{ insertEvent(ev);
  re_schedule();

  return TRUE;
}


static void
uninstallEvent(Event ev)
{ if ( TheSchedule()->scheduled == ev )
  { ev->flags |= EV_DONE;
    re_schedule();
  }

  freeEvent(ev);
}

#endif /*SHARED_TABLE*/
#endif /*__WINDOWS__*/


		 /*******************************
		 *	PROLOG CONNECTION	*
		 *******************************/

static int
unify_timer(term_t t, Event ev)
{ if ( !PL_is_variable(t) )
    return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 0, t, "unbound");

  return PL_unify_term(t,
		       PL_FUNCTOR, FUNCTOR_alarm1,
		         PL_POINTER, ev);
}


static int
get_timer(term_t t, Event *ev)
{ if ( PL_is_functor(t, FUNCTOR_alarm1) )
  { term_t a = PL_new_term_ref();
    void *p;

    PL_get_arg(1, t, a);
    if ( PL_get_pointer(a, &p) )
    { Event e = p;

      if ( e->magic == EV_MAGIC )
      { *ev = e;
        return TRUE;
      } else
      { return pl_error("get_timer", 1, NULL,
			ERR_DOMAIN, t, "alarm");
      }
    }
  }

  return pl_error("get_timer", 1, NULL,
		  ERR_ARGTYPE, 1, t, "alarm");
}


static int
pl_get_bool_ex(term_t arg, int *val)
{ if ( PL_get_bool(arg, val) )
    return TRUE;

  return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 0, arg, "bool");
}


static foreign_t
alarm4(term_t time, term_t callable, term_t id, term_t options)
{ Event ev;
  double t;
  struct timeval tv;
  module_t m = NULL;
  unsigned long flags = 0L;
    
  if ( options )
  { term_t tail = PL_copy_term_ref(options);
    term_t head = PL_new_term_ref();

    while( PL_get_list(tail, head, tail) )
    { atom_t name;
      int arity;

      if ( PL_get_name_arity(head, &name, &arity) )
      { if ( arity == 1 )
	{ term_t arg = PL_new_term_ref();

	  PL_get_arg(1, head, arg);

	  if ( name == ATOM_remove )
	  { int t = FALSE;

	    if ( !pl_get_bool_ex(arg, &t) )
	      return FALSE;
	    if ( t )
	      flags |= EV_REMOVE;
	  } else if ( name == ATOM_install )
	  { int t = TRUE;

	    if ( !pl_get_bool_ex(arg, &t) )
	      return FALSE;
	    if ( !t )
	      flags |= EV_NOINSTALL;
	  }
	}
      }
    }
    if ( !PL_get_nil(tail) )
      return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 4, options, "list");
  }

  if ( !PL_get_float(time, &t) )
    return pl_error(NULL, 0, NULL, ERR_ARGTYPE, 1,
		    time, "number");
		    
  gettimeofday(&tv, NULL);
  tv.tv_usec += (long)((t-floor(t))*1000000);
  tv.tv_sec  += (long)t;
  if ( tv.tv_usec >= 1000000 )
  { tv.tv_usec -= 1000000;
    tv.tv_sec++;
  }

  if ( !(ev = allocEvent(&tv)) )
    return FALSE;
  ev->time = t;
  if ( !unify_timer(id, ev) )
  { freeEvent(ev);
    return FALSE;
  }

  ev->flags = flags;
  PL_strip_module(callable, &m, callable);
  ev->module = m;
  ev->goal = PL_record(callable);

  if ( !(ev->flags & EV_NOINSTALL) )
  { if ( !installEvent(ev) )
    { freeEvent(ev);
      return FALSE;
    }
  }

  return TRUE;
}


static foreign_t
alarm3(term_t time, term_t callable, term_t id)
{ return alarm4(time, callable, id, 0);
}


static foreign_t
install_alarm(term_t alarm)
{ Event ev = NULL;

  if ( !get_timer(alarm, &ev) )
    return FALSE;

  if ( !installEvent(ev) )
  { freeEvent(ev);
    return FALSE;
  }

  return TRUE;
}


static foreign_t
remove_alarm(term_t alarm)
{ Event ev = NULL;

  if ( !get_timer(alarm, &ev) )
    return FALSE;

  uninstallEvent(ev);

  return TRUE;
}


static foreign_t
current_alarms(term_t time, term_t goal, term_t id, term_t status,
	       term_t matching)
{ Event ev;
  term_t next = PL_new_term_ref();
  term_t g    = PL_new_term_ref();
  term_t tail = PL_copy_term_ref(matching);
  term_t head = PL_new_term_ref();
  term_t av   = PL_new_term_refs(4);
#ifdef SHARED_TABLE
  pthread_t self = pthread_self();
#endif

  LOCK();
  ev = TheSchedule()->first;

  for(; ev; ev = ev->next)
  { atom_t s;
    double at;
    fid_t fid;

#ifdef SHARED_TABLE
    if ( !pthread_equal(self, ev->thread_id) )
      continue;
#endif

    fid = PL_open_foreign_frame();

    if ( ev->flags & EV_DONE )
      s = ATOM_done;
    else if ( ev == TheSchedule()->scheduled )
      s = ATOM_next;
    else
      s = ATOM_scheduled;
    
    if ( !PL_unify_atom(status, s) )
      goto nomatch;

    PL_recorded(ev->goal, g);
    if ( !PL_unify_term(goal,
			PL_FUNCTOR, FUNCTOR_module2,
			  PL_ATOM, PL_module_name(ev->module),
			  PL_TERM, g) )
      goto nomatch;

    at = (double)ev->at.tv_sec + (double)ev->at.tv_usec / 1000000.0;
    if ( !PL_unify_float(time, at) )
      goto nomatch;

    if ( !unify_timer(id, ev) )
      goto nomatch;
      
    PL_discard_foreign_frame(fid);

    PL_put_float(av+0, at);		/* time */
    PL_recorded(ev->goal, av+1);	/* goal */
    PL_put_variable(av+2);		/* id */
    unify_timer(av+2, ev);
    PL_put_atom(av+3, s);		/* status */
    PL_cons_functor_v(next, FUNCTOR_alarm4, av);

    if ( PL_unify_list(tail, head, tail) &&
	 PL_unify(head, next) )
    { continue;
    } else
    { PL_close_foreign_frame(fid);
      UNLOCK();

      return FALSE;
    }

  nomatch:
    PL_discard_foreign_frame(fid);
  }
  UNLOCK();

  return PL_unify_nil(tail);
}


install_t
install()
{ MODULE_user	  = PL_new_module(PL_new_atom("user"));

  FUNCTOR_alarm1  = PL_new_functor(PL_new_atom("$alarm"), 1);
  FUNCTOR_alarm4  = PL_new_functor(PL_new_atom("alarm"), 4);
  FUNCTOR_module2 = PL_new_functor(PL_new_atom(":"), 2);

  ATOM_remove	  = PL_new_atom("remove");
  ATOM_install	  = PL_new_atom("install");
  ATOM_done	  = PL_new_atom("done");
  ATOM_next	  = PL_new_atom("next");
  ATOM_scheduled  = PL_new_atom("scheduled");

  PREDICATE_call1 = PL_predicate("call", 1, "user");

  PL_register_foreign("alarm",          4, alarm4,         PL_FA_TRANSPARENT);
  PL_register_foreign("alarm",          3, alarm3,         PL_FA_TRANSPARENT);
  PL_register_foreign("remove_alarm",   1, remove_alarm,   0);
  PL_register_foreign("install_alarm",  1, install_alarm,  0);
  PL_register_foreign("remove_alarm_notrace",1, remove_alarm,   PL_FA_NOTRACE);
  PL_register_foreign("current_alarms", 5, current_alarms, 0);
#ifdef O_DEBUG
  PL_register_foreign("time_debug",	1, pl_time_debug,  0);
#endif

#if defined(_REENTRANT) && !defined(SHARED_TABLE)
  pthread_key_create(&key, free_schedule);
#endif
  installHandler();
}


install_t
uninstall()
{ cleanup();

#if defined(_REENTRANT) && !defined(SHARED_TABLE)
  pthread_key_delete(key);
#endif
}