xref: /qemu/hw/rtc/mc146818rtc.c (revision a976ed3f)
1 /*
2  * QEMU MC146818 RTC emulation
3  *
4  * Copyright (c) 2003-2004 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
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/irq.h"
31 #include "hw/qdev-properties.h"
32 #include "qemu/timer.h"
33 #include "sysemu/sysemu.h"
34 #include "sysemu/replay.h"
35 #include "sysemu/reset.h"
36 #include "sysemu/runstate.h"
37 #include "hw/rtc/mc146818rtc.h"
38 #include "hw/rtc/mc146818rtc_regs.h"
39 #include "migration/vmstate.h"
40 #include "qapi/error.h"
41 #include "qapi/qapi-events-misc-target.h"
42 #include "qapi/visitor.h"
43 #include "exec/address-spaces.h"
44 #include "hw/rtc/mc146818rtc_regs.h"
45 
46 #ifdef TARGET_I386
47 #include "qapi/qapi-commands-misc-target.h"
48 #include "hw/i386/apic.h"
49 #endif
50 
51 //#define DEBUG_CMOS
52 //#define DEBUG_COALESCED
53 
54 #ifdef DEBUG_CMOS
55 # define CMOS_DPRINTF(format, ...)      printf(format, ## __VA_ARGS__)
56 #else
57 # define CMOS_DPRINTF(format, ...)      do { } while (0)
58 #endif
59 
60 #ifdef DEBUG_COALESCED
61 # define DPRINTF_C(format, ...)      printf(format, ## __VA_ARGS__)
62 #else
63 # define DPRINTF_C(format, ...)      do { } while (0)
64 #endif
65 
66 #define SEC_PER_MIN     60
67 #define MIN_PER_HOUR    60
68 #define SEC_PER_HOUR    3600
69 #define HOUR_PER_DAY    24
70 #define SEC_PER_DAY     86400
71 
72 #define RTC_REINJECT_ON_ACK_COUNT 20
73 #define RTC_CLOCK_RATE            32768
74 #define UIP_HOLD_LENGTH           (8 * NANOSECONDS_PER_SECOND / 32768)
75 
76 static void rtc_set_time(RTCState *s);
77 static void rtc_update_time(RTCState *s);
78 static void rtc_set_cmos(RTCState *s, const struct tm *tm);
79 static inline int rtc_from_bcd(RTCState *s, int a);
80 static uint64_t get_next_alarm(RTCState *s);
81 
82 static inline bool rtc_running(RTCState *s)
83 {
84     return (!(s->cmos_data[RTC_REG_B] & REG_B_SET) &&
85             (s->cmos_data[RTC_REG_A] & 0x70) <= 0x20);
86 }
87 
88 static uint64_t get_guest_rtc_ns(RTCState *s)
89 {
90     uint64_t guest_clock = qemu_clock_get_ns(rtc_clock);
91 
92     return s->base_rtc * NANOSECONDS_PER_SECOND +
93         guest_clock - s->last_update + s->offset;
94 }
95 
96 static void rtc_coalesced_timer_update(RTCState *s)
97 {
98     if (s->irq_coalesced == 0) {
99         timer_del(s->coalesced_timer);
100     } else {
101         /* divide each RTC interval to 2 - 8 smaller intervals */
102         int c = MIN(s->irq_coalesced, 7) + 1;
103         int64_t next_clock = qemu_clock_get_ns(rtc_clock) +
104             periodic_clock_to_ns(s->period / c);
105         timer_mod(s->coalesced_timer, next_clock);
106     }
107 }
108 
109 static QLIST_HEAD(, RTCState) rtc_devices =
110     QLIST_HEAD_INITIALIZER(rtc_devices);
111 
112 #ifdef TARGET_I386
113 void qmp_rtc_reset_reinjection(Error **errp)
114 {
115     RTCState *s;
116 
117     QLIST_FOREACH(s, &rtc_devices, link) {
118         s->irq_coalesced = 0;
119     }
120 }
121 
122 static bool rtc_policy_slew_deliver_irq(RTCState *s)
123 {
124     apic_reset_irq_delivered();
125     qemu_irq_raise(s->irq);
126     return apic_get_irq_delivered();
127 }
128 
129 static void rtc_coalesced_timer(void *opaque)
130 {
131     RTCState *s = opaque;
132 
133     if (s->irq_coalesced != 0) {
134         s->cmos_data[RTC_REG_C] |= 0xc0;
135         DPRINTF_C("cmos: injecting from timer\n");
136         if (rtc_policy_slew_deliver_irq(s)) {
137             s->irq_coalesced--;
138             DPRINTF_C("cmos: coalesced irqs decreased to %d\n",
139                       s->irq_coalesced);
140         }
141     }
142 
143     rtc_coalesced_timer_update(s);
144 }
145 #else
146 static bool rtc_policy_slew_deliver_irq(RTCState *s)
147 {
148     assert(0);
149     return false;
150 }
151 #endif
152 
153 static uint32_t rtc_periodic_clock_ticks(RTCState *s)
154 {
155     int period_code;
156 
157     if (!(s->cmos_data[RTC_REG_B] & REG_B_PIE)) {
158         return 0;
159      }
160 
161     period_code = s->cmos_data[RTC_REG_A] & 0x0f;
162 
163     return periodic_period_to_clock(period_code);
164 }
165 
166 /*
167  * handle periodic timer. @old_period indicates the periodic timer update
168  * is just due to period adjustment.
169  */
170 static void
171 periodic_timer_update(RTCState *s, int64_t current_time, uint32_t old_period, bool period_change)
172 {
173     uint32_t period;
174     int64_t cur_clock, next_irq_clock, lost_clock = 0;
175 
176     period = rtc_periodic_clock_ticks(s);
177     s->period = period;
178 
179     if (!period) {
180         s->irq_coalesced = 0;
181         timer_del(s->periodic_timer);
182         return;
183     }
184 
185     /* compute 32 khz clock */
186     cur_clock =
187         muldiv64(current_time, RTC_CLOCK_RATE, NANOSECONDS_PER_SECOND);
188 
189     /*
190      * if the periodic timer's update is due to period re-configuration,
191      * we should count the clock since last interrupt.
192      */
193     if (old_period && period_change) {
194         int64_t last_periodic_clock, next_periodic_clock;
195 
196         next_periodic_clock = muldiv64(s->next_periodic_time,
197                                 RTC_CLOCK_RATE, NANOSECONDS_PER_SECOND);
198         last_periodic_clock = next_periodic_clock - old_period;
199         lost_clock = cur_clock - last_periodic_clock;
200         assert(lost_clock >= 0);
201     }
202 
203     /*
204      * s->irq_coalesced can change for two reasons:
205      *
206      * a) if one or more periodic timer interrupts have been lost,
207      *    lost_clock will be more that a period.
208      *
209      * b) when the period may be reconfigured, we expect the OS to
210      *    treat delayed tick as the new period.  So, when switching
211      *    from a shorter to a longer period, scale down the missing,
212      *    because the OS will treat past delayed ticks as longer
213      *    (leftovers are put back into lost_clock).  When switching
214      *    to a shorter period, scale up the missing ticks since the
215      *    OS handler will treat past delayed ticks as shorter.
216      */
217     if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
218         uint32_t old_irq_coalesced = s->irq_coalesced;
219 
220         lost_clock += old_irq_coalesced * old_period;
221         s->irq_coalesced = lost_clock / s->period;
222         lost_clock %= s->period;
223         if (old_irq_coalesced != s->irq_coalesced ||
224             old_period != s->period) {
225             DPRINTF_C("cmos: coalesced irqs scaled from %d to %d, "
226                       "period scaled from %d to %d\n", old_irq_coalesced,
227                       s->irq_coalesced, old_period, s->period);
228             rtc_coalesced_timer_update(s);
229         }
230     } else {
231         /*
232          * no way to compensate the interrupt if LOST_TICK_POLICY_SLEW
233          * is not used, we should make the time progress anyway.
234          */
235         lost_clock = MIN(lost_clock, period);
236     }
237 
238     assert(lost_clock >= 0 && lost_clock <= period);
239 
240     next_irq_clock = cur_clock + period - lost_clock;
241     s->next_periodic_time = periodic_clock_to_ns(next_irq_clock) + 1;
242     timer_mod(s->periodic_timer, s->next_periodic_time);
243 }
244 
245 static void rtc_periodic_timer(void *opaque)
246 {
247     RTCState *s = opaque;
248 
249     periodic_timer_update(s, s->next_periodic_time, s->period, false);
250     s->cmos_data[RTC_REG_C] |= REG_C_PF;
251     if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {
252         s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
253         if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
254             if (s->irq_reinject_on_ack_count >= RTC_REINJECT_ON_ACK_COUNT)
255                 s->irq_reinject_on_ack_count = 0;
256             if (!rtc_policy_slew_deliver_irq(s)) {
257                 s->irq_coalesced++;
258                 rtc_coalesced_timer_update(s);
259                 DPRINTF_C("cmos: coalesced irqs increased to %d\n",
260                           s->irq_coalesced);
261             }
262         } else
263             qemu_irq_raise(s->irq);
264     }
265 }
266 
267 /* handle update-ended timer */
268 static void check_update_timer(RTCState *s)
269 {
270     uint64_t next_update_time;
271     uint64_t guest_nsec;
272     int next_alarm_sec;
273 
274     /* From the data sheet: "Holding the dividers in reset prevents
275      * interrupts from operating, while setting the SET bit allows"
276      * them to occur.
277      */
278     if ((s->cmos_data[RTC_REG_A] & 0x60) == 0x60) {
279         assert((s->cmos_data[RTC_REG_A] & REG_A_UIP) == 0);
280         timer_del(s->update_timer);
281         return;
282     }
283 
284     guest_nsec = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
285     next_update_time = qemu_clock_get_ns(rtc_clock)
286         + NANOSECONDS_PER_SECOND - guest_nsec;
287 
288     /* Compute time of next alarm.  One second is already accounted
289      * for in next_update_time.
290      */
291     next_alarm_sec = get_next_alarm(s);
292     s->next_alarm_time = next_update_time +
293                          (next_alarm_sec - 1) * NANOSECONDS_PER_SECOND;
294 
295     /* If update_in_progress latched the UIP bit, we must keep the timer
296      * programmed to the next second, so that UIP is cleared.  Otherwise,
297      * if UF is already set, we might be able to optimize.
298      */
299     if (!(s->cmos_data[RTC_REG_A] & REG_A_UIP) &&
300         (s->cmos_data[RTC_REG_C] & REG_C_UF)) {
301         /* If AF cannot change (i.e. either it is set already, or
302          * SET=1 and then the time is not updated), nothing to do.
303          */
304         if ((s->cmos_data[RTC_REG_B] & REG_B_SET) ||
305             (s->cmos_data[RTC_REG_C] & REG_C_AF)) {
306             timer_del(s->update_timer);
307             return;
308         }
309 
310         /* UF is set, but AF is clear.  Program the timer to target
311          * the alarm time.  */
312         next_update_time = s->next_alarm_time;
313     }
314     if (next_update_time != timer_expire_time_ns(s->update_timer)) {
315         timer_mod(s->update_timer, next_update_time);
316     }
317 }
318 
319 static inline uint8_t convert_hour(RTCState *s, uint8_t hour)
320 {
321     if (!(s->cmos_data[RTC_REG_B] & REG_B_24H)) {
322         hour %= 12;
323         if (s->cmos_data[RTC_HOURS] & 0x80) {
324             hour += 12;
325         }
326     }
327     return hour;
328 }
329 
330 static uint64_t get_next_alarm(RTCState *s)
331 {
332     int32_t alarm_sec, alarm_min, alarm_hour, cur_hour, cur_min, cur_sec;
333     int32_t hour, min, sec;
334 
335     rtc_update_time(s);
336 
337     alarm_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS_ALARM]);
338     alarm_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES_ALARM]);
339     alarm_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS_ALARM]);
340     alarm_hour = alarm_hour == -1 ? -1 : convert_hour(s, alarm_hour);
341 
342     cur_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS]);
343     cur_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES]);
344     cur_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS]);
345     cur_hour = convert_hour(s, cur_hour);
346 
347     if (alarm_hour == -1) {
348         alarm_hour = cur_hour;
349         if (alarm_min == -1) {
350             alarm_min = cur_min;
351             if (alarm_sec == -1) {
352                 alarm_sec = cur_sec + 1;
353             } else if (cur_sec > alarm_sec) {
354                 alarm_min++;
355             }
356         } else if (cur_min == alarm_min) {
357             if (alarm_sec == -1) {
358                 alarm_sec = cur_sec + 1;
359             } else {
360                 if (cur_sec > alarm_sec) {
361                     alarm_hour++;
362                 }
363             }
364             if (alarm_sec == SEC_PER_MIN) {
365                 /* wrap to next hour, minutes is not in don't care mode */
366                 alarm_sec = 0;
367                 alarm_hour++;
368             }
369         } else if (cur_min > alarm_min) {
370             alarm_hour++;
371         }
372     } else if (cur_hour == alarm_hour) {
373         if (alarm_min == -1) {
374             alarm_min = cur_min;
375             if (alarm_sec == -1) {
376                 alarm_sec = cur_sec + 1;
377             } else if (cur_sec > alarm_sec) {
378                 alarm_min++;
379             }
380 
381             if (alarm_sec == SEC_PER_MIN) {
382                 alarm_sec = 0;
383                 alarm_min++;
384             }
385             /* wrap to next day, hour is not in don't care mode */
386             alarm_min %= MIN_PER_HOUR;
387         } else if (cur_min == alarm_min) {
388             if (alarm_sec == -1) {
389                 alarm_sec = cur_sec + 1;
390             }
391             /* wrap to next day, hours+minutes not in don't care mode */
392             alarm_sec %= SEC_PER_MIN;
393         }
394     }
395 
396     /* values that are still don't care fire at the next min/sec */
397     if (alarm_min == -1) {
398         alarm_min = 0;
399     }
400     if (alarm_sec == -1) {
401         alarm_sec = 0;
402     }
403 
404     /* keep values in range */
405     if (alarm_sec == SEC_PER_MIN) {
406         alarm_sec = 0;
407         alarm_min++;
408     }
409     if (alarm_min == MIN_PER_HOUR) {
410         alarm_min = 0;
411         alarm_hour++;
412     }
413     alarm_hour %= HOUR_PER_DAY;
414 
415     hour = alarm_hour - cur_hour;
416     min = hour * MIN_PER_HOUR + alarm_min - cur_min;
417     sec = min * SEC_PER_MIN + alarm_sec - cur_sec;
418     return sec <= 0 ? sec + SEC_PER_DAY : sec;
419 }
420 
421 static void rtc_update_timer(void *opaque)
422 {
423     RTCState *s = opaque;
424     int32_t irqs = REG_C_UF;
425     int32_t new_irqs;
426 
427     assert((s->cmos_data[RTC_REG_A] & 0x60) != 0x60);
428 
429     /* UIP might have been latched, update time and clear it.  */
430     rtc_update_time(s);
431     s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
432 
433     if (qemu_clock_get_ns(rtc_clock) >= s->next_alarm_time) {
434         irqs |= REG_C_AF;
435         if (s->cmos_data[RTC_REG_B] & REG_B_AIE) {
436             qemu_system_wakeup_request(QEMU_WAKEUP_REASON_RTC, NULL);
437         }
438     }
439 
440     new_irqs = irqs & ~s->cmos_data[RTC_REG_C];
441     s->cmos_data[RTC_REG_C] |= irqs;
442     if ((new_irqs & s->cmos_data[RTC_REG_B]) != 0) {
443         s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
444         qemu_irq_raise(s->irq);
445     }
446     check_update_timer(s);
447 }
448 
449 static void cmos_ioport_write(void *opaque, hwaddr addr,
450                               uint64_t data, unsigned size)
451 {
452     RTCState *s = opaque;
453     uint32_t old_period;
454     bool update_periodic_timer;
455 
456     if ((addr & 1) == 0) {
457         s->cmos_index = data & 0x7f;
458     } else {
459         CMOS_DPRINTF("cmos: write index=0x%02x val=0x%02" PRIx64 "\n",
460                      s->cmos_index, data);
461         switch(s->cmos_index) {
462         case RTC_SECONDS_ALARM:
463         case RTC_MINUTES_ALARM:
464         case RTC_HOURS_ALARM:
465             s->cmos_data[s->cmos_index] = data;
466             check_update_timer(s);
467             break;
468         case RTC_IBM_PS2_CENTURY_BYTE:
469             s->cmos_index = RTC_CENTURY;
470             /* fall through */
471         case RTC_CENTURY:
472         case RTC_SECONDS:
473         case RTC_MINUTES:
474         case RTC_HOURS:
475         case RTC_DAY_OF_WEEK:
476         case RTC_DAY_OF_MONTH:
477         case RTC_MONTH:
478         case RTC_YEAR:
479             s->cmos_data[s->cmos_index] = data;
480             /* if in set mode, do not update the time */
481             if (rtc_running(s)) {
482                 rtc_set_time(s);
483                 check_update_timer(s);
484             }
485             break;
486         case RTC_REG_A:
487             update_periodic_timer = (s->cmos_data[RTC_REG_A] ^ data) & 0x0f;
488             old_period = rtc_periodic_clock_ticks(s);
489 
490             if ((data & 0x60) == 0x60) {
491                 if (rtc_running(s)) {
492                     rtc_update_time(s);
493                 }
494                 /* What happens to UIP when divider reset is enabled is
495                  * unclear from the datasheet.  Shouldn't matter much
496                  * though.
497                  */
498                 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
499             } else if (((s->cmos_data[RTC_REG_A] & 0x60) == 0x60) &&
500                     (data & 0x70)  <= 0x20) {
501                 /* when the divider reset is removed, the first update cycle
502                  * begins one-half second later*/
503                 if (!(s->cmos_data[RTC_REG_B] & REG_B_SET)) {
504                     s->offset = 500000000;
505                     rtc_set_time(s);
506                 }
507                 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
508             }
509             /* UIP bit is read only */
510             s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |
511                 (s->cmos_data[RTC_REG_A] & REG_A_UIP);
512 
513             if (update_periodic_timer) {
514                 periodic_timer_update(s, qemu_clock_get_ns(rtc_clock),
515                                       old_period, true);
516             }
517 
518             check_update_timer(s);
519             break;
520         case RTC_REG_B:
521             update_periodic_timer = (s->cmos_data[RTC_REG_B] ^ data)
522                                        & REG_B_PIE;
523             old_period = rtc_periodic_clock_ticks(s);
524 
525             if (data & REG_B_SET) {
526                 /* update cmos to when the rtc was stopping */
527                 if (rtc_running(s)) {
528                     rtc_update_time(s);
529                 }
530                 /* set mode: reset UIP mode */
531                 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
532                 data &= ~REG_B_UIE;
533             } else {
534                 /* if disabling set mode, update the time */
535                 if ((s->cmos_data[RTC_REG_B] & REG_B_SET) &&
536                     (s->cmos_data[RTC_REG_A] & 0x70) <= 0x20) {
537                     s->offset = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
538                     rtc_set_time(s);
539                 }
540             }
541             /* if an interrupt flag is already set when the interrupt
542              * becomes enabled, raise an interrupt immediately.  */
543             if (data & s->cmos_data[RTC_REG_C] & REG_C_MASK) {
544                 s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
545                 qemu_irq_raise(s->irq);
546             } else {
547                 s->cmos_data[RTC_REG_C] &= ~REG_C_IRQF;
548                 qemu_irq_lower(s->irq);
549             }
550             s->cmos_data[RTC_REG_B] = data;
551 
552             if (update_periodic_timer) {
553                 periodic_timer_update(s, qemu_clock_get_ns(rtc_clock),
554                                       old_period, true);
555             }
556 
557             check_update_timer(s);
558             break;
559         case RTC_REG_C:
560         case RTC_REG_D:
561             /* cannot write to them */
562             break;
563         default:
564             s->cmos_data[s->cmos_index] = data;
565             break;
566         }
567     }
568 }
569 
570 static inline int rtc_to_bcd(RTCState *s, int a)
571 {
572     if (s->cmos_data[RTC_REG_B] & REG_B_DM) {
573         return a;
574     } else {
575         return ((a / 10) << 4) | (a % 10);
576     }
577 }
578 
579 static inline int rtc_from_bcd(RTCState *s, int a)
580 {
581     if ((a & 0xc0) == 0xc0) {
582         return -1;
583     }
584     if (s->cmos_data[RTC_REG_B] & REG_B_DM) {
585         return a;
586     } else {
587         return ((a >> 4) * 10) + (a & 0x0f);
588     }
589 }
590 
591 static void rtc_get_time(RTCState *s, struct tm *tm)
592 {
593     tm->tm_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS]);
594     tm->tm_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES]);
595     tm->tm_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS] & 0x7f);
596     if (!(s->cmos_data[RTC_REG_B] & REG_B_24H)) {
597         tm->tm_hour %= 12;
598         if (s->cmos_data[RTC_HOURS] & 0x80) {
599             tm->tm_hour += 12;
600         }
601     }
602     tm->tm_wday = rtc_from_bcd(s, s->cmos_data[RTC_DAY_OF_WEEK]) - 1;
603     tm->tm_mday = rtc_from_bcd(s, s->cmos_data[RTC_DAY_OF_MONTH]);
604     tm->tm_mon = rtc_from_bcd(s, s->cmos_data[RTC_MONTH]) - 1;
605     tm->tm_year =
606         rtc_from_bcd(s, s->cmos_data[RTC_YEAR]) + s->base_year +
607         rtc_from_bcd(s, s->cmos_data[RTC_CENTURY]) * 100 - 1900;
608 }
609 
610 static void rtc_set_time(RTCState *s)
611 {
612     struct tm tm;
613 
614     rtc_get_time(s, &tm);
615     s->base_rtc = mktimegm(&tm);
616     s->last_update = qemu_clock_get_ns(rtc_clock);
617 
618     qapi_event_send_rtc_change(qemu_timedate_diff(&tm));
619 }
620 
621 static void rtc_set_cmos(RTCState *s, const struct tm *tm)
622 {
623     int year;
624 
625     s->cmos_data[RTC_SECONDS] = rtc_to_bcd(s, tm->tm_sec);
626     s->cmos_data[RTC_MINUTES] = rtc_to_bcd(s, tm->tm_min);
627     if (s->cmos_data[RTC_REG_B] & REG_B_24H) {
628         /* 24 hour format */
629         s->cmos_data[RTC_HOURS] = rtc_to_bcd(s, tm->tm_hour);
630     } else {
631         /* 12 hour format */
632         int h = (tm->tm_hour % 12) ? tm->tm_hour % 12 : 12;
633         s->cmos_data[RTC_HOURS] = rtc_to_bcd(s, h);
634         if (tm->tm_hour >= 12)
635             s->cmos_data[RTC_HOURS] |= 0x80;
636     }
637     s->cmos_data[RTC_DAY_OF_WEEK] = rtc_to_bcd(s, tm->tm_wday + 1);
638     s->cmos_data[RTC_DAY_OF_MONTH] = rtc_to_bcd(s, tm->tm_mday);
639     s->cmos_data[RTC_MONTH] = rtc_to_bcd(s, tm->tm_mon + 1);
640     year = tm->tm_year + 1900 - s->base_year;
641     s->cmos_data[RTC_YEAR] = rtc_to_bcd(s, year % 100);
642     s->cmos_data[RTC_CENTURY] = rtc_to_bcd(s, year / 100);
643 }
644 
645 static void rtc_update_time(RTCState *s)
646 {
647     struct tm ret;
648     time_t guest_sec;
649     int64_t guest_nsec;
650 
651     guest_nsec = get_guest_rtc_ns(s);
652     guest_sec = guest_nsec / NANOSECONDS_PER_SECOND;
653     gmtime_r(&guest_sec, &ret);
654 
655     /* Is SET flag of Register B disabled? */
656     if ((s->cmos_data[RTC_REG_B] & REG_B_SET) == 0) {
657         rtc_set_cmos(s, &ret);
658     }
659 }
660 
661 static int update_in_progress(RTCState *s)
662 {
663     int64_t guest_nsec;
664 
665     if (!rtc_running(s)) {
666         return 0;
667     }
668     if (timer_pending(s->update_timer)) {
669         int64_t next_update_time = timer_expire_time_ns(s->update_timer);
670         /* Latch UIP until the timer expires.  */
671         if (qemu_clock_get_ns(rtc_clock) >=
672             (next_update_time - UIP_HOLD_LENGTH)) {
673             s->cmos_data[RTC_REG_A] |= REG_A_UIP;
674             return 1;
675         }
676     }
677 
678     guest_nsec = get_guest_rtc_ns(s);
679     /* UIP bit will be set at last 244us of every second. */
680     if ((guest_nsec % NANOSECONDS_PER_SECOND) >=
681         (NANOSECONDS_PER_SECOND - UIP_HOLD_LENGTH)) {
682         return 1;
683     }
684     return 0;
685 }
686 
687 static uint64_t cmos_ioport_read(void *opaque, hwaddr addr,
688                                  unsigned size)
689 {
690     RTCState *s = opaque;
691     int ret;
692     if ((addr & 1) == 0) {
693         return 0xff;
694     } else {
695         switch(s->cmos_index) {
696         case RTC_IBM_PS2_CENTURY_BYTE:
697             s->cmos_index = RTC_CENTURY;
698             /* fall through */
699         case RTC_CENTURY:
700         case RTC_SECONDS:
701         case RTC_MINUTES:
702         case RTC_HOURS:
703         case RTC_DAY_OF_WEEK:
704         case RTC_DAY_OF_MONTH:
705         case RTC_MONTH:
706         case RTC_YEAR:
707             /* if not in set mode, calibrate cmos before
708              * reading*/
709             if (rtc_running(s)) {
710                 rtc_update_time(s);
711             }
712             ret = s->cmos_data[s->cmos_index];
713             break;
714         case RTC_REG_A:
715             ret = s->cmos_data[s->cmos_index];
716             if (update_in_progress(s)) {
717                 ret |= REG_A_UIP;
718             }
719             break;
720         case RTC_REG_C:
721             ret = s->cmos_data[s->cmos_index];
722             qemu_irq_lower(s->irq);
723             s->cmos_data[RTC_REG_C] = 0x00;
724             if (ret & (REG_C_UF | REG_C_AF)) {
725                 check_update_timer(s);
726             }
727 
728             if(s->irq_coalesced &&
729                     (s->cmos_data[RTC_REG_B] & REG_B_PIE) &&
730                     s->irq_reinject_on_ack_count < RTC_REINJECT_ON_ACK_COUNT) {
731                 s->irq_reinject_on_ack_count++;
732                 s->cmos_data[RTC_REG_C] |= REG_C_IRQF | REG_C_PF;
733                 DPRINTF_C("cmos: injecting on ack\n");
734                 if (rtc_policy_slew_deliver_irq(s)) {
735                     s->irq_coalesced--;
736                     DPRINTF_C("cmos: coalesced irqs decreased to %d\n",
737                               s->irq_coalesced);
738                 }
739             }
740             break;
741         default:
742             ret = s->cmos_data[s->cmos_index];
743             break;
744         }
745         CMOS_DPRINTF("cmos: read index=0x%02x val=0x%02x\n",
746                      s->cmos_index, ret);
747         return ret;
748     }
749 }
750 
751 void rtc_set_memory(ISADevice *dev, int addr, int val)
752 {
753     RTCState *s = MC146818_RTC(dev);
754     if (addr >= 0 && addr <= 127)
755         s->cmos_data[addr] = val;
756 }
757 
758 int rtc_get_memory(ISADevice *dev, int addr)
759 {
760     RTCState *s = MC146818_RTC(dev);
761     assert(addr >= 0 && addr <= 127);
762     return s->cmos_data[addr];
763 }
764 
765 static void rtc_set_date_from_host(ISADevice *dev)
766 {
767     RTCState *s = MC146818_RTC(dev);
768     struct tm tm;
769 
770     qemu_get_timedate(&tm, 0);
771 
772     s->base_rtc = mktimegm(&tm);
773     s->last_update = qemu_clock_get_ns(rtc_clock);
774     s->offset = 0;
775 
776     /* set the CMOS date */
777     rtc_set_cmos(s, &tm);
778 }
779 
780 static int rtc_pre_save(void *opaque)
781 {
782     RTCState *s = opaque;
783 
784     rtc_update_time(s);
785 
786     return 0;
787 }
788 
789 static int rtc_post_load(void *opaque, int version_id)
790 {
791     RTCState *s = opaque;
792 
793     if (version_id <= 2 || rtc_clock == QEMU_CLOCK_REALTIME) {
794         rtc_set_time(s);
795         s->offset = 0;
796         check_update_timer(s);
797     }
798     s->period = rtc_periodic_clock_ticks(s);
799 
800     /* The periodic timer is deterministic in record/replay mode,
801      * so there is no need to update it after loading the vmstate.
802      * Reading RTC here would misalign record and replay.
803      */
804     if (replay_mode == REPLAY_MODE_NONE) {
805         uint64_t now = qemu_clock_get_ns(rtc_clock);
806         if (now < s->next_periodic_time ||
807             now > (s->next_periodic_time + get_max_clock_jump())) {
808             periodic_timer_update(s, qemu_clock_get_ns(rtc_clock), s->period, false);
809         }
810     }
811 
812     if (version_id >= 2) {
813         if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
814             rtc_coalesced_timer_update(s);
815         }
816     }
817     return 0;
818 }
819 
820 static bool rtc_irq_reinject_on_ack_count_needed(void *opaque)
821 {
822     RTCState *s = (RTCState *)opaque;
823     return s->irq_reinject_on_ack_count != 0;
824 }
825 
826 static const VMStateDescription vmstate_rtc_irq_reinject_on_ack_count = {
827     .name = "mc146818rtc/irq_reinject_on_ack_count",
828     .version_id = 1,
829     .minimum_version_id = 1,
830     .needed = rtc_irq_reinject_on_ack_count_needed,
831     .fields = (VMStateField[]) {
832         VMSTATE_UINT16(irq_reinject_on_ack_count, RTCState),
833         VMSTATE_END_OF_LIST()
834     }
835 };
836 
837 static const VMStateDescription vmstate_rtc = {
838     .name = "mc146818rtc",
839     .version_id = 3,
840     .minimum_version_id = 1,
841     .pre_save = rtc_pre_save,
842     .post_load = rtc_post_load,
843     .fields = (VMStateField[]) {
844         VMSTATE_BUFFER(cmos_data, RTCState),
845         VMSTATE_UINT8(cmos_index, RTCState),
846         VMSTATE_UNUSED(7*4),
847         VMSTATE_TIMER_PTR(periodic_timer, RTCState),
848         VMSTATE_INT64(next_periodic_time, RTCState),
849         VMSTATE_UNUSED(3*8),
850         VMSTATE_UINT32_V(irq_coalesced, RTCState, 2),
851         VMSTATE_UINT32_V(period, RTCState, 2),
852         VMSTATE_UINT64_V(base_rtc, RTCState, 3),
853         VMSTATE_UINT64_V(last_update, RTCState, 3),
854         VMSTATE_INT64_V(offset, RTCState, 3),
855         VMSTATE_TIMER_PTR_V(update_timer, RTCState, 3),
856         VMSTATE_UINT64_V(next_alarm_time, RTCState, 3),
857         VMSTATE_END_OF_LIST()
858     },
859     .subsections = (const VMStateDescription*[]) {
860         &vmstate_rtc_irq_reinject_on_ack_count,
861         NULL
862     }
863 };
864 
865 /* set CMOS shutdown status register (index 0xF) as S3_resume(0xFE)
866    BIOS will read it and start S3 resume at POST Entry */
867 static void rtc_notify_suspend(Notifier *notifier, void *data)
868 {
869     RTCState *s = container_of(notifier, RTCState, suspend_notifier);
870     rtc_set_memory(ISA_DEVICE(s), 0xF, 0xFE);
871 }
872 
873 static void rtc_reset(void *opaque)
874 {
875     RTCState *s = opaque;
876 
877     s->cmos_data[RTC_REG_B] &= ~(REG_B_PIE | REG_B_AIE | REG_B_SQWE);
878     s->cmos_data[RTC_REG_C] &= ~(REG_C_UF | REG_C_IRQF | REG_C_PF | REG_C_AF);
879     check_update_timer(s);
880 
881     qemu_irq_lower(s->irq);
882 
883     if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
884         s->irq_coalesced = 0;
885         s->irq_reinject_on_ack_count = 0;
886     }
887 }
888 
889 static const MemoryRegionOps cmos_ops = {
890     .read = cmos_ioport_read,
891     .write = cmos_ioport_write,
892     .impl = {
893         .min_access_size = 1,
894         .max_access_size = 1,
895     },
896     .endianness = DEVICE_LITTLE_ENDIAN,
897 };
898 
899 static void rtc_get_date(Object *obj, struct tm *current_tm, Error **errp)
900 {
901     RTCState *s = MC146818_RTC(obj);
902 
903     rtc_update_time(s);
904     rtc_get_time(s, current_tm);
905 }
906 
907 static void rtc_realizefn(DeviceState *dev, Error **errp)
908 {
909     ISADevice *isadev = ISA_DEVICE(dev);
910     RTCState *s = MC146818_RTC(dev);
911 
912     s->cmos_data[RTC_REG_A] = 0x26;
913     s->cmos_data[RTC_REG_B] = 0x02;
914     s->cmos_data[RTC_REG_C] = 0x00;
915     s->cmos_data[RTC_REG_D] = 0x80;
916 
917     /* This is for historical reasons.  The default base year qdev property
918      * was set to 2000 for most machine types before the century byte was
919      * implemented.
920      *
921      * This if statement means that the century byte will be always 0
922      * (at least until 2079...) for base_year = 1980, but will be set
923      * correctly for base_year = 2000.
924      */
925     if (s->base_year == 2000) {
926         s->base_year = 0;
927     }
928 
929     rtc_set_date_from_host(isadev);
930 
931     switch (s->lost_tick_policy) {
932 #ifdef TARGET_I386
933     case LOST_TICK_POLICY_SLEW:
934         s->coalesced_timer =
935             timer_new_ns(rtc_clock, rtc_coalesced_timer, s);
936         break;
937 #endif
938     case LOST_TICK_POLICY_DISCARD:
939         break;
940     default:
941         error_setg(errp, "Invalid lost tick policy.");
942         return;
943     }
944 
945     s->periodic_timer = timer_new_ns(rtc_clock, rtc_periodic_timer, s);
946     s->update_timer = timer_new_ns(rtc_clock, rtc_update_timer, s);
947     check_update_timer(s);
948 
949     s->suspend_notifier.notify = rtc_notify_suspend;
950     qemu_register_suspend_notifier(&s->suspend_notifier);
951 
952     memory_region_init_io(&s->io, OBJECT(s), &cmos_ops, s, "rtc", 2);
953     isa_register_ioport(isadev, &s->io, RTC_ISA_BASE);
954 
955     /* register rtc 0x70 port for coalesced_pio */
956     memory_region_set_flush_coalesced(&s->io);
957     memory_region_init_io(&s->coalesced_io, OBJECT(s), &cmos_ops,
958                           s, "rtc-index", 1);
959     memory_region_add_subregion(&s->io, 0, &s->coalesced_io);
960     memory_region_add_coalescing(&s->coalesced_io, 0, 1);
961 
962     qdev_set_legacy_instance_id(dev, RTC_ISA_BASE, 3);
963     qemu_register_reset(rtc_reset, s);
964 
965     object_property_add_tm(OBJECT(s), "date", rtc_get_date, NULL);
966 
967     qdev_init_gpio_out(dev, &s->irq, 1);
968     QLIST_INSERT_HEAD(&rtc_devices, s, link);
969 }
970 
971 ISADevice *mc146818_rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq)
972 {
973     DeviceState *dev;
974     ISADevice *isadev;
975 
976     isadev = isa_create(bus, TYPE_MC146818_RTC);
977     dev = DEVICE(isadev);
978     qdev_prop_set_int32(dev, "base_year", base_year);
979     qdev_init_nofail(dev);
980     if (intercept_irq) {
981         qdev_connect_gpio_out(dev, 0, intercept_irq);
982     } else {
983         isa_connect_gpio_out(isadev, 0, RTC_ISA_IRQ);
984     }
985 
986     object_property_add_alias(qdev_get_machine(), "rtc-time", OBJECT(isadev),
987                               "date", NULL);
988 
989     return isadev;
990 }
991 
992 static Property mc146818rtc_properties[] = {
993     DEFINE_PROP_INT32("base_year", RTCState, base_year, 1980),
994     DEFINE_PROP_LOSTTICKPOLICY("lost_tick_policy", RTCState,
995                                lost_tick_policy, LOST_TICK_POLICY_DISCARD),
996     DEFINE_PROP_END_OF_LIST(),
997 };
998 
999 static void rtc_resetdev(DeviceState *d)
1000 {
1001     RTCState *s = MC146818_RTC(d);
1002 
1003     /* Reason: VM do suspend self will set 0xfe
1004      * Reset any values other than 0xfe(Guest suspend case) */
1005     if (s->cmos_data[0x0f] != 0xfe) {
1006         s->cmos_data[0x0f] = 0x00;
1007     }
1008 }
1009 
1010 static void rtc_class_initfn(ObjectClass *klass, void *data)
1011 {
1012     DeviceClass *dc = DEVICE_CLASS(klass);
1013 
1014     dc->realize = rtc_realizefn;
1015     dc->reset = rtc_resetdev;
1016     dc->vmsd = &vmstate_rtc;
1017     device_class_set_props(dc, mc146818rtc_properties);
1018 }
1019 
1020 static const TypeInfo mc146818rtc_info = {
1021     .name          = TYPE_MC146818_RTC,
1022     .parent        = TYPE_ISA_DEVICE,
1023     .instance_size = sizeof(RTCState),
1024     .class_init    = rtc_class_initfn,
1025 };
1026 
1027 static void mc146818rtc_register_types(void)
1028 {
1029     type_register_static(&mc146818rtc_info);
1030 }
1031 
1032 type_init(mc146818rtc_register_types)
1033