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