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