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