base.cc revision 9652:553ad940c9db
1/*
2 * Copyright (c) 2012 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Authors: Andreas Sandberg
38 */
39
40#include <linux/kvm.h>
41#include <sys/ioctl.h>
42#include <sys/mman.h>
43#include <unistd.h>
44
45#include <cerrno>
46#include <csignal>
47#include <ostream>
48
49#include "arch/utility.hh"
50#include "cpu/kvm/base.hh"
51#include "debug/Kvm.hh"
52#include "debug/KvmIO.hh"
53#include "debug/KvmRun.hh"
54#include "params/BaseKvmCPU.hh"
55#include "sim/process.hh"
56#include "sim/system.hh"
57
58/* Used by some KVM macros */
59#define PAGE_SIZE pageSize
60
61volatile bool timerOverflowed = false;
62
63static void
64onTimerOverflow(int signo, siginfo_t *si, void *data)
65{
66    timerOverflowed = true;
67}
68
69BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
70    : BaseCPU(params),
71      vm(*params->kvmVM),
72      _status(Idle),
73      dataPort(name() + ".dcache_port", this),
74      instPort(name() + ".icache_port", this),
75      threadContextDirty(true),
76      kvmStateDirty(false),
77      vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
78      _kvmRun(NULL), mmioRing(NULL),
79      pageSize(sysconf(_SC_PAGE_SIZE)),
80      tickEvent(*this),
81      hostFactor(params->hostFactor)
82{
83    if (pageSize == -1)
84        panic("KVM: Failed to determine host page size (%i)\n",
85              errno);
86
87    thread = new SimpleThread(this, 0, params->system,
88                              params->itb, params->dtb, params->isa[0]);
89    thread->setStatus(ThreadContext::Halted);
90    tc = thread->getTC();
91    threadContexts.push_back(tc);
92
93    setupCounters();
94    setupSignalHandler();
95
96    runTimer.reset(new PosixKvmTimer(KVM_TIMER_SIGNAL, CLOCK_MONOTONIC,
97                                     params->hostFactor,
98                                     params->clock));
99}
100
101BaseKvmCPU::~BaseKvmCPU()
102{
103    if (_kvmRun)
104        munmap(_kvmRun, vcpuMMapSize);
105    close(vcpuFD);
106}
107
108void
109BaseKvmCPU::init()
110{
111    BaseCPU::init();
112
113    if (numThreads != 1)
114        fatal("KVM: Multithreading not supported");
115
116    tc->initMemProxies(tc);
117
118    // initialize CPU, including PC
119    if (FullSystem && !switchedOut())
120        TheISA::initCPU(tc, tc->contextId());
121
122    mmio_req.setThreadContext(tc->contextId(), 0);
123}
124
125void
126BaseKvmCPU::startup()
127{
128    Kvm &kvm(vm.kvm);
129
130    BaseCPU::startup();
131
132    assert(vcpuFD == -1);
133
134    // Tell the VM that a CPU is about to start.
135    vm.cpuStartup();
136
137    // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
138    // not guaranteed that the parent KVM VM has initialized at that
139    // point. Initialize virtual CPUs here instead.
140    vcpuFD = vm.createVCPU(vcpuID);
141
142    // Map the KVM run structure */
143    vcpuMMapSize = kvm.getVCPUMMapSize();
144    _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
145                                     PROT_READ | PROT_WRITE, MAP_SHARED,
146                                     vcpuFD, 0);
147    if (_kvmRun == MAP_FAILED)
148        panic("KVM: Failed to map run data structure\n");
149
150    // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
151    // available. The offset into the KVM's communication page is
152    // provided by the coalesced MMIO capability.
153    int mmioOffset(kvm.capCoalescedMMIO());
154    if (mmioOffset) {
155        inform("KVM: Coalesced IO available\n");
156        mmioRing = (struct kvm_coalesced_mmio_ring *)(
157            (char *)_kvmRun + (mmioOffset * pageSize));
158    } else {
159        inform("KVM: Coalesced not supported by host OS\n");
160    }
161}
162
163void
164BaseKvmCPU::regStats()
165{
166    using namespace Stats;
167
168    BaseCPU::regStats();
169
170    numVMExits
171        .name(name() + ".numVMExits")
172        .desc("total number of KVM exits")
173        ;
174
175    numMMIO
176        .name(name() + ".numMMIO")
177        .desc("number of VM exits due to memory mapped IO")
178        ;
179
180    numCoalescedMMIO
181        .name(name() + ".numCoalescedMMIO")
182        .desc("number of coalesced memory mapped IO requests")
183        ;
184
185    numIO
186        .name(name() + ".numIO")
187        .desc("number of VM exits due to legacy IO")
188        ;
189
190    numHalt
191        .name(name() + ".numHalt")
192        .desc("number of VM exits due to wait for interrupt instructions")
193        ;
194
195    numInterrupts
196        .name(name() + ".numInterrupts")
197        .desc("number of interrupts delivered")
198        ;
199
200    numHypercalls
201        .name(name() + ".numHypercalls")
202        .desc("number of hypercalls")
203        ;
204}
205
206void
207BaseKvmCPU::serializeThread(std::ostream &os, ThreadID tid)
208{
209    // Update the thread context so we have something to serialize.
210    syncThreadContext();
211
212    assert(tid == 0);
213    assert(_status == Idle);
214    thread->serialize(os);
215}
216
217void
218BaseKvmCPU::unserializeThread(Checkpoint *cp, const std::string &section,
219                              ThreadID tid)
220{
221    assert(tid == 0);
222    assert(_status == Idle);
223    thread->unserialize(cp, section);
224    threadContextDirty = true;
225}
226
227unsigned int
228BaseKvmCPU::drain(DrainManager *dm)
229{
230    if (switchedOut())
231        return 0;
232
233    DPRINTF(Kvm, "drain\n");
234
235    // De-schedule the tick event so we don't insert any more MMIOs
236    // into the system while it is draining.
237    if (tickEvent.scheduled())
238        deschedule(tickEvent);
239
240    _status = Idle;
241    return 0;
242}
243
244void
245BaseKvmCPU::drainResume()
246{
247    assert(!tickEvent.scheduled());
248
249    // We might have been switched out. In that case, we don't need to
250    // do anything.
251    if (switchedOut())
252        return;
253
254    DPRINTF(Kvm, "drainResume\n");
255    verifyMemoryMode();
256
257    // The tick event is de-scheduled as a part of the draining
258    // process. Re-schedule it if the thread context is active.
259    if (tc->status() == ThreadContext::Active) {
260        schedule(tickEvent, nextCycle());
261        _status = Running;
262    } else {
263        _status = Idle;
264    }
265}
266
267void
268BaseKvmCPU::switchOut()
269{
270    DPRINTF(Kvm, "switchOut\n");
271
272    // Make sure to update the thread context in case, the new CPU
273    // will need to access it.
274    syncThreadContext();
275
276    BaseCPU::switchOut();
277
278    // We should have drained prior to executing a switchOut, which
279    // means that the tick event shouldn't be scheduled and the CPU is
280    // idle.
281    assert(!tickEvent.scheduled());
282    assert(_status == Idle);
283}
284
285void
286BaseKvmCPU::takeOverFrom(BaseCPU *cpu)
287{
288    DPRINTF(Kvm, "takeOverFrom\n");
289
290    BaseCPU::takeOverFrom(cpu);
291
292    // We should have drained prior to executing a switchOut, which
293    // means that the tick event shouldn't be scheduled and the CPU is
294    // idle.
295    assert(!tickEvent.scheduled());
296    assert(_status == Idle);
297    assert(threadContexts.size() == 1);
298
299    // The BaseCPU updated the thread context, make sure that we
300    // synchronize next time we enter start the CPU.
301    threadContextDirty = true;
302}
303
304void
305BaseKvmCPU::verifyMemoryMode() const
306{
307    if (!(system->isAtomicMode() && system->bypassCaches())) {
308        fatal("The KVM-based CPUs requires the memory system to be in the "
309              "'atomic_noncaching' mode.\n");
310    }
311}
312
313void
314BaseKvmCPU::wakeup()
315{
316    DPRINTF(Kvm, "wakeup()\n");
317
318    if (thread->status() != ThreadContext::Suspended)
319        return;
320
321    thread->activate();
322}
323
324void
325BaseKvmCPU::activateContext(ThreadID thread_num, Cycles delay)
326{
327    DPRINTF(Kvm, "ActivateContext %d (%d cycles)\n", thread_num, delay);
328
329    assert(thread_num == 0);
330    assert(thread);
331
332    assert(_status == Idle);
333    assert(!tickEvent.scheduled());
334
335    numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend)
336        * hostFactor;
337
338    schedule(tickEvent, clockEdge(delay));
339    _status = Running;
340}
341
342
343void
344BaseKvmCPU::suspendContext(ThreadID thread_num)
345{
346    DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
347
348    assert(thread_num == 0);
349    assert(thread);
350
351    if (_status == Idle)
352        return;
353
354    assert(_status == Running);
355
356    // The tick event may no be scheduled if the quest has requested
357    // the monitor to wait for interrupts. The normal CPU models can
358    // get their tick events descheduled by quiesce instructions, but
359    // that can't happen here.
360    if (tickEvent.scheduled())
361        deschedule(tickEvent);
362
363    _status = Idle;
364}
365
366void
367BaseKvmCPU::deallocateContext(ThreadID thread_num)
368{
369    // for now, these are equivalent
370    suspendContext(thread_num);
371}
372
373void
374BaseKvmCPU::haltContext(ThreadID thread_num)
375{
376    // for now, these are equivalent
377    suspendContext(thread_num);
378}
379
380ThreadContext *
381BaseKvmCPU::getContext(int tn)
382{
383    assert(tn == 0);
384    syncThreadContext();
385    return tc;
386}
387
388
389Counter
390BaseKvmCPU::totalInsts() const
391{
392    return hwInstructions.read();
393}
394
395Counter
396BaseKvmCPU::totalOps() const
397{
398    hack_once("Pretending totalOps is equivalent to totalInsts()\n");
399    return hwInstructions.read();
400}
401
402void
403BaseKvmCPU::dump()
404{
405    inform("State dumping not implemented.");
406}
407
408void
409BaseKvmCPU::tick()
410{
411    assert(_status == Running);
412
413    DPRINTF(KvmRun, "Entering KVM...\n");
414
415    Tick ticksToExecute(mainEventQueue.nextTick() - curTick());
416    Tick ticksExecuted(kvmRun(ticksToExecute));
417
418    Tick delay(ticksExecuted + handleKvmExit());
419
420    switch (_status) {
421      case Running:
422        schedule(tickEvent, clockEdge(ticksToCycles(delay)));
423        break;
424
425      default:
426        /* The CPU is halted or waiting for an interrupt from a
427         * device. Don't start it. */
428        break;
429    }
430}
431
432Tick
433BaseKvmCPU::kvmRun(Tick ticks)
434{
435    uint64_t baseCycles(hwCycles.read());
436    uint64_t baseInstrs(hwInstructions.read());
437
438    // We might need to update the KVM state.
439    syncKvmState();
440    // Entering into KVM implies that we'll have to reload the thread
441    // context from KVM if we want to access it. Flag the KVM state as
442    // dirty with respect to the cached thread context.
443    kvmStateDirty = true;
444
445    if (ticks < runTimer->resolution()) {
446        DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
447                ticks, runTimer->resolution());
448        ticks = runTimer->resolution();
449    }
450
451    DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
452    timerOverflowed = false;
453    runTimer->arm(ticks);
454    startCounters();
455    if (ioctl(KVM_RUN) == -1) {
456        if (errno != EINTR)
457            panic("KVM: Failed to start virtual CPU (errno: %i)\n",
458                  errno);
459    }
460    stopCounters();
461    runTimer->disarm();
462
463    uint64_t cyclesExecuted(hwCycles.read() - baseCycles);
464    Tick ticksExecuted(runTimer->ticksFromHostCycles(cyclesExecuted));
465
466    if (ticksExecuted < ticks &&
467        timerOverflowed &&
468        _kvmRun->exit_reason == KVM_EXIT_INTR) {
469        // TODO: We should probably do something clever here...
470        warn("KVM: Early timer event, requested %i ticks but got %i ticks.\n",
471             ticks, ticksExecuted);
472    }
473
474    numCycles += cyclesExecuted * hostFactor;
475    ++numVMExits;
476
477    DPRINTF(KvmRun, "KVM: Executed %i instructions in %i cycles (%i ticks, sim cycles: %i).\n",
478            hwInstructions.read() - baseInstrs,
479            cyclesExecuted,
480            ticksExecuted,
481            cyclesExecuted * hostFactor);
482
483    return ticksExecuted + flushCoalescedMMIO();
484}
485
486void
487BaseKvmCPU::kvmNonMaskableInterrupt()
488{
489    ++numInterrupts;
490    if (ioctl(KVM_NMI) == -1)
491        panic("KVM: Failed to deliver NMI to virtual CPU\n");
492}
493
494void
495BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
496{
497    ++numInterrupts;
498    if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
499        panic("KVM: Failed to deliver interrupt to virtual CPU\n");
500}
501
502void
503BaseKvmCPU::getRegisters(struct kvm_regs &regs) const
504{
505    if (ioctl(KVM_GET_REGS, &regs) == -1)
506        panic("KVM: Failed to get guest registers\n");
507}
508
509void
510BaseKvmCPU::setRegisters(const struct kvm_regs &regs)
511{
512    if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
513        panic("KVM: Failed to set guest registers\n");
514}
515
516void
517BaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
518{
519    if (ioctl(KVM_GET_SREGS, &regs) == -1)
520        panic("KVM: Failed to get guest special registers\n");
521}
522
523void
524BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
525{
526    if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
527        panic("KVM: Failed to set guest special registers\n");
528}
529
530void
531BaseKvmCPU::getFPUState(struct kvm_fpu &state) const
532{
533    if (ioctl(KVM_GET_FPU, &state) == -1)
534        panic("KVM: Failed to get guest FPU state\n");
535}
536
537void
538BaseKvmCPU::setFPUState(const struct kvm_fpu &state)
539{
540    if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
541        panic("KVM: Failed to set guest FPU state\n");
542}
543
544
545void
546BaseKvmCPU::setOneReg(uint64_t id, const void *addr)
547{
548#ifdef KVM_SET_ONE_REG
549    struct kvm_one_reg reg;
550    reg.id = id;
551    reg.addr = (uint64_t)addr;
552
553    if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
554        panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
555              id, errno);
556    }
557#else
558    panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
559#endif
560}
561
562void
563BaseKvmCPU::getOneReg(uint64_t id, void *addr) const
564{
565#ifdef KVM_GET_ONE_REG
566    struct kvm_one_reg reg;
567    reg.id = id;
568    reg.addr = (uint64_t)addr;
569
570    if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
571        panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
572              id, errno);
573    }
574#else
575    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
576#endif
577}
578
579std::string
580BaseKvmCPU::getAndFormatOneReg(uint64_t id) const
581{
582#ifdef KVM_GET_ONE_REG
583    std::ostringstream ss;
584
585    ss.setf(std::ios::hex, std::ios::basefield);
586    ss.setf(std::ios::showbase);
587#define HANDLE_INTTYPE(len)                      \
588    case KVM_REG_SIZE_U ## len: {                \
589        uint ## len ## _t value;                 \
590        getOneReg(id, &value);                   \
591        ss << value;                             \
592    }  break
593
594#define HANDLE_ARRAY(len)                       \
595    case KVM_REG_SIZE_U ## len: {               \
596        uint8_t value[len / 8];                 \
597        getOneReg(id, value);                   \
598        ss << "[" << value[0];                  \
599        for (int i = 1; i < len  / 8; ++i)      \
600            ss << ", " << value[i];             \
601        ss << "]";                              \
602      } break
603
604    switch (id & KVM_REG_SIZE_MASK) {
605        HANDLE_INTTYPE(8);
606        HANDLE_INTTYPE(16);
607        HANDLE_INTTYPE(32);
608        HANDLE_INTTYPE(64);
609        HANDLE_ARRAY(128);
610        HANDLE_ARRAY(256);
611        HANDLE_ARRAY(512);
612        HANDLE_ARRAY(1024);
613      default:
614        ss << "??";
615    }
616
617#undef HANDLE_INTTYPE
618#undef HANDLE_ARRAY
619
620    return ss.str();
621#else
622    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
623#endif
624}
625
626void
627BaseKvmCPU::syncThreadContext()
628{
629    if (!kvmStateDirty)
630        return;
631
632    assert(!threadContextDirty);
633
634    updateThreadContext();
635    kvmStateDirty = false;
636}
637
638void
639BaseKvmCPU::syncKvmState()
640{
641    if (!threadContextDirty)
642        return;
643
644    assert(!kvmStateDirty);
645
646    updateKvmState();
647    threadContextDirty = false;
648}
649
650Tick
651BaseKvmCPU::handleKvmExit()
652{
653    DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
654
655    switch (_kvmRun->exit_reason) {
656      case KVM_EXIT_UNKNOWN:
657        return handleKvmExitUnknown();
658
659      case KVM_EXIT_EXCEPTION:
660        return handleKvmExitException();
661
662      case KVM_EXIT_IO:
663        ++numIO;
664        return handleKvmExitIO();
665
666      case KVM_EXIT_HYPERCALL:
667        ++numHypercalls;
668        return handleKvmExitHypercall();
669
670      case KVM_EXIT_HLT:
671        /* The guest has halted and is waiting for interrupts */
672        DPRINTF(Kvm, "handleKvmExitHalt\n");
673        ++numHalt;
674
675        // Suspend the thread until the next interrupt arrives
676        thread->suspend();
677
678        // This is actually ignored since the thread is suspended.
679        return 0;
680
681      case KVM_EXIT_MMIO:
682        /* Service memory mapped IO requests */
683        DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
684                _kvmRun->mmio.is_write,
685                _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
686
687        ++numMMIO;
688        return doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
689                            _kvmRun->mmio.len, _kvmRun->mmio.is_write);
690
691      case KVM_EXIT_IRQ_WINDOW_OPEN:
692        return handleKvmExitIRQWindowOpen();
693
694      case KVM_EXIT_FAIL_ENTRY:
695        return handleKvmExitFailEntry();
696
697      case KVM_EXIT_INTR:
698        /* KVM was interrupted by a signal, restart it in the next
699         * tick. */
700        return 0;
701
702      case KVM_EXIT_INTERNAL_ERROR:
703        panic("KVM: Internal error (suberror: %u)\n",
704              _kvmRun->internal.suberror);
705
706      default:
707        panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
708    }
709}
710
711Tick
712BaseKvmCPU::handleKvmExitIO()
713{
714    panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
715          _kvmRun->io.direction, _kvmRun->io.size,
716          _kvmRun->io.port, _kvmRun->io.count);
717}
718
719Tick
720BaseKvmCPU::handleKvmExitHypercall()
721{
722    panic("KVM: Unhandled hypercall\n");
723}
724
725Tick
726BaseKvmCPU::handleKvmExitIRQWindowOpen()
727{
728    warn("KVM: Unhandled IRQ window.\n");
729    return 0;
730}
731
732
733Tick
734BaseKvmCPU::handleKvmExitUnknown()
735{
736    panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
737          _kvmRun->hw.hardware_exit_reason);
738}
739
740Tick
741BaseKvmCPU::handleKvmExitException()
742{
743    panic("KVM: Got exception when starting vCPU "
744          "(exception: %u, error_code: %u)\n",
745          _kvmRun->ex.exception, _kvmRun->ex.error_code);
746}
747
748Tick
749BaseKvmCPU::handleKvmExitFailEntry()
750{
751    panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
752          _kvmRun->fail_entry.hardware_entry_failure_reason);
753}
754
755Tick
756BaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
757{
758    mmio_req.setPhys(paddr, size,
759                     0, /* flags */
760                     dataMasterId());
761
762    const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
763    Packet pkt(&mmio_req, cmd);
764    pkt.dataStatic(data);
765    return dataPort.sendAtomic(&pkt);
766}
767
768int
769BaseKvmCPU::ioctl(int request, long p1) const
770{
771    if (vcpuFD == -1)
772        panic("KVM: CPU ioctl called before initialization\n");
773
774    return ::ioctl(vcpuFD, request, p1);
775}
776
777Tick
778BaseKvmCPU::flushCoalescedMMIO()
779{
780    if (!mmioRing)
781        return 0;
782
783    DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
784
785    // TODO: We might need to do synchronization when we start to
786    // support multiple CPUs
787    Tick ticks(0);
788    while (mmioRing->first != mmioRing->last) {
789        struct kvm_coalesced_mmio &ent(
790            mmioRing->coalesced_mmio[mmioRing->first]);
791
792        DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
793                ent.phys_addr, ent.len);
794
795        ++numCoalescedMMIO;
796        ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
797
798        mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
799    }
800
801    return ticks;
802}
803
804void
805BaseKvmCPU::setupSignalHandler()
806{
807    struct sigaction sa;
808
809    memset(&sa, 0, sizeof(sa));
810    sa.sa_sigaction = onTimerOverflow;
811    sa.sa_flags = SA_SIGINFO | SA_RESTART;
812    if (sigaction(KVM_TIMER_SIGNAL, &sa, NULL) == -1)
813        panic("KVM: Failed to setup vCPU signal handler\n");
814}
815
816void
817BaseKvmCPU::setupCounters()
818{
819    DPRINTF(Kvm, "Attaching cycle counter...\n");
820    PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
821                                PERF_COUNT_HW_CPU_CYCLES);
822    cfgCycles.disabled(true)
823        .pinned(true);
824    hwCycles.attach(cfgCycles,
825                    0); // TID (0 => currentThread)
826
827    DPRINTF(Kvm, "Attaching instruction counter...\n");
828    PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
829                                      PERF_COUNT_HW_INSTRUCTIONS);
830    hwInstructions.attach(cfgInstructions,
831                          0, // TID (0 => currentThread)
832                          hwCycles);
833}
834
835void
836BaseKvmCPU::startCounters()
837{
838    // We only need to start/stop the hwCycles counter since hwCycles
839    // and hwInstructions are a counter group with hwCycles as the
840    // group leader.
841    hwCycles.start();
842}
843
844void
845BaseKvmCPU::stopCounters()
846{
847    hwCycles.stop();
848}
849