xref: /openbmc/qemu/hw/rtc/mc146818rtc.c (revision 1ea5208f)
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/aml-build.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 static void rtc_set_time(RTCState *s);
78 static void rtc_update_time(RTCState *s);
79 static void rtc_set_cmos(RTCState *s, const struct tm *tm);
80 static inline int rtc_from_bcd(RTCState *s, int a);
81 static uint64_t get_next_alarm(RTCState *s);
82 
83 static inline bool rtc_running(RTCState *s)
84 {
85     return (!(s->cmos_data[RTC_REG_B] & REG_B_SET) &&
86             (s->cmos_data[RTC_REG_A] & 0x70) <= 0x20);
87 }
88 
89 static uint64_t get_guest_rtc_ns(RTCState *s)
90 {
91     uint64_t guest_clock = qemu_clock_get_ns(rtc_clock);
92 
93     return s->base_rtc * NANOSECONDS_PER_SECOND +
94         guest_clock - s->last_update + s->offset;
95 }
96 
97 static void rtc_coalesced_timer_update(RTCState *s)
98 {
99     if (s->irq_coalesced == 0) {
100         timer_del(s->coalesced_timer);
101     } else {
102         /* divide each RTC interval to 2 - 8 smaller intervals */
103         int c = MIN(s->irq_coalesced, 7) + 1;
104         int64_t next_clock = qemu_clock_get_ns(rtc_clock) +
105             periodic_clock_to_ns(s->period / c);
106         timer_mod(s->coalesced_timer, next_clock);
107     }
108 }
109 
110 static QLIST_HEAD(, RTCState) rtc_devices =
111     QLIST_HEAD_INITIALIZER(rtc_devices);
112 
113 #ifdef TARGET_I386
114 void qmp_rtc_reset_reinjection(Error **errp)
115 {
116     RTCState *s;
117 
118     QLIST_FOREACH(s, &rtc_devices, link) {
119         s->irq_coalesced = 0;
120     }
121 }
122 
123 static bool rtc_policy_slew_deliver_irq(RTCState *s)
124 {
125     apic_reset_irq_delivered();
126     qemu_irq_raise(s->irq);
127     return apic_get_irq_delivered();
128 }
129 
130 static void rtc_coalesced_timer(void *opaque)
131 {
132     RTCState *s = opaque;
133 
134     if (s->irq_coalesced != 0) {
135         s->cmos_data[RTC_REG_C] |= 0xc0;
136         DPRINTF_C("cmos: injecting from timer\n");
137         if (rtc_policy_slew_deliver_irq(s)) {
138             s->irq_coalesced--;
139             DPRINTF_C("cmos: coalesced irqs decreased to %d\n",
140                       s->irq_coalesced);
141         }
142     }
143 
144     rtc_coalesced_timer_update(s);
145 }
146 #else
147 static bool rtc_policy_slew_deliver_irq(RTCState *s)
148 {
149     assert(0);
150     return false;
151 }
152 #endif
153 
154 static uint32_t rtc_periodic_clock_ticks(RTCState *s)
155 {
156     int period_code;
157 
158     if (!(s->cmos_data[RTC_REG_B] & REG_B_PIE)) {
159         return 0;
160      }
161 
162     period_code = s->cmos_data[RTC_REG_A] & 0x0f;
163 
164     return periodic_period_to_clock(period_code);
165 }
166 
167 /*
168  * handle periodic timer. @old_period indicates the periodic timer update
169  * is just due to period adjustment.
170  */
171 static void
172 periodic_timer_update(RTCState *s, int64_t current_time, uint32_t old_period, bool period_change)
173 {
174     uint32_t period;
175     int64_t cur_clock, next_irq_clock, lost_clock = 0;
176 
177     period = rtc_periodic_clock_ticks(s);
178     s->period = period;
179 
180     if (!period) {
181         s->irq_coalesced = 0;
182         timer_del(s->periodic_timer);
183         return;
184     }
185 
186     /* compute 32 khz clock */
187     cur_clock =
188         muldiv64(current_time, RTC_CLOCK_RATE, NANOSECONDS_PER_SECOND);
189 
190     /*
191      * if the periodic timer's update is due to period re-configuration,
192      * we should count the clock since last interrupt.
193      */
194     if (old_period && period_change) {
195         int64_t last_periodic_clock, next_periodic_clock;
196 
197         next_periodic_clock = muldiv64(s->next_periodic_time,
198                                 RTC_CLOCK_RATE, NANOSECONDS_PER_SECOND);
199         last_periodic_clock = next_periodic_clock - old_period;
200         lost_clock = cur_clock - last_periodic_clock;
201         assert(lost_clock >= 0);
202     }
203 
204     /*
205      * s->irq_coalesced can change for two reasons:
206      *
207      * a) if one or more periodic timer interrupts have been lost,
208      *    lost_clock will be more that a period.
209      *
210      * b) when the period may be reconfigured, we expect the OS to
211      *    treat delayed tick as the new period.  So, when switching
212      *    from a shorter to a longer period, scale down the missing,
213      *    because the OS will treat past delayed ticks as longer
214      *    (leftovers are put back into lost_clock).  When switching
215      *    to a shorter period, scale up the missing ticks since the
216      *    OS handler will treat past delayed ticks as shorter.
217      */
218     if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
219         uint32_t old_irq_coalesced = s->irq_coalesced;
220 
221         lost_clock += old_irq_coalesced * old_period;
222         s->irq_coalesced = lost_clock / s->period;
223         lost_clock %= s->period;
224         if (old_irq_coalesced != s->irq_coalesced ||
225             old_period != s->period) {
226             DPRINTF_C("cmos: coalesced irqs scaled from %d to %d, "
227                       "period scaled from %d to %d\n", old_irq_coalesced,
228                       s->irq_coalesced, old_period, s->period);
229             rtc_coalesced_timer_update(s);
230         }
231     } else {
232         /*
233          * no way to compensate the interrupt if LOST_TICK_POLICY_SLEW
234          * is not used, we should make the time progress anyway.
235          */
236         lost_clock = MIN(lost_clock, period);
237     }
238 
239     assert(lost_clock >= 0 && lost_clock <= period);
240 
241     next_irq_clock = cur_clock + period - lost_clock;
242     s->next_periodic_time = periodic_clock_to_ns(next_irq_clock) + 1;
243     timer_mod(s->periodic_timer, s->next_periodic_time);
244 }
245 
246 static void rtc_periodic_timer(void *opaque)
247 {
248     RTCState *s = opaque;
249 
250     periodic_timer_update(s, s->next_periodic_time, s->period, false);
251     s->cmos_data[RTC_REG_C] |= REG_C_PF;
252     if (s->cmos_data[RTC_REG_B] & REG_B_PIE) {
253         s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
254         if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
255             if (s->irq_reinject_on_ack_count >= RTC_REINJECT_ON_ACK_COUNT)
256                 s->irq_reinject_on_ack_count = 0;
257             if (!rtc_policy_slew_deliver_irq(s)) {
258                 s->irq_coalesced++;
259                 rtc_coalesced_timer_update(s);
260                 DPRINTF_C("cmos: coalesced irqs increased to %d\n",
261                           s->irq_coalesced);
262             }
263         } else
264             qemu_irq_raise(s->irq);
265     }
266 }
267 
268 /* handle update-ended timer */
269 static void check_update_timer(RTCState *s)
270 {
271     uint64_t next_update_time;
272     uint64_t guest_nsec;
273     int next_alarm_sec;
274 
275     /* From the data sheet: "Holding the dividers in reset prevents
276      * interrupts from operating, while setting the SET bit allows"
277      * them to occur.
278      */
279     if ((s->cmos_data[RTC_REG_A] & 0x60) == 0x60) {
280         assert((s->cmos_data[RTC_REG_A] & REG_A_UIP) == 0);
281         timer_del(s->update_timer);
282         return;
283     }
284 
285     guest_nsec = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
286     next_update_time = qemu_clock_get_ns(rtc_clock)
287         + NANOSECONDS_PER_SECOND - guest_nsec;
288 
289     /* Compute time of next alarm.  One second is already accounted
290      * for in next_update_time.
291      */
292     next_alarm_sec = get_next_alarm(s);
293     s->next_alarm_time = next_update_time +
294                          (next_alarm_sec - 1) * NANOSECONDS_PER_SECOND;
295 
296     /* If update_in_progress latched the UIP bit, we must keep the timer
297      * programmed to the next second, so that UIP is cleared.  Otherwise,
298      * if UF is already set, we might be able to optimize.
299      */
300     if (!(s->cmos_data[RTC_REG_A] & REG_A_UIP) &&
301         (s->cmos_data[RTC_REG_C] & REG_C_UF)) {
302         /* If AF cannot change (i.e. either it is set already, or
303          * SET=1 and then the time is not updated), nothing to do.
304          */
305         if ((s->cmos_data[RTC_REG_B] & REG_B_SET) ||
306             (s->cmos_data[RTC_REG_C] & REG_C_AF)) {
307             timer_del(s->update_timer);
308             return;
309         }
310 
311         /* UF is set, but AF is clear.  Program the timer to target
312          * the alarm time.  */
313         next_update_time = s->next_alarm_time;
314     }
315     if (next_update_time != timer_expire_time_ns(s->update_timer)) {
316         timer_mod(s->update_timer, next_update_time);
317     }
318 }
319 
320 static inline uint8_t convert_hour(RTCState *s, uint8_t hour)
321 {
322     if (!(s->cmos_data[RTC_REG_B] & REG_B_24H)) {
323         hour %= 12;
324         if (s->cmos_data[RTC_HOURS] & 0x80) {
325             hour += 12;
326         }
327     }
328     return hour;
329 }
330 
331 static uint64_t get_next_alarm(RTCState *s)
332 {
333     int32_t alarm_sec, alarm_min, alarm_hour, cur_hour, cur_min, cur_sec;
334     int32_t hour, min, sec;
335 
336     rtc_update_time(s);
337 
338     alarm_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS_ALARM]);
339     alarm_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES_ALARM]);
340     alarm_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS_ALARM]);
341     alarm_hour = alarm_hour == -1 ? -1 : convert_hour(s, alarm_hour);
342 
343     cur_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS]);
344     cur_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES]);
345     cur_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS]);
346     cur_hour = convert_hour(s, cur_hour);
347 
348     if (alarm_hour == -1) {
349         alarm_hour = cur_hour;
350         if (alarm_min == -1) {
351             alarm_min = cur_min;
352             if (alarm_sec == -1) {
353                 alarm_sec = cur_sec + 1;
354             } else if (cur_sec > alarm_sec) {
355                 alarm_min++;
356             }
357         } else if (cur_min == alarm_min) {
358             if (alarm_sec == -1) {
359                 alarm_sec = cur_sec + 1;
360             } else {
361                 if (cur_sec > alarm_sec) {
362                     alarm_hour++;
363                 }
364             }
365             if (alarm_sec == SEC_PER_MIN) {
366                 /* wrap to next hour, minutes is not in don't care mode */
367                 alarm_sec = 0;
368                 alarm_hour++;
369             }
370         } else if (cur_min > alarm_min) {
371             alarm_hour++;
372         }
373     } else if (cur_hour == alarm_hour) {
374         if (alarm_min == -1) {
375             alarm_min = cur_min;
376             if (alarm_sec == -1) {
377                 alarm_sec = cur_sec + 1;
378             } else if (cur_sec > alarm_sec) {
379                 alarm_min++;
380             }
381 
382             if (alarm_sec == SEC_PER_MIN) {
383                 alarm_sec = 0;
384                 alarm_min++;
385             }
386             /* wrap to next day, hour is not in don't care mode */
387             alarm_min %= MIN_PER_HOUR;
388         } else if (cur_min == alarm_min) {
389             if (alarm_sec == -1) {
390                 alarm_sec = cur_sec + 1;
391             }
392             /* wrap to next day, hours+minutes not in don't care mode */
393             alarm_sec %= SEC_PER_MIN;
394         }
395     }
396 
397     /* values that are still don't care fire at the next min/sec */
398     if (alarm_min == -1) {
399         alarm_min = 0;
400     }
401     if (alarm_sec == -1) {
402         alarm_sec = 0;
403     }
404 
405     /* keep values in range */
406     if (alarm_sec == SEC_PER_MIN) {
407         alarm_sec = 0;
408         alarm_min++;
409     }
410     if (alarm_min == MIN_PER_HOUR) {
411         alarm_min = 0;
412         alarm_hour++;
413     }
414     alarm_hour %= HOUR_PER_DAY;
415 
416     hour = alarm_hour - cur_hour;
417     min = hour * MIN_PER_HOUR + alarm_min - cur_min;
418     sec = min * SEC_PER_MIN + alarm_sec - cur_sec;
419     return sec <= 0 ? sec + SEC_PER_DAY : sec;
420 }
421 
422 static void rtc_update_timer(void *opaque)
423 {
424     RTCState *s = opaque;
425     int32_t irqs = REG_C_UF;
426     int32_t new_irqs;
427 
428     assert((s->cmos_data[RTC_REG_A] & 0x60) != 0x60);
429 
430     /* UIP might have been latched, update time and clear it.  */
431     rtc_update_time(s);
432     s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
433 
434     if (qemu_clock_get_ns(rtc_clock) >= s->next_alarm_time) {
435         irqs |= REG_C_AF;
436         if (s->cmos_data[RTC_REG_B] & REG_B_AIE) {
437             qemu_system_wakeup_request(QEMU_WAKEUP_REASON_RTC, NULL);
438         }
439     }
440 
441     new_irqs = irqs & ~s->cmos_data[RTC_REG_C];
442     s->cmos_data[RTC_REG_C] |= irqs;
443     if ((new_irqs & s->cmos_data[RTC_REG_B]) != 0) {
444         s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
445         qemu_irq_raise(s->irq);
446     }
447     check_update_timer(s);
448 }
449 
450 static void cmos_ioport_write(void *opaque, hwaddr addr,
451                               uint64_t data, unsigned size)
452 {
453     RTCState *s = opaque;
454     uint32_t old_period;
455     bool update_periodic_timer;
456 
457     if ((addr & 1) == 0) {
458         s->cmos_index = data & 0x7f;
459     } else {
460         CMOS_DPRINTF("cmos: write index=0x%02x val=0x%02" PRIx64 "\n",
461                      s->cmos_index, data);
462         switch(s->cmos_index) {
463         case RTC_SECONDS_ALARM:
464         case RTC_MINUTES_ALARM:
465         case RTC_HOURS_ALARM:
466             s->cmos_data[s->cmos_index] = data;
467             check_update_timer(s);
468             break;
469         case RTC_IBM_PS2_CENTURY_BYTE:
470             s->cmos_index = RTC_CENTURY;
471             /* fall through */
472         case RTC_CENTURY:
473         case RTC_SECONDS:
474         case RTC_MINUTES:
475         case RTC_HOURS:
476         case RTC_DAY_OF_WEEK:
477         case RTC_DAY_OF_MONTH:
478         case RTC_MONTH:
479         case RTC_YEAR:
480             s->cmos_data[s->cmos_index] = data;
481             /* if in set mode, do not update the time */
482             if (rtc_running(s)) {
483                 rtc_set_time(s);
484                 check_update_timer(s);
485             }
486             break;
487         case RTC_REG_A:
488             update_periodic_timer = (s->cmos_data[RTC_REG_A] ^ data) & 0x0f;
489             old_period = rtc_periodic_clock_ticks(s);
490 
491             if ((data & 0x60) == 0x60) {
492                 if (rtc_running(s)) {
493                     rtc_update_time(s);
494                 }
495                 /* What happens to UIP when divider reset is enabled is
496                  * unclear from the datasheet.  Shouldn't matter much
497                  * though.
498                  */
499                 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
500             } else if (((s->cmos_data[RTC_REG_A] & 0x60) == 0x60) &&
501                     (data & 0x70)  <= 0x20) {
502                 /* when the divider reset is removed, the first update cycle
503                  * begins one-half second later*/
504                 if (!(s->cmos_data[RTC_REG_B] & REG_B_SET)) {
505                     s->offset = 500000000;
506                     rtc_set_time(s);
507                 }
508                 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
509             }
510             /* UIP bit is read only */
511             s->cmos_data[RTC_REG_A] = (data & ~REG_A_UIP) |
512                 (s->cmos_data[RTC_REG_A] & REG_A_UIP);
513 
514             if (update_periodic_timer) {
515                 periodic_timer_update(s, qemu_clock_get_ns(rtc_clock),
516                                       old_period, true);
517             }
518 
519             check_update_timer(s);
520             break;
521         case RTC_REG_B:
522             update_periodic_timer = (s->cmos_data[RTC_REG_B] ^ data)
523                                        & REG_B_PIE;
524             old_period = rtc_periodic_clock_ticks(s);
525 
526             if (data & REG_B_SET) {
527                 /* update cmos to when the rtc was stopping */
528                 if (rtc_running(s)) {
529                     rtc_update_time(s);
530                 }
531                 /* set mode: reset UIP mode */
532                 s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;
533                 data &= ~REG_B_UIE;
534             } else {
535                 /* if disabling set mode, update the time */
536                 if ((s->cmos_data[RTC_REG_B] & REG_B_SET) &&
537                     (s->cmos_data[RTC_REG_A] & 0x70) <= 0x20) {
538                     s->offset = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;
539                     rtc_set_time(s);
540                 }
541             }
542             /* if an interrupt flag is already set when the interrupt
543              * becomes enabled, raise an interrupt immediately.  */
544             if (data & s->cmos_data[RTC_REG_C] & REG_C_MASK) {
545                 s->cmos_data[RTC_REG_C] |= REG_C_IRQF;
546                 qemu_irq_raise(s->irq);
547             } else {
548                 s->cmos_data[RTC_REG_C] &= ~REG_C_IRQF;
549                 qemu_irq_lower(s->irq);
550             }
551             s->cmos_data[RTC_REG_B] = data;
552 
553             if (update_periodic_timer) {
554                 periodic_timer_update(s, qemu_clock_get_ns(rtc_clock),
555                                       old_period, true);
556             }
557 
558             check_update_timer(s);
559             break;
560         case RTC_REG_C:
561         case RTC_REG_D:
562             /* cannot write to them */
563             break;
564         default:
565             s->cmos_data[s->cmos_index] = data;
566             break;
567         }
568     }
569 }
570 
571 static inline int rtc_to_bcd(RTCState *s, int a)
572 {
573     if (s->cmos_data[RTC_REG_B] & REG_B_DM) {
574         return a;
575     } else {
576         return ((a / 10) << 4) | (a % 10);
577     }
578 }
579 
580 static inline int rtc_from_bcd(RTCState *s, int a)
581 {
582     if ((a & 0xc0) == 0xc0) {
583         return -1;
584     }
585     if (s->cmos_data[RTC_REG_B] & REG_B_DM) {
586         return a;
587     } else {
588         return ((a >> 4) * 10) + (a & 0x0f);
589     }
590 }
591 
592 static void rtc_get_time(RTCState *s, struct tm *tm)
593 {
594     tm->tm_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS]);
595     tm->tm_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES]);
596     tm->tm_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS] & 0x7f);
597     if (!(s->cmos_data[RTC_REG_B] & REG_B_24H)) {
598         tm->tm_hour %= 12;
599         if (s->cmos_data[RTC_HOURS] & 0x80) {
600             tm->tm_hour += 12;
601         }
602     }
603     tm->tm_wday = rtc_from_bcd(s, s->cmos_data[RTC_DAY_OF_WEEK]) - 1;
604     tm->tm_mday = rtc_from_bcd(s, s->cmos_data[RTC_DAY_OF_MONTH]);
605     tm->tm_mon = rtc_from_bcd(s, s->cmos_data[RTC_MONTH]) - 1;
606     tm->tm_year =
607         rtc_from_bcd(s, s->cmos_data[RTC_YEAR]) + s->base_year +
608         rtc_from_bcd(s, s->cmos_data[RTC_CENTURY]) * 100 - 1900;
609 }
610 
611 static void rtc_set_time(RTCState *s)
612 {
613     struct tm tm;
614     g_autofree const char *qom_path = object_get_canonical_path(OBJECT(s));
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), qom_path);
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 const MemoryRegionOps cmos_ops = {
876     .read = cmos_ioport_read,
877     .write = cmos_ioport_write,
878     .impl = {
879         .min_access_size = 1,
880         .max_access_size = 1,
881     },
882     .endianness = DEVICE_LITTLE_ENDIAN,
883 };
884 
885 static void rtc_get_date(Object *obj, struct tm *current_tm, Error **errp)
886 {
887     RTCState *s = MC146818_RTC(obj);
888 
889     rtc_update_time(s);
890     rtc_get_time(s, current_tm);
891 }
892 
893 static void rtc_realizefn(DeviceState *dev, Error **errp)
894 {
895     ISADevice *isadev = ISA_DEVICE(dev);
896     RTCState *s = MC146818_RTC(dev);
897 
898     s->cmos_data[RTC_REG_A] = 0x26;
899     s->cmos_data[RTC_REG_B] = 0x02;
900     s->cmos_data[RTC_REG_C] = 0x00;
901     s->cmos_data[RTC_REG_D] = 0x80;
902 
903     /* This is for historical reasons.  The default base year qdev property
904      * was set to 2000 for most machine types before the century byte was
905      * implemented.
906      *
907      * This if statement means that the century byte will be always 0
908      * (at least until 2079...) for base_year = 1980, but will be set
909      * correctly for base_year = 2000.
910      */
911     if (s->base_year == 2000) {
912         s->base_year = 0;
913     }
914 
915     if (s->isairq >= ISA_NUM_IRQS) {
916         error_setg(errp, "Maximum value for \"irq\" is: %u", ISA_NUM_IRQS - 1);
917         return;
918     }
919 
920     rtc_set_date_from_host(isadev);
921 
922     switch (s->lost_tick_policy) {
923 #ifdef TARGET_I386
924     case LOST_TICK_POLICY_SLEW:
925         s->coalesced_timer =
926             timer_new_ns(rtc_clock, rtc_coalesced_timer, s);
927         break;
928 #endif
929     case LOST_TICK_POLICY_DISCARD:
930         break;
931     default:
932         error_setg(errp, "Invalid lost tick policy.");
933         return;
934     }
935 
936     s->periodic_timer = timer_new_ns(rtc_clock, rtc_periodic_timer, s);
937     s->update_timer = timer_new_ns(rtc_clock, rtc_update_timer, s);
938     check_update_timer(s);
939 
940     s->suspend_notifier.notify = rtc_notify_suspend;
941     qemu_register_suspend_notifier(&s->suspend_notifier);
942 
943     memory_region_init_io(&s->io, OBJECT(s), &cmos_ops, s, "rtc", 2);
944     isa_register_ioport(isadev, &s->io, RTC_ISA_BASE);
945 
946     /* register rtc 0x70 port for coalesced_pio */
947     memory_region_set_flush_coalesced(&s->io);
948     memory_region_init_io(&s->coalesced_io, OBJECT(s), &cmos_ops,
949                           s, "rtc-index", 1);
950     memory_region_add_subregion(&s->io, 0, &s->coalesced_io);
951     memory_region_add_coalescing(&s->coalesced_io, 0, 1);
952 
953     qdev_set_legacy_instance_id(dev, RTC_ISA_BASE, 3);
954 
955     object_property_add_tm(OBJECT(s), "date", rtc_get_date);
956 
957     qdev_init_gpio_out(dev, &s->irq, 1);
958     QLIST_INSERT_HEAD(&rtc_devices, s, link);
959 }
960 
961 ISADevice *mc146818_rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq)
962 {
963     DeviceState *dev;
964     ISADevice *isadev;
965     RTCState *s;
966 
967     isadev = isa_new(TYPE_MC146818_RTC);
968     dev = DEVICE(isadev);
969     s = MC146818_RTC(isadev);
970     qdev_prop_set_int32(dev, "base_year", base_year);
971     isa_realize_and_unref(isadev, bus, &error_fatal);
972     if (intercept_irq) {
973         qdev_connect_gpio_out(dev, 0, intercept_irq);
974     } else {
975         isa_connect_gpio_out(isadev, 0, s->isairq);
976     }
977 
978     object_property_add_alias(qdev_get_machine(), "rtc-time", OBJECT(isadev),
979                               "date");
980 
981     return isadev;
982 }
983 
984 static Property mc146818rtc_properties[] = {
985     DEFINE_PROP_INT32("base_year", RTCState, base_year, 1980),
986     DEFINE_PROP_UINT8("irq", RTCState, isairq, RTC_ISA_IRQ),
987     DEFINE_PROP_LOSTTICKPOLICY("lost_tick_policy", RTCState,
988                                lost_tick_policy, LOST_TICK_POLICY_DISCARD),
989     DEFINE_PROP_END_OF_LIST(),
990 };
991 
992 static void rtc_reset_enter(Object *obj, ResetType type)
993 {
994     RTCState *s = MC146818_RTC(obj);
995 
996     /* Reason: VM do suspend self will set 0xfe
997      * Reset any values other than 0xfe(Guest suspend case) */
998     if (s->cmos_data[0x0f] != 0xfe) {
999         s->cmos_data[0x0f] = 0x00;
1000     }
1001 
1002     s->cmos_data[RTC_REG_B] &= ~(REG_B_PIE | REG_B_AIE | REG_B_SQWE);
1003     s->cmos_data[RTC_REG_C] &= ~(REG_C_UF | REG_C_IRQF | REG_C_PF | REG_C_AF);
1004     check_update_timer(s);
1005 
1006 
1007     if (s->lost_tick_policy == LOST_TICK_POLICY_SLEW) {
1008         s->irq_coalesced = 0;
1009         s->irq_reinject_on_ack_count = 0;
1010     }
1011 }
1012 
1013 static void rtc_reset_hold(Object *obj)
1014 {
1015     RTCState *s = MC146818_RTC(obj);
1016 
1017     qemu_irq_lower(s->irq);
1018 }
1019 
1020 static void rtc_build_aml(ISADevice *isadev, Aml *scope)
1021 {
1022     RTCState *s = MC146818_RTC(isadev);
1023     Aml *dev;
1024     Aml *crs;
1025 
1026     /*
1027      * Reserving 8 io ports here, following what physical hardware
1028      * does, even though qemu only responds to the first two ports.
1029      */
1030     crs = aml_resource_template();
1031     aml_append(crs, aml_io(AML_DECODE16, RTC_ISA_BASE, RTC_ISA_BASE,
1032                            0x01, 0x08));
1033     aml_append(crs, aml_irq_no_flags(s->isairq));
1034 
1035     dev = aml_device("RTC");
1036     aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0B00")));
1037     aml_append(dev, aml_name_decl("_CRS", crs));
1038 
1039     aml_append(scope, dev);
1040 }
1041 
1042 static void rtc_class_initfn(ObjectClass *klass, void *data)
1043 {
1044     DeviceClass *dc = DEVICE_CLASS(klass);
1045     ResettableClass *rc = RESETTABLE_CLASS(klass);
1046     ISADeviceClass *isa = ISA_DEVICE_CLASS(klass);
1047 
1048     dc->realize = rtc_realizefn;
1049     dc->vmsd = &vmstate_rtc;
1050     rc->phases.enter = rtc_reset_enter;
1051     rc->phases.hold = rtc_reset_hold;
1052     isa->build_aml = rtc_build_aml;
1053     device_class_set_props(dc, mc146818rtc_properties);
1054     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1055 }
1056 
1057 static const TypeInfo mc146818rtc_info = {
1058     .name          = TYPE_MC146818_RTC,
1059     .parent        = TYPE_ISA_DEVICE,
1060     .instance_size = sizeof(RTCState),
1061     .class_init    = rtc_class_initfn,
1062 };
1063 
1064 static void mc146818rtc_register_types(void)
1065 {
1066     type_register_static(&mc146818rtc_info);
1067 }
1068 
1069 type_init(mc146818rtc_register_types)
1070