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