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