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