cpus.c 53.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * QEMU System Emulator
 *
 * Copyright (c) 2003-2008 Fabrice Bellard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/* Needed early for CONFIG_BSD etc. */
P
Peter Maydell 已提交
26
#include "qemu/osdep.h"
27
#include "qemu-common.h"
28
#include "qemu/config-file.h"
29
#include "cpu.h"
30
#include "monitor/monitor.h"
W
Wenchao Xia 已提交
31
#include "qapi/qmp/qerror.h"
32
#include "qemu/error-report.h"
33
#include "sysemu/sysemu.h"
34
#include "sysemu/block-backend.h"
35
#include "exec/gdbstub.h"
36
#include "sysemu/dma.h"
37
#include "sysemu/hw_accel.h"
38
#include "sysemu/kvm.h"
39
#include "sysemu/hax.h"
L
Luiz Capitulino 已提交
40
#include "qmp-commands.h"
41
#include "exec/exec-all.h"
42

43
#include "qemu/thread.h"
44 45
#include "sysemu/cpus.h"
#include "sysemu/qtest.h"
46 47
#include "qemu/main-loop.h"
#include "qemu/bitmap.h"
48
#include "qemu/seqlock.h"
49
#include "tcg.h"
W
Wenchao Xia 已提交
50
#include "qapi-event.h"
51
#include "hw/nmi.h"
52
#include "sysemu/replay.h"
J
Jan Kiszka 已提交
53

54 55 56 57
#ifdef CONFIG_LINUX

#include <sys/prctl.h>

M
Marcelo Tosatti 已提交
58 59 60 61
#ifndef PR_MCE_KILL
#define PR_MCE_KILL 33
#endif

62 63 64 65 66 67 68 69 70 71
#ifndef PR_MCE_KILL_SET
#define PR_MCE_KILL_SET 1
#endif

#ifndef PR_MCE_KILL_EARLY
#define PR_MCE_KILL_EARLY 1
#endif

#endif /* CONFIG_LINUX */

72 73
int64_t max_delay;
int64_t max_advance;
74

75 76 77 78 79 80 81 82
/* vcpu throttling controls */
static QEMUTimer *throttle_timer;
static unsigned int throttle_percentage;

#define CPU_THROTTLE_PCT_MIN 1
#define CPU_THROTTLE_PCT_MAX 99
#define CPU_THROTTLE_TIMESLICE_NS 10000000

83 84 85 86 87
bool cpu_is_stopped(CPUState *cpu)
{
    return cpu->stopped || !runstate_is_running();
}

88
static bool cpu_thread_is_idle(CPUState *cpu)
89
{
90
    if (cpu->stop || cpu->queued_work_first) {
91 92
        return false;
    }
93
    if (cpu_is_stopped(cpu)) {
94 95
        return true;
    }
96
    if (!cpu->halted || cpu_has_work(cpu) ||
97
        kvm_halt_in_kernel()) {
98 99 100 101 102 103 104
        return false;
    }
    return true;
}

static bool all_cpu_threads_idle(void)
{
105
    CPUState *cpu;
106

A
Andreas Färber 已提交
107
    CPU_FOREACH(cpu) {
108
        if (!cpu_thread_is_idle(cpu)) {
109 110 111 112 113 114
            return false;
        }
    }
    return true;
}

P
Paolo Bonzini 已提交
115 116 117
/***********************************************************/
/* guest cycle counter */

118 119
/* Protected by TimersState seqlock */

120
static bool icount_sleep = true;
121
static int64_t vm_clock_warp_start = -1;
P
Paolo Bonzini 已提交
122 123 124 125
/* Conversion factor from emulated instructions to virtual clock ticks.  */
static int icount_time_shift;
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
#define MAX_ICOUNT_SHIFT 10
126

P
Paolo Bonzini 已提交
127 128 129 130 131
static QEMUTimer *icount_rt_timer;
static QEMUTimer *icount_vm_timer;
static QEMUTimer *icount_warp_timer;

typedef struct TimersState {
132
    /* Protected by BQL.  */
P
Paolo Bonzini 已提交
133 134
    int64_t cpu_ticks_prev;
    int64_t cpu_ticks_offset;
135 136 137 138 139

    /* cpu_clock_offset can be read out of BQL, so protect it with
     * this lock.
     */
    QemuSeqLock vm_clock_seqlock;
P
Paolo Bonzini 已提交
140 141 142
    int64_t cpu_clock_offset;
    int32_t cpu_ticks_enabled;
    int64_t dummy;
143 144 145 146 147

    /* Compensate for varying guest execution speed.  */
    int64_t qemu_icount_bias;
    /* Only written by TCG thread */
    int64_t qemu_icount;
P
Paolo Bonzini 已提交
148 149
} TimersState;

L
Liu Ping Fan 已提交
150
static TimersState timers_state;
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
bool mttcg_enabled;

/*
 * We default to false if we know other options have been enabled
 * which are currently incompatible with MTTCG. Otherwise when each
 * guest (target) has been updated to support:
 *   - atomic instructions
 *   - memory ordering primitives (barriers)
 * they can set the appropriate CONFIG flags in ${target}-softmmu.mak
 *
 * Once a guest architecture has been converted to the new primitives
 * there are two remaining limitations to check.
 *
 * - The guest can't be oversized (e.g. 64 bit guest on 32 bit host)
 * - The host must have a stronger memory order than the guest
 *
 * It may be possible in future to support strong guests on weak hosts
 * but that will require tagging all load/stores in a guest with their
 * implicit memory order requirements which would likely slow things
 * down a lot.
 */

static bool check_tcg_memory_orders_compatible(void)
{
#if defined(TCG_GUEST_DEFAULT_MO) && defined(TCG_TARGET_DEFAULT_MO)
    return (TCG_GUEST_DEFAULT_MO & ~TCG_TARGET_DEFAULT_MO) == 0;
#else
    return false;
#endif
}

static bool default_mttcg_enabled(void)
{
184
    if (use_icount || TCG_OVERSIZED_GUEST) {
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        return false;
    } else {
#ifdef TARGET_SUPPORTS_MTTCG
        return check_tcg_memory_orders_compatible();
#else
        return false;
#endif
    }
}

void qemu_tcg_configure(QemuOpts *opts, Error **errp)
{
    const char *t = qemu_opt_get(opts, "thread");
    if (t) {
        if (strcmp(t, "multi") == 0) {
            if (TCG_OVERSIZED_GUEST) {
                error_setg(errp, "No MTTCG when guest word size > hosts");
202 203
            } else if (use_icount) {
                error_setg(errp, "No MTTCG when icount is enabled");
204
            } else {
N
Nikunj A Dadhania 已提交
205
#ifndef TARGET_SUPPORTS_MTTCG
206 207 208
                error_report("Guest not yet converted to MTTCG - "
                             "you may get unexpected results");
#endif
209 210 211
                if (!check_tcg_memory_orders_compatible()) {
                    error_report("Guest expects a stronger memory ordering "
                                 "than the host provides");
212
                    error_printf("This may cause strange/hard to debug errors\n");
213 214 215 216 217 218 219 220 221 222 223 224
                }
                mttcg_enabled = true;
            }
        } else if (strcmp(t, "single") == 0) {
            mttcg_enabled = false;
        } else {
            error_setg(errp, "Invalid 'thread' setting %s", t);
        }
    } else {
        mttcg_enabled = default_mttcg_enabled();
    }
}
P
Paolo Bonzini 已提交
225

226 227 228 229 230 231 232 233 234
/* The current number of executed instructions is based on what we
 * originally budgeted minus the current state of the decrementing
 * icount counters in extra/u16.low.
 */
static int64_t cpu_get_icount_executed(CPUState *cpu)
{
    return cpu->icount_budget - (cpu->icount_decr.u16.low + cpu->icount_extra);
}

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
/*
 * Update the global shared timer_state.qemu_icount to take into
 * account executed instructions. This is done by the TCG vCPU
 * thread so the main-loop can see time has moved forward.
 */
void cpu_update_icount(CPUState *cpu)
{
    int64_t executed = cpu_get_icount_executed(cpu);
    cpu->icount_budget -= executed;

#ifdef CONFIG_ATOMIC64
    atomic_set__nocheck(&timers_state.qemu_icount,
                        atomic_read__nocheck(&timers_state.qemu_icount) +
                        executed);
#else /* FIXME: we need 64bit atomics to do this safely */
    timers_state.qemu_icount += executed;
#endif
}

254
int64_t cpu_get_icount_raw(void)
P
Paolo Bonzini 已提交
255 256
{
    int64_t icount;
257
    CPUState *cpu = current_cpu;
P
Paolo Bonzini 已提交
258

259
    icount = atomic_read(&timers_state.qemu_icount);
260
    if (cpu && cpu->running) {
261
        if (!cpu->can_do_io) {
262 263
            fprintf(stderr, "Bad icount read\n");
            exit(1);
P
Paolo Bonzini 已提交
264
        }
265 266
        /* Take into account what has run */
        icount += cpu_get_icount_executed(cpu);
P
Paolo Bonzini 已提交
267
    }
268 269 270 271 272 273 274
    return icount;
}

/* Return the virtual CPU time, based on the instruction counter.  */
static int64_t cpu_get_icount_locked(void)
{
    int64_t icount = cpu_get_icount_raw();
275
    return timers_state.qemu_icount_bias + cpu_icount_to_ns(icount);
P
Paolo Bonzini 已提交
276 277
}

P
Paolo Bonzini 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290
int64_t cpu_get_icount(void)
{
    int64_t icount;
    unsigned start;

    do {
        start = seqlock_read_begin(&timers_state.vm_clock_seqlock);
        icount = cpu_get_icount_locked();
    } while (seqlock_read_retry(&timers_state.vm_clock_seqlock, start));

    return icount;
}

291 292 293 294 295
int64_t cpu_icount_to_ns(int64_t icount)
{
    return icount << icount_time_shift;
}

C
Cao jin 已提交
296 297 298 299 300 301
/* return the time elapsed in VM between vm_start and vm_stop.  Unless
 * icount is active, cpu_get_ticks() uses units of the host CPU cycle
 * counter.
 *
 * Caller must hold the BQL
 */
P
Paolo Bonzini 已提交
302 303
int64_t cpu_get_ticks(void)
{
P
Paolo Bonzini 已提交
304 305
    int64_t ticks;

P
Paolo Bonzini 已提交
306 307 308
    if (use_icount) {
        return cpu_get_icount();
    }
P
Paolo Bonzini 已提交
309 310 311

    ticks = timers_state.cpu_ticks_offset;
    if (timers_state.cpu_ticks_enabled) {
312
        ticks += cpu_get_host_ticks();
P
Paolo Bonzini 已提交
313 314 315 316 317 318 319
    }

    if (timers_state.cpu_ticks_prev > ticks) {
        /* Note: non increasing ticks may happen if the host uses
           software suspend */
        timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
        ticks = timers_state.cpu_ticks_prev;
P
Paolo Bonzini 已提交
320
    }
P
Paolo Bonzini 已提交
321 322 323

    timers_state.cpu_ticks_prev = ticks;
    return ticks;
P
Paolo Bonzini 已提交
324 325
}

326
static int64_t cpu_get_clock_locked(void)
P
Paolo Bonzini 已提交
327
{
328
    int64_t time;
329

330
    time = timers_state.cpu_clock_offset;
P
Paolo Bonzini 已提交
331
    if (timers_state.cpu_ticks_enabled) {
332
        time += get_clock();
P
Paolo Bonzini 已提交
333
    }
334

335
    return time;
336 337
}

C
Cao jin 已提交
338
/* Return the monotonic time elapsed in VM, i.e.,
339 340
 * the time between vm_start and vm_stop
 */
341 342 343 344 345 346 347 348 349 350 351
int64_t cpu_get_clock(void)
{
    int64_t ti;
    unsigned start;

    do {
        start = seqlock_read_begin(&timers_state.vm_clock_seqlock);
        ti = cpu_get_clock_locked();
    } while (seqlock_read_retry(&timers_state.vm_clock_seqlock, start));

    return ti;
P
Paolo Bonzini 已提交
352 353
}

354
/* enable cpu_get_ticks()
355
 * Caller must hold BQL which serves as mutex for vm_clock_seqlock.
356
 */
P
Paolo Bonzini 已提交
357 358
void cpu_enable_ticks(void)
{
359
    /* Here, the really thing protected by seqlock is cpu_clock_offset. */
360
    seqlock_write_begin(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
361
    if (!timers_state.cpu_ticks_enabled) {
362
        timers_state.cpu_ticks_offset -= cpu_get_host_ticks();
P
Paolo Bonzini 已提交
363 364 365
        timers_state.cpu_clock_offset -= get_clock();
        timers_state.cpu_ticks_enabled = 1;
    }
366
    seqlock_write_end(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
367 368 369
}

/* disable cpu_get_ticks() : the clock is stopped. You must not call
370
 * cpu_get_ticks() after that.
371
 * Caller must hold BQL which serves as mutex for vm_clock_seqlock.
372
 */
P
Paolo Bonzini 已提交
373 374
void cpu_disable_ticks(void)
{
375
    /* Here, the really thing protected by seqlock is cpu_clock_offset. */
376
    seqlock_write_begin(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
377
    if (timers_state.cpu_ticks_enabled) {
378
        timers_state.cpu_ticks_offset += cpu_get_host_ticks();
379
        timers_state.cpu_clock_offset = cpu_get_clock_locked();
P
Paolo Bonzini 已提交
380 381
        timers_state.cpu_ticks_enabled = 0;
    }
382
    seqlock_write_end(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
383 384 385 386 387 388
}

/* Correlation between real and virtual time is always going to be
   fairly approximate, so ignore small variation.
   When the guest is idle real and virtual time will be aligned in
   the IO wait loop.  */
389
#define ICOUNT_WOBBLE (NANOSECONDS_PER_SECOND / 10)
P
Paolo Bonzini 已提交
390 391 392 393 394 395

static void icount_adjust(void)
{
    int64_t cur_time;
    int64_t cur_icount;
    int64_t delta;
396 397

    /* Protected by TimersState mutex.  */
P
Paolo Bonzini 已提交
398
    static int64_t last_delta;
399

P
Paolo Bonzini 已提交
400 401 402 403
    /* If the VM is not running, then do nothing.  */
    if (!runstate_is_running()) {
        return;
    }
404

405
    seqlock_write_begin(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
406 407
    cur_time = cpu_get_clock_locked();
    cur_icount = cpu_get_icount_locked();
408

P
Paolo Bonzini 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    delta = cur_icount - cur_time;
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
    if (delta > 0
        && last_delta + ICOUNT_WOBBLE < delta * 2
        && icount_time_shift > 0) {
        /* The guest is getting too far ahead.  Slow time down.  */
        icount_time_shift--;
    }
    if (delta < 0
        && last_delta - ICOUNT_WOBBLE > delta * 2
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
        /* The guest is getting too far behind.  Speed time up.  */
        icount_time_shift++;
    }
    last_delta = delta;
424 425
    timers_state.qemu_icount_bias = cur_icount
                              - (timers_state.qemu_icount << icount_time_shift);
426
    seqlock_write_end(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
427 428 429 430
}

static void icount_adjust_rt(void *opaque)
{
431
    timer_mod(icount_rt_timer,
432
              qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);
P
Paolo Bonzini 已提交
433 434 435 436 437
    icount_adjust();
}

static void icount_adjust_vm(void *opaque)
{
438 439
    timer_mod(icount_vm_timer,
                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
440
                   NANOSECONDS_PER_SECOND / 10);
P
Paolo Bonzini 已提交
441 442 443 444 445 446 447 448
    icount_adjust();
}

static int64_t qemu_icount_round(int64_t count)
{
    return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
}

449
static void icount_warp_rt(void)
P
Paolo Bonzini 已提交
450
{
451 452 453
    unsigned seq;
    int64_t warp_start;

P
Paolo Bonzini 已提交
454 455 456
    /* The icount_warp_timer is rescheduled soon after vm_clock_warp_start
     * changes from -1 to another value, so the race here is okay.
     */
457 458 459 460 461 462
    do {
        seq = seqlock_read_begin(&timers_state.vm_clock_seqlock);
        warp_start = vm_clock_warp_start;
    } while (seqlock_read_retry(&timers_state.vm_clock_seqlock, seq));

    if (warp_start == -1) {
P
Paolo Bonzini 已提交
463 464 465
        return;
    }

466
    seqlock_write_begin(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
467
    if (runstate_is_running()) {
468 469
        int64_t clock = REPLAY_CLOCK(REPLAY_CLOCK_VIRTUAL_RT,
                                     cpu_get_clock_locked());
P
Paolo Bonzini 已提交
470 471 472 473
        int64_t warp_delta;

        warp_delta = clock - vm_clock_warp_start;
        if (use_icount == 2) {
P
Paolo Bonzini 已提交
474
            /*
475
             * In adaptive mode, do not let QEMU_CLOCK_VIRTUAL run too
P
Paolo Bonzini 已提交
476 477
             * far ahead of real time.
             */
P
Paolo Bonzini 已提交
478
            int64_t cur_icount = cpu_get_icount_locked();
479
            int64_t delta = clock - cur_icount;
P
Paolo Bonzini 已提交
480
            warp_delta = MIN(warp_delta, delta);
P
Paolo Bonzini 已提交
481
        }
482
        timers_state.qemu_icount_bias += warp_delta;
P
Paolo Bonzini 已提交
483 484
    }
    vm_clock_warp_start = -1;
485
    seqlock_write_end(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
486 487 488 489

    if (qemu_clock_expired(QEMU_CLOCK_VIRTUAL)) {
        qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
    }
P
Paolo Bonzini 已提交
490 491
}

P
Pavel Dovgalyuk 已提交
492
static void icount_timer_cb(void *opaque)
493
{
P
Pavel Dovgalyuk 已提交
494 495 496 497
    /* No need for a checkpoint because the timer already synchronizes
     * with CHECKPOINT_CLOCK_VIRTUAL_RT.
     */
    icount_warp_rt();
498 499
}

P
Paolo Bonzini 已提交
500 501
void qtest_clock_warp(int64_t dest)
{
502
    int64_t clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
503
    AioContext *aio_context;
P
Paolo Bonzini 已提交
504
    assert(qtest_enabled());
505
    aio_context = qemu_get_aio_context();
P
Paolo Bonzini 已提交
506
    while (clock < dest) {
507
        int64_t deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
508
        int64_t warp = qemu_soonest_timeout(dest - clock, deadline);
509

510
        seqlock_write_begin(&timers_state.vm_clock_seqlock);
511
        timers_state.qemu_icount_bias += warp;
512
        seqlock_write_end(&timers_state.vm_clock_seqlock);
P
Paolo Bonzini 已提交
513

514
        qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL);
515
        timerlist_run_timers(aio_context->tlg.tl[QEMU_CLOCK_VIRTUAL]);
516
        clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
P
Paolo Bonzini 已提交
517
    }
518
    qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
P
Paolo Bonzini 已提交
519 520
}

P
Pavel Dovgalyuk 已提交
521
void qemu_start_warp_timer(void)
P
Paolo Bonzini 已提交
522
{
523
    int64_t clock;
P
Paolo Bonzini 已提交
524 525
    int64_t deadline;

P
Pavel Dovgalyuk 已提交
526
    if (!use_icount) {
P
Paolo Bonzini 已提交
527 528 529
        return;
    }

P
Pavel Dovgalyuk 已提交
530 531 532 533 534 535 536 537
    /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
     * do not fire, so computing the deadline does not make sense.
     */
    if (!runstate_is_running()) {
        return;
    }

    /* warp clock deterministically in record/replay mode */
P
Pavel Dovgalyuk 已提交
538
    if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_START)) {
P
Pavel Dovgalyuk 已提交
539 540 541
        return;
    }

542
    if (!all_cpu_threads_idle()) {
P
Paolo Bonzini 已提交
543 544 545
        return;
    }

P
Paolo Bonzini 已提交
546 547
    if (qtest_enabled()) {
        /* When testing, qtest commands advance icount.  */
P
Pavel Dovgalyuk 已提交
548
        return;
P
Paolo Bonzini 已提交
549 550
    }

551
    /* We want to use the earliest deadline from ALL vm_clocks */
552
    clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);
553
    deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
554
    if (deadline < 0) {
555 556 557 558 559
        static bool notified;
        if (!icount_sleep && !notified) {
            error_report("WARNING: icount sleep disabled and no active timers");
            notified = true;
        }
560
        return;
561 562
    }

P
Paolo Bonzini 已提交
563 564
    if (deadline > 0) {
        /*
565
         * Ensure QEMU_CLOCK_VIRTUAL proceeds even when the virtual CPU goes to
P
Paolo Bonzini 已提交
566 567 568
         * sleep.  Otherwise, the CPU might be waiting for a future timer
         * interrupt to wake it up, but the interrupt never comes because
         * the vCPU isn't running any insns and thus doesn't advance the
569
         * QEMU_CLOCK_VIRTUAL.
P
Paolo Bonzini 已提交
570
         */
571 572 573 574 575 576 577 578
        if (!icount_sleep) {
            /*
             * We never let VCPUs sleep in no sleep icount mode.
             * If there is a pending QEMU_CLOCK_VIRTUAL timer we just advance
             * to the next QEMU_CLOCK_VIRTUAL event and notify it.
             * It is useful when we want a deterministic execution time,
             * isolated from host latencies.
             */
579
            seqlock_write_begin(&timers_state.vm_clock_seqlock);
580
            timers_state.qemu_icount_bias += deadline;
581
            seqlock_write_end(&timers_state.vm_clock_seqlock);
582 583 584 585 586 587 588 589 590 591
            qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
        } else {
            /*
             * We do stop VCPUs and only advance QEMU_CLOCK_VIRTUAL after some
             * "real" time, (related to the time left until the next event) has
             * passed. The QEMU_CLOCK_VIRTUAL_RT clock will do this.
             * This avoids that the warps are visible externally; for example,
             * you will not be sending network packets continuously instead of
             * every 100ms.
             */
592
            seqlock_write_begin(&timers_state.vm_clock_seqlock);
593 594 595
            if (vm_clock_warp_start == -1 || vm_clock_warp_start > clock) {
                vm_clock_warp_start = clock;
            }
596
            seqlock_write_end(&timers_state.vm_clock_seqlock);
597
            timer_mod_anticipate(icount_warp_timer, clock + deadline);
598
        }
599
    } else if (deadline == 0) {
600
        qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
P
Paolo Bonzini 已提交
601 602 603
    }
}

P
Pavel Dovgalyuk 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
static void qemu_account_warp_timer(void)
{
    if (!use_icount || !icount_sleep) {
        return;
    }

    /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
     * do not fire, so computing the deadline does not make sense.
     */
    if (!runstate_is_running()) {
        return;
    }

    /* warp clock deterministically in record/replay mode */
    if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_ACCOUNT)) {
        return;
    }

    timer_del(icount_warp_timer);
    icount_warp_rt();
}

626 627 628 629 630 631 632 633 634 635 636 637
static bool icount_state_needed(void *opaque)
{
    return use_icount;
}

/*
 * This is a subsection for icount migration.
 */
static const VMStateDescription icount_vmstate_timers = {
    .name = "timer/icount",
    .version_id = 1,
    .minimum_version_id = 1,
638
    .needed = icount_state_needed,
639 640 641 642 643 644 645
    .fields = (VMStateField[]) {
        VMSTATE_INT64(qemu_icount_bias, TimersState),
        VMSTATE_INT64(qemu_icount, TimersState),
        VMSTATE_END_OF_LIST()
    }
};

P
Paolo Bonzini 已提交
646 647 648 649
static const VMStateDescription vmstate_timers = {
    .name = "timer",
    .version_id = 2,
    .minimum_version_id = 1,
650
    .fields = (VMStateField[]) {
P
Paolo Bonzini 已提交
651 652 653 654
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
        VMSTATE_INT64(dummy, TimersState),
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
        VMSTATE_END_OF_LIST()
655
    },
656 657 658
    .subsections = (const VMStateDescription*[]) {
        &icount_vmstate_timers,
        NULL
P
Paolo Bonzini 已提交
659 660 661
    }
};

662
static void cpu_throttle_thread(CPUState *cpu, run_on_cpu_data opaque)
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
{
    double pct;
    double throttle_ratio;
    long sleeptime_ns;

    if (!cpu_throttle_get_percentage()) {
        return;
    }

    pct = (double)cpu_throttle_get_percentage()/100;
    throttle_ratio = pct / (1 - pct);
    sleeptime_ns = (long)(throttle_ratio * CPU_THROTTLE_TIMESLICE_NS);

    qemu_mutex_unlock_iothread();
    atomic_set(&cpu->throttle_thread_scheduled, 0);
    g_usleep(sleeptime_ns / 1000); /* Convert ns to us for usleep call */
    qemu_mutex_lock_iothread();
}

static void cpu_throttle_timer_tick(void *opaque)
{
    CPUState *cpu;
    double pct;

    /* Stop the timer if needed */
    if (!cpu_throttle_get_percentage()) {
        return;
    }
    CPU_FOREACH(cpu) {
        if (!atomic_xchg(&cpu->throttle_thread_scheduled, 1)) {
693 694
            async_run_on_cpu(cpu, cpu_throttle_thread,
                             RUN_ON_CPU_NULL);
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
        }
    }

    pct = (double)cpu_throttle_get_percentage()/100;
    timer_mod(throttle_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT) +
                                   CPU_THROTTLE_TIMESLICE_NS / (1-pct));
}

void cpu_throttle_set(int new_throttle_pct)
{
    /* Ensure throttle percentage is within valid range */
    new_throttle_pct = MIN(new_throttle_pct, CPU_THROTTLE_PCT_MAX);
    new_throttle_pct = MAX(new_throttle_pct, CPU_THROTTLE_PCT_MIN);

    atomic_set(&throttle_percentage, new_throttle_pct);

    timer_mod(throttle_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT) +
                                       CPU_THROTTLE_TIMESLICE_NS);
}

void cpu_throttle_stop(void)
{
    atomic_set(&throttle_percentage, 0);
}

bool cpu_throttle_active(void)
{
    return (cpu_throttle_get_percentage() != 0);
}

int cpu_throttle_get_percentage(void)
{
    return atomic_read(&throttle_percentage);
}

730 731
void cpu_ticks_init(void)
{
E
Emilio G. Cota 已提交
732
    seqlock_init(&timers_state.vm_clock_seqlock);
733
    vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
734 735
    throttle_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,
                                           cpu_throttle_timer_tick, NULL);
736 737
}

738
void configure_icount(QemuOpts *opts, Error **errp)
P
Paolo Bonzini 已提交
739
{
740
    const char *option;
741
    char *rem_str = NULL;
742 743

    option = qemu_opt_get(opts, "shift");
P
Paolo Bonzini 已提交
744
    if (!option) {
745 746 747
        if (qemu_opt_get(opts, "align") != NULL) {
            error_setg(errp, "Please specify shift option when using align");
        }
P
Paolo Bonzini 已提交
748 749
        return;
    }
750 751

    icount_sleep = qemu_opt_get_bool(opts, "sleep", true);
752 753
    if (icount_sleep) {
        icount_warp_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,
P
Pavel Dovgalyuk 已提交
754
                                         icount_timer_cb, NULL);
755
    }
756

757
    icount_align_option = qemu_opt_get_bool(opts, "align", false);
758 759

    if (icount_align_option && !icount_sleep) {
760
        error_setg(errp, "align=on and sleep=off are incompatible");
761
    }
P
Paolo Bonzini 已提交
762
    if (strcmp(option, "auto") != 0) {
763 764 765 766 767
        errno = 0;
        icount_time_shift = strtol(option, &rem_str, 0);
        if (errno != 0 || *rem_str != '\0' || !strlen(option)) {
            error_setg(errp, "icount: Invalid shift value");
        }
P
Paolo Bonzini 已提交
768 769
        use_icount = 1;
        return;
770 771
    } else if (icount_align_option) {
        error_setg(errp, "shift=auto and align=on are incompatible");
772
    } else if (!icount_sleep) {
773
        error_setg(errp, "shift=auto and sleep=off are incompatible");
P
Paolo Bonzini 已提交
774 775 776 777 778 779 780 781 782 783 784 785 786
    }

    use_icount = 2;

    /* 125MIPS seems a reasonable initial guess at the guest speed.
       It will be corrected fairly quickly anyway.  */
    icount_time_shift = 3;

    /* Have both realtime and virtual time triggers for speed adjustment.
       The realtime trigger catches emulated time passing too slowly,
       the virtual time trigger catches emulated time passing too fast.
       Realtime triggers occur even when idle, so use them less frequently
       than VM triggers.  */
787 788
    icount_rt_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL_RT,
                                   icount_adjust_rt, NULL);
789
    timer_mod(icount_rt_timer,
790
                   qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);
791 792 793 794
    icount_vm_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
                                        icount_adjust_vm, NULL);
    timer_mod(icount_vm_timer,
                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
795
                   NANOSECONDS_PER_SECOND / 10);
P
Paolo Bonzini 已提交
796 797
}

798 799 800 801 802 803 804 805 806 807 808 809 810
/***********************************************************/
/* TCG vCPU kick timer
 *
 * The kick timer is responsible for moving single threaded vCPU
 * emulation on to the next vCPU. If more than one vCPU is running a
 * timer event with force a cpu->exit so the next vCPU can get
 * scheduled.
 *
 * The timer is removed if all vCPUs are idle and restarted again once
 * idleness is complete.
 */

static QEMUTimer *tcg_kick_vcpu_timer;
811
static CPUState *tcg_current_rr_cpu;
812 813 814 815 816 817 818 819

#define TCG_KICK_PERIOD (NANOSECONDS_PER_SECOND / 10)

static inline int64_t qemu_tcg_next_kick(void)
{
    return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + TCG_KICK_PERIOD;
}

820 821 822 823 824 825 826 827 828 829 830 831
/* Kick the currently round-robin scheduled vCPU */
static void qemu_cpu_kick_rr_cpu(void)
{
    CPUState *cpu;
    do {
        cpu = atomic_mb_read(&tcg_current_rr_cpu);
        if (cpu) {
            cpu_exit(cpu);
        }
    } while (cpu != atomic_mb_read(&tcg_current_rr_cpu));
}

832 833 834 835
static void do_nothing(CPUState *cpu, run_on_cpu_data unused)
{
}

836 837
void qemu_timer_notify_cb(void *opaque, QEMUClockType type)
{
838 839 840 841 842 843 844 845 846 847 848 849 850
    if (!use_icount || type != QEMU_CLOCK_VIRTUAL) {
        qemu_notify_event();
        return;
    }

    if (!qemu_in_vcpu_thread() && first_cpu) {
        /* qemu_cpu_kick is not enough to kick a halted CPU out of
         * qemu_tcg_wait_io_event.  async_run_on_cpu, instead,
         * causes cpu_thread_is_idle to return false.  This way,
         * handle_icount_deadline can run.
         */
        async_run_on_cpu(first_cpu, do_nothing, RUN_ON_CPU_NULL);
    }
851 852
}

853 854 855
static void kick_tcg_thread(void *opaque)
{
    timer_mod(tcg_kick_vcpu_timer, qemu_tcg_next_kick());
856
    qemu_cpu_kick_rr_cpu();
857 858 859 860
}

static void start_tcg_kick_timer(void)
{
A
Alex Bennée 已提交
861
    if (!mttcg_enabled && !tcg_kick_vcpu_timer && CPU_NEXT(first_cpu)) {
862 863 864 865 866 867 868 869 870 871 872 873 874 875
        tcg_kick_vcpu_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
                                           kick_tcg_thread, NULL);
        timer_mod(tcg_kick_vcpu_timer, qemu_tcg_next_kick());
    }
}

static void stop_tcg_kick_timer(void)
{
    if (tcg_kick_vcpu_timer) {
        timer_del(tcg_kick_vcpu_timer);
        tcg_kick_vcpu_timer = NULL;
    }
}

876 877 878 879
/***********************************************************/
void hw_error(const char *fmt, ...)
{
    va_list ap;
880
    CPUState *cpu;
881 882 883 884 885

    va_start(ap, fmt);
    fprintf(stderr, "qemu: hardware error: ");
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
A
Andreas Färber 已提交
886
    CPU_FOREACH(cpu) {
887
        fprintf(stderr, "CPU #%d:\n", cpu->cpu_index);
888
        cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU);
889 890 891 892 893 894 895
    }
    va_end(ap);
    abort();
}

void cpu_synchronize_all_states(void)
{
896
    CPUState *cpu;
897

A
Andreas Färber 已提交
898
    CPU_FOREACH(cpu) {
899
        cpu_synchronize_state(cpu);
900 901 902 903 904
    }
}

void cpu_synchronize_all_post_reset(void)
{
905
    CPUState *cpu;
906

A
Andreas Färber 已提交
907
    CPU_FOREACH(cpu) {
908
        cpu_synchronize_post_reset(cpu);
909 910 911 912 913
    }
}

void cpu_synchronize_all_post_init(void)
{
914
    CPUState *cpu;
915

A
Andreas Färber 已提交
916
    CPU_FOREACH(cpu) {
917
        cpu_synchronize_post_init(cpu);
918 919 920
    }
}

921
static int do_vm_stop(RunState state)
922
{
923 924
    int ret = 0;

925
    if (runstate_is_running()) {
926 927
        cpu_disable_ticks();
        pause_all_vcpus();
928
        runstate_set(state);
929
        vm_state_notify(0, state);
W
Wenchao Xia 已提交
930
        qapi_event_send_stop(&error_abort);
931
    }
932

933
    bdrv_drain_all();
934
    replay_disable_events();
935
    ret = bdrv_flush_all();
936

937
    return ret;
938 939
}

940
static bool cpu_can_run(CPUState *cpu)
941
{
A
Andreas Färber 已提交
942
    if (cpu->stop) {
943
        return false;
944
    }
945
    if (cpu_is_stopped(cpu)) {
946
        return false;
947
    }
948
    return true;
949 950
}

951
static void cpu_handle_guest_debug(CPUState *cpu)
952
{
953
    gdb_set_stop_cpu(cpu);
954
    qemu_system_debug_request();
955
    cpu->stopped = true;
956 957
}

958 959 960 961 962 963 964 965 966 967 968 969
#ifdef CONFIG_LINUX
static void sigbus_reraise(void)
{
    sigset_t set;
    struct sigaction action;

    memset(&action, 0, sizeof(action));
    action.sa_handler = SIG_DFL;
    if (!sigaction(SIGBUS, &action, NULL)) {
        raise(SIGBUS);
        sigemptyset(&set);
        sigaddset(&set, SIGBUS);
970
        pthread_sigmask(SIG_UNBLOCK, &set, NULL);
971 972 973 974 975
    }
    perror("Failed to re-raise SIGBUS!\n");
    abort();
}

976
static void sigbus_handler(int n, siginfo_t *siginfo, void *ctx)
977
{
978 979 980 981
    if (siginfo->si_code != BUS_MCEERR_AO && siginfo->si_code != BUS_MCEERR_AR) {
        sigbus_reraise();
    }

982 983 984 985 986 987 988 989 990 991
    if (current_cpu) {
        /* Called asynchronously in VCPU thread.  */
        if (kvm_on_sigbus_vcpu(current_cpu, siginfo->si_code, siginfo->si_addr)) {
            sigbus_reraise();
        }
    } else {
        /* Called synchronously (via signalfd) in main thread.  */
        if (kvm_on_sigbus(siginfo->si_code, siginfo->si_addr)) {
            sigbus_reraise();
        }
992 993 994 995 996 997 998 999 1000
    }
}

static void qemu_init_sigbus(void)
{
    struct sigaction action;

    memset(&action, 0, sizeof(action));
    action.sa_flags = SA_SIGINFO;
1001
    action.sa_sigaction = sigbus_handler;
1002 1003 1004 1005 1006 1007 1008 1009
    sigaction(SIGBUS, &action, NULL);

    prctl(PR_MCE_KILL, PR_MCE_KILL_SET, PR_MCE_KILL_EARLY, 0, 0);
}
#else /* !CONFIG_LINUX */
static void qemu_init_sigbus(void)
{
}
1010
#endif /* !CONFIG_LINUX */
1011

1012
static QemuMutex qemu_global_mutex;
1013 1014 1015 1016 1017 1018 1019 1020

static QemuThread io_thread;

/* cpu creation */
static QemuCond qemu_cpu_cond;
/* system init */
static QemuCond qemu_pause_cond;

P
Paolo Bonzini 已提交
1021
void qemu_init_cpu_loop(void)
1022
{
1023
    qemu_init_sigbus();
1024 1025
    qemu_cond_init(&qemu_cpu_cond);
    qemu_cond_init(&qemu_pause_cond);
1026 1027
    qemu_mutex_init(&qemu_global_mutex);

J
Jan Kiszka 已提交
1028
    qemu_thread_get_self(&io_thread);
1029 1030
}

1031
void run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data)
M
Marcelo Tosatti 已提交
1032
{
1033
    do_run_on_cpu(cpu, func, data, &qemu_global_mutex);
C
Chegu Vinod 已提交
1034 1035
}

G
Gu Zheng 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
static void qemu_kvm_destroy_vcpu(CPUState *cpu)
{
    if (kvm_destroy_vcpu(cpu) < 0) {
        error_report("kvm_destroy_vcpu failed");
        exit(EXIT_FAILURE);
    }
}

static void qemu_tcg_destroy_vcpu(CPUState *cpu)
{
}

1048
static void qemu_wait_io_event_common(CPUState *cpu)
1049
{
A
Alex Bennée 已提交
1050
    atomic_mb_set(&cpu->thread_kicked, false);
A
Andreas Färber 已提交
1051 1052
    if (cpu->stop) {
        cpu->stop = false;
1053
        cpu->stopped = true;
1054
        qemu_cond_broadcast(&qemu_pause_cond);
1055
    }
1056
    process_queued_cpu_work(cpu);
A
Alex Bennée 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065
}

static bool qemu_tcg_should_sleep(CPUState *cpu)
{
    if (mttcg_enabled) {
        return cpu_thread_is_idle(cpu);
    } else {
        return all_cpu_threads_idle();
    }
1066 1067
}

1068
static void qemu_tcg_wait_io_event(CPUState *cpu)
1069
{
A
Alex Bennée 已提交
1070
    while (qemu_tcg_should_sleep(cpu)) {
1071
        stop_tcg_kick_timer();
1072
        qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
1073
    }
1074

1075 1076
    start_tcg_kick_timer();

A
Alex Bennée 已提交
1077
    qemu_wait_io_event_common(cpu);
1078 1079
}

1080
static void qemu_kvm_wait_io_event(CPUState *cpu)
1081
{
1082
    while (cpu_thread_is_idle(cpu)) {
A
Andreas Färber 已提交
1083
        qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
1084
    }
1085

1086
    qemu_wait_io_event_common(cpu);
1087 1088
}

1089
static void *qemu_kvm_cpu_thread_fn(void *arg)
1090
{
1091
    CPUState *cpu = arg;
J
Jan Kiszka 已提交
1092
    int r;
1093

1094 1095
    rcu_register_thread();

1096
    qemu_mutex_lock_iothread();
1097
    qemu_thread_get_self(cpu->thread);
A
Andreas Färber 已提交
1098
    cpu->thread_id = qemu_get_thread_id();
1099
    cpu->can_do_io = 1;
1100
    current_cpu = cpu;
1101

1102
    r = kvm_init_vcpu(cpu);
J
Jan Kiszka 已提交
1103 1104 1105 1106
    if (r < 0) {
        fprintf(stderr, "kvm_init_vcpu failed: %s\n", strerror(-r));
        exit(1);
    }
1107

1108
    kvm_init_cpu_signals(cpu);
1109 1110

    /* signal CPU creation */
1111
    cpu->created = true;
1112 1113
    qemu_cond_signal(&qemu_cpu_cond);

G
Gu Zheng 已提交
1114
    do {
1115
        if (cpu_can_run(cpu)) {
1116
            r = kvm_cpu_exec(cpu);
1117
            if (r == EXCP_DEBUG) {
1118
                cpu_handle_guest_debug(cpu);
1119
            }
1120
        }
1121
        qemu_kvm_wait_io_event(cpu);
G
Gu Zheng 已提交
1122
    } while (!cpu->unplug || cpu_can_run(cpu));
1123

G
Gu Zheng 已提交
1124
    qemu_kvm_destroy_vcpu(cpu);
1125 1126
    cpu->created = false;
    qemu_cond_signal(&qemu_cpu_cond);
G
Gu Zheng 已提交
1127
    qemu_mutex_unlock_iothread();
1128 1129 1130
    return NULL;
}

A
Anthony Liguori 已提交
1131 1132 1133 1134 1135 1136
static void *qemu_dummy_cpu_thread_fn(void *arg)
{
#ifdef _WIN32
    fprintf(stderr, "qtest is not supported under Windows\n");
    exit(1);
#else
1137
    CPUState *cpu = arg;
A
Anthony Liguori 已提交
1138 1139 1140
    sigset_t waitset;
    int r;

1141 1142
    rcu_register_thread();

A
Anthony Liguori 已提交
1143
    qemu_mutex_lock_iothread();
1144
    qemu_thread_get_self(cpu->thread);
A
Andreas Färber 已提交
1145
    cpu->thread_id = qemu_get_thread_id();
1146
    cpu->can_do_io = 1;
A
Alex Bennée 已提交
1147
    current_cpu = cpu;
A
Anthony Liguori 已提交
1148 1149 1150 1151 1152

    sigemptyset(&waitset);
    sigaddset(&waitset, SIG_IPI);

    /* signal CPU creation */
1153
    cpu->created = true;
A
Anthony Liguori 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    qemu_cond_signal(&qemu_cpu_cond);

    while (1) {
        qemu_mutex_unlock_iothread();
        do {
            int sig;
            r = sigwait(&waitset, &sig);
        } while (r == -1 && (errno == EAGAIN || errno == EINTR));
        if (r == -1) {
            perror("sigwait");
            exit(1);
        }
        qemu_mutex_lock_iothread();
1167
        qemu_wait_io_event_common(cpu);
A
Anthony Liguori 已提交
1168 1169 1170 1171 1172 1173
    }

    return NULL;
#endif
}

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
static int64_t tcg_get_icount_limit(void)
{
    int64_t deadline;

    if (replay_mode != REPLAY_MODE_PLAY) {
        deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

        /* Maintain prior (possibly buggy) behaviour where if no deadline
         * was set (as there is no QEMU_CLOCK_VIRTUAL timer) or it is more than
         * INT32_MAX nanoseconds ahead, we still use INT32_MAX
         * nanoseconds.
         */
        if ((deadline < 0) || (deadline > INT32_MAX)) {
            deadline = INT32_MAX;
        }

        return qemu_icount_round(deadline);
    } else {
        return replay_get_instructions();
    }
}

1196 1197
static void handle_icount_deadline(void)
{
1198
    assert(qemu_in_vcpu_thread());
1199 1200 1201 1202 1203
    if (use_icount) {
        int64_t deadline =
            qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

        if (deadline == 0) {
1204
            /* Wake up other AioContexts.  */
1205
            qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
1206
            qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL);
1207 1208 1209 1210
        }
    }
}

1211
static void prepare_icount_for_run(CPUState *cpu)
1212 1213 1214 1215
{
    if (use_icount) {
        int64_t count;
        int decr;
1216 1217 1218 1219 1220 1221 1222 1223 1224

        /* These should always be cleared by process_icount_data after
         * each vCPU execution. However u16.high can be raised
         * asynchronously by cpu_exit/cpu_interrupt/tcg_handle_interrupt
         */
        g_assert(cpu->icount_decr.u16.low == 0);
        g_assert(cpu->icount_extra == 0);


1225
        count = tcg_get_icount_limit();
1226

1227 1228 1229 1230
        /* To calculate what we have executed so far we need to know
         * what we originally budgeted to run this cycle */
        cpu->icount_budget = count;

1231 1232 1233 1234 1235
        decr = (count > 0xffff) ? 0xffff : count;
        count -= decr;
        cpu->icount_decr.u16.low = decr;
        cpu->icount_extra = count;
    }
1236 1237 1238 1239
}

static void process_icount_data(CPUState *cpu)
{
1240
    if (use_icount) {
1241
        /* Account for executed instructions */
1242
        cpu_update_icount(cpu);
1243 1244 1245

        /* Reset the counters */
        cpu->icount_decr.u16.low = 0;
1246
        cpu->icount_extra = 0;
1247 1248
        cpu->icount_budget = 0;

1249 1250
        replay_account_executed_instructions();
    }
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
}


static int tcg_cpu_exec(CPUState *cpu)
{
    int ret;
#ifdef CONFIG_PROFILER
    int64_t ti;
#endif

#ifdef CONFIG_PROFILER
    ti = profile_getclock();
#endif
    qemu_mutex_unlock_iothread();
    cpu_exec_start(cpu);
    ret = cpu_exec(cpu);
    cpu_exec_end(cpu);
    qemu_mutex_lock_iothread();
#ifdef CONFIG_PROFILER
    tcg_time += profile_getclock() - ti;
#endif
1272 1273 1274
    return ret;
}

A
Alex Bennée 已提交
1275 1276 1277 1278
/* Destroy any remaining vCPUs which have been unplugged and have
 * finished running
 */
static void deal_with_unplugged_cpus(void)
1279
{
A
Alex Bennée 已提交
1280
    CPUState *cpu;
1281

A
Alex Bennée 已提交
1282 1283 1284 1285 1286
    CPU_FOREACH(cpu) {
        if (cpu->unplug && !cpu_can_run(cpu)) {
            qemu_tcg_destroy_vcpu(cpu);
            cpu->created = false;
            qemu_cond_signal(&qemu_cpu_cond);
1287 1288 1289 1290
            break;
        }
    }
}
J
Jan Kiszka 已提交
1291

1292 1293 1294 1295 1296 1297 1298 1299 1300
/* Single-threaded TCG
 *
 * In the single-threaded case each vCPU is simulated in turn. If
 * there is more than a single vCPU we create a simple timer to kick
 * the vCPU and ensure we don't get stuck in a tight loop in one vCPU.
 * This is done explicitly rather than relying on side-effects
 * elsewhere.
 */

A
Alex Bennée 已提交
1301
static void *qemu_tcg_rr_cpu_thread_fn(void *arg)
1302
{
1303
    CPUState *cpu = arg;
1304

1305 1306
    rcu_register_thread();

1307
    qemu_mutex_lock_iothread();
1308
    qemu_thread_get_self(cpu->thread);
1309

1310 1311 1312
    CPU_FOREACH(cpu) {
        cpu->thread_id = qemu_get_thread_id();
        cpu->created = true;
1313
        cpu->can_do_io = 1;
1314
    }
1315 1316
    qemu_cond_signal(&qemu_cpu_cond);

1317
    /* wait for initial kick-off after machine start */
1318
    while (first_cpu->stopped) {
1319
        qemu_cond_wait(first_cpu->halt_cond, &qemu_global_mutex);
1320 1321

        /* process any pending work */
A
Andreas Färber 已提交
1322
        CPU_FOREACH(cpu) {
A
Alex Bennée 已提交
1323
            current_cpu = cpu;
1324
            qemu_wait_io_event_common(cpu);
1325
        }
1326
    }
1327

1328 1329
    start_tcg_kick_timer();

A
Alex Bennée 已提交
1330 1331
    cpu = first_cpu;

A
Alex Bennée 已提交
1332 1333 1334
    /* process any pending work */
    cpu->exit_request = 1;

1335
    while (1) {
A
Alex Bennée 已提交
1336 1337 1338
        /* Account partial waits to QEMU_CLOCK_VIRTUAL.  */
        qemu_account_warp_timer();

1339 1340 1341 1342 1343
        /* Run the timers here.  This is much more efficient than
         * waking up the I/O thread and waiting for completion.
         */
        handle_icount_deadline();

A
Alex Bennée 已提交
1344 1345 1346 1347
        if (!cpu) {
            cpu = first_cpu;
        }

A
Alex Bennée 已提交
1348 1349
        while (cpu && !cpu->queued_work_first && !cpu->exit_request) {

1350
            atomic_mb_set(&tcg_current_rr_cpu, cpu);
A
Alex Bennée 已提交
1351
            current_cpu = cpu;
A
Alex Bennée 已提交
1352 1353 1354 1355 1356 1357

            qemu_clock_enable(QEMU_CLOCK_VIRTUAL,
                              (cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);

            if (cpu_can_run(cpu)) {
                int r;
1358 1359 1360

                prepare_icount_for_run(cpu);

A
Alex Bennée 已提交
1361
                r = tcg_cpu_exec(cpu);
1362 1363 1364

                process_icount_data(cpu);

A
Alex Bennée 已提交
1365 1366 1367
                if (r == EXCP_DEBUG) {
                    cpu_handle_guest_debug(cpu);
                    break;
1368 1369 1370 1371 1372
                } else if (r == EXCP_ATOMIC) {
                    qemu_mutex_unlock_iothread();
                    cpu_exec_step_atomic(cpu);
                    qemu_mutex_lock_iothread();
                    break;
A
Alex Bennée 已提交
1373
                }
A
Alex Bennée 已提交
1374
            } else if (cpu->stop) {
A
Alex Bennée 已提交
1375 1376 1377 1378 1379 1380
                if (cpu->unplug) {
                    cpu = CPU_NEXT(cpu);
                }
                break;
            }

A
Alex Bennée 已提交
1381 1382 1383
            cpu = CPU_NEXT(cpu);
        } /* while (cpu && !cpu->exit_request).. */

1384 1385
        /* Does not need atomic_mb_set because a spurious wakeup is okay.  */
        atomic_set(&tcg_current_rr_cpu, NULL);
A
Alex Bennée 已提交
1386

A
Alex Bennée 已提交
1387 1388 1389
        if (cpu && cpu->exit_request) {
            atomic_mb_set(&cpu->exit_request, 0);
        }
1390

A
Alex Bennée 已提交
1391
        qemu_tcg_wait_io_event(cpu ? cpu : QTAILQ_FIRST(&cpus));
A
Alex Bennée 已提交
1392
        deal_with_unplugged_cpus();
1393 1394 1395 1396 1397
    }

    return NULL;
}

1398 1399 1400 1401
static void *qemu_hax_cpu_thread_fn(void *arg)
{
    CPUState *cpu = arg;
    int r;
V
Vincent Palatin 已提交
1402 1403

    qemu_mutex_lock_iothread();
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    qemu_thread_get_self(cpu->thread);

    cpu->thread_id = qemu_get_thread_id();
    cpu->created = true;
    cpu->halted = 0;
    current_cpu = cpu;

    hax_init_vcpu(cpu);
    qemu_cond_signal(&qemu_cpu_cond);

    while (1) {
        if (cpu_can_run(cpu)) {
            r = hax_smp_cpu_exec(cpu);
            if (r == EXCP_DEBUG) {
                cpu_handle_guest_debug(cpu);
            }
        }

        while (cpu_thread_is_idle(cpu)) {
            qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
        }
#ifdef _WIN32
        SleepEx(0, TRUE);
#endif
        qemu_wait_io_event_common(cpu);
    }
    return NULL;
}

#ifdef _WIN32
static void CALLBACK dummy_apc_func(ULONG_PTR unused)
{
}
#endif

A
Alex Bennée 已提交
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
/* Multi-threaded TCG
 *
 * In the multi-threaded case each vCPU has its own thread. The TLS
 * variable current_cpu can be used deep in the code to find the
 * current CPUState for a given thread.
 */

static void *qemu_tcg_cpu_thread_fn(void *arg)
{
    CPUState *cpu = arg;

1450 1451
    g_assert(!use_icount);

A
Alex Bennée 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
    rcu_register_thread();

    qemu_mutex_lock_iothread();
    qemu_thread_get_self(cpu->thread);

    cpu->thread_id = qemu_get_thread_id();
    cpu->created = true;
    cpu->can_do_io = 1;
    current_cpu = cpu;
    qemu_cond_signal(&qemu_cpu_cond);

    /* process any pending work */
    cpu->exit_request = 1;

    while (1) {
        if (cpu_can_run(cpu)) {
            int r;
            r = tcg_cpu_exec(cpu);
            switch (r) {
            case EXCP_DEBUG:
                cpu_handle_guest_debug(cpu);
                break;
            case EXCP_HALTED:
                /* during start-up the vCPU is reset and the thread is
                 * kicked several times. If we don't ensure we go back
                 * to sleep in the halted state we won't cleanly
                 * start-up when the vCPU is enabled.
                 *
                 * cpu->halted should ensure we sleep in wait_io_event
                 */
                g_assert(cpu->halted);
                break;
1484 1485 1486 1487
            case EXCP_ATOMIC:
                qemu_mutex_unlock_iothread();
                cpu_exec_step_atomic(cpu);
                qemu_mutex_lock_iothread();
A
Alex Bennée 已提交
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
            default:
                /* Ignore everything else? */
                break;
            }
        }

        atomic_mb_set(&cpu->exit_request, 0);
        qemu_tcg_wait_io_event(cpu);
    }

    return NULL;
}

1501
static void qemu_cpu_kick_thread(CPUState *cpu)
P
Paolo Bonzini 已提交
1502 1503 1504 1505
{
#ifndef _WIN32
    int err;

P
Paolo Bonzini 已提交
1506 1507
    if (cpu->thread_kicked) {
        return;
1508
    }
P
Paolo Bonzini 已提交
1509
    cpu->thread_kicked = true;
1510
    err = pthread_kill(cpu->thread->thread, SIG_IPI);
P
Paolo Bonzini 已提交
1511 1512 1513 1514 1515
    if (err) {
        fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
        exit(1);
    }
#else /* _WIN32 */
1516 1517 1518 1519 1520 1521 1522
    if (!qemu_cpu_is_self(cpu)) {
        if (!QueueUserAPC(dummy_apc_func, cpu->hThread, 0)) {
            fprintf(stderr, "%s: QueueUserAPC failed with error %lu\n",
                    __func__, GetLastError());
            exit(1);
        }
    }
P
Paolo Bonzini 已提交
1523 1524
#endif
}
1525

1526
void qemu_cpu_kick(CPUState *cpu)
1527
{
A
Andreas Färber 已提交
1528
    qemu_cond_broadcast(cpu->halt_cond);
P
Paolo Bonzini 已提交
1529
    if (tcg_enabled()) {
1530
        cpu_exit(cpu);
A
Alex Bennée 已提交
1531
        /* NOP unless doing single-thread RR */
1532
        qemu_cpu_kick_rr_cpu();
P
Paolo Bonzini 已提交
1533
    } else {
1534 1535 1536 1537 1538 1539 1540
        if (hax_enabled()) {
            /*
             * FIXME: race condition with the exit_request check in
             * hax_vcpu_hax_exec
             */
            cpu->exit_request = 1;
        }
P
Paolo Bonzini 已提交
1541 1542
        qemu_cpu_kick_thread(cpu);
    }
1543 1544
}

1545
void qemu_cpu_kick_self(void)
1546
{
1547
    assert(current_cpu);
1548
    qemu_cpu_kick_thread(current_cpu);
1549 1550
}

1551
bool qemu_cpu_is_self(CPUState *cpu)
1552
{
1553
    return qemu_thread_is_self(cpu->thread);
1554 1555
}

1556
bool qemu_in_vcpu_thread(void)
J
Juan Quintela 已提交
1557
{
1558
    return current_cpu && qemu_cpu_is_self(current_cpu);
J
Juan Quintela 已提交
1559 1560
}

1561 1562 1563 1564 1565 1566 1567
static __thread bool iothread_locked = false;

bool qemu_mutex_iothread_locked(void)
{
    return iothread_locked;
}

1568 1569
void qemu_mutex_lock_iothread(void)
{
1570 1571
    g_assert(!qemu_mutex_iothread_locked());
    qemu_mutex_lock(&qemu_global_mutex);
1572
    iothread_locked = true;
1573 1574 1575 1576
}

void qemu_mutex_unlock_iothread(void)
{
1577
    g_assert(qemu_mutex_iothread_locked());
1578
    iothread_locked = false;
1579 1580 1581
    qemu_mutex_unlock(&qemu_global_mutex);
}

1582
static bool all_vcpus_paused(void)
1583
{
A
Andreas Färber 已提交
1584
    CPUState *cpu;
1585

A
Andreas Färber 已提交
1586
    CPU_FOREACH(cpu) {
1587
        if (!cpu->stopped) {
1588
            return false;
1589
        }
1590 1591
    }

1592
    return true;
1593 1594 1595 1596
}

void pause_all_vcpus(void)
{
A
Andreas Färber 已提交
1597
    CPUState *cpu;
1598

1599
    qemu_clock_enable(QEMU_CLOCK_VIRTUAL, false);
A
Andreas Färber 已提交
1600
    CPU_FOREACH(cpu) {
1601 1602
        cpu->stop = true;
        qemu_cpu_kick(cpu);
1603 1604
    }

J
Juan Quintela 已提交
1605
    if (qemu_in_vcpu_thread()) {
1606 1607 1608
        cpu_stop_current();
    }

1609
    while (!all_vcpus_paused()) {
1610
        qemu_cond_wait(&qemu_pause_cond, &qemu_global_mutex);
A
Andreas Färber 已提交
1611
        CPU_FOREACH(cpu) {
1612
            qemu_cpu_kick(cpu);
1613 1614 1615 1616
        }
    }
}

1617 1618 1619 1620 1621 1622 1623
void cpu_resume(CPUState *cpu)
{
    cpu->stop = false;
    cpu->stopped = false;
    qemu_cpu_kick(cpu);
}

1624 1625
void resume_all_vcpus(void)
{
A
Andreas Färber 已提交
1626
    CPUState *cpu;
1627

1628
    qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
A
Andreas Färber 已提交
1629
    CPU_FOREACH(cpu) {
1630
        cpu_resume(cpu);
1631 1632 1633
    }
}

G
Gu Zheng 已提交
1634 1635 1636 1637 1638 1639 1640
void cpu_remove(CPUState *cpu)
{
    cpu->stop = true;
    cpu->unplug = true;
    qemu_cpu_kick(cpu);
}

1641 1642 1643 1644 1645 1646 1647 1648
void cpu_remove_sync(CPUState *cpu)
{
    cpu_remove(cpu);
    while (cpu->created) {
        qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
    }
}

1649 1650 1651
/* For temporary buffers for forming a name */
#define VCPU_THREAD_NAME_SIZE 16

1652
static void qemu_tcg_init_vcpu(CPUState *cpu)
1653
{
1654
    char thread_name[VCPU_THREAD_NAME_SIZE];
A
Alex Bennée 已提交
1655 1656
    static QemuCond *single_tcg_halt_cond;
    static QemuThread *single_tcg_cpu_thread;
1657

A
Alex Bennée 已提交
1658
    if (qemu_tcg_mttcg_enabled() || !single_tcg_cpu_thread) {
1659
        cpu->thread = g_malloc0(sizeof(QemuThread));
A
Andreas Färber 已提交
1660 1661
        cpu->halt_cond = g_malloc0(sizeof(QemuCond));
        qemu_cond_init(cpu->halt_cond);
A
Alex Bennée 已提交
1662 1663 1664 1665 1666

        if (qemu_tcg_mttcg_enabled()) {
            /* create a thread per vCPU with TCG (MTTCG) */
            parallel_cpus = true;
            snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/TCG",
1667
                 cpu->cpu_index);
A
Alex Bennée 已提交
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681

            qemu_thread_create(cpu->thread, thread_name, qemu_tcg_cpu_thread_fn,
                               cpu, QEMU_THREAD_JOINABLE);

        } else {
            /* share a single thread for all cpus with TCG */
            snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "ALL CPUs/TCG");
            qemu_thread_create(cpu->thread, thread_name,
                               qemu_tcg_rr_cpu_thread_fn,
                               cpu, QEMU_THREAD_JOINABLE);

            single_tcg_halt_cond = cpu->halt_cond;
            single_tcg_cpu_thread = cpu->thread;
        }
P
Paolo Bonzini 已提交
1682
#ifdef _WIN32
1683
        cpu->hThread = qemu_thread_get_handle(cpu->thread);
P
Paolo Bonzini 已提交
1684
#endif
1685
        while (!cpu->created) {
1686
            qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
1687
        }
1688
    } else {
A
Alex Bennée 已提交
1689 1690 1691
        /* For non-MTTCG cases we share the thread */
        cpu->thread = single_tcg_cpu_thread;
        cpu->halt_cond = single_tcg_halt_cond;
1692 1693 1694
    }
}

1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
static void qemu_hax_start_vcpu(CPUState *cpu)
{
    char thread_name[VCPU_THREAD_NAME_SIZE];

    cpu->thread = g_malloc0(sizeof(QemuThread));
    cpu->halt_cond = g_malloc0(sizeof(QemuCond));
    qemu_cond_init(cpu->halt_cond);

    snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/HAX",
             cpu->cpu_index);
    qemu_thread_create(cpu->thread, thread_name, qemu_hax_cpu_thread_fn,
                       cpu, QEMU_THREAD_JOINABLE);
#ifdef _WIN32
    cpu->hThread = qemu_thread_get_handle(cpu->thread);
#endif
    while (!cpu->created) {
        qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
    }
}

1715
static void qemu_kvm_start_vcpu(CPUState *cpu)
1716
{
1717 1718
    char thread_name[VCPU_THREAD_NAME_SIZE];

1719
    cpu->thread = g_malloc0(sizeof(QemuThread));
A
Andreas Färber 已提交
1720 1721
    cpu->halt_cond = g_malloc0(sizeof(QemuCond));
    qemu_cond_init(cpu->halt_cond);
1722 1723 1724 1725
    snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/KVM",
             cpu->cpu_index);
    qemu_thread_create(cpu->thread, thread_name, qemu_kvm_cpu_thread_fn,
                       cpu, QEMU_THREAD_JOINABLE);
1726
    while (!cpu->created) {
1727
        qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
1728
    }
1729 1730
}

1731
static void qemu_dummy_start_vcpu(CPUState *cpu)
A
Anthony Liguori 已提交
1732
{
1733 1734
    char thread_name[VCPU_THREAD_NAME_SIZE];

1735
    cpu->thread = g_malloc0(sizeof(QemuThread));
A
Andreas Färber 已提交
1736 1737
    cpu->halt_cond = g_malloc0(sizeof(QemuCond));
    qemu_cond_init(cpu->halt_cond);
1738 1739 1740
    snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/DUMMY",
             cpu->cpu_index);
    qemu_thread_create(cpu->thread, thread_name, qemu_dummy_cpu_thread_fn, cpu,
A
Anthony Liguori 已提交
1741
                       QEMU_THREAD_JOINABLE);
1742
    while (!cpu->created) {
A
Anthony Liguori 已提交
1743 1744 1745 1746
        qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
    }
}

1747
void qemu_init_vcpu(CPUState *cpu)
1748
{
1749 1750
    cpu->nr_cores = smp_cores;
    cpu->nr_threads = smp_threads;
1751
    cpu->stopped = true;
1752 1753 1754 1755 1756

    if (!cpu->as) {
        /* If the target cpu hasn't set up any address spaces itself,
         * give it the default one.
         */
1757 1758
        AddressSpace *as = address_space_init_shareable(cpu->memory,
                                                        "cpu-memory");
1759
        cpu->num_ases = 1;
1760
        cpu_address_space_init(cpu, as, 0);
1761 1762
    }

1763
    if (kvm_enabled()) {
1764
        qemu_kvm_start_vcpu(cpu);
1765 1766
    } else if (hax_enabled()) {
        qemu_hax_start_vcpu(cpu);
A
Anthony Liguori 已提交
1767
    } else if (tcg_enabled()) {
1768
        qemu_tcg_init_vcpu(cpu);
A
Anthony Liguori 已提交
1769
    } else {
1770
        qemu_dummy_start_vcpu(cpu);
1771
    }
1772 1773
}

1774
void cpu_stop_current(void)
1775
{
1776 1777 1778 1779
    if (current_cpu) {
        current_cpu->stop = false;
        current_cpu->stopped = true;
        cpu_exit(current_cpu);
1780
        qemu_cond_broadcast(&qemu_pause_cond);
1781
    }
1782 1783
}

1784
int vm_stop(RunState state)
1785
{
J
Juan Quintela 已提交
1786
    if (qemu_in_vcpu_thread()) {
1787
        qemu_system_vmstop_request_prepare();
1788
        qemu_system_vmstop_request(state);
1789 1790 1791 1792
        /*
         * FIXME: should not return to device code in case
         * vm_stop() has been requested.
         */
1793
        cpu_stop_current();
1794
        return 0;
1795
    }
1796 1797

    return do_vm_stop(state);
1798 1799
}

C
Claudio Imbrenda 已提交
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
/**
 * Prepare for (re)starting the VM.
 * Returns -1 if the vCPUs are not to be restarted (e.g. if they are already
 * running or in case of an error condition), 0 otherwise.
 */
int vm_prepare_start(void)
{
    RunState requested;
    int res = 0;

    qemu_vmstop_requested(&requested);
    if (runstate_is_running() && requested == RUN_STATE__MAX) {
        return -1;
    }

    /* Ensure that a STOP/RESUME pair of events is emitted if a
     * vmstop request was pending.  The BLOCK_IO_ERROR event, for
     * example, according to documentation is always followed by
     * the STOP event.
     */
    if (runstate_is_running()) {
        qapi_event_send_stop(&error_abort);
        res = -1;
    } else {
        replay_enable_events();
        cpu_enable_ticks();
        runstate_set(RUN_STATE_RUNNING);
        vm_state_notify(1, RUN_STATE_RUNNING);
    }

    /* We are sending this now, but the CPUs will be resumed shortly later */
    qapi_event_send_resume(&error_abort);
    return res;
}

void vm_start(void)
{
    if (!vm_prepare_start()) {
        resume_all_vcpus();
    }
}

1842 1843
/* does a state transition even if the VM is already stopped,
   current state is forgotten forever */
1844
int vm_stop_force_state(RunState state)
1845 1846
{
    if (runstate_is_running()) {
1847
        return vm_stop(state);
1848 1849
    } else {
        runstate_set(state);
1850 1851

        bdrv_drain_all();
1852 1853
        /* Make sure to return an error if the flush in a previous vm_stop()
         * failed. */
1854
        return bdrv_flush_all();
1855 1856 1857
    }
}

1858
void list_cpus(FILE *f, fprintf_function cpu_fprintf, const char *optarg)
1859 1860
{
    /* XXX: implement xxx_cpu_list for targets that still miss it */
P
Peter Maydell 已提交
1861 1862
#if defined(cpu_list)
    cpu_list(f, cpu_fprintf);
1863 1864
#endif
}
L
Luiz Capitulino 已提交
1865 1866 1867 1868

CpuInfoList *qmp_query_cpus(Error **errp)
{
    CpuInfoList *head = NULL, *cur_item = NULL;
1869
    CPUState *cpu;
L
Luiz Capitulino 已提交
1870

A
Andreas Färber 已提交
1871
    CPU_FOREACH(cpu) {
L
Luiz Capitulino 已提交
1872
        CpuInfoList *info;
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
#if defined(TARGET_I386)
        X86CPU *x86_cpu = X86_CPU(cpu);
        CPUX86State *env = &x86_cpu->env;
#elif defined(TARGET_PPC)
        PowerPCCPU *ppc_cpu = POWERPC_CPU(cpu);
        CPUPPCState *env = &ppc_cpu->env;
#elif defined(TARGET_SPARC)
        SPARCCPU *sparc_cpu = SPARC_CPU(cpu);
        CPUSPARCState *env = &sparc_cpu->env;
#elif defined(TARGET_MIPS)
        MIPSCPU *mips_cpu = MIPS_CPU(cpu);
        CPUMIPSState *env = &mips_cpu->env;
1885 1886 1887
#elif defined(TARGET_TRICORE)
        TriCoreCPU *tricore_cpu = TRICORE_CPU(cpu);
        CPUTriCoreState *env = &tricore_cpu->env;
1888
#endif
L
Luiz Capitulino 已提交
1889

1890
        cpu_synchronize_state(cpu);
L
Luiz Capitulino 已提交
1891 1892 1893

        info = g_malloc0(sizeof(*info));
        info->value = g_malloc0(sizeof(*info->value));
1894
        info->value->CPU = cpu->cpu_index;
1895
        info->value->current = (cpu == first_cpu);
1896
        info->value->halted = cpu->halted;
1897
        info->value->qom_path = object_get_canonical_path(OBJECT(cpu));
A
Andreas Färber 已提交
1898
        info->value->thread_id = cpu->thread_id;
L
Luiz Capitulino 已提交
1899
#if defined(TARGET_I386)
E
Eric Blake 已提交
1900
        info->value->arch = CPU_INFO_ARCH_X86;
1901
        info->value->u.x86.pc = env->eip + env->segs[R_CS].base;
L
Luiz Capitulino 已提交
1902
#elif defined(TARGET_PPC)
E
Eric Blake 已提交
1903
        info->value->arch = CPU_INFO_ARCH_PPC;
1904
        info->value->u.ppc.nip = env->nip;
L
Luiz Capitulino 已提交
1905
#elif defined(TARGET_SPARC)
E
Eric Blake 已提交
1906
        info->value->arch = CPU_INFO_ARCH_SPARC;
1907 1908
        info->value->u.q_sparc.pc = env->pc;
        info->value->u.q_sparc.npc = env->npc;
L
Luiz Capitulino 已提交
1909
#elif defined(TARGET_MIPS)
E
Eric Blake 已提交
1910
        info->value->arch = CPU_INFO_ARCH_MIPS;
1911
        info->value->u.q_mips.PC = env->active_tc.PC;
1912
#elif defined(TARGET_TRICORE)
E
Eric Blake 已提交
1913
        info->value->arch = CPU_INFO_ARCH_TRICORE;
1914
        info->value->u.tricore.PC = env->PC;
E
Eric Blake 已提交
1915 1916
#else
        info->value->arch = CPU_INFO_ARCH_OTHER;
L
Luiz Capitulino 已提交
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
#endif

        /* XXX: waiting for the qapi to support GSList */
        if (!cur_item) {
            head = cur_item = info;
        } else {
            cur_item->next = info;
            cur_item = info;
        }
    }

    return head;
}
L
Luiz Capitulino 已提交
1930 1931 1932 1933 1934 1935

void qmp_memsave(int64_t addr, int64_t size, const char *filename,
                 bool has_cpu, int64_t cpu_index, Error **errp)
{
    FILE *f;
    uint32_t l;
1936
    CPUState *cpu;
L
Luiz Capitulino 已提交
1937
    uint8_t buf[1024];
1938
    int64_t orig_addr = addr, orig_size = size;
L
Luiz Capitulino 已提交
1939 1940 1941 1942 1943

    if (!has_cpu) {
        cpu_index = 0;
    }

1944 1945
    cpu = qemu_get_cpu(cpu_index);
    if (cpu == NULL) {
1946 1947
        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
                   "a CPU number");
L
Luiz Capitulino 已提交
1948 1949 1950 1951 1952
        return;
    }

    f = fopen(filename, "wb");
    if (!f) {
1953
        error_setg_file_open(errp, errno, filename);
L
Luiz Capitulino 已提交
1954 1955 1956 1957 1958 1959 1960
        return;
    }

    while (size != 0) {
        l = sizeof(buf);
        if (l > size)
            l = size;
1961
        if (cpu_memory_rw_debug(cpu, addr, buf, l, 0) != 0) {
1962 1963
            error_setg(errp, "Invalid addr 0x%016" PRIx64 "/size %" PRId64
                             " specified", orig_addr, orig_size);
1964 1965
            goto exit;
        }
L
Luiz Capitulino 已提交
1966
        if (fwrite(buf, 1, l, f) != l) {
1967
            error_setg(errp, QERR_IO_ERROR);
L
Luiz Capitulino 已提交
1968 1969 1970 1971 1972 1973 1974 1975 1976
            goto exit;
        }
        addr += l;
        size -= l;
    }

exit:
    fclose(f);
}
L
Luiz Capitulino 已提交
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986

void qmp_pmemsave(int64_t addr, int64_t size, const char *filename,
                  Error **errp)
{
    FILE *f;
    uint32_t l;
    uint8_t buf[1024];

    f = fopen(filename, "wb");
    if (!f) {
1987
        error_setg_file_open(errp, errno, filename);
L
Luiz Capitulino 已提交
1988 1989 1990 1991 1992 1993 1994
        return;
    }

    while (size != 0) {
        l = sizeof(buf);
        if (l > size)
            l = size;
1995
        cpu_physical_memory_read(addr, buf, l);
L
Luiz Capitulino 已提交
1996
        if (fwrite(buf, 1, l, f) != l) {
1997
            error_setg(errp, QERR_IO_ERROR);
L
Luiz Capitulino 已提交
1998 1999 2000 2001 2002 2003 2004 2005 2006
            goto exit;
        }
        addr += l;
        size -= l;
    }

exit:
    fclose(f);
}
L
Luiz Capitulino 已提交
2007 2008 2009

void qmp_inject_nmi(Error **errp)
{
2010
    nmi_monitor_handle(monitor_get_cpu_index(), errp);
L
Luiz Capitulino 已提交
2011
}
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028

void dump_drift_info(FILE *f, fprintf_function cpu_fprintf)
{
    if (!use_icount) {
        return;
    }

    cpu_fprintf(f, "Host - Guest clock  %"PRIi64" ms\n",
                (cpu_get_clock() - cpu_get_icount())/SCALE_MS);
    if (icount_align_option) {
        cpu_fprintf(f, "Max guest delay     %"PRIi64" ms\n", -max_delay/SCALE_MS);
        cpu_fprintf(f, "Max guest advance   %"PRIi64" ms\n", max_advance/SCALE_MS);
    } else {
        cpu_fprintf(f, "Max guest delay     NA\n");
        cpu_fprintf(f, "Max guest advance   NA\n");
    }
}