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