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