-
Notifications
You must be signed in to change notification settings - Fork 0
/
sim_timer.c
3651 lines (3275 loc) · 152 KB
/
sim_timer.c
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
/* sim_timer.c: simulator timer library
Copyright (c) 1993-2010, Robert M Supnik
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
ROBERT M SUPNIK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Robert M Supnik shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Robert M Supnik.
21-Oct-11 MP Fixed throttling in several ways:
- Sleep for the observed clock tick size while throttling
- Recompute the throttling wait once every 10 seconds
to account for varying instruction mixes during
different phases of a simulator execution or to
accommodate the presence of other load on the host
system.
- Each of the pre-existing throttling modes (Kcps,
Mcps, and %) all compute the appropriate throttling
interval dynamically. These dynamic computations
assume that 100% of the host CPU is dedicated to
the current simulator during this computation.
This assumption may not always be true and under
certain conditions may never provide a way to
correctly determine the appropriate throttling
wait. An additional throttling mode has been added
which allows the simulator operator to explicitly
state the desired throttling wait parameters.
These are specified by:
SET THROT insts/delay
where 'insts' is the number of instructions to
execute before sleeping for 'delay' milliseconds.
22-Apr-11 MP Fixed Asynch I/O support to reasonably account cycles
when an idle wait is terminated by an external event
05-Jan-11 MP Added Asynch I/O support
29-Dec-10 MP Fixed clock resolution determination for Unix platforms
22-Sep-08 RMS Added "stability threshold" for idle routine
27-May-08 RMS Fixed bug in Linux idle routines (from Walter Mueller)
18-Jun-07 RMS Modified idle to exclude counted delays
22-Mar-07 RMS Added sim_rtcn_init_all
17-Oct-06 RMS Added idle support (based on work by Mark Pizzolato)
Added throttle support
16-Aug-05 RMS Fixed C++ declaration and cast problems
02-Jan-04 RMS Split out from SCP
This library includes the following routines:
sim_timer_init - initialize timing system
sim_rtc_init - initialize calibration
sim_rtc_calb - calibrate clock
sim_idle - virtual machine idle
sim_os_msec - return elapsed time in msec
sim_os_sleep - sleep specified number of seconds
sim_os_ms_sleep - sleep specified number of milliseconds
sim_idle_ms_sleep - sleep specified number of milliseconds
or until awakened by an asynchronous
event
sim_timespec_diff subtract two timespec values
sim_timer_activate_after schedule unit for specific time
sim_timer_activate_time determine activation time
sim_timer_activate_time_usecs determine activation time in usecs
sim_rom_read_with_delay delay for default or specified delay
sim_get_rom_delay_factor get current or initialize 1usec delay factor
sim_set_rom_delay_factor set specific delay factor
The calibration, idle, and throttle routines are OS-independent; the _os_
routines are not.
*/
#define NOT_MUX_USING_CODE /* sim_tmxr library provider or agnostic */
#include "sim_defs.h"
#include "sim_scp_private.h"
#define SIM_INTERNAL_CLK (SIM_NTIMERS+(1<<30))
#define SIM_INTERNAL_UNIT sim_internal_timer_unit
#ifndef MIN
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif
uint32 sim_idle_ms_sleep (unsigned int msec);
static uint32 _sim_os_msec (void);
/* MS_MIN_GRANULARITY exists here so that timing behavior for hosts systems */
/* with slow clock ticks can be assessed and tested without actually having */
/* that slow a clock tick on the development platform */
//#define MS_MIN_GRANULARITY 20 /* Uncomment to simulate 20ms host tick size.*/
/* some Solaris and BSD hosts come this way */
#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)
uint32 real_sim_idle_ms_sleep (unsigned int msec);
uint32 real_sim_os_msec (void);
uint32 real_sim_os_ms_sleep (unsigned int msec);
static uint32 real_sim_os_sleep_min_ms = 0;
static uint32 real_sim_os_sleep_inc_ms = 0;
uint32 sim_idle_ms_sleep (unsigned int msec)
{
uint32 real_start = real_sim_os_msec ();
uint32 start = (real_start / MS_MIN_GRANULARITY) * MS_MIN_GRANULARITY;
uint32 tick_left;
if (msec == 0)
return 0;
if (real_start == start)
tick_left = 0;
else
tick_left = MS_MIN_GRANULARITY - (real_start - start);
if (msec <= tick_left)
real_sim_idle_ms_sleep (tick_left);
else
real_sim_idle_ms_sleep (((msec + MS_MIN_GRANULARITY - 1) / MS_MIN_GRANULARITY) * MS_MIN_GRANULARITY);
return (sim_os_msec () - start);
}
static uint32 _sim_os_msec (void)
{
return (real_sim_os_msec ()/MS_MIN_GRANULARITY)*MS_MIN_GRANULARITY;
}
uint32 sim_os_ms_sleep (unsigned int msec)
{
msec = MS_MIN_GRANULARITY*((msec+MS_MIN_GRANULARITY-1)/MS_MIN_GRANULARITY);
return real_sim_os_ms_sleep (msec);
}
#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */
t_bool sim_idle_enab = FALSE; /* global flag */
volatile t_bool sim_idle_wait = FALSE; /* global flag */
uint32 sim_vm_initial_ips = SIM_INITIAL_IPS;
static uint32 sim_precalibrate_ips = SIM_INITIAL_IPS;
static int32 sim_calb_tmr = -1; /* the system calibrated timer */
static int32 sim_calb_tmr_last = -1; /* shadow value when at sim> prompt */
static double sim_inst_per_sec_last = 0; /* shadow value when at sim> prompt */
static uint32 sim_stop_time = 0; /* time when sim_stop_timer_services was called */
double sim_time_at_sim_prompt = 0; /* time spent processing commands from sim> prompt */
static uint32 sim_idle_rate_ms = 0; /* Minimum Sleep time */
static uint32 sim_os_sleep_min_ms = 0;
static uint32 sim_os_sleep_inc_ms = 0;
static uint32 sim_os_clock_resoluton_ms = 0;
static uint32 sim_os_tick_hz = 0;
static uint32 sim_idle_stable = SIM_IDLE_STDFLT;
static uint32 sim_idle_calib_pct = 100;
static double sim_timer_stop_time = 0;
static uint32 sim_rom_delay = 0;
static uint32 sim_throt_ms_start = 0;
static uint32 sim_throt_ms_stop = 0;
static uint32 sim_throt_type = 0;
static uint32 sim_throt_val = 0;
static uint32 sim_throt_drift_pct = SIM_THROT_DRIFT_PCT_DFLT;
static uint32 sim_throt_state = SIM_THROT_STATE_INIT;
static double sim_throt_cps;
static double sim_throt_peak_cps;
static double sim_throt_inst_start;
static uint32 sim_throt_sleep_time = 0;
static int32 sim_throt_wait = 0;
static uint32 sim_throt_delay = 3;
#define CLK_TPS 100
#define CLK_INIT (sim_precalibrate_ips/CLK_TPS)
static int32 sim_int_clk_tps;
static t_bool sim_timer_calib_enabled = TRUE;
static struct timespec sim_timer_uncalib_base_time = {0, 0};
static t_bool sim_throttle_has_been_enabled = FALSE;
typedef struct RTC {
UNIT *clock_unit; /* registered ticking clock unit */
UNIT *timer_unit; /* points to related clock assist unit (sim_timer_units) */
UNIT *clock_cosched_queue;
int32 cosched_interval;
uint32 ticks; /* ticks */
uint32 hz; /* tick rate */
uint32 last_hz; /* prior tick rate */
uint32 rtime; /* real time (usecs) */
uint32 vtime; /* virtual time (usecs) */
double gtime; /* instruction time */
uint32 nxintv; /* next interval */
int32 based; /* base delay */
int32 currd; /* current delay */
int32 initd; /* initial delay */
uint32 elapsed; /* seconds since init */
uint32 calibrations; /* calibration count */
double clock_skew_max; /* asynchronous max skew */
double clock_tick_size; /* 1/hz */
uint32 calib_initializations; /* Initialization Count */
double calib_tick_time; /* ticks time */
double calib_tick_time_tot; /* ticks time - total*/
uint32 calib_ticks_acked; /* ticks Acked */
uint32 calib_ticks_acked_tot; /* ticks Acked - total */
uint32 clock_ticks; /* ticks delivered since catchup base */
uint32 clock_ticks_tot; /* ticks delivered since catchup base - total */
double clock_init_base_time; /* reference time for clock initialization */
double clock_tick_start_time; /* reference time when ticking started */
double clock_catchup_base_time; /* reference time for catchup ticks */
uint32 clock_catchup_ticks; /* Record of catchups */
uint32 clock_catchup_ticks_tot; /* Record of catchups - total */
uint32 clock_catchup_ticks_curr;/* Record of catchups in this second */
t_bool clock_catchup_pending; /* clock tick catchup pending */
t_bool clock_catchup_eligible; /* clock tick catchup eligible */
uint32 clock_time_idled; /* total time idled */
uint32 clock_time_idled_last; /* total time idled as of the previous second */
uint32 clock_calib_skip_idle; /* Calibrations skipped due to idling */
uint32 clock_calib_gap2big; /* Calibrations skipped Gap Too Big */
uint32 clock_calib_backwards; /* Calibrations skipped Clock Running Backwards */
} RTC;
RTC rtcs[SIM_NTIMERS+1];
UNIT sim_timer_units[SIM_NTIMERS+1];/* Clock assist units */
/* one for each timer and one for an internal */
/* clock if no clocks are registered. */
static t_bool sim_catchup_ticks = TRUE;
#if defined (SIM_ASYNCH_CLOCKS) && !defined (SIM_ASYNCH_IO)
#undef SIM_ASYNCH_CLOCKS
#endif
t_bool sim_asynch_timer = FALSE;
#if defined (SIM_ASYNCH_CLOCKS)
UNIT * volatile sim_wallclock_queue = QUEUE_LIST_END;
UNIT * volatile sim_wallclock_entry = NULL;
#endif
/* Forward Declarations */
t_stat sim_timer_set_async (int32 flag, CONST char *cptr);
t_stat sim_timer_set_catchup (int32 flag, CONST char *cptr);
t_stat sim_timer_set_calib (int32 flag, CONST char *cptr);
t_stat sim_timer_set_stop (int32 flag, CONST char *cptr);
t_stat sim_timer_set_uncalib_base (int32 flag, CONST char *cptr);
uint32 sim_os_msec (void)
{
if (sim_timer_calib_enabled)
return _sim_os_msec ();
return (uint32)((1000.0 * sim_gtime ()) / sim_precalibrate_ips);
}
#define sleep1Samples 100
static uint32 _compute_minimum_sleep (void)
{
uint32 i, tot, tim;
sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);
#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)
real_sim_idle_ms_sleep (2); /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
tot += real_sim_idle_ms_sleep (1);
tim = tot / sleep1Samples; /* Truncated average */
real_sim_os_sleep_min_ms = tim;
real_sim_idle_ms_sleep (2); /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
tot += real_sim_idle_ms_sleep (real_sim_os_sleep_min_ms + 1);
tim = tot / sleep1Samples; /* Truncated average */
real_sim_os_sleep_inc_ms = tim - real_sim_os_sleep_min_ms;
#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */
sim_idle_ms_sleep (2); /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
tot += sim_idle_ms_sleep (1);
tim = tot / sleep1Samples; /* Truncated average */
sim_os_sleep_min_ms = tim;
sim_idle_ms_sleep (2); /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
tot += sim_idle_ms_sleep (sim_os_sleep_min_ms + 1);
tim = tot / sleep1Samples; /* Truncated average */
sim_os_sleep_inc_ms = tim - sim_os_sleep_min_ms;
sim_os_set_thread_priority (PRIORITY_NORMAL);
return sim_os_sleep_min_ms;
}
#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)
#define sim_idle_ms_sleep real_sim_idle_ms_sleep
#define sim_os_msec real_sim_os_msec
#define sim_os_ms_sleep real_sim_os_ms_sleep
#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */
#if defined(SIM_ASYNCH_IO)
uint32 sim_idle_ms_sleep (unsigned int msec)
{
struct timespec start_time, end_time, done_time, delta_time;
uint32 delta_ms;
t_bool timedout = FALSE;
clock_gettime(CLOCK_REALTIME, &start_time);
end_time = start_time;
end_time.tv_sec += (msec/1000);
end_time.tv_nsec += 1000000*(msec%1000);
if (end_time.tv_nsec >= 1000000000) {
end_time.tv_sec += end_time.tv_nsec/1000000000;
end_time.tv_nsec = end_time.tv_nsec%1000000000;
}
pthread_mutex_lock (&sim_asynch_lock);
sim_idle_wait = TRUE;
if (pthread_cond_timedwait (&sim_asynch_wake, &sim_asynch_lock, &end_time))
timedout = TRUE;
else
sim_asynch_check = 0; /* force check of asynch queue now */
sim_idle_wait = FALSE;
pthread_mutex_unlock (&sim_asynch_lock);
clock_gettime(CLOCK_REALTIME, &done_time);
if (!timedout) {
AIO_UPDATE_QUEUE;
}
sim_timespec_diff (&delta_time, &done_time, &start_time);
delta_ms = (uint32)((delta_time.tv_sec * 1000) + ((delta_time.tv_nsec + 500000) / 1000000));
return delta_ms;
}
#else
uint32 sim_idle_ms_sleep (unsigned int msec)
{
return sim_os_ms_sleep (msec);
}
#endif
/* Mark the need for the sim_os_set_thread_priority routine, */
/* allowing the feature and/or platform dependent code to provide it */
#define NEED_THREAD_PRIORITY
/* If we've got pthreads support then use pthreads mechanisms */
#if defined(USE_READER_THREAD)
#undef NEED_THREAD_PRIORITY
#if defined(_WIN32)
/* On Windows there are several potentially disjoint threading APIs */
/* in use (base win32 pthreads, libSDL provided threading, and direct */
/* calls to beginthreadex), so go directly to the Win32 threading APIs */
/* to manage thread priority */
t_stat sim_os_set_thread_priority (int below_normal_above)
{
const static int val[3] = {THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL};
if ((below_normal_above < -1) || (below_normal_above > 1))
return SCPE_ARG;
SetThreadPriority (GetCurrentThread(), val[1 + below_normal_above]);
return SCPE_OK;
}
#else
/* Native pthreads priority implementation */
t_stat sim_os_set_thread_priority (int below_normal_above)
{
int sched_policy, min_prio, max_prio;
struct sched_param sched_priority;
if ((below_normal_above < -1) || (below_normal_above > 1))
return SCPE_ARG;
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
min_prio = sched_get_priority_min(sched_policy);
max_prio = sched_get_priority_max(sched_policy);
switch (below_normal_above) {
case PRIORITY_BELOW_NORMAL:
sched_priority.sched_priority = min_prio;
break;
case PRIORITY_NORMAL:
sched_priority.sched_priority = (max_prio + min_prio) / 2;
break;
case PRIORITY_ABOVE_NORMAL:
sched_priority.sched_priority = max_prio;
break;
}
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);
return SCPE_OK;
}
#endif
#endif /* defined(USE_READER_THREAD) */
/* OS-dependent timer and clock routines */
/* VMS */
#if defined (VMS)
#if defined (__VAX)
#define sys$gettim SYS$GETTIM
#define sys$setimr SYS$SETIMR
#define lib$emul LIB$EMUL
#define sys$waitfr SYS$WAITFR
#define lib$subx LIB$SUBX
#define lib$ediv LIB$EDIV
#endif
#include <starlet.h>
#include <lib$routines.h>
#include <unistd.h>
const t_bool rtc_avail = TRUE;
static uint32 _sim_os_msec (void)
{
uint32 quo, htod, tod[2];
int32 i;
sys$gettim (tod); /* time 0.1usec */
/* To convert to msec, must divide a 64b quantity by 10000. This is actually done
by dividing the 96b quantity 0'time by 10000, producing 64b of quotient, the
high 32b of which are discarded. This can probably be done by a clever multiply...
*/
quo = htod = 0;
for (i = 0; i < 64; i++) { /* 64b quo */
htod = (htod << 1) | ((tod[1] >> 31) & 1); /* shift divd */
tod[1] = (tod[1] << 1) | ((tod[0] >> 31) & 1);
tod[0] = tod[0] << 1;
quo = quo << 1; /* shift quo */
if (htod >= 10000) { /* divd work? */
htod = htod - 10000; /* subtract */
quo = quo | 1; /* set quo bit */
}
}
return quo;
}
void sim_os_sleep (unsigned int sec)
{
sleep (sec);
}
uint32 sim_os_ms_sleep_init (void)
{
return _compute_minimum_sleep ();
}
uint32 sim_os_ms_sleep (unsigned int msec)
{
uint32 stime = sim_os_msec ();
uint32 qtime[2];
int32 nsfactor = -10000;
static int32 zero = 0;
lib$emul (&msec, &nsfactor, &zero, qtime);
sys$setimr (2, qtime, 0, 0);
sys$waitfr (2);
return sim_os_msec () - stime;
}
#ifdef NEED_CLOCK_GETTIME
int clock_gettime(int clk_id, struct timespec *tp)
{
uint32 secs, ns, tod[2], unixbase[2] = {0xd53e8000, 0x019db1de};
if (clk_id != CLOCK_REALTIME)
return -1;
sys$gettim (tod); /* time 0.1usec */
lib$subx(tod, unixbase, tod); /* convert to unix base */
lib$ediv(&10000000, tod, &secs, &ns); /* isolate seconds & 100ns parts */
tp->tv_sec = secs;
tp->tv_nsec = ns*100;
return 0;
}
#endif /* CLOCK_REALTIME */
#elif defined (_WIN32)
/* Win32 routines */
const t_bool rtc_avail = TRUE;
static uint32 _sim_os_msec (void)
{
return timeGetTime (); /* use Multi-Media time source */
}
void sim_os_sleep (unsigned int sec)
{
Sleep (sec * 1000);
}
static TIMECAPS timers;
void sim_timer_exit (void)
{
timeEndPeriod (timers.wPeriodMin);
}
uint32 sim_os_ms_sleep_init (void)
{
MMRESULT mm_status;
mm_status = timeGetDevCaps (&timers, sizeof (timers));
if (mm_status != TIMERR_NOERROR) {
fprintf (stderr, "timeGetDevCaps() returned: 0x%X, Last Error: 0x%X\n", mm_status, (unsigned int)GetLastError());
return 0;
}
if (timers.wPeriodMin == 0) {
fprintf (stderr, "Unreasonable MultiMedia timer minimum value of 0\n");
return 0;
}
mm_status = timeBeginPeriod (timers.wPeriodMin);
if (mm_status != TIMERR_NOERROR) {
fprintf (stderr, "timeBeginPeriod() returned: 0x%X, Last Error: 0x%X\n", mm_status, (unsigned int)GetLastError());
return 0;
}
atexit (sim_timer_exit);
/* return measured actual minimum sleep time */
return _compute_minimum_sleep ();
}
uint32 sim_os_ms_sleep (unsigned int msec)
{
uint32 stime = sim_os_msec();
Sleep (msec);
return sim_os_msec () - stime;
}
#if defined(NEED_CLOCK_GETTIME)
int clock_gettime(int clk_id, struct timespec *tp)
{
t_uint64 now, unixbase;
if (clk_id != CLOCK_REALTIME)
return -1;
unixbase = 116444736;
unixbase *= 1000000000;
GetSystemTimeAsFileTime((FILETIME*)&now);
now -= unixbase;
tp->tv_sec = (long)(now/10000000);
tp->tv_nsec = (now%10000000)*100;
return 0;
}
#endif
t_stat sim_os_process_cpu_times (double *system, double *user)
{
t_uint64 ftCreation, ftExit, ftKernel, ftUser;
GetProcessTimes (GetCurrentProcess(), (FILETIME *)&ftCreation, (FILETIME *)&ftExit, (FILETIME *)&ftKernel, (FILETIME *)&ftUser);
*system = (double)(ftKernel / 10000000) + (((double)(ftKernel % 10000000)) / 10000000.0);
*user = (double)(ftUser / 10000000) + (((double)(ftUser % 10000000)) / 10000000.0);
return SCPE_OK;
}
#else
/* UNIX routines */
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#define NANOS_PER_MILLI 1000000
#define MILLIS_PER_SEC 1000
const t_bool rtc_avail = TRUE;
static uint32 _sim_os_msec (void)
{
struct timeval cur;
struct timezone foo;
uint32 msec;
gettimeofday (&cur, &foo);
msec = (((uint32) cur.tv_sec) * 1000) + (((uint32) cur.tv_usec) / 1000);
return msec;
}
void sim_os_sleep (unsigned int sec)
{
sleep (sec);
}
uint32 sim_os_ms_sleep_init (void)
{
return _compute_minimum_sleep ();
}
#include <sys/time.h>
#include <sys/resource.h>
t_stat sim_os_process_cpu_times (double *system, double *user)
{
struct rusage usage;
*system = 0.0;
*user = 0.0;
if (0 == getrusage (RUSAGE_SELF, &usage)) {
*system = ((double)usage.ru_stime.tv_sec) + ((double)usage.ru_stime.tv_usec / 1000000.0);
*user = ((double)usage.ru_utime.tv_sec) + ((double)usage.ru_utime.tv_usec / 1000000.0);
}
return SCPE_OK;
}
#if !defined(_POSIX_SOURCE)
#ifdef NEED_CLOCK_GETTIME
typedef int clockid_t;
int clock_gettime(clockid_t clk_id, struct timespec *tp)
{
struct timeval cur;
struct timezone foo;
if (clk_id != CLOCK_REALTIME)
return -1;
gettimeofday (&cur, &foo);
tp->tv_sec = cur.tv_sec;
tp->tv_nsec = cur.tv_usec*1000;
return 0;
}
#endif /* CLOCK_REALTIME */
#endif /* !defined(_POSIX_SOURCE) && defined(SIM_ASYNCH_IO) */
uint32 sim_os_ms_sleep (unsigned int milliseconds)
{
uint32 stime = sim_os_msec ();
struct timespec treq;
treq.tv_sec = milliseconds / MILLIS_PER_SEC;
treq.tv_nsec = (milliseconds % MILLIS_PER_SEC) * NANOS_PER_MILLI;
(void) nanosleep (&treq, NULL);
return sim_os_msec () - stime;
}
#if defined(NEED_THREAD_PRIORITY)
#undef NEED_THREAD_PRIORITY
#include <sys/time.h>
#include <sys/resource.h>
t_stat sim_os_set_thread_priority (int below_normal_above)
{
if ((below_normal_above < -1) || (below_normal_above > 1))
return SCPE_ARG;
errno = 0;
switch (below_normal_above) {
case PRIORITY_BELOW_NORMAL:
if ((getpriority (PRIO_PROCESS, 0) <= 0) && /* at or above normal pri? */
(errno == 0))
setpriority (PRIO_PROCESS, 0, 10);
break;
case PRIORITY_NORMAL:
if (getpriority (PRIO_PROCESS, 0) != 0) /* at or above normal pri? */
setpriority (PRIO_PROCESS, 0, 0);
break;
case PRIORITY_ABOVE_NORMAL:
if ((getpriority (PRIO_PROCESS, 0) <= 0) && /* at or above normal pri? */
(errno == 0))
setpriority (PRIO_PROCESS, 0, -10);
break;
}
return SCPE_OK;
}
#endif /* defined(NEED_THREAD_PRIORITY) */
#endif
/* If one hasn't been provided yet, then just stub it */
#if defined(NEED_THREAD_PRIORITY)
t_stat sim_os_set_thread_priority (int below_normal_above)
{
return SCPE_OK;
}
#endif
#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)
/* Make sure to use the substitute routines */
#undef sim_idle_ms_sleep
#undef sim_os_msec
#undef sim_os_ms_sleep
#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */
/* diff = min - sub */
void
sim_timespec_diff (struct timespec *diff, struct timespec *min, struct timespec *sub)
{
/* move the minuend value to the difference and operate there. */
*diff = *min;
/* Borrow as needed for the nsec value */
while (sub->tv_nsec > diff->tv_nsec) {
--diff->tv_sec;
diff->tv_nsec += 1000000000;
}
diff->tv_nsec -= sub->tv_nsec;
diff->tv_sec -= sub->tv_sec;
/* Normalize the result */
while (diff->tv_nsec >= 1000000000) {
++diff->tv_sec;
diff->tv_nsec -= 1000000000;
}
}
/* Forward declarations */
static double _timespec_to_double (struct timespec *time);
static void _double_to_timespec (struct timespec *time, double dtime);
static t_bool _rtcn_tick_catchup_check (RTC *rtc, int32 time);
static void _rtcn_configure_calibrated_clock (int32 newtmr);
static t_bool _sim_coschedule_cancel (UNIT *uptr);
static t_bool _sim_wallclock_cancel (UNIT *uptr);
static t_bool _sim_wallclock_is_active (UNIT *uptr);
t_stat sim_timer_show_idle_mode (FILE* st, UNIT* uptr, int32 val, CONST void * desc);
#if defined(SIM_ASYNCH_CLOCKS)
static int sim_timespec_compare (struct timespec *a, struct timespec *b)
{
while (a->tv_nsec >= 1000000000) {
a->tv_nsec -= 1000000000;
++a->tv_sec;
}
while (b->tv_nsec >= 1000000000) {
b->tv_nsec -= 1000000000;
++b->tv_sec;
}
if (a->tv_sec < b->tv_sec)
return -1;
if (a->tv_sec > b->tv_sec)
return 1;
if (a->tv_nsec < b->tv_nsec)
return -1;
if (a->tv_nsec > b->tv_nsec)
return 1;
else
return 0;
}
#endif /* defined(SIM_ASYNCH_CLOCKS) */
/* OS independent clock calibration package */
static uint32 sim_idle_cyc_ms = 0; /* Cycles per millisecond while not idling */
static uint32 sim_idle_cyc_sleep = 0; /* Cycles per minimum sleep interval */
static double sim_idle_end_time = 0.0; /* Time when last idle completed */
UNIT sim_stop_unit; /* Stop unit */
UNIT sim_internal_timer_unit; /* Internal calibration timer */
int32 sim_internal_timer_time; /* Pending internal timer delay */
UNIT sim_throttle_unit; /* one for throttle */
t_stat sim_throt_svc (UNIT *uptr);
t_stat sim_timer_tick_svc (UNIT *uptr);
t_stat sim_timer_stop_svc (UNIT *uptr);
#define DBG_IDL TIMER_DBG_IDLE /* idling */
#define DBG_QUE TIMER_DBG_QUEUE /* queue activities */
#define DBG_MUX TIMER_DBG_MUX /* tmxr queue activities */
#define DBG_TRC 0x008 /* tracing */
#define DBG_CAL 0x010 /* calibration activities */
#define DBG_TIM 0x020 /* timer thread activities */
#define DBG_THR 0x040 /* throttle activities */
#define DBG_ACK 0x080 /* interrupt acknowledgement activities */
#define DBG_CHK 0x100 /* check scheduled activation time*/
#define DBG_INT 0x200 /* internal timer activities */
#define DBG_GET 0x400 /* get_time activities */
#define DBG_TIK 0x800 /* tick activities */
DEBTAB sim_timer_debug[] = {
{"TRACE", DBG_TRC, "Trace routine calls"},
{"IDLE", DBG_IDL, "Idling activities"},
{"QUEUE", DBG_QUE, "Event queuing activities"},
{"IACK", DBG_ACK, "interrupt acknowledgement activities"},
{"CALIB", DBG_CAL, "Calibration activities"},
{"TICK", DBG_TIK, "Calibration tick activities"},
{"TIME", DBG_TIM, "Activation and scheduling activities"},
{"GETTIME", DBG_GET, "get_time activities"},
{"INTER", DBG_INT, "Internal timer activities"},
{"THROT", DBG_THR, "Throttling activities"},
{"MUX", DBG_MUX, "Tmxr scheduling activities"},
{"CHECK", DBG_CHK, "Check scheduled activation time"},
{0}
};
/* Forward device declarations */
extern DEVICE sim_timer_dev;
extern DEVICE sim_throttle_dev;
extern DEVICE sim_stop_dev;
void sim_rtcn_init_all (void)
{
int32 tmr;
RTC *rtc;
for (tmr = 0; tmr <= SIM_NTIMERS; tmr++) {
rtc = &rtcs[tmr];
if (rtc->initd != 0)
sim_rtcn_init (rtc->initd, tmr);
}
}
int32 sim_rtcn_init (int32 time, int32 tmr)
{
return sim_rtcn_init_unit (NULL, time, tmr);
}
int32 sim_rtcn_init_unit (UNIT *uptr, int32 time, int32 tmr)
{
return sim_rtcn_init_unit_ticks (uptr, time, tmr, 0);
}
int32 sim_rtcn_init_unit_ticks (UNIT *uptr, int32 time, int32 tmr, int32 ticksper)
{
RTC *rtc;
if (time == 0)
time = 1;
if (tmr == SIM_INTERNAL_CLK)
tmr = SIM_NTIMERS;
else {
if ((tmr < 0) || (tmr >= SIM_NTIMERS))
return time;
}
rtc = &rtcs[tmr];
/*
* If we'd previously succeeded in calibrating a tick value, then use that
* delay as a better default to setup when we're re-initialized.
* Re-initializing happens on any boot.
*/
if (rtc->currd)
time = rtc->currd;
if (!uptr)
uptr = rtc->clock_unit;
if (ticksper)
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_init_unit_ticks(unit=%s, time=%d, tmr=%d, ticks=%d)\n", uptr ? sim_uname(uptr) : "", time, tmr, ticksper);
else
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_init_unit(unit=%s, time=%d, tmr=%d)\n", uptr ? sim_uname(uptr) : "", time, tmr);
if (uptr) {
if (!rtc->clock_unit)
sim_register_clock_unit_tmr (uptr, tmr);
}
rtc->gtime = sim_gtime();
rtc->rtime = sim_is_running ? sim_os_msec () : sim_stop_time;
rtc->vtime = rtc->rtime;
rtc->nxintv = 1000;
rtc->ticks = 0;
rtc->last_hz = rtc->hz;
rtc->hz = ticksper;
rtc->based = time;
rtc->currd = time;
rtc->initd = time;
rtc->elapsed = 0;
rtc->calibrations = 0;
rtc->clock_ticks_tot += rtc->clock_ticks;
rtc->clock_ticks = 0;
rtc->calib_tick_time_tot += rtc->calib_tick_time;
rtc->calib_tick_time = 0;
rtc->clock_catchup_pending = FALSE;
rtc->clock_catchup_eligible = FALSE;
rtc->clock_catchup_ticks_tot += rtc->clock_catchup_ticks;
rtc->clock_catchup_ticks = 0;
rtc->clock_catchup_ticks_curr = 0;
rtc->calib_ticks_acked_tot += rtc->calib_ticks_acked;
rtc->calib_ticks_acked = 0;
++rtc->calib_initializations;
rtc->clock_init_base_time = sim_timenow_double ();
_rtcn_configure_calibrated_clock (tmr);
return time;
}
int32 sim_rtcn_calb_tick (int32 tmr)
{
RTC *rtc = &rtcs[tmr];
return sim_rtcn_calb (rtc->hz, tmr);
}
int32 sim_rtcn_calb (uint32 ticksper, int32 tmr)
{
uint32 new_rtime, delta_rtime, last_idle_pct, catchup_ticks_curr;
int32 delta_vtime;
double new_gtime;
int32 new_currd;
int32 itmr;
RTC *rtc;
if (tmr == SIM_INTERNAL_CLK)
tmr = SIM_NTIMERS;
else {
if ((tmr < 0) || (tmr >= SIM_NTIMERS))
return 10000;
}
rtc = &rtcs[tmr];
if (rtc->hz != ticksper) { /* changing tick rate? */
uint32 prior_hz = rtc->hz;
if (tmr == sim_calb_tmr_last) /* restarting after having previously been the calibrated timer? */
ticksper = rtc->last_hz; /* Use the prior tick rate */
if (rtc->hz == 0)
rtc->clock_tick_start_time = sim_timenow_double ();
if ((rtc->last_hz != 0) && (rtc->last_hz != ticksper) && (ticksper != 0))
rtc->currd = (int32)(sim_timer_inst_per_sec () / ticksper);
rtc->last_hz = rtc->hz;
rtc->hz = ticksper;
_rtcn_configure_calibrated_clock (tmr);
if (ticksper != 0) {
RTC *crtc = &rtcs[sim_calb_tmr];
rtc->clock_tick_size = 1.0 / ticksper;
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d,tmr=%d) currd=%d, prior_hz=%d\n", ticksper, tmr, rtc->currd, (int)prior_hz);
if ((tmr != sim_calb_tmr) && rtc->clock_unit && (ticksper > crtc->hz)) {
sim_catchup_ticks = TRUE;
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(%d) - forcing catchup ticks for %s ticking at %d, host tick rate %ds\n", tmr, sim_uname (rtc->clock_unit), ticksper, sim_os_tick_hz);
_rtcn_tick_catchup_check (rtc, 0);
}
}
else
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d,tmr=%d) timer stopped currd was %d, prior_hz=%d\n", ticksper, tmr, rtc->currd, (int)prior_hz);
}
if (ticksper == 0) /* running? */
return 10000;
if (rtc->clock_unit == NULL) { /* Not using TIMER units? */
rtc->clock_ticks += 1;
rtc->calib_tick_time += rtc->clock_tick_size;
}
if (rtc->clock_catchup_pending) { /* catchup tick? */
++rtc->clock_catchup_ticks; /* accumulating which were catchups */
++rtc->clock_catchup_ticks_curr;
rtc->clock_catchup_pending = FALSE;
}
rtc->ticks += 1; /* count ticks */
if (rtc->ticks < ticksper) /* 1 sec yet? */
return rtc->currd;
catchup_ticks_curr = rtc->clock_catchup_ticks_curr;
rtc->clock_catchup_ticks_curr = 0;
rtc->ticks = 0; /* reset ticks */
rtc->elapsed += 1; /* count sec */
if (!rtc_avail) /* no timer? */
return rtc->currd;
if (sim_calb_tmr != tmr) {
rtc->currd = (int32)(sim_timer_inst_per_sec()/ticksper);
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(tmr=%d) calibrated against internal system tmr=%d, tickper=%d (result: %d)\n", tmr, sim_calb_tmr, ticksper, rtc->currd);
return rtc->currd;
}
new_rtime = sim_os_msec (); /* wall time */
if (!sim_signaled_int_char &&
((new_rtime - sim_last_poll_kbd_time) > 500)) {
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(tmr=%d) gratuitious keyboard poll after %d msecs\n", tmr, (int)(new_rtime - sim_last_poll_kbd_time));
(void)sim_poll_kbd ();
}
++rtc->calibrations; /* count calibrations */
sim_debug (DBG_TRC, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d, tmr=%d)\n", ticksper, tmr);
if (new_rtime < rtc->rtime) { /* time running backwards? */
/* This happens when the value returned by sim_os_msec wraps (as an uint32) */
/* Wrapping will happen initially sometime before a simulator has been running */
/* for 49 days approximately every 49 days thereafter. */
++rtc->clock_calib_backwards; /* Count statistic */
sim_debug (DBG_CAL, &sim_timer_dev, "time running backwards - OldTime: %u, NewTime: %u, result: %d\n", rtc->rtime, new_rtime, rtc->currd);
rtc->vtime = rtc->rtime = new_rtime; /* reset wall time */
rtc->nxintv = 1000;
rtc->based = rtc->currd;
if (rtc->clock_catchup_eligible) {
rtc->clock_catchup_base_time = sim_timenow_double();
rtc->calib_tick_time = 0.0;
}
return rtc->currd; /* can't calibrate */
}
delta_rtime = new_rtime - rtc->rtime; /* elapsed wtime */
rtc->rtime = new_rtime; /* adv wall time */
rtc->vtime += 1000; /* adv sim time */
if (delta_rtime > 30000) { /* gap too big? */
/* This simulator process has somehow been suspended for a significant */
/* amount of time. This will certainly happen if the host system has */
/* slept or hibernated. It also might happen when a simulator */
/* developer stops the simulator at a breakpoint (a process, not simh */
/* breakpoint). To accomodate this, we set the calibration state to */
/* ignore what happened and proceed from here. */
++rtc->clock_calib_gap2big; /* Count statistic */
rtc->vtime = rtc->rtime; /* sync virtual and real time */
rtc->nxintv = 1000; /* reset next interval */
rtc->gtime = sim_gtime(); /* save instruction time */
rtc->based = rtc->currd;
if (rtc->clock_catchup_eligible)
rtc->calib_tick_time += ((double)delta_rtime / 1000.0);/* advance tick time */
sim_debug (DBG_CAL, &sim_timer_dev, "gap too big: delta = %d - result: %d\n", delta_rtime, rtc->currd);
return rtc->currd; /* can't calibr */
}
last_idle_pct = 0; /* normally force calibration */
if (tmr != SIM_NTIMERS) {
if (delta_rtime != 0) /* avoid divide by zero */
last_idle_pct = MIN(100, (uint32)(100.0 * (((double)(rtc->clock_time_idled - rtc->clock_time_idled_last)) / ((double)delta_rtime))));