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