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