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