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