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