1 ////////////////////////////////////////////////////////////////////////
2 // $Id: virt_timer.cc 14109 2021-01-30 23:55:24Z vruppert $
3 /////////////////////////////////////////////////////////////////////////
4 //
5 // Copyright (C) 2002-2021 The Bochs Project
6 //
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Lesser General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // Lesser General Public License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public
18 // License along with this library; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ////////////////////////////////////////////////////////////////////////
21
22 /////////////////////////////////////////////////////////////////////////
23 //
24 //Realtime Algorithm (with gettimeofday)
25 // HAVE:
26 // Real number of usec.
27 // Emulated number of usec.
28 // WANT:
29 // Number of ticks to use.
30 // Number of emulated usec to wait until next try.
31 //
32 // ticks=number of ticks needed to match total real usec.
33 // if(desired ticks > max ticks for elapsed real time)
34 // ticks = max ticks for elapsed real time.
35 // if(desired ticks > max ticks for elapsed emulated usec)
36 // ticks = max ticks for emulated usec.
37 // next wait ticks = number of ticks until next event.
38 // next wait real usec = (current ticks + next wait ticks) * usec per ticks
39 // next wait emulated usec = next wait real usec * emulated usec / real usec
40 // if(next wait emulated usec < minimum emulated usec for next wait ticks)
41 // next wait emulated usec = minimum emulated usec for next wait ticks.
42 // if(next wait emulated usec > max emulated usec wait)
43 // next wait emulated usec = max emulated usec wait.
44 //
45 // How to calculate elapsed real time:
46 // store an unused time value whenever no ticks are used in a given time.
47 // add this to the current elapsed time.
48 // How to calculate elapsed emulated time:
49 // same as above.
50 // Above can be done by not updating last_usec and last_sec.
51 //
52 // How to calculate emulated usec/real usec:
53 // Each time there are actual ticks:
54 // Alpha_product(old emulated usec, emulated usec);
55 // Alpha_product(old real usec, real usec);
56 // Divide resulting values.
57 //
58 /////////////////////////////////////////////////////////////////////////
59
60 #include "bochs.h"
61 #include "gui/siminterface.h"
62 #include "param_names.h"
63 #include "virt_timer.h"
64
65 //Important constant #defines:
66 #define USEC_PER_SECOND (1000000)
67
68
69 // define a macro to convert floating point numbers into 64-bit integers.
70 // In MSVC++ you can convert a 64-bit float into a 64-bit signed integer,
71 // but it will not convert a 64-bit float into a 64-bit unsigned integer.
72 // This macro works around that.
73 #define F2I(x) ((Bit64u)(Bit64s) (x))
74 #define I2F(x) ((double)(Bit64s) (x))
75
76 //CONFIGURATION #defines:
77
78
79 //MAINLINE Configuration (For realtime PIT):
80
81 //How much faster than real time we can go:
82 #define MAX_MULT (1.25)
83
84 //Minimum number of emulated useconds per second.
85 // Now calculated using BX_MIN_IPS, the minimum number of
86 // instructions per second.
87 #define MIN_USEC_PER_SECOND (((((Bit64u)USEC_PER_SECOND)*((Bit64u)BX_MIN_IPS))/((Bit64u)ips))+(Bit64u)1)
88
89
90 //DEBUG configuration:
91
92 //Debug with printf options.
93 #define DEBUG_REALTIME_WITH_PRINTF 0
94
95
96 #define GET_VIRT_REALTIME64_USEC() (bx_get_realtime64_usec())
97 //Set up Logging.
98 #define LOG_THIS bx_virt_timer.
99
100 //A single instance.
101 bx_virt_timer_c bx_virt_timer;
102
103
104 //USEC_ALPHA is multiplier for the past.
105 //USEC_ALPHA_B is 1-USEC_ALPHA, or multiplier for the present.
106 #define USEC_ALPHA ((double)(.8))
107 #define USEC_ALPHA_B ((double)(((double)1)-USEC_ALPHA))
108 #define USEC_ALPHA2 ((double)(.5))
109 #define USEC_ALPHA2_B ((double)(((double)1)-USEC_ALPHA2))
110 #define ALPHA_LOWER(old,new) ((Bit64u)((old<new)?((USEC_ALPHA*(I2F(old)))+(USEC_ALPHA_B*(I2F(new)))):((USEC_ALPHA2*(I2F(old)))+(USEC_ALPHA2_B*(I2F(new))))))
111
112
113 //Conversion between emulated useconds and optionally realtime ticks.
114 #define TICKS_TO_USEC(a) (((a)*usec_per_second)/ticks_per_second)
115 #define USEC_TO_TICKS(a) (((a)*ticks_per_second)/usec_per_second)
116
bx_virt_timer_c()117 bx_virt_timer_c::bx_virt_timer_c()
118 {
119 put("virt_timer", "VTIMER");
120
121 setup();
122 }
123
124 const Bit64u bx_virt_timer_c::NullTimerInterval = BX_MAX_VIRTUAL_TIME;
125
nullTimer(void * this_ptr)126 void bx_virt_timer_c::nullTimer(void* this_ptr)
127 {
128 UNUSED(this_ptr);
129 }
130
periodic(Bit64u time_passed,bool mode)131 void bx_virt_timer_c::periodic(Bit64u time_passed, bool mode)
132 {
133 //Assert that we haven't skipped any events.
134 BX_ASSERT (time_passed <= s[mode].timers_next_event_time);
135 BX_ASSERT(!in_timer_handler);
136
137 //Update time variables.
138 s[mode].timers_next_event_time -= time_passed;
139 s[mode].current_timers_time += time_passed;
140
141 //If no events are occurring, just pass the time and we're done.
142 if (time_passed < s[mode].timers_next_event_time) return;
143
144 //Starting timer handler calls.
145 in_timer_handler = 1;
146 //Otherwise, cause any events to occur that should.
147 unsigned i;
148 for (i=0;i<numTimers;i++) {
149 if (timer[i].inUse && timer[i].active) {
150 if (timer[i].realtime != mode) continue;
151 //Assert that we haven't skipped any timers.
152 BX_ASSERT(s[mode].current_timers_time <= timer[i].timeToFire);
153 if (timer[i].timeToFire == s[mode].current_timers_time) {
154 if (timer[i].continuous) {
155 timer[i].timeToFire += timer[i].period;
156 } else {
157 timer[i].active = 0;
158 }
159 //This function MUST return, or the timer mechanism
160 // will be broken.
161 timer[i].funct(timer[i].this_ptr);
162 }
163 }
164 }
165 //Finished timer handler calls.
166 in_timer_handler = 0;
167 //Use a second FOR loop so that a timer function call can
168 // change the behavior of another timer.
169 //s[mode].timers_next_event_time normally contains a cycle count, not a cycle time.
170 // here we use it as a temporary variable that IS a cycle time,
171 // but then convert it back to a cycle count afterwards.
172 s[mode].timers_next_event_time = s[mode].current_timers_time + BX_MAX_VIRTUAL_TIME;
173 for (i=0;i<numTimers;i++) {
174 if (timer[i].inUse && timer[i].active && (timer[i].realtime == mode) &&
175 ((timer[i].timeToFire)<s[mode].timers_next_event_time)) {
176 s[mode].timers_next_event_time = timer[i].timeToFire;
177 }
178 }
179 s[mode].timers_next_event_time -= s[mode].current_timers_time;
180 next_event_time_update(mode);
181 //FIXME
182 }
183
184
185 //Get the current virtual time.
186 // This may return the same value on subsequent calls.
time_usec(bool mode)187 Bit64u bx_virt_timer_c::time_usec(bool mode)
188 {
189 //Update the time here only if we're not in a timer handler.
190 //If we're in a timer handler we're up-to-date, and otherwise
191 // this prevents call stack loops.
192 if (!in_timer_handler) {
193 timer_handler(mode);
194 }
195 return s[mode].current_timers_time;
196 }
197
198 //Get the current virtual time.
199 // This will return a monotonically increasing value.
200 // MUST NOT be called from within a timer interrupt.
time_usec_sequential(bool mode)201 Bit64u bx_virt_timer_c::time_usec_sequential(bool mode)
202 {
203 //Can't prevent call stack loops here, so this
204 // MUST NOT be called from within a timer handler.
205 BX_ASSERT(s[mode].timers_next_event_time>0);
206 BX_ASSERT(!in_timer_handler);
207
208 if (s[mode].last_sequential_time >= s[mode].current_timers_time) {
209 periodic(1, mode);
210 s[mode].last_sequential_time = s[mode].current_timers_time;
211 }
212 return s[mode].current_timers_time;
213 }
214
215
216 //Register a timer handler to go off after a given interval.
217 //Register a timer handler to go off with a periodic interval.
register_timer(void * this_ptr,bx_timer_handler_t handler,Bit32u useconds,bool continuous,bool active,bool realtime,const char * id)218 int bx_virt_timer_c::register_timer(void *this_ptr, bx_timer_handler_t handler,
219 Bit32u useconds, bool continuous,
220 bool active, bool realtime,
221 const char *id)
222 {
223 //We don't like starting with a zero period timer.
224 BX_ASSERT((!active) || (useconds>0));
225
226 //Search for an unused timer.
227 unsigned int i;
228 for (i=0; i < numTimers; i++) {
229 if ((timer[i].inUse == 0) || (i == numTimers))
230 break;
231 }
232 // If we didn't find a free slot, increment the bound, numTimers.
233 if (i == numTimers)
234 numTimers++; // One new timer installed.
235 BX_ASSERT(numTimers<BX_MAX_VIRTUAL_TIMERS);
236
237 timer[i].inUse = 1;
238 timer[i].period = useconds;
239 timer[i].timeToFire = s[realtime].current_timers_time + (Bit64u)useconds;
240 timer[i].active = active;
241 timer[i].realtime = realtime;
242 timer[i].continuous = continuous;
243 timer[i].funct = handler;
244 timer[i].this_ptr = this_ptr;
245 strncpy(timer[i].id, id, BxMaxTimerIDLen);
246 timer[i].id[BxMaxTimerIDLen-1]=0; //I like null terminated strings.
247
248 if (realtime) {
249 BX_DEBUG(("Timer #%d ('%s') using realtime synchronisation mode", i, timer[i].id));
250 } else {
251 BX_DEBUG(("Timer #%d ('%s') using standard mode", i, timer[i].id));
252 }
253 if (useconds < s[realtime].timers_next_event_time) {
254 s[realtime].timers_next_event_time = useconds;
255 next_event_time_update(realtime);
256 //FIXME
257 }
258 return i;
259 }
260
261 //unregister a previously registered timer.
unregisterTimer(unsigned timerID)262 bool bx_virt_timer_c::unregisterTimer(unsigned timerID)
263 {
264 BX_ASSERT(timerID < BX_MAX_VIRTUAL_TIMERS);
265
266 if (timer[timerID].active) {
267 BX_PANIC(("unregisterTimer: timer '%s' is still active!", timer[timerID].id));
268 return(0); // Fail.
269 }
270
271 //No need to prevent doing this to unused timers.
272 timer[timerID].inUse = 0;
273 if (timerID == (numTimers-1)) numTimers--;
274 return 1;
275 }
276
start_timers(void)277 void bx_virt_timer_c::start_timers(void)
278 {
279 //FIXME
280 }
281
282 //activate a deactivated but registered timer.
activate_timer(unsigned timer_index,Bit32u useconds,bool continuous)283 void bx_virt_timer_c::activate_timer(unsigned timer_index, Bit32u useconds,
284 bool continuous)
285 {
286 BX_ASSERT(timer_index < BX_MAX_VIRTUAL_TIMERS);
287
288 BX_ASSERT(timer[timer_index].inUse);
289 BX_ASSERT(useconds>0);
290
291 bool realtime = timer[timer_index].realtime;
292 timer[timer_index].period = useconds;
293 timer[timer_index].timeToFire = s[realtime].current_timers_time + (Bit64u)useconds;
294 timer[timer_index].active = 1;
295 timer[timer_index].continuous = continuous;
296
297 if (useconds < s[realtime].timers_next_event_time) {
298 s[realtime].timers_next_event_time = useconds;
299 next_event_time_update(realtime);
300 //FIXME
301 }
302 }
303
304 //deactivate (but don't unregister) a currently registered timer.
deactivate_timer(unsigned timer_index)305 void bx_virt_timer_c::deactivate_timer(unsigned timer_index)
306 {
307 BX_ASSERT(timer_index < BX_MAX_VIRTUAL_TIMERS);
308
309 //No need to prevent doing this to unused/inactive timers.
310 timer[timer_index].active = 0;
311 }
312
advance_virtual_time(Bit64u time_passed,bool mode)313 void bx_virt_timer_c::advance_virtual_time(Bit64u time_passed, bool mode)
314 {
315 BX_ASSERT(time_passed <= s[mode].virtual_next_event_time);
316
317 s[mode].current_virtual_time += time_passed;
318 s[mode].virtual_next_event_time -= time_passed;
319
320 if (s[mode].current_virtual_time > s[mode].current_timers_time) {
321 periodic(s[mode].current_virtual_time - s[mode].current_timers_time, mode);
322 }
323 }
324
325 //Called when next_event_time changes.
next_event_time_update(bool mode)326 void bx_virt_timer_c::next_event_time_update(bool mode)
327 {
328 s[mode].virtual_next_event_time = s[mode].timers_next_event_time + s[mode].current_timers_time - s[mode].current_virtual_time;
329 if (init_done) {
330 bx_pc_system.deactivate_timer(s[mode].system_timer_id);
331 BX_ASSERT(s[mode].virtual_next_event_time);
332 bx_pc_system.activate_timer(s[mode].system_timer_id,
333 (Bit32u)BX_MIN(0x7FFFFFFF,BX_MAX(1,TICKS_TO_USEC(s[mode].virtual_next_event_time))),
334 0);
335 }
336 }
337
setup(void)338 void bx_virt_timer_c::setup(void)
339 {
340 numTimers = 0;
341 in_timer_handler = 0;
342 for (unsigned i = 0; i < 2; i++) {
343 s[i].current_timers_time = 0;
344 s[i].timers_next_event_time = BX_MAX_VIRTUAL_TIME;
345 s[i].last_sequential_time = 0;
346 s[i].virtual_next_event_time = BX_MAX_VIRTUAL_TIME;
347 s[i].current_virtual_time = 0;
348 }
349 init_done = 0;
350 }
351
init(void)352 void bx_virt_timer_c::init(void)
353 {
354 // Local copy of IPS value to avoid reading it frequently in timer handler
355 ips = SIM->get_param_num(BXPN_IPS)->get();
356
357 register_timer(this, nullTimer, (Bit32u)NullTimerInterval, 1, 1, 0, "Null Timer #1");
358 register_timer(this, nullTimer, (Bit32u)NullTimerInterval, 1, 1, 1, "Null Timer #2");
359
360 s[0].system_timer_id = bx_pc_system.register_timer(this, pc_system_timer_handler_0,
361 (Bit32u)s[0].virtual_next_event_time, 0, 1, "Virtual Timer #0");
362 s[1].system_timer_id = bx_pc_system.register_timer(this, pc_system_timer_handler_1,
363 (Bit32u)s[1].virtual_next_event_time, 0, 1, "Virtual Timer #1");
364
365 //Real time variables:
366 #if BX_HAVE_REALTIME_USEC
367 last_real_time = GET_VIRT_REALTIME64_USEC();
368 #endif
369 total_real_usec = 0;
370 last_realtime_delta = 0;
371 real_time_delay = 0;
372 //System time variables:
373 last_usec = 0;
374 usec_per_second = USEC_PER_SECOND;
375 stored_delta = 0;
376 last_system_usec = 0;
377 em_last_realtime = 0;
378 //Virtual timer variables:
379 total_ticks = 0;
380 last_realtime_ticks = 0;
381 ticks_per_second = USEC_PER_SECOND;
382
383 init_done = 1;
384 }
385
register_state(void)386 void bx_virt_timer_c::register_state(void)
387 {
388 unsigned i;
389 char name[4];
390
391 bx_list_c *list = new bx_list_c(SIM->get_bochs_root(), "virt_timer", "Virtual Timer State");
392 bx_list_c *vtimers = new bx_list_c(list, "timer");
393 for (i = 0; i < numTimers; i++) {
394 sprintf(name, "%u", i);
395 bx_list_c *bxtimer = new bx_list_c(vtimers, name);
396 BXRS_PARAM_BOOL(bxtimer, inUse, timer[i].inUse);
397 BXRS_DEC_PARAM_FIELD(bxtimer, period, timer[i].period);
398 BXRS_DEC_PARAM_FIELD(bxtimer, timeToFire, timer[i].timeToFire);
399 BXRS_PARAM_BOOL(bxtimer, active, timer[i].active);
400 BXRS_PARAM_BOOL(bxtimer, continuous, timer[i].continuous);
401 BXRS_PARAM_BOOL(bxtimer, realtime, timer[i].realtime);
402 }
403 bx_list_c *sys = new bx_list_c(list, "s");
404 for (i = 0; i < 2; i++) {
405 sprintf(name, "%u", i);
406 bx_list_c *snum = new bx_list_c(sys, name);
407 BXRS_DEC_PARAM_FIELD(snum, current_timers_time, s[i].current_timers_time);
408 BXRS_DEC_PARAM_FIELD(snum, timers_next_event_time, s[i].timers_next_event_time);
409 BXRS_DEC_PARAM_FIELD(snum, last_sequential_time, s[i].last_sequential_time);
410 BXRS_DEC_PARAM_FIELD(snum, virtual_next_event_time, s[i].virtual_next_event_time);
411 BXRS_DEC_PARAM_FIELD(snum, current_virtual_time, s[i].current_virtual_time);
412 }
413 BXRS_DEC_PARAM_SIMPLE(list, last_real_time);
414 BXRS_DEC_PARAM_SIMPLE(list, total_real_usec);
415 BXRS_DEC_PARAM_SIMPLE(list, last_realtime_delta);
416 BXRS_DEC_PARAM_SIMPLE(list, last_usec);
417 BXRS_DEC_PARAM_SIMPLE(list, usec_per_second);
418 BXRS_DEC_PARAM_SIMPLE(list, stored_delta);
419 BXRS_DEC_PARAM_SIMPLE(list, last_system_usec);
420 BXRS_DEC_PARAM_SIMPLE(list, em_last_realtime);
421 BXRS_DEC_PARAM_SIMPLE(list, total_ticks);
422 BXRS_DEC_PARAM_SIMPLE(list, last_realtime_ticks);
423 BXRS_DEC_PARAM_SIMPLE(list, ticks_per_second);
424 }
425
timer_handler(bool mode)426 void bx_virt_timer_c::timer_handler(bool mode)
427 {
428 if (!mode) {
429 Bit64u temp_final_time = bx_pc_system.time_usec();
430 temp_final_time -= s[0].current_virtual_time;
431 while (temp_final_time) {
432 if ((temp_final_time)>(s[0].virtual_next_event_time)) {
433 temp_final_time -= s[0].virtual_next_event_time;
434 advance_virtual_time(s[0].virtual_next_event_time, 0);
435 } else {
436 advance_virtual_time(temp_final_time, 0);
437 temp_final_time -= temp_final_time;
438 }
439 }
440 bx_pc_system.activate_timer(s[0].system_timer_id,
441 (Bit32u)BX_MIN(0x7FFFFFFF,(s[0].virtual_next_event_time>2)?(s[0].virtual_next_event_time-2):1),
442 0);
443 return;
444 }
445
446 Bit64u usec_delta = bx_pc_system.time_usec()-last_usec;
447
448 if (usec_delta) {
449 #if BX_HAVE_REALTIME_USEC
450 Bit64u ticks_delta = 0;
451 Bit64u real_time_delta = GET_VIRT_REALTIME64_USEC() - last_real_time - real_time_delay;
452 Bit64u real_time_total = real_time_delta + total_real_usec;
453 Bit64u system_time_delta = (Bit64u)usec_delta + (Bit64u)stored_delta;
454 if (real_time_delta) {
455 last_realtime_delta = real_time_delta;
456 last_realtime_ticks = total_ticks;
457 }
458 ticks_per_second = USEC_PER_SECOND;
459
460 //Start out with the number of ticks we would like
461 // to have to line up with real time.
462 ticks_delta = real_time_total - total_ticks;
463 if (real_time_total < total_ticks) {
464 //This slows us down if we're already ahead.
465 // probably only an issue on startup, but it solves some problems.
466 ticks_delta = 0;
467 }
468 if (ticks_delta + total_ticks - last_realtime_ticks > (F2I(MAX_MULT * I2F(last_realtime_delta)))) {
469 //This keeps us from going too fast in relation to real time.
470 #if 0
471 ticks_delta = (F2I(MAX_MULT * I2F(last_realtime_delta))) + last_realtime_ticks - total_ticks;
472 #endif
473 ticks_per_second = F2I(MAX_MULT * I2F(USEC_PER_SECOND));
474 }
475 if (ticks_delta > system_time_delta * USEC_PER_SECOND / MIN_USEC_PER_SECOND) {
476 //This keeps us from having too few instructions between ticks.
477 ticks_delta = system_time_delta * USEC_PER_SECOND / MIN_USEC_PER_SECOND;
478 }
479 if (ticks_delta > s[1].virtual_next_event_time) {
480 //This keeps us from missing ticks.
481 ticks_delta = s[1].virtual_next_event_time;
482 }
483
484 if (ticks_delta) {
485
486 # if DEBUG_REALTIME_WITH_PRINTF
487 //Every second print some info.
488 if (((last_real_time + real_time_delta) / USEC_PER_SECOND) > (last_real_time / USEC_PER_SECOND)) {
489 Bit64u temp1, temp2, temp3, temp4;
490 temp1 = (Bit64u) total_real_usec;
491 temp2 = (total_real_usec);
492 temp3 = (Bit64u)total_ticks;
493 temp4 = (Bit64u)((total_real_usec) - total_ticks);
494 printf("useconds: " FMT_LL "u, ", temp1);
495 printf("expect ticks: " FMT_LL "u, ", temp2);
496 printf("ticks: " FMT_LL "u, ", temp3);
497 printf("diff: " FMT_LL "u\n", temp4);
498 }
499 # endif
500
501 last_real_time += real_time_delta;
502 total_real_usec += real_time_delta;
503 last_system_usec += system_time_delta;
504 stored_delta = 0;
505 total_ticks += ticks_delta;
506 } else {
507 stored_delta = system_time_delta;
508 }
509
510 Bit64u a = usec_per_second, b;
511 if (real_time_delta) {
512 //FIXME
513 Bit64u em_realtime_delta = last_system_usec + stored_delta - em_last_realtime;
514 b=((Bit64u)USEC_PER_SECOND * em_realtime_delta / real_time_delta);
515 em_last_realtime = last_system_usec + stored_delta;
516 } else {
517 b=a;
518 }
519 usec_per_second = ALPHA_LOWER(a,b);
520 #else
521 BX_ASSERT(0);
522 #endif
523 #if BX_HAVE_REALTIME_USEC
524 advance_virtual_time(ticks_delta, 1);
525 #endif
526 }
527
528 last_usec=last_usec + usec_delta;
529 bx_pc_system.deactivate_timer(s[1].system_timer_id);
530 BX_ASSERT(s[1].virtual_next_event_time);
531 bx_pc_system.activate_timer(s[1].system_timer_id,
532 (Bit32u)BX_MIN(0x7FFFFFFF,BX_MAX(1,TICKS_TO_USEC(s[1].virtual_next_event_time))),
533 0);
534 }
535
pc_system_timer_handler_0(void * this_ptr)536 void bx_virt_timer_c::pc_system_timer_handler_0(void* this_ptr)
537 {
538 ((bx_virt_timer_c *)this_ptr)->timer_handler(0);
539 }
540
pc_system_timer_handler_1(void * this_ptr)541 void bx_virt_timer_c::pc_system_timer_handler_1(void* this_ptr)
542 {
543 ((bx_virt_timer_c *)this_ptr)->timer_handler(1);
544 }
545
set_realtime_delay()546 void bx_virt_timer_c::set_realtime_delay()
547 {
548 real_time_delay = GET_VIRT_REALTIME64_USEC() - last_real_time;
549 }
550