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