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