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