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