Merge remote-tracking branch 'remotes/dgilbert-gitlab/tags/pull-migration-20210726a...
[qemu/armbru.git] / hw / rtc / mc146818rtc.c
blob4fbafddb226d4e65fa2e4504ab225f0a7696590d
1 /*
2 * QEMU MC146818 RTC emulation
4 * Copyright (c) 2003-2004 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "qemu-common.h"
27 #include "qemu/cutils.h"
28 #include "qemu/module.h"
29 #include "qemu/bcd.h"
30 #include "hw/acpi/aml-build.h"
31 #include "hw/irq.h"
32 #include "hw/qdev-properties.h"
33 #include "hw/qdev-properties-system.h"
34 #include "qemu/timer.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/replay.h"
37 #include "sysemu/reset.h"
38 #include "sysemu/runstate.h"
39 #include "hw/rtc/mc146818rtc.h"
40 #include "hw/rtc/mc146818rtc_regs.h"
41 #include "migration/vmstate.h"
42 #include "qapi/error.h"
43 #include "qapi/qapi-events-misc-target.h"
44 #include "qapi/visitor.h"
45 #include "hw/rtc/mc146818rtc_regs.h"
47 #ifdef TARGET_I386
48 #include "qapi/qapi-commands-misc-target.h"
49 #include "hw/i386/apic.h"
50 #endif
52 //#define DEBUG_CMOS
53 //#define DEBUG_COALESCED
55 #ifdef DEBUG_CMOS
56 # define CMOS_DPRINTF(format, ...) printf(format, ## __VA_ARGS__)
57 #else
58 # define CMOS_DPRINTF(format, ...) do { } while (0)
59 #endif
61 #ifdef DEBUG_COALESCED
62 # define DPRINTF_C(format, ...) printf(format, ## __VA_ARGS__)
63 #else
64 # define DPRINTF_C(format, ...) do { } while (0)
65 #endif
67 #define SEC_PER_MIN 60
68 #define MIN_PER_HOUR 60
69 #define SEC_PER_HOUR 3600
70 #define HOUR_PER_DAY 24
71 #define SEC_PER_DAY 86400
73 #define RTC_REINJECT_ON_ACK_COUNT 20
74 #define RTC_CLOCK_RATE 32768
75 #define UIP_HOLD_LENGTH (8 * NANOSECONDS_PER_SECOND / 32768)
77 static void rtc_set_time(RTCState *s);
78 static void rtc_update_time(RTCState *s);
79 static void rtc_set_cmos(RTCState *s, const struct tm *tm);
80 static inline int rtc_from_bcd(RTCState *s, int a);
81 static uint64_t get_next_alarm(RTCState *s);
83 static inline bool rtc_running(RTCState *s)
85 return (!(s->cmos_data[RTC_REG_B] & REG_B_SET) &&
86 (s->cmos_data[RTC_REG_A] & 0x70) <= 0x20);
89 static uint64_t get_guest_rtc_ns(RTCState *s)
91 uint64_t guest_clock = qemu_clock_get_ns(rtc_clock);
93 return s->base_rtc * NANOSECONDS_PER_SECOND +
94 guest_clock - s->last_update + s->offset;
97 static void rtc_coalesced_timer_update(RTCState *s)
99 if (s->irq_coalesced == 0) {
100 timer_del(s->coalesced_timer);
101 } else {
102 /* divide each RTC interval to 2 - 8 smaller intervals */
103 int c = MIN(s->irq_coalesced, 7) + 1;
104 int64_t next_clock = qemu_clock_get_ns(rtc_clock) +
105 periodic_clock_to_ns(s->period / c);
106 timer_mod(s->coalesced_timer, next_clock);
110 static QLIST_HEAD(, RTCState) rtc_devices =
111 QLIST_HEAD_INITIALIZER(rtc_devices);
113 #ifdef TARGET_I386
114 void qmp_rtc_reset_reinjection(Error **errp)
116 RTCState *s;
118 QLIST_FOREACH(s, &rtc_devices, link) {
119 s->irq_coalesced = 0;
123 static bool rtc_policy_slew_deliver_irq(RTCState *s)
125 apic_reset_irq_delivered();
126 qemu_irq_raise(s->irq);
127 return apic_get_irq_delivered();
130 static void rtc_coalesced_timer(void *opaque)
132 RTCState *s = opaque;
134 if (s->irq_coalesced != 0) {
135 s->cmos_data[RTC_REG_C] |= 0xc0;
136 DPRINTF_C("cmos: injecting from timer\n");
137 if (rtc_policy_slew_deliver_irq(s)) {
138 s->irq_coalesced--;
139 DPRINTF_C("cmos: coalesced irqs decreased to %d\n",
140 s->irq_coalesced);
144 rtc_coalesced_timer_update(s);
146 #else
147 static bool rtc_policy_slew_deliver_irq(RTCState *s)
149 assert(0);
150 return false;
152 #endif
154 static uint32_t rtc_periodic_clock_ticks(RTCState *s)
156 int period_code;
158 if (!(s->cmos_data[RTC_REG_B] & REG_B_PIE)) {
159 return 0;
162 period_code = s->cmos_data[RTC_REG_A] & 0x0f;
164 return periodic_period_to_clock(period_code);
168 * handle periodic timer. @old_period indicates the periodic timer update
169 * is just due to period adjustment.
171 static void
172 periodic_timer_update(RTCState *s, int64_t current_time, uint32_t old_period, bool period_change)
174 uint32_t period;
175 int64_t cur_clock, next_irq_clock, lost_clock = 0;
177 period = rtc_periodic_clock_ticks(s);
178 s->period = period;
180 if (!period) {
181 s->irq_coalesced = 0;
182 timer_del(s->periodic_timer);
183 return;
186 /* compute 32 khz clock */
187 cur_clock =
188 muldiv64(current_time, RTC_CLOCK_RATE, NANOSECONDS_PER_SECOND);
191 * if the periodic timer's update is due to period re-configuration,
192 * we should count the clock since last interrupt.
194 if (old_period && period_change) {
195 int64_t last_periodic_clock, next_periodic_clock;
197 next_periodic_clock = muldiv64(s->next_periodic_time,
198 RTC_CLOCK_RATE, NANOSECONDS_PER_SECOND);
199 last_periodic_clock = next_periodic_clock - old_period;
200 lost_clock = cur_clock - last_periodic_clock;
201 assert(lost_clock >= 0);
205 * s->irq_coalesced can change for two reasons:
207 * a) if one or more periodic timer interrupts have been lost,
208 * lost_clock will be more that a period.
210 * b) when the period may be reconfigured, we expect the OS to
211 * treat delayed tick as the new period. So, when switching
212 * from a shorter to a longer period, scale down the missing,
213 * because the OS will treat past delayed ticks as longer
214 * (leftovers are put back into lost_clock). When switching
215 * to a shorter period, scale up the missing ticks since the
216 * OS handler will treat past delayed ticks as shorter.
218 if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
219 uint32_t old_irq_coalesced = s->irq_coalesced;
221 lost_clock += old_irq_coalesced * old_period;
222 s->irq_coalesced = lost_clock / s->period;
223 lost_clock %= s->period;
224 if (old_irq_coalesced != s->irq_coalesced ||
225 old_period != s->period) {
226 DPRINTF_C("cmos: coalesced irqs scaled from %d to %d, "
227 "period scaled from %d to %d\n", old_irq_coalesced,
228 s->irq_coalesced, old_period, s->period);
229 rtc_coalesced_timer_update(s);
231 } else {
233 * no way to compensate the interrupt if LOST_TICK_POLICY_SLEW
234 * is not used, we should make the time progress anyway.
236 lost_clock = MIN(lost_clock, period);
239 assert(lost_clock >= 0 && lost_clock <= period);
241 next_irq_clock = cur_clock + period - lost_clock;
242 s->next_periodic_time = periodic_clock_to_ns(next_irq_clock) + 1;
243 timer_mod(s->periodic_timer, s->next_periodic_time);
246 static void rtc_periodic_timer(void *opaque)
248 RTCState *s = opaque;
250 periodic_timer_update(s, s->next_periodic_time, s->period, false);
251 s->cmos_data[RTC_REG_C] |= REG_C_PF;
252 if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {
253 s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
254 if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
255 if (s->irq_reinject_on_ack_count >= RTC_REINJECT_ON_ACK_COUNT)
256 s->irq_reinject_on_ack_count = 0;
257 if (!rtc_policy_slew_deliver_irq(s)) {
258 s->irq_coalesced++;
259 rtc_coalesced_timer_update(s);
260 DPRINTF_C("cmos: coalesced irqs increased to %d\n",
261 s->irq_coalesced);
263 } else
264 qemu_irq_raise(s->irq);
268 /* handle update-ended timer */
269 static void check_update_timer(RTCState *s)
271 uint64_t next_update_time;
272 uint64_t guest_nsec;
273 int next_alarm_sec;
275 /* From the data sheet: "Holding the dividers in reset prevents
276 * interrupts from operating, while setting the SET bit allows"
277 * them to occur.
279 if ((s->cmos_data[RTC_REG_A] & 0x60) == 0x60) {
280 assert((s->cmos_data[RTC_REG_A] & REG_A_UIP) == 0);
281 timer_del(s->update_timer);
282 return;
285 guest_nsec = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
286 next_update_time = qemu_clock_get_ns(rtc_clock)
287 + NANOSECONDS_PER_SECOND - guest_nsec;
289 /* Compute time of next alarm. One second is already accounted
290 * for in next_update_time.
292 next_alarm_sec = get_next_alarm(s);
293 s->next_alarm_time = next_update_time +
294 (next_alarm_sec - 1) * NANOSECONDS_PER_SECOND;
296 /* If update_in_progress latched the UIP bit, we must keep the timer
297 * programmed to the next second, so that UIP is cleared. Otherwise,
298 * if UF is already set, we might be able to optimize.
300 if (!(s->cmos_data[RTC_REG_A] & REG_A_UIP) &&
301 (s->cmos_data[RTC_REG_C] & REG_C_UF)) {
302 /* If AF cannot change (i.e. either it is set already, or
303 * SET=1 and then the time is not updated), nothing to do.
305 if ((s->cmos_data[RTC_REG_B] & REG_B_SET) ||
306 (s->cmos_data[RTC_REG_C] & REG_C_AF)) {
307 timer_del(s->update_timer);
308 return;
311 /* UF is set, but AF is clear. Program the timer to target
312 * the alarm time. */
313 next_update_time = s->next_alarm_time;
315 if (next_update_time != timer_expire_time_ns(s->update_timer)) {
316 timer_mod(s->update_timer, next_update_time);
320 static inline uint8_t convert_hour(RTCState *s, uint8_t hour)
322 if (!(s->cmos_data[RTC_REG_B] & REG_B_24H)) {
323 hour %= 12;
324 if (s->cmos_data[RTC_HOURS] & 0x80) {
325 hour += 12;
328 return hour;
331 static uint64_t get_next_alarm(RTCState *s)
333 int32_t alarm_sec, alarm_min, alarm_hour, cur_hour, cur_min, cur_sec;
334 int32_t hour, min, sec;
336 rtc_update_time(s);
338 alarm_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS_ALARM]);
339 alarm_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES_ALARM]);
340 alarm_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS_ALARM]);
341 alarm_hour = alarm_hour == -1 ? -1 : convert_hour(s, alarm_hour);
343 cur_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS]);
344 cur_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES]);
345 cur_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS]);
346 cur_hour = convert_hour(s, cur_hour);
348 if (alarm_hour == -1) {
349 alarm_hour = cur_hour;
350 if (alarm_min == -1) {
351 alarm_min = cur_min;
352 if (alarm_sec == -1) {
353 alarm_sec = cur_sec + 1;
354 } else if (cur_sec > alarm_sec) {
355 alarm_min++;
357 } else if (cur_min == alarm_min) {
358 if (alarm_sec == -1) {
359 alarm_sec = cur_sec + 1;
360 } else {
361 if (cur_sec > alarm_sec) {
362 alarm_hour++;
365 if (alarm_sec == SEC_PER_MIN) {
366 /* wrap to next hour, minutes is not in don't care mode */
367 alarm_sec = 0;
368 alarm_hour++;
370 } else if (cur_min > alarm_min) {
371 alarm_hour++;
373 } else if (cur_hour == alarm_hour) {
374 if (alarm_min == -1) {
375 alarm_min = cur_min;
376 if (alarm_sec == -1) {
377 alarm_sec = cur_sec + 1;
378 } else if (cur_sec > alarm_sec) {
379 alarm_min++;
382 if (alarm_sec == SEC_PER_MIN) {
383 alarm_sec = 0;
384 alarm_min++;
386 /* wrap to next day, hour is not in don't care mode */
387 alarm_min %= MIN_PER_HOUR;
388 } else if (cur_min == alarm_min) {
389 if (alarm_sec == -1) {
390 alarm_sec = cur_sec + 1;
392 /* wrap to next day, hours+minutes not in don't care mode */
393 alarm_sec %= SEC_PER_MIN;
397 /* values that are still don't care fire at the next min/sec */
398 if (alarm_min == -1) {
399 alarm_min = 0;
401 if (alarm_sec == -1) {
402 alarm_sec = 0;
405 /* keep values in range */
406 if (alarm_sec == SEC_PER_MIN) {
407 alarm_sec = 0;
408 alarm_min++;
410 if (alarm_min == MIN_PER_HOUR) {
411 alarm_min = 0;
412 alarm_hour++;
414 alarm_hour %= HOUR_PER_DAY;
416 hour = alarm_hour - cur_hour;
417 min = hour * MIN_PER_HOUR + alarm_min - cur_min;
418 sec = min * SEC_PER_MIN + alarm_sec - cur_sec;
419 return sec <= 0 ? sec + SEC_PER_DAY : sec;
422 static void rtc_update_timer(void *opaque)
424 RTCState *s = opaque;
425 int32_t irqs = REG_C_UF;
426 int32_t new_irqs;
428 assert((s->cmos_data[RTC_REG_A] & 0x60) != 0x60);
430 /* UIP might have been latched, update time and clear it. */
431 rtc_update_time(s);
432 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
434 if (qemu_clock_get_ns(rtc_clock) >= s->next_alarm_time) {
435 irqs |= REG_C_AF;
436 if (s->cmos_data[RTC_REG_B] & REG_B_AIE) {
437 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_RTC, NULL);
441 new_irqs = irqs & ~s->cmos_data[RTC_REG_C];
442 s->cmos_data[RTC_REG_C] |= irqs;
443 if ((new_irqs & s->cmos_data[RTC_REG_B]) != 0) {
444 s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
445 qemu_irq_raise(s->irq);
447 check_update_timer(s);
450 static void cmos_ioport_write(void *opaque, hwaddr addr,
451 uint64_t data, unsigned size)
453 RTCState *s = opaque;
454 uint32_t old_period;
455 bool update_periodic_timer;
457 if ((addr & 1) == 0) {
458 s->cmos_index = data & 0x7f;
459 } else {
460 CMOS_DPRINTF("cmos: write index=0x%02x val=0x%02" PRIx64 "\n",
461 s->cmos_index, data);
462 switch(s->cmos_index) {
463 case RTC_SECONDS_ALARM:
464 case RTC_MINUTES_ALARM:
465 case RTC_HOURS_ALARM:
466 s->cmos_data[s->cmos_index] = data;
467 check_update_timer(s);
468 break;
469 case RTC_IBM_PS2_CENTURY_BYTE:
470 s->cmos_index = RTC_CENTURY;
471 /* fall through */
472 case RTC_CENTURY:
473 case RTC_SECONDS:
474 case RTC_MINUTES:
475 case RTC_HOURS:
476 case RTC_DAY_OF_WEEK:
477 case RTC_DAY_OF_MONTH:
478 case RTC_MONTH:
479 case RTC_YEAR:
480 s->cmos_data[s->cmos_index] = data;
481 /* if in set mode, do not update the time */
482 if (rtc_running(s)) {
483 rtc_set_time(s);
484 check_update_timer(s);
486 break;
487 case RTC_REG_A:
488 update_periodic_timer = (s->cmos_data[RTC_REG_A] ^ data) & 0x0f;
489 old_period = rtc_periodic_clock_ticks(s);
491 if ((data & 0x60) == 0x60) {
492 if (rtc_running(s)) {
493 rtc_update_time(s);
495 /* What happens to UIP when divider reset is enabled is
496 * unclear from the datasheet. Shouldn't matter much
497 * though.
499 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
500 } else if (((s->cmos_data[RTC_REG_A] & 0x60) == 0x60) &&
501 (data & 0x70) <= 0x20) {
502 /* when the divider reset is removed, the first update cycle
503 * begins one-half second later*/
504 if (!(s->cmos_data[RTC_REG_B] & REG_B_SET)) {
505 s->offset = 500000000;
506 rtc_set_time(s);
508 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
510 /* UIP bit is read only */
511 s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |
512 (s->cmos_data[RTC_REG_A] & REG_A_UIP);
514 if (update_periodic_timer) {
515 periodic_timer_update(s, qemu_clock_get_ns(rtc_clock),
516 old_period, true);
519 check_update_timer(s);
520 break;
521 case RTC_REG_B:
522 update_periodic_timer = (s->cmos_data[RTC_REG_B] ^ data)
523 & REG_B_PIE;
524 old_period = rtc_periodic_clock_ticks(s);
526 if (data & REG_B_SET) {
527 /* update cmos to when the rtc was stopping */
528 if (rtc_running(s)) {
529 rtc_update_time(s);
531 /* set mode: reset UIP mode */
532 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
533 data &= ~REG_B_UIE;
534 } else {
535 /* if disabling set mode, update the time */
536 if ((s->cmos_data[RTC_REG_B] & REG_B_SET) &&
537 (s->cmos_data[RTC_REG_A] & 0x70) <= 0x20) {
538 s->offset = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
539 rtc_set_time(s);
542 /* if an interrupt flag is already set when the interrupt
543 * becomes enabled, raise an interrupt immediately. */
544 if (data & s->cmos_data[RTC_REG_C] & REG_C_MASK) {
545 s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
546 qemu_irq_raise(s->irq);
547 } else {
548 s->cmos_data[RTC_REG_C] &= ~REG_C_IRQF;
549 qemu_irq_lower(s->irq);
551 s->cmos_data[RTC_REG_B] = data;
553 if (update_periodic_timer) {
554 periodic_timer_update(s, qemu_clock_get_ns(rtc_clock),
555 old_period, true);
558 check_update_timer(s);
559 break;
560 case RTC_REG_C:
561 case RTC_REG_D:
562 /* cannot write to them */
563 break;
564 default:
565 s->cmos_data[s->cmos_index] = data;
566 break;
571 static inline int rtc_to_bcd(RTCState *s, int a)
573 if (s->cmos_data[RTC_REG_B] & REG_B_DM) {
574 return a;
575 } else {
576 return ((a / 10) << 4) | (a % 10);
580 static inline int rtc_from_bcd(RTCState *s, int a)
582 if ((a & 0xc0) == 0xc0) {
583 return -1;
585 if (s->cmos_data[RTC_REG_B] & REG_B_DM) {
586 return a;
587 } else {
588 return ((a >> 4) * 10) + (a & 0x0f);
592 static void rtc_get_time(RTCState *s, struct tm *tm)
594 tm->tm_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS]);
595 tm->tm_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES]);
596 tm->tm_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS] & 0x7f);
597 if (!(s->cmos_data[RTC_REG_B] & REG_B_24H)) {
598 tm->tm_hour %= 12;
599 if (s->cmos_data[RTC_HOURS] & 0x80) {
600 tm->tm_hour += 12;
603 tm->tm_wday = rtc_from_bcd(s, s->cmos_data[RTC_DAY_OF_WEEK]) - 1;
604 tm->tm_mday = rtc_from_bcd(s, s->cmos_data[RTC_DAY_OF_MONTH]);
605 tm->tm_mon = rtc_from_bcd(s, s->cmos_data[RTC_MONTH]) - 1;
606 tm->tm_year =
607 rtc_from_bcd(s, s->cmos_data[RTC_YEAR]) + s->base_year +
608 rtc_from_bcd(s, s->cmos_data[RTC_CENTURY]) * 100 - 1900;
611 static void rtc_set_time(RTCState *s)
613 struct tm tm;
615 rtc_get_time(s, &tm);
616 s->base_rtc = mktimegm(&tm);
617 s->last_update = qemu_clock_get_ns(rtc_clock);
619 qapi_event_send_rtc_change(qemu_timedate_diff(&tm));
622 static void rtc_set_cmos(RTCState *s, const struct tm *tm)
624 int year;
626 s->cmos_data[RTC_SECONDS] = rtc_to_bcd(s, tm->tm_sec);
627 s->cmos_data[RTC_MINUTES] = rtc_to_bcd(s, tm->tm_min);
628 if (s->cmos_data[RTC_REG_B] & REG_B_24H) {
629 /* 24 hour format */
630 s->cmos_data[RTC_HOURS] = rtc_to_bcd(s, tm->tm_hour);
631 } else {
632 /* 12 hour format */
633 int h = (tm->tm_hour % 12) ? tm->tm_hour % 12 : 12;
634 s->cmos_data[RTC_HOURS] = rtc_to_bcd(s, h);
635 if (tm->tm_hour >= 12)
636 s->cmos_data[RTC_HOURS] |= 0x80;
638 s->cmos_data[RTC_DAY_OF_WEEK] = rtc_to_bcd(s, tm->tm_wday + 1);
639 s->cmos_data[RTC_DAY_OF_MONTH] = rtc_to_bcd(s, tm->tm_mday);
640 s->cmos_data[RTC_MONTH] = rtc_to_bcd(s, tm->tm_mon + 1);
641 year = tm->tm_year + 1900 - s->base_year;
642 s->cmos_data[RTC_YEAR] = rtc_to_bcd(s, year % 100);
643 s->cmos_data[RTC_CENTURY] = rtc_to_bcd(s, year / 100);
646 static void rtc_update_time(RTCState *s)
648 struct tm ret;
649 time_t guest_sec;
650 int64_t guest_nsec;
652 guest_nsec = get_guest_rtc_ns(s);
653 guest_sec = guest_nsec / NANOSECONDS_PER_SECOND;
654 gmtime_r(&guest_sec, &ret);
656 /* Is SET flag of Register B disabled? */
657 if ((s->cmos_data[RTC_REG_B] & REG_B_SET) == 0) {
658 rtc_set_cmos(s, &ret);
662 static int update_in_progress(RTCState *s)
664 int64_t guest_nsec;
666 if (!rtc_running(s)) {
667 return 0;
669 if (timer_pending(s->update_timer)) {
670 int64_t next_update_time = timer_expire_time_ns(s->update_timer);
671 /* Latch UIP until the timer expires. */
672 if (qemu_clock_get_ns(rtc_clock) >=
673 (next_update_time - UIP_HOLD_LENGTH)) {
674 s->cmos_data[RTC_REG_A] |= REG_A_UIP;
675 return 1;
679 guest_nsec = get_guest_rtc_ns(s);
680 /* UIP bit will be set at last 244us of every second. */
681 if ((guest_nsec % NANOSECONDS_PER_SECOND) >=
682 (NANOSECONDS_PER_SECOND - UIP_HOLD_LENGTH)) {
683 return 1;
685 return 0;
688 static uint64_t cmos_ioport_read(void *opaque, hwaddr addr,
689 unsigned size)
691 RTCState *s = opaque;
692 int ret;
693 if ((addr & 1) == 0) {
694 return 0xff;
695 } else {
696 switch(s->cmos_index) {
697 case RTC_IBM_PS2_CENTURY_BYTE:
698 s->cmos_index = RTC_CENTURY;
699 /* fall through */
700 case RTC_CENTURY:
701 case RTC_SECONDS:
702 case RTC_MINUTES:
703 case RTC_HOURS:
704 case RTC_DAY_OF_WEEK:
705 case RTC_DAY_OF_MONTH:
706 case RTC_MONTH:
707 case RTC_YEAR:
708 /* if not in set mode, calibrate cmos before
709 * reading*/
710 if (rtc_running(s)) {
711 rtc_update_time(s);
713 ret = s->cmos_data[s->cmos_index];
714 break;
715 case RTC_REG_A:
716 ret = s->cmos_data[s->cmos_index];
717 if (update_in_progress(s)) {
718 ret |= REG_A_UIP;
720 break;
721 case RTC_REG_C:
722 ret = s->cmos_data[s->cmos_index];
723 qemu_irq_lower(s->irq);
724 s->cmos_data[RTC_REG_C] = 0x00;
725 if (ret & (REG_C_UF | REG_C_AF)) {
726 check_update_timer(s);
729 if(s->irq_coalesced &&
730 (s->cmos_data[RTC_REG_B] & REG_B_PIE) &&
731 s->irq_reinject_on_ack_count < RTC_REINJECT_ON_ACK_COUNT) {
732 s->irq_reinject_on_ack_count++;
733 s->cmos_data[RTC_REG_C] |= REG_C_IRQF | REG_C_PF;
734 DPRINTF_C("cmos: injecting on ack\n");
735 if (rtc_policy_slew_deliver_irq(s)) {
736 s->irq_coalesced--;
737 DPRINTF_C("cmos: coalesced irqs decreased to %d\n",
738 s->irq_coalesced);
741 break;
742 default:
743 ret = s->cmos_data[s->cmos_index];
744 break;
746 CMOS_DPRINTF("cmos: read index=0x%02x val=0x%02x\n",
747 s->cmos_index, ret);
748 return ret;
752 void rtc_set_memory(ISADevice *dev, int addr, int val)
754 RTCState *s = MC146818_RTC(dev);
755 if (addr >= 0 && addr <= 127)
756 s->cmos_data[addr] = val;
759 int rtc_get_memory(ISADevice *dev, int addr)
761 RTCState *s = MC146818_RTC(dev);
762 assert(addr >= 0 && addr <= 127);
763 return s->cmos_data[addr];
766 static void rtc_set_date_from_host(ISADevice *dev)
768 RTCState *s = MC146818_RTC(dev);
769 struct tm tm;
771 qemu_get_timedate(&tm, 0);
773 s->base_rtc = mktimegm(&tm);
774 s->last_update = qemu_clock_get_ns(rtc_clock);
775 s->offset = 0;
777 /* set the CMOS date */
778 rtc_set_cmos(s, &tm);
781 static int rtc_pre_save(void *opaque)
783 RTCState *s = opaque;
785 rtc_update_time(s);
787 return 0;
790 static int rtc_post_load(void *opaque, int version_id)
792 RTCState *s = opaque;
794 if (version_id <= 2 || rtc_clock == QEMU_CLOCK_REALTIME) {
795 rtc_set_time(s);
796 s->offset = 0;
797 check_update_timer(s);
799 s->period = rtc_periodic_clock_ticks(s);
801 /* The periodic timer is deterministic in record/replay mode,
802 * so there is no need to update it after loading the vmstate.
803 * Reading RTC here would misalign record and replay.
805 if (replay_mode == REPLAY_MODE_NONE) {
806 uint64_t now = qemu_clock_get_ns(rtc_clock);
807 if (now < s->next_periodic_time ||
808 now > (s->next_periodic_time + get_max_clock_jump())) {
809 periodic_timer_update(s, qemu_clock_get_ns(rtc_clock), s->period, false);
813 if (version_id >= 2) {
814 if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
815 rtc_coalesced_timer_update(s);
818 return 0;
821 static bool rtc_irq_reinject_on_ack_count_needed(void *opaque)
823 RTCState *s = (RTCState *)opaque;
824 return s->irq_reinject_on_ack_count != 0;
827 static const VMStateDescription vmstate_rtc_irq_reinject_on_ack_count = {
828 .name = "mc146818rtc/irq_reinject_on_ack_count",
829 .version_id = 1,
830 .minimum_version_id = 1,
831 .needed = rtc_irq_reinject_on_ack_count_needed,
832 .fields = (VMStateField[]) {
833 VMSTATE_UINT16(irq_reinject_on_ack_count, RTCState),
834 VMSTATE_END_OF_LIST()
838 static const VMStateDescription vmstate_rtc = {
839 .name = "mc146818rtc",
840 .version_id = 3,
841 .minimum_version_id = 1,
842 .pre_save = rtc_pre_save,
843 .post_load = rtc_post_load,
844 .fields = (VMStateField[]) {
845 VMSTATE_BUFFER(cmos_data, RTCState),
846 VMSTATE_UINT8(cmos_index, RTCState),
847 VMSTATE_UNUSED(7*4),
848 VMSTATE_TIMER_PTR(periodic_timer, RTCState),
849 VMSTATE_INT64(next_periodic_time, RTCState),
850 VMSTATE_UNUSED(3*8),
851 VMSTATE_UINT32_V(irq_coalesced, RTCState, 2),
852 VMSTATE_UINT32_V(period, RTCState, 2),
853 VMSTATE_UINT64_V(base_rtc, RTCState, 3),
854 VMSTATE_UINT64_V(last_update, RTCState, 3),
855 VMSTATE_INT64_V(offset, RTCState, 3),
856 VMSTATE_TIMER_PTR_V(update_timer, RTCState, 3),
857 VMSTATE_UINT64_V(next_alarm_time, RTCState, 3),
858 VMSTATE_END_OF_LIST()
860 .subsections = (const VMStateDescription*[]) {
861 &vmstate_rtc_irq_reinject_on_ack_count,
862 NULL
866 /* set CMOS shutdown status register (index 0xF) as S3_resume(0xFE)
867 BIOS will read it and start S3 resume at POST Entry */
868 static void rtc_notify_suspend(Notifier *notifier, void *data)
870 RTCState *s = container_of(notifier, RTCState, suspend_notifier);
871 rtc_set_memory(ISA_DEVICE(s), 0xF, 0xFE);
874 static const MemoryRegionOps cmos_ops = {
875 .read = cmos_ioport_read,
876 .write = cmos_ioport_write,
877 .impl = {
878 .min_access_size = 1,
879 .max_access_size = 1,
881 .endianness = DEVICE_LITTLE_ENDIAN,
884 static void rtc_get_date(Object *obj, struct tm *current_tm, Error **errp)
886 RTCState *s = MC146818_RTC(obj);
888 rtc_update_time(s);
889 rtc_get_time(s, current_tm);
892 static void rtc_realizefn(DeviceState *dev, Error **errp)
894 ISADevice *isadev = ISA_DEVICE(dev);
895 RTCState *s = MC146818_RTC(dev);
897 s->cmos_data[RTC_REG_A] = 0x26;
898 s->cmos_data[RTC_REG_B] = 0x02;
899 s->cmos_data[RTC_REG_C] = 0x00;
900 s->cmos_data[RTC_REG_D] = 0x80;
902 /* This is for historical reasons. The default base year qdev property
903 * was set to 2000 for most machine types before the century byte was
904 * implemented.
906 * This if statement means that the century byte will be always 0
907 * (at least until 2079...) for base_year = 1980, but will be set
908 * correctly for base_year = 2000.
910 if (s->base_year == 2000) {
911 s->base_year = 0;
914 rtc_set_date_from_host(isadev);
916 switch (s->lost_tick_policy) {
917 #ifdef TARGET_I386
918 case LOST_TICK_POLICY_SLEW:
919 s->coalesced_timer =
920 timer_new_ns(rtc_clock, rtc_coalesced_timer, s);
921 break;
922 #endif
923 case LOST_TICK_POLICY_DISCARD:
924 break;
925 default:
926 error_setg(errp, "Invalid lost tick policy.");
927 return;
930 s->periodic_timer = timer_new_ns(rtc_clock, rtc_periodic_timer, s);
931 s->update_timer = timer_new_ns(rtc_clock, rtc_update_timer, s);
932 check_update_timer(s);
934 s->suspend_notifier.notify = rtc_notify_suspend;
935 qemu_register_suspend_notifier(&s->suspend_notifier);
937 memory_region_init_io(&s->io, OBJECT(s), &cmos_ops, s, "rtc", 2);
938 isa_register_ioport(isadev, &s->io, RTC_ISA_BASE);
940 /* register rtc 0x70 port for coalesced_pio */
941 memory_region_set_flush_coalesced(&s->io);
942 memory_region_init_io(&s->coalesced_io, OBJECT(s), &cmos_ops,
943 s, "rtc-index", 1);
944 memory_region_add_subregion(&s->io, 0, &s->coalesced_io);
945 memory_region_add_coalescing(&s->coalesced_io, 0, 1);
947 qdev_set_legacy_instance_id(dev, RTC_ISA_BASE, 3);
949 object_property_add_tm(OBJECT(s), "date", rtc_get_date);
951 qdev_init_gpio_out(dev, &s->irq, 1);
952 QLIST_INSERT_HEAD(&rtc_devices, s, link);
955 ISADevice *mc146818_rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq)
957 DeviceState *dev;
958 ISADevice *isadev;
960 isadev = isa_new(TYPE_MC146818_RTC);
961 dev = DEVICE(isadev);
962 qdev_prop_set_int32(dev, "base_year", base_year);
963 isa_realize_and_unref(isadev, bus, &error_fatal);
964 if (intercept_irq) {
965 qdev_connect_gpio_out(dev, 0, intercept_irq);
966 } else {
967 isa_connect_gpio_out(isadev, 0, RTC_ISA_IRQ);
970 object_property_add_alias(qdev_get_machine(), "rtc-time", OBJECT(isadev),
971 "date");
973 return isadev;
976 static Property mc146818rtc_properties[] = {
977 DEFINE_PROP_INT32("base_year", RTCState, base_year, 1980),
978 DEFINE_PROP_LOSTTICKPOLICY("lost_tick_policy", RTCState,
979 lost_tick_policy, LOST_TICK_POLICY_DISCARD),
980 DEFINE_PROP_END_OF_LIST(),
983 static void rtc_reset_enter(Object *obj, ResetType type)
985 RTCState *s = MC146818_RTC(obj);
987 /* Reason: VM do suspend self will set 0xfe
988 * Reset any values other than 0xfe(Guest suspend case) */
989 if (s->cmos_data[0x0f] != 0xfe) {
990 s->cmos_data[0x0f] = 0x00;
993 s->cmos_data[RTC_REG_B] &= ~(REG_B_PIE | REG_B_AIE | REG_B_SQWE);
994 s->cmos_data[RTC_REG_C] &= ~(REG_C_UF | REG_C_IRQF | REG_C_PF | REG_C_AF);
995 check_update_timer(s);
998 if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
999 s->irq_coalesced = 0;
1000 s->irq_reinject_on_ack_count = 0;
1004 static void rtc_reset_hold(Object *obj)
1006 RTCState *s = MC146818_RTC(obj);
1008 qemu_irq_lower(s->irq);
1011 static void rtc_build_aml(ISADevice *isadev, Aml *scope)
1013 Aml *dev;
1014 Aml *crs;
1017 * Reserving 8 io ports here, following what physical hardware
1018 * does, even though qemu only responds to the first two ports.
1020 crs = aml_resource_template();
1021 aml_append(crs, aml_io(AML_DECODE16, RTC_ISA_BASE, RTC_ISA_BASE,
1022 0x01, 0x08));
1023 aml_append(crs, aml_irq_no_flags(RTC_ISA_IRQ));
1025 dev = aml_device("RTC");
1026 aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0B00")));
1027 aml_append(dev, aml_name_decl("_CRS", crs));
1029 aml_append(scope, dev);
1032 static void rtc_class_initfn(ObjectClass *klass, void *data)
1034 DeviceClass *dc = DEVICE_CLASS(klass);
1035 ResettableClass *rc = RESETTABLE_CLASS(klass);
1036 ISADeviceClass *isa = ISA_DEVICE_CLASS(klass);
1038 dc->realize = rtc_realizefn;
1039 dc->vmsd = &vmstate_rtc;
1040 rc->phases.enter = rtc_reset_enter;
1041 rc->phases.hold = rtc_reset_hold;
1042 isa->build_aml = rtc_build_aml;
1043 device_class_set_props(dc, mc146818rtc_properties);
1044 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1047 static const TypeInfo mc146818rtc_info = {
1048 .name = TYPE_MC146818_RTC,
1049 .parent = TYPE_ISA_DEVICE,
1050 .instance_size = sizeof(RTCState),
1051 .class_init = rtc_class_initfn,
1054 static void mc146818rtc_register_types(void)
1056 type_register_static(&mc146818rtc_info);
1059 type_init(mc146818rtc_register_types)