base.cc (10553:c1ad57c53a36) base.cc (10653:e3fc6bc7f97e)
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/mmapped_ipr.hh"
50#include "arch/utility.hh"
51#include "cpu/kvm/base.hh"
52#include "debug/Checkpoint.hh"
53#include "debug/Drain.hh"
54#include "debug/Kvm.hh"
55#include "debug/KvmIO.hh"
56#include "debug/KvmRun.hh"
57#include "params/BaseKvmCPU.hh"
58#include "sim/process.hh"
59#include "sim/system.hh"
60
61#include <signal.h>
62
63/* Used by some KVM macros */
64#define PAGE_SIZE pageSize
65
66BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
67 : BaseCPU(params),
68 vm(*params->kvmVM),
69 _status(Idle),
70 dataPort(name() + ".dcache_port", this),
71 instPort(name() + ".icache_port", this),
72 threadContextDirty(true),
73 kvmStateDirty(false),
74 vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
75 _kvmRun(NULL), mmioRing(NULL),
76 pageSize(sysconf(_SC_PAGE_SIZE)),
77 tickEvent(*this),
78 activeInstPeriod(0),
79 perfControlledByTimer(params->usePerfOverflow),
80 hostFactor(params->hostFactor),
81 drainManager(NULL),
82 ctrInsts(0)
83{
84 if (pageSize == -1)
85 panic("KVM: Failed to determine host page size (%i)\n",
86 errno);
87
88 if (FullSystem)
89 thread = new SimpleThread(this, 0, params->system, params->itb, params->dtb,
90 params->isa[0]);
91 else
92 thread = new SimpleThread(this, /* thread_num */ 0, params->system,
93 params->workload[0], params->itb,
94 params->dtb, params->isa[0]);
95
96 thread->setStatus(ThreadContext::Halted);
97 tc = thread->getTC();
98 threadContexts.push_back(tc);
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());
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/mmapped_ipr.hh"
50#include "arch/utility.hh"
51#include "cpu/kvm/base.hh"
52#include "debug/Checkpoint.hh"
53#include "debug/Drain.hh"
54#include "debug/Kvm.hh"
55#include "debug/KvmIO.hh"
56#include "debug/KvmRun.hh"
57#include "params/BaseKvmCPU.hh"
58#include "sim/process.hh"
59#include "sim/system.hh"
60
61#include <signal.h>
62
63/* Used by some KVM macros */
64#define PAGE_SIZE pageSize
65
66BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
67 : BaseCPU(params),
68 vm(*params->kvmVM),
69 _status(Idle),
70 dataPort(name() + ".dcache_port", this),
71 instPort(name() + ".icache_port", this),
72 threadContextDirty(true),
73 kvmStateDirty(false),
74 vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
75 _kvmRun(NULL), mmioRing(NULL),
76 pageSize(sysconf(_SC_PAGE_SIZE)),
77 tickEvent(*this),
78 activeInstPeriod(0),
79 perfControlledByTimer(params->usePerfOverflow),
80 hostFactor(params->hostFactor),
81 drainManager(NULL),
82 ctrInsts(0)
83{
84 if (pageSize == -1)
85 panic("KVM: Failed to determine host page size (%i)\n",
86 errno);
87
88 if (FullSystem)
89 thread = new SimpleThread(this, 0, params->system, params->itb, params->dtb,
90 params->isa[0]);
91 else
92 thread = new SimpleThread(this, /* thread_num */ 0, params->system,
93 params->workload[0], params->itb,
94 params->dtb, params->isa[0]);
95
96 thread->setStatus(ThreadContext::Halted);
97 tc = thread->getTC();
98 threadContexts.push_back(tc);
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 const BaseKvmCPUParams * const p(
129 dynamic_cast<const BaseKvmCPUParams *>(params()));
130
131 Kvm &kvm(vm.kvm);
132
133 BaseCPU::startup();
134
135 assert(vcpuFD == -1);
136
137 // Tell the VM that a CPU is about to start.
138 vm.cpuStartup();
139
140 // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
141 // not guaranteed that the parent KVM VM has initialized at that
142 // point. Initialize virtual CPUs here instead.
143 vcpuFD = vm.createVCPU(vcpuID);
144
145 // Map the KVM run structure */
146 vcpuMMapSize = kvm.getVCPUMMapSize();
147 _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
148 PROT_READ | PROT_WRITE, MAP_SHARED,
149 vcpuFD, 0);
150 if (_kvmRun == MAP_FAILED)
151 panic("KVM: Failed to map run data structure\n");
152
153 // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
154 // available. The offset into the KVM's communication page is
155 // provided by the coalesced MMIO capability.
156 int mmioOffset(kvm.capCoalescedMMIO());
157 if (!p->useCoalescedMMIO) {
158 inform("KVM: Coalesced MMIO disabled by config.\n");
159 } else if (mmioOffset) {
160 inform("KVM: Coalesced IO available\n");
161 mmioRing = (struct kvm_coalesced_mmio_ring *)(
162 (char *)_kvmRun + (mmioOffset * pageSize));
163 } else {
164 inform("KVM: Coalesced not supported by host OS\n");
165 }
166
167 thread->startup();
168
169 Event *startupEvent(
170 new EventWrapper<BaseKvmCPU,
171 &BaseKvmCPU::startupThread>(this, true));
172 schedule(startupEvent, curTick());
173}
174
175void
176BaseKvmCPU::startupThread()
177{
178 // Do thread-specific initialization. We need to setup signal
179 // delivery for counters and timers from within the thread that
180 // will execute the event queue to ensure that signals are
181 // delivered to the right threads.
182 const BaseKvmCPUParams * const p(
183 dynamic_cast<const BaseKvmCPUParams *>(params()));
184
185 vcpuThread = pthread_self();
186
187 // Setup signal handlers. This has to be done after the vCPU is
188 // created since it manipulates the vCPU signal mask.
189 setupSignalHandler();
190
191 setupCounters();
192
193 if (p->usePerfOverflow)
194 runTimer.reset(new PerfKvmTimer(hwCycles,
195 KVM_KICK_SIGNAL,
196 p->hostFactor,
197 p->hostFreq));
198 else
199 runTimer.reset(new PosixKvmTimer(KVM_KICK_SIGNAL, CLOCK_MONOTONIC,
200 p->hostFactor,
201 p->hostFreq));
202
203}
204
205void
206BaseKvmCPU::regStats()
207{
208 using namespace Stats;
209
210 BaseCPU::regStats();
211
212 numInsts
213 .name(name() + ".committedInsts")
214 .desc("Number of instructions committed")
215 ;
216
217 numVMExits
218 .name(name() + ".numVMExits")
219 .desc("total number of KVM exits")
220 ;
221
222 numVMHalfEntries
223 .name(name() + ".numVMHalfEntries")
224 .desc("number of KVM entries to finalize pending operations")
225 ;
226
227 numExitSignal
228 .name(name() + ".numExitSignal")
229 .desc("exits due to signal delivery")
230 ;
231
232 numMMIO
233 .name(name() + ".numMMIO")
234 .desc("number of VM exits due to memory mapped IO")
235 ;
236
237 numCoalescedMMIO
238 .name(name() + ".numCoalescedMMIO")
239 .desc("number of coalesced memory mapped IO requests")
240 ;
241
242 numIO
243 .name(name() + ".numIO")
244 .desc("number of VM exits due to legacy IO")
245 ;
246
247 numHalt
248 .name(name() + ".numHalt")
249 .desc("number of VM exits due to wait for interrupt instructions")
250 ;
251
252 numInterrupts
253 .name(name() + ".numInterrupts")
254 .desc("number of interrupts delivered")
255 ;
256
257 numHypercalls
258 .name(name() + ".numHypercalls")
259 .desc("number of hypercalls")
260 ;
261}
262
263void
264BaseKvmCPU::serializeThread(std::ostream &os, ThreadID tid)
265{
266 if (DTRACE(Checkpoint)) {
267 DPRINTF(Checkpoint, "KVM: Serializing thread %i:\n", tid);
268 dump();
269 }
270
271 assert(tid == 0);
272 assert(_status == Idle);
273 thread->serialize(os);
274}
275
276void
277BaseKvmCPU::unserializeThread(Checkpoint *cp, const std::string &section,
278 ThreadID tid)
279{
280 DPRINTF(Checkpoint, "KVM: Unserialize thread %i:\n", tid);
281
282 assert(tid == 0);
283 assert(_status == Idle);
284 thread->unserialize(cp, section);
285 threadContextDirty = true;
286}
287
288unsigned int
289BaseKvmCPU::drain(DrainManager *dm)
290{
291 if (switchedOut())
292 return 0;
293
294 DPRINTF(Drain, "BaseKvmCPU::drain\n");
295 switch (_status) {
296 case Running:
297 // The base KVM code is normally ready when it is in the
298 // Running state, but the architecture specific code might be
299 // of a different opinion. This may happen when the CPU been
300 // notified of an event that hasn't been accepted by the vCPU
301 // yet.
302 if (!archIsDrained()) {
303 drainManager = dm;
304 return 1;
305 }
306
307 // The state of the CPU is consistent, so we don't need to do
308 // anything special to drain it. We simply de-schedule the
309 // tick event and enter the Idle state to prevent nasty things
310 // like MMIOs from happening.
311 if (tickEvent.scheduled())
312 deschedule(tickEvent);
313 _status = Idle;
314
315 /** FALLTHROUGH */
316 case Idle:
317 // Idle, no need to drain
318 assert(!tickEvent.scheduled());
319
320 // Sync the thread context here since we'll need it when we
321 // switch CPUs or checkpoint the CPU.
322 syncThreadContext();
323
324 return 0;
325
326 case RunningServiceCompletion:
327 // The CPU has just requested a service that was handled in
328 // the RunningService state, but the results have still not
329 // been reported to the CPU. Now, we /could/ probably just
330 // update the register state ourselves instead of letting KVM
331 // handle it, but that would be tricky. Instead, we enter KVM
332 // and let it do its stuff.
333 drainManager = dm;
334
335 DPRINTF(Drain, "KVM CPU is waiting for service completion, "
336 "requesting drain.\n");
337 return 1;
338
339 case RunningService:
340 // We need to drain since the CPU is waiting for service (e.g., MMIOs)
341 drainManager = dm;
342
343 DPRINTF(Drain, "KVM CPU is waiting for service, requesting drain.\n");
344 return 1;
345
346 default:
347 panic("KVM: Unhandled CPU state in drain()\n");
348 return 0;
349 }
350}
351
352void
353BaseKvmCPU::drainResume()
354{
355 assert(!tickEvent.scheduled());
356
357 // We might have been switched out. In that case, we don't need to
358 // do anything.
359 if (switchedOut())
360 return;
361
362 DPRINTF(Kvm, "drainResume\n");
363 verifyMemoryMode();
364
365 // The tick event is de-scheduled as a part of the draining
366 // process. Re-schedule it if the thread context is active.
367 if (tc->status() == ThreadContext::Active) {
368 schedule(tickEvent, nextCycle());
369 _status = Running;
370 } else {
371 _status = Idle;
372 }
373}
374
375void
376BaseKvmCPU::switchOut()
377{
378 DPRINTF(Kvm, "switchOut\n");
379
380 BaseCPU::switchOut();
381
382 // We should have drained prior to executing a switchOut, which
383 // means that the tick event shouldn't be scheduled and the CPU is
384 // idle.
385 assert(!tickEvent.scheduled());
386 assert(_status == Idle);
387}
388
389void
390BaseKvmCPU::takeOverFrom(BaseCPU *cpu)
391{
392 DPRINTF(Kvm, "takeOverFrom\n");
393
394 BaseCPU::takeOverFrom(cpu);
395
396 // We should have drained prior to executing a switchOut, which
397 // means that the tick event shouldn't be scheduled and the CPU is
398 // idle.
399 assert(!tickEvent.scheduled());
400 assert(_status == Idle);
401 assert(threadContexts.size() == 1);
402
403 // Force an update of the KVM state here instead of flagging the
404 // TC as dirty. This is not ideal from a performance point of
405 // view, but it makes debugging easier as it allows meaningful KVM
406 // state to be dumped before and after a takeover.
407 updateKvmState();
408 threadContextDirty = false;
409}
410
411void
412BaseKvmCPU::verifyMemoryMode() const
413{
414 if (!(system->isAtomicMode() && system->bypassCaches())) {
415 fatal("The KVM-based CPUs requires the memory system to be in the "
416 "'atomic_noncaching' mode.\n");
417 }
418}
419
420void
421BaseKvmCPU::wakeup()
422{
423 DPRINTF(Kvm, "wakeup()\n");
424 // This method might have been called from another
425 // context. Migrate to this SimObject's event queue when
426 // delivering the wakeup signal.
427 EventQueue::ScopedMigration migrate(eventQueue());
428
429 // Kick the vCPU to get it to come out of KVM.
430 kick();
431
432 if (thread->status() != ThreadContext::Suspended)
433 return;
434
435 thread->activate();
436}
437
438void
439BaseKvmCPU::activateContext(ThreadID thread_num)
440{
441 DPRINTF(Kvm, "ActivateContext %d\n", thread_num);
442
443 assert(thread_num == 0);
444 assert(thread);
445
446 assert(_status == Idle);
447 assert(!tickEvent.scheduled());
448
449 numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend);
450
451 schedule(tickEvent, clockEdge(Cycles(0)));
452 _status = Running;
453}
454
455
456void
457BaseKvmCPU::suspendContext(ThreadID thread_num)
458{
459 DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
460
461 assert(thread_num == 0);
462 assert(thread);
463
464 if (_status == Idle)
465 return;
466
467 assert(_status == Running || _status == RunningServiceCompletion);
468
469 // The tick event may no be scheduled if the quest has requested
470 // the monitor to wait for interrupts. The normal CPU models can
471 // get their tick events descheduled by quiesce instructions, but
472 // that can't happen here.
473 if (tickEvent.scheduled())
474 deschedule(tickEvent);
475
476 _status = Idle;
477}
478
479void
480BaseKvmCPU::deallocateContext(ThreadID thread_num)
481{
482 // for now, these are equivalent
483 suspendContext(thread_num);
484}
485
486void
487BaseKvmCPU::haltContext(ThreadID thread_num)
488{
489 // for now, these are equivalent
490 suspendContext(thread_num);
491}
492
493ThreadContext *
494BaseKvmCPU::getContext(int tn)
495{
496 assert(tn == 0);
497 syncThreadContext();
498 return tc;
499}
500
501
502Counter
503BaseKvmCPU::totalInsts() const
504{
505 return ctrInsts;
506}
507
508Counter
509BaseKvmCPU::totalOps() const
510{
511 hack_once("Pretending totalOps is equivalent to totalInsts()\n");
512 return ctrInsts;
513}
514
515void
516BaseKvmCPU::dump()
517{
518 inform("State dumping not implemented.");
519}
520
521void
522BaseKvmCPU::tick()
523{
524 Tick delay(0);
525 assert(_status != Idle);
526
527 switch (_status) {
528 case RunningService:
529 // handleKvmExit() will determine the next state of the CPU
530 delay = handleKvmExit();
531
532 if (tryDrain())
533 _status = Idle;
534 break;
535
536 case RunningServiceCompletion:
537 case Running: {
538 EventQueue *q = curEventQueue();
539 Tick ticksToExecute(q->nextTick() - curTick());
540
541 // We might need to update the KVM state.
542 syncKvmState();
543
544 // Setup any pending instruction count breakpoints using
545 // PerfEvent.
546 setupInstStop();
547
548 DPRINTF(KvmRun, "Entering KVM...\n");
549 if (drainManager) {
550 // Force an immediate exit from KVM after completing
551 // pending operations. The architecture-specific code
552 // takes care to run until it is in a state where it can
553 // safely be drained.
554 delay = kvmRunDrain();
555 } else {
556 delay = kvmRun(ticksToExecute);
557 }
558
559 // The CPU might have been suspended before entering into
560 // KVM. Assume that the CPU was suspended /before/ entering
561 // into KVM and skip the exit handling.
562 if (_status == Idle)
563 break;
564
565 // Entering into KVM implies that we'll have to reload the thread
566 // context from KVM if we want to access it. Flag the KVM state as
567 // dirty with respect to the cached thread context.
568 kvmStateDirty = true;
569
570 // Enter into the RunningService state unless the
571 // simulation was stopped by a timer.
572 if (_kvmRun->exit_reason != KVM_EXIT_INTR) {
573 _status = RunningService;
574 } else {
575 ++numExitSignal;
576 _status = Running;
577 }
578
579 // Service any pending instruction events. The vCPU should
580 // have exited in time for the event using the instruction
581 // counter configured by setupInstStop().
582 comInstEventQueue[0]->serviceEvents(ctrInsts);
583 system->instEventQueue.serviceEvents(system->totalNumInsts);
584
585 if (tryDrain())
586 _status = Idle;
587 } break;
588
589 default:
590 panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
591 _status);
592 }
593
594 // Schedule a new tick if we are still running
595 if (_status != Idle)
596 schedule(tickEvent, clockEdge(ticksToCycles(delay)));
597}
598
599Tick
600BaseKvmCPU::kvmRunDrain()
601{
602 // By default, the only thing we need to drain is a pending IO
603 // operation which assumes that we are in the
604 // RunningServiceCompletion state.
605 assert(_status == RunningServiceCompletion);
606
607 // Deliver the data from the pending IO operation and immediately
608 // exit.
609 return kvmRun(0);
610}
611
612uint64_t
613BaseKvmCPU::getHostCycles() const
614{
615 return hwCycles.read();
616}
617
618Tick
619BaseKvmCPU::kvmRun(Tick ticks)
620{
621 Tick ticksExecuted;
622 DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
623
624 if (ticks == 0) {
625 // Settings ticks == 0 is a special case which causes an entry
626 // into KVM that finishes pending operations (e.g., IO) and
627 // then immediately exits.
628 DPRINTF(KvmRun, "KVM: Delivering IO without full guest entry\n");
629
630 ++numVMHalfEntries;
631
632 // Send a KVM_KICK_SIGNAL to the vCPU thread (i.e., this
633 // thread). The KVM control signal is masked while executing
634 // in gem5 and gets unmasked temporarily as when entering
635 // KVM. See setSignalMask() and setupSignalHandler().
636 kick();
637
638 // Start the vCPU. KVM will check for signals after completing
639 // pending operations (IO). Since the KVM_KICK_SIGNAL is
640 // pending, this forces an immediate exit to gem5 again. We
641 // don't bother to setup timers since this shouldn't actually
642 // execute any code (other than completing half-executed IO
643 // instructions) in the guest.
644 ioctlRun();
645
646 // We always execute at least one cycle to prevent the
647 // BaseKvmCPU::tick() to be rescheduled on the same tick
648 // twice.
649 ticksExecuted = clockPeriod();
650 } else {
651 // This method is executed as a result of a tick event. That
652 // means that the event queue will be locked when entering the
653 // method. We temporarily unlock the event queue to allow
654 // other threads to steal control of this thread to inject
655 // interrupts. They will typically lock the queue and then
656 // force an exit from KVM by kicking the vCPU.
657 EventQueue::ScopedRelease release(curEventQueue());
658
659 if (ticks < runTimer->resolution()) {
660 DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
661 ticks, runTimer->resolution());
662 ticks = runTimer->resolution();
663 }
664
665 // Get hardware statistics after synchronizing contexts. The KVM
666 // state update might affect guest cycle counters.
667 uint64_t baseCycles(getHostCycles());
668 uint64_t baseInstrs(hwInstructions.read());
669
670 // Arm the run timer and start the cycle timer if it isn't
671 // controlled by the overflow timer. Starting/stopping the cycle
672 // timer automatically starts the other perf timers as they are in
673 // the same counter group.
674 runTimer->arm(ticks);
675 if (!perfControlledByTimer)
676 hwCycles.start();
677
678 ioctlRun();
679
680 runTimer->disarm();
681 if (!perfControlledByTimer)
682 hwCycles.stop();
683
684 // The control signal may have been delivered after we exited
685 // from KVM. It will be pending in that case since it is
686 // masked when we aren't executing in KVM. Discard it to make
687 // sure we don't deliver it immediately next time we try to
688 // enter into KVM.
689 discardPendingSignal(KVM_KICK_SIGNAL);
690
691 const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles);
692 const uint64_t simCyclesExecuted(hostCyclesExecuted * hostFactor);
693 const uint64_t instsExecuted(hwInstructions.read() - baseInstrs);
694 ticksExecuted = runTimer->ticksFromHostCycles(hostCyclesExecuted);
695
696 /* Update statistics */
697 numCycles += simCyclesExecuted;;
698 numInsts += instsExecuted;
699 ctrInsts += instsExecuted;
700 system->totalNumInsts += instsExecuted;
701
702 DPRINTF(KvmRun,
703 "KVM: Executed %i instructions in %i cycles "
704 "(%i ticks, sim cycles: %i).\n",
705 instsExecuted, hostCyclesExecuted, ticksExecuted, simCyclesExecuted);
706 }
707
708 ++numVMExits;
709
710 return ticksExecuted + flushCoalescedMMIO();
711}
712
713void
714BaseKvmCPU::kvmNonMaskableInterrupt()
715{
716 ++numInterrupts;
717 if (ioctl(KVM_NMI) == -1)
718 panic("KVM: Failed to deliver NMI to virtual CPU\n");
719}
720
721void
722BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
723{
724 ++numInterrupts;
725 if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
726 panic("KVM: Failed to deliver interrupt to virtual CPU\n");
727}
728
729void
730BaseKvmCPU::getRegisters(struct kvm_regs &regs) const
731{
732 if (ioctl(KVM_GET_REGS, &regs) == -1)
733 panic("KVM: Failed to get guest registers\n");
734}
735
736void
737BaseKvmCPU::setRegisters(const struct kvm_regs &regs)
738{
739 if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
740 panic("KVM: Failed to set guest registers\n");
741}
742
743void
744BaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
745{
746 if (ioctl(KVM_GET_SREGS, &regs) == -1)
747 panic("KVM: Failed to get guest special registers\n");
748}
749
750void
751BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
752{
753 if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
754 panic("KVM: Failed to set guest special registers\n");
755}
756
757void
758BaseKvmCPU::getFPUState(struct kvm_fpu &state) const
759{
760 if (ioctl(KVM_GET_FPU, &state) == -1)
761 panic("KVM: Failed to get guest FPU state\n");
762}
763
764void
765BaseKvmCPU::setFPUState(const struct kvm_fpu &state)
766{
767 if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
768 panic("KVM: Failed to set guest FPU state\n");
769}
770
771
772void
773BaseKvmCPU::setOneReg(uint64_t id, const void *addr)
774{
775#ifdef KVM_SET_ONE_REG
776 struct kvm_one_reg reg;
777 reg.id = id;
778 reg.addr = (uint64_t)addr;
779
780 if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
781 panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
782 id, errno);
783 }
784#else
785 panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
786#endif
787}
788
789void
790BaseKvmCPU::getOneReg(uint64_t id, void *addr) const
791{
792#ifdef KVM_GET_ONE_REG
793 struct kvm_one_reg reg;
794 reg.id = id;
795 reg.addr = (uint64_t)addr;
796
797 if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
798 panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
799 id, errno);
800 }
801#else
802 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
803#endif
804}
805
806std::string
807BaseKvmCPU::getAndFormatOneReg(uint64_t id) const
808{
809#ifdef KVM_GET_ONE_REG
810 std::ostringstream ss;
811
812 ss.setf(std::ios::hex, std::ios::basefield);
813 ss.setf(std::ios::showbase);
814#define HANDLE_INTTYPE(len) \
815 case KVM_REG_SIZE_U ## len: { \
816 uint ## len ## _t value; \
817 getOneReg(id, &value); \
818 ss << value; \
819 } break
820
821#define HANDLE_ARRAY(len) \
822 case KVM_REG_SIZE_U ## len: { \
823 uint8_t value[len / 8]; \
824 getOneReg(id, value); \
825 ss << "[" << value[0]; \
826 for (int i = 1; i < len / 8; ++i) \
827 ss << ", " << value[i]; \
828 ss << "]"; \
829 } break
830
831 switch (id & KVM_REG_SIZE_MASK) {
832 HANDLE_INTTYPE(8);
833 HANDLE_INTTYPE(16);
834 HANDLE_INTTYPE(32);
835 HANDLE_INTTYPE(64);
836 HANDLE_ARRAY(128);
837 HANDLE_ARRAY(256);
838 HANDLE_ARRAY(512);
839 HANDLE_ARRAY(1024);
840 default:
841 ss << "??";
842 }
843
844#undef HANDLE_INTTYPE
845#undef HANDLE_ARRAY
846
847 return ss.str();
848#else
849 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
850#endif
851}
852
853void
854BaseKvmCPU::syncThreadContext()
855{
856 if (!kvmStateDirty)
857 return;
858
859 assert(!threadContextDirty);
860
861 updateThreadContext();
862 kvmStateDirty = false;
863}
864
865void
866BaseKvmCPU::syncKvmState()
867{
868 if (!threadContextDirty)
869 return;
870
871 assert(!kvmStateDirty);
872
873 updateKvmState();
874 threadContextDirty = false;
875}
876
877Tick
878BaseKvmCPU::handleKvmExit()
879{
880 DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
881 assert(_status == RunningService);
882
883 // Switch into the running state by default. Individual handlers
884 // can override this.
885 _status = Running;
886 switch (_kvmRun->exit_reason) {
887 case KVM_EXIT_UNKNOWN:
888 return handleKvmExitUnknown();
889
890 case KVM_EXIT_EXCEPTION:
891 return handleKvmExitException();
892
893 case KVM_EXIT_IO:
894 _status = RunningServiceCompletion;
895 ++numIO;
896 return handleKvmExitIO();
897
898 case KVM_EXIT_HYPERCALL:
899 ++numHypercalls;
900 return handleKvmExitHypercall();
901
902 case KVM_EXIT_HLT:
903 /* The guest has halted and is waiting for interrupts */
904 DPRINTF(Kvm, "handleKvmExitHalt\n");
905 ++numHalt;
906
907 // Suspend the thread until the next interrupt arrives
908 thread->suspend();
909
910 // This is actually ignored since the thread is suspended.
911 return 0;
912
913 case KVM_EXIT_MMIO:
914 _status = RunningServiceCompletion;
915 /* Service memory mapped IO requests */
916 DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
917 _kvmRun->mmio.is_write,
918 _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
919
920 ++numMMIO;
921 return doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
922 _kvmRun->mmio.len, _kvmRun->mmio.is_write);
923
924 case KVM_EXIT_IRQ_WINDOW_OPEN:
925 return handleKvmExitIRQWindowOpen();
926
927 case KVM_EXIT_FAIL_ENTRY:
928 return handleKvmExitFailEntry();
929
930 case KVM_EXIT_INTR:
931 /* KVM was interrupted by a signal, restart it in the next
932 * tick. */
933 return 0;
934
935 case KVM_EXIT_INTERNAL_ERROR:
936 panic("KVM: Internal error (suberror: %u)\n",
937 _kvmRun->internal.suberror);
938
939 default:
940 dump();
941 panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
942 }
943}
944
945Tick
946BaseKvmCPU::handleKvmExitIO()
947{
948 panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
949 _kvmRun->io.direction, _kvmRun->io.size,
950 _kvmRun->io.port, _kvmRun->io.count);
951}
952
953Tick
954BaseKvmCPU::handleKvmExitHypercall()
955{
956 panic("KVM: Unhandled hypercall\n");
957}
958
959Tick
960BaseKvmCPU::handleKvmExitIRQWindowOpen()
961{
962 warn("KVM: Unhandled IRQ window.\n");
963 return 0;
964}
965
966
967Tick
968BaseKvmCPU::handleKvmExitUnknown()
969{
970 dump();
971 panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
972 _kvmRun->hw.hardware_exit_reason);
973}
974
975Tick
976BaseKvmCPU::handleKvmExitException()
977{
978 dump();
979 panic("KVM: Got exception when starting vCPU "
980 "(exception: %u, error_code: %u)\n",
981 _kvmRun->ex.exception, _kvmRun->ex.error_code);
982}
983
984Tick
985BaseKvmCPU::handleKvmExitFailEntry()
986{
987 dump();
988 panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
989 _kvmRun->fail_entry.hardware_entry_failure_reason);
990}
991
992Tick
993BaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
994{
995 ThreadContext *tc(thread->getTC());
996 syncThreadContext();
997
121}
122
123void
124BaseKvmCPU::startup()
125{
126 const BaseKvmCPUParams * const p(
127 dynamic_cast<const BaseKvmCPUParams *>(params()));
128
129 Kvm &kvm(vm.kvm);
130
131 BaseCPU::startup();
132
133 assert(vcpuFD == -1);
134
135 // Tell the VM that a CPU is about to start.
136 vm.cpuStartup();
137
138 // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
139 // not guaranteed that the parent KVM VM has initialized at that
140 // point. Initialize virtual CPUs here instead.
141 vcpuFD = vm.createVCPU(vcpuID);
142
143 // Map the KVM run structure */
144 vcpuMMapSize = kvm.getVCPUMMapSize();
145 _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
146 PROT_READ | PROT_WRITE, MAP_SHARED,
147 vcpuFD, 0);
148 if (_kvmRun == MAP_FAILED)
149 panic("KVM: Failed to map run data structure\n");
150
151 // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
152 // available. The offset into the KVM's communication page is
153 // provided by the coalesced MMIO capability.
154 int mmioOffset(kvm.capCoalescedMMIO());
155 if (!p->useCoalescedMMIO) {
156 inform("KVM: Coalesced MMIO disabled by config.\n");
157 } else if (mmioOffset) {
158 inform("KVM: Coalesced IO available\n");
159 mmioRing = (struct kvm_coalesced_mmio_ring *)(
160 (char *)_kvmRun + (mmioOffset * pageSize));
161 } else {
162 inform("KVM: Coalesced not supported by host OS\n");
163 }
164
165 thread->startup();
166
167 Event *startupEvent(
168 new EventWrapper<BaseKvmCPU,
169 &BaseKvmCPU::startupThread>(this, true));
170 schedule(startupEvent, curTick());
171}
172
173void
174BaseKvmCPU::startupThread()
175{
176 // Do thread-specific initialization. We need to setup signal
177 // delivery for counters and timers from within the thread that
178 // will execute the event queue to ensure that signals are
179 // delivered to the right threads.
180 const BaseKvmCPUParams * const p(
181 dynamic_cast<const BaseKvmCPUParams *>(params()));
182
183 vcpuThread = pthread_self();
184
185 // Setup signal handlers. This has to be done after the vCPU is
186 // created since it manipulates the vCPU signal mask.
187 setupSignalHandler();
188
189 setupCounters();
190
191 if (p->usePerfOverflow)
192 runTimer.reset(new PerfKvmTimer(hwCycles,
193 KVM_KICK_SIGNAL,
194 p->hostFactor,
195 p->hostFreq));
196 else
197 runTimer.reset(new PosixKvmTimer(KVM_KICK_SIGNAL, CLOCK_MONOTONIC,
198 p->hostFactor,
199 p->hostFreq));
200
201}
202
203void
204BaseKvmCPU::regStats()
205{
206 using namespace Stats;
207
208 BaseCPU::regStats();
209
210 numInsts
211 .name(name() + ".committedInsts")
212 .desc("Number of instructions committed")
213 ;
214
215 numVMExits
216 .name(name() + ".numVMExits")
217 .desc("total number of KVM exits")
218 ;
219
220 numVMHalfEntries
221 .name(name() + ".numVMHalfEntries")
222 .desc("number of KVM entries to finalize pending operations")
223 ;
224
225 numExitSignal
226 .name(name() + ".numExitSignal")
227 .desc("exits due to signal delivery")
228 ;
229
230 numMMIO
231 .name(name() + ".numMMIO")
232 .desc("number of VM exits due to memory mapped IO")
233 ;
234
235 numCoalescedMMIO
236 .name(name() + ".numCoalescedMMIO")
237 .desc("number of coalesced memory mapped IO requests")
238 ;
239
240 numIO
241 .name(name() + ".numIO")
242 .desc("number of VM exits due to legacy IO")
243 ;
244
245 numHalt
246 .name(name() + ".numHalt")
247 .desc("number of VM exits due to wait for interrupt instructions")
248 ;
249
250 numInterrupts
251 .name(name() + ".numInterrupts")
252 .desc("number of interrupts delivered")
253 ;
254
255 numHypercalls
256 .name(name() + ".numHypercalls")
257 .desc("number of hypercalls")
258 ;
259}
260
261void
262BaseKvmCPU::serializeThread(std::ostream &os, ThreadID tid)
263{
264 if (DTRACE(Checkpoint)) {
265 DPRINTF(Checkpoint, "KVM: Serializing thread %i:\n", tid);
266 dump();
267 }
268
269 assert(tid == 0);
270 assert(_status == Idle);
271 thread->serialize(os);
272}
273
274void
275BaseKvmCPU::unserializeThread(Checkpoint *cp, const std::string &section,
276 ThreadID tid)
277{
278 DPRINTF(Checkpoint, "KVM: Unserialize thread %i:\n", tid);
279
280 assert(tid == 0);
281 assert(_status == Idle);
282 thread->unserialize(cp, section);
283 threadContextDirty = true;
284}
285
286unsigned int
287BaseKvmCPU::drain(DrainManager *dm)
288{
289 if (switchedOut())
290 return 0;
291
292 DPRINTF(Drain, "BaseKvmCPU::drain\n");
293 switch (_status) {
294 case Running:
295 // The base KVM code is normally ready when it is in the
296 // Running state, but the architecture specific code might be
297 // of a different opinion. This may happen when the CPU been
298 // notified of an event that hasn't been accepted by the vCPU
299 // yet.
300 if (!archIsDrained()) {
301 drainManager = dm;
302 return 1;
303 }
304
305 // The state of the CPU is consistent, so we don't need to do
306 // anything special to drain it. We simply de-schedule the
307 // tick event and enter the Idle state to prevent nasty things
308 // like MMIOs from happening.
309 if (tickEvent.scheduled())
310 deschedule(tickEvent);
311 _status = Idle;
312
313 /** FALLTHROUGH */
314 case Idle:
315 // Idle, no need to drain
316 assert(!tickEvent.scheduled());
317
318 // Sync the thread context here since we'll need it when we
319 // switch CPUs or checkpoint the CPU.
320 syncThreadContext();
321
322 return 0;
323
324 case RunningServiceCompletion:
325 // The CPU has just requested a service that was handled in
326 // the RunningService state, but the results have still not
327 // been reported to the CPU. Now, we /could/ probably just
328 // update the register state ourselves instead of letting KVM
329 // handle it, but that would be tricky. Instead, we enter KVM
330 // and let it do its stuff.
331 drainManager = dm;
332
333 DPRINTF(Drain, "KVM CPU is waiting for service completion, "
334 "requesting drain.\n");
335 return 1;
336
337 case RunningService:
338 // We need to drain since the CPU is waiting for service (e.g., MMIOs)
339 drainManager = dm;
340
341 DPRINTF(Drain, "KVM CPU is waiting for service, requesting drain.\n");
342 return 1;
343
344 default:
345 panic("KVM: Unhandled CPU state in drain()\n");
346 return 0;
347 }
348}
349
350void
351BaseKvmCPU::drainResume()
352{
353 assert(!tickEvent.scheduled());
354
355 // We might have been switched out. In that case, we don't need to
356 // do anything.
357 if (switchedOut())
358 return;
359
360 DPRINTF(Kvm, "drainResume\n");
361 verifyMemoryMode();
362
363 // The tick event is de-scheduled as a part of the draining
364 // process. Re-schedule it if the thread context is active.
365 if (tc->status() == ThreadContext::Active) {
366 schedule(tickEvent, nextCycle());
367 _status = Running;
368 } else {
369 _status = Idle;
370 }
371}
372
373void
374BaseKvmCPU::switchOut()
375{
376 DPRINTF(Kvm, "switchOut\n");
377
378 BaseCPU::switchOut();
379
380 // We should have drained prior to executing a switchOut, which
381 // means that the tick event shouldn't be scheduled and the CPU is
382 // idle.
383 assert(!tickEvent.scheduled());
384 assert(_status == Idle);
385}
386
387void
388BaseKvmCPU::takeOverFrom(BaseCPU *cpu)
389{
390 DPRINTF(Kvm, "takeOverFrom\n");
391
392 BaseCPU::takeOverFrom(cpu);
393
394 // We should have drained prior to executing a switchOut, which
395 // means that the tick event shouldn't be scheduled and the CPU is
396 // idle.
397 assert(!tickEvent.scheduled());
398 assert(_status == Idle);
399 assert(threadContexts.size() == 1);
400
401 // Force an update of the KVM state here instead of flagging the
402 // TC as dirty. This is not ideal from a performance point of
403 // view, but it makes debugging easier as it allows meaningful KVM
404 // state to be dumped before and after a takeover.
405 updateKvmState();
406 threadContextDirty = false;
407}
408
409void
410BaseKvmCPU::verifyMemoryMode() const
411{
412 if (!(system->isAtomicMode() && system->bypassCaches())) {
413 fatal("The KVM-based CPUs requires the memory system to be in the "
414 "'atomic_noncaching' mode.\n");
415 }
416}
417
418void
419BaseKvmCPU::wakeup()
420{
421 DPRINTF(Kvm, "wakeup()\n");
422 // This method might have been called from another
423 // context. Migrate to this SimObject's event queue when
424 // delivering the wakeup signal.
425 EventQueue::ScopedMigration migrate(eventQueue());
426
427 // Kick the vCPU to get it to come out of KVM.
428 kick();
429
430 if (thread->status() != ThreadContext::Suspended)
431 return;
432
433 thread->activate();
434}
435
436void
437BaseKvmCPU::activateContext(ThreadID thread_num)
438{
439 DPRINTF(Kvm, "ActivateContext %d\n", thread_num);
440
441 assert(thread_num == 0);
442 assert(thread);
443
444 assert(_status == Idle);
445 assert(!tickEvent.scheduled());
446
447 numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend);
448
449 schedule(tickEvent, clockEdge(Cycles(0)));
450 _status = Running;
451}
452
453
454void
455BaseKvmCPU::suspendContext(ThreadID thread_num)
456{
457 DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
458
459 assert(thread_num == 0);
460 assert(thread);
461
462 if (_status == Idle)
463 return;
464
465 assert(_status == Running || _status == RunningServiceCompletion);
466
467 // The tick event may no be scheduled if the quest has requested
468 // the monitor to wait for interrupts. The normal CPU models can
469 // get their tick events descheduled by quiesce instructions, but
470 // that can't happen here.
471 if (tickEvent.scheduled())
472 deschedule(tickEvent);
473
474 _status = Idle;
475}
476
477void
478BaseKvmCPU::deallocateContext(ThreadID thread_num)
479{
480 // for now, these are equivalent
481 suspendContext(thread_num);
482}
483
484void
485BaseKvmCPU::haltContext(ThreadID thread_num)
486{
487 // for now, these are equivalent
488 suspendContext(thread_num);
489}
490
491ThreadContext *
492BaseKvmCPU::getContext(int tn)
493{
494 assert(tn == 0);
495 syncThreadContext();
496 return tc;
497}
498
499
500Counter
501BaseKvmCPU::totalInsts() const
502{
503 return ctrInsts;
504}
505
506Counter
507BaseKvmCPU::totalOps() const
508{
509 hack_once("Pretending totalOps is equivalent to totalInsts()\n");
510 return ctrInsts;
511}
512
513void
514BaseKvmCPU::dump()
515{
516 inform("State dumping not implemented.");
517}
518
519void
520BaseKvmCPU::tick()
521{
522 Tick delay(0);
523 assert(_status != Idle);
524
525 switch (_status) {
526 case RunningService:
527 // handleKvmExit() will determine the next state of the CPU
528 delay = handleKvmExit();
529
530 if (tryDrain())
531 _status = Idle;
532 break;
533
534 case RunningServiceCompletion:
535 case Running: {
536 EventQueue *q = curEventQueue();
537 Tick ticksToExecute(q->nextTick() - curTick());
538
539 // We might need to update the KVM state.
540 syncKvmState();
541
542 // Setup any pending instruction count breakpoints using
543 // PerfEvent.
544 setupInstStop();
545
546 DPRINTF(KvmRun, "Entering KVM...\n");
547 if (drainManager) {
548 // Force an immediate exit from KVM after completing
549 // pending operations. The architecture-specific code
550 // takes care to run until it is in a state where it can
551 // safely be drained.
552 delay = kvmRunDrain();
553 } else {
554 delay = kvmRun(ticksToExecute);
555 }
556
557 // The CPU might have been suspended before entering into
558 // KVM. Assume that the CPU was suspended /before/ entering
559 // into KVM and skip the exit handling.
560 if (_status == Idle)
561 break;
562
563 // Entering into KVM implies that we'll have to reload the thread
564 // context from KVM if we want to access it. Flag the KVM state as
565 // dirty with respect to the cached thread context.
566 kvmStateDirty = true;
567
568 // Enter into the RunningService state unless the
569 // simulation was stopped by a timer.
570 if (_kvmRun->exit_reason != KVM_EXIT_INTR) {
571 _status = RunningService;
572 } else {
573 ++numExitSignal;
574 _status = Running;
575 }
576
577 // Service any pending instruction events. The vCPU should
578 // have exited in time for the event using the instruction
579 // counter configured by setupInstStop().
580 comInstEventQueue[0]->serviceEvents(ctrInsts);
581 system->instEventQueue.serviceEvents(system->totalNumInsts);
582
583 if (tryDrain())
584 _status = Idle;
585 } break;
586
587 default:
588 panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
589 _status);
590 }
591
592 // Schedule a new tick if we are still running
593 if (_status != Idle)
594 schedule(tickEvent, clockEdge(ticksToCycles(delay)));
595}
596
597Tick
598BaseKvmCPU::kvmRunDrain()
599{
600 // By default, the only thing we need to drain is a pending IO
601 // operation which assumes that we are in the
602 // RunningServiceCompletion state.
603 assert(_status == RunningServiceCompletion);
604
605 // Deliver the data from the pending IO operation and immediately
606 // exit.
607 return kvmRun(0);
608}
609
610uint64_t
611BaseKvmCPU::getHostCycles() const
612{
613 return hwCycles.read();
614}
615
616Tick
617BaseKvmCPU::kvmRun(Tick ticks)
618{
619 Tick ticksExecuted;
620 DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
621
622 if (ticks == 0) {
623 // Settings ticks == 0 is a special case which causes an entry
624 // into KVM that finishes pending operations (e.g., IO) and
625 // then immediately exits.
626 DPRINTF(KvmRun, "KVM: Delivering IO without full guest entry\n");
627
628 ++numVMHalfEntries;
629
630 // Send a KVM_KICK_SIGNAL to the vCPU thread (i.e., this
631 // thread). The KVM control signal is masked while executing
632 // in gem5 and gets unmasked temporarily as when entering
633 // KVM. See setSignalMask() and setupSignalHandler().
634 kick();
635
636 // Start the vCPU. KVM will check for signals after completing
637 // pending operations (IO). Since the KVM_KICK_SIGNAL is
638 // pending, this forces an immediate exit to gem5 again. We
639 // don't bother to setup timers since this shouldn't actually
640 // execute any code (other than completing half-executed IO
641 // instructions) in the guest.
642 ioctlRun();
643
644 // We always execute at least one cycle to prevent the
645 // BaseKvmCPU::tick() to be rescheduled on the same tick
646 // twice.
647 ticksExecuted = clockPeriod();
648 } else {
649 // This method is executed as a result of a tick event. That
650 // means that the event queue will be locked when entering the
651 // method. We temporarily unlock the event queue to allow
652 // other threads to steal control of this thread to inject
653 // interrupts. They will typically lock the queue and then
654 // force an exit from KVM by kicking the vCPU.
655 EventQueue::ScopedRelease release(curEventQueue());
656
657 if (ticks < runTimer->resolution()) {
658 DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
659 ticks, runTimer->resolution());
660 ticks = runTimer->resolution();
661 }
662
663 // Get hardware statistics after synchronizing contexts. The KVM
664 // state update might affect guest cycle counters.
665 uint64_t baseCycles(getHostCycles());
666 uint64_t baseInstrs(hwInstructions.read());
667
668 // Arm the run timer and start the cycle timer if it isn't
669 // controlled by the overflow timer. Starting/stopping the cycle
670 // timer automatically starts the other perf timers as they are in
671 // the same counter group.
672 runTimer->arm(ticks);
673 if (!perfControlledByTimer)
674 hwCycles.start();
675
676 ioctlRun();
677
678 runTimer->disarm();
679 if (!perfControlledByTimer)
680 hwCycles.stop();
681
682 // The control signal may have been delivered after we exited
683 // from KVM. It will be pending in that case since it is
684 // masked when we aren't executing in KVM. Discard it to make
685 // sure we don't deliver it immediately next time we try to
686 // enter into KVM.
687 discardPendingSignal(KVM_KICK_SIGNAL);
688
689 const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles);
690 const uint64_t simCyclesExecuted(hostCyclesExecuted * hostFactor);
691 const uint64_t instsExecuted(hwInstructions.read() - baseInstrs);
692 ticksExecuted = runTimer->ticksFromHostCycles(hostCyclesExecuted);
693
694 /* Update statistics */
695 numCycles += simCyclesExecuted;;
696 numInsts += instsExecuted;
697 ctrInsts += instsExecuted;
698 system->totalNumInsts += instsExecuted;
699
700 DPRINTF(KvmRun,
701 "KVM: Executed %i instructions in %i cycles "
702 "(%i ticks, sim cycles: %i).\n",
703 instsExecuted, hostCyclesExecuted, ticksExecuted, simCyclesExecuted);
704 }
705
706 ++numVMExits;
707
708 return ticksExecuted + flushCoalescedMMIO();
709}
710
711void
712BaseKvmCPU::kvmNonMaskableInterrupt()
713{
714 ++numInterrupts;
715 if (ioctl(KVM_NMI) == -1)
716 panic("KVM: Failed to deliver NMI to virtual CPU\n");
717}
718
719void
720BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
721{
722 ++numInterrupts;
723 if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
724 panic("KVM: Failed to deliver interrupt to virtual CPU\n");
725}
726
727void
728BaseKvmCPU::getRegisters(struct kvm_regs &regs) const
729{
730 if (ioctl(KVM_GET_REGS, &regs) == -1)
731 panic("KVM: Failed to get guest registers\n");
732}
733
734void
735BaseKvmCPU::setRegisters(const struct kvm_regs &regs)
736{
737 if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
738 panic("KVM: Failed to set guest registers\n");
739}
740
741void
742BaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
743{
744 if (ioctl(KVM_GET_SREGS, &regs) == -1)
745 panic("KVM: Failed to get guest special registers\n");
746}
747
748void
749BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
750{
751 if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
752 panic("KVM: Failed to set guest special registers\n");
753}
754
755void
756BaseKvmCPU::getFPUState(struct kvm_fpu &state) const
757{
758 if (ioctl(KVM_GET_FPU, &state) == -1)
759 panic("KVM: Failed to get guest FPU state\n");
760}
761
762void
763BaseKvmCPU::setFPUState(const struct kvm_fpu &state)
764{
765 if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
766 panic("KVM: Failed to set guest FPU state\n");
767}
768
769
770void
771BaseKvmCPU::setOneReg(uint64_t id, const void *addr)
772{
773#ifdef KVM_SET_ONE_REG
774 struct kvm_one_reg reg;
775 reg.id = id;
776 reg.addr = (uint64_t)addr;
777
778 if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
779 panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
780 id, errno);
781 }
782#else
783 panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
784#endif
785}
786
787void
788BaseKvmCPU::getOneReg(uint64_t id, void *addr) const
789{
790#ifdef KVM_GET_ONE_REG
791 struct kvm_one_reg reg;
792 reg.id = id;
793 reg.addr = (uint64_t)addr;
794
795 if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
796 panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
797 id, errno);
798 }
799#else
800 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
801#endif
802}
803
804std::string
805BaseKvmCPU::getAndFormatOneReg(uint64_t id) const
806{
807#ifdef KVM_GET_ONE_REG
808 std::ostringstream ss;
809
810 ss.setf(std::ios::hex, std::ios::basefield);
811 ss.setf(std::ios::showbase);
812#define HANDLE_INTTYPE(len) \
813 case KVM_REG_SIZE_U ## len: { \
814 uint ## len ## _t value; \
815 getOneReg(id, &value); \
816 ss << value; \
817 } break
818
819#define HANDLE_ARRAY(len) \
820 case KVM_REG_SIZE_U ## len: { \
821 uint8_t value[len / 8]; \
822 getOneReg(id, value); \
823 ss << "[" << value[0]; \
824 for (int i = 1; i < len / 8; ++i) \
825 ss << ", " << value[i]; \
826 ss << "]"; \
827 } break
828
829 switch (id & KVM_REG_SIZE_MASK) {
830 HANDLE_INTTYPE(8);
831 HANDLE_INTTYPE(16);
832 HANDLE_INTTYPE(32);
833 HANDLE_INTTYPE(64);
834 HANDLE_ARRAY(128);
835 HANDLE_ARRAY(256);
836 HANDLE_ARRAY(512);
837 HANDLE_ARRAY(1024);
838 default:
839 ss << "??";
840 }
841
842#undef HANDLE_INTTYPE
843#undef HANDLE_ARRAY
844
845 return ss.str();
846#else
847 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
848#endif
849}
850
851void
852BaseKvmCPU::syncThreadContext()
853{
854 if (!kvmStateDirty)
855 return;
856
857 assert(!threadContextDirty);
858
859 updateThreadContext();
860 kvmStateDirty = false;
861}
862
863void
864BaseKvmCPU::syncKvmState()
865{
866 if (!threadContextDirty)
867 return;
868
869 assert(!kvmStateDirty);
870
871 updateKvmState();
872 threadContextDirty = false;
873}
874
875Tick
876BaseKvmCPU::handleKvmExit()
877{
878 DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
879 assert(_status == RunningService);
880
881 // Switch into the running state by default. Individual handlers
882 // can override this.
883 _status = Running;
884 switch (_kvmRun->exit_reason) {
885 case KVM_EXIT_UNKNOWN:
886 return handleKvmExitUnknown();
887
888 case KVM_EXIT_EXCEPTION:
889 return handleKvmExitException();
890
891 case KVM_EXIT_IO:
892 _status = RunningServiceCompletion;
893 ++numIO;
894 return handleKvmExitIO();
895
896 case KVM_EXIT_HYPERCALL:
897 ++numHypercalls;
898 return handleKvmExitHypercall();
899
900 case KVM_EXIT_HLT:
901 /* The guest has halted and is waiting for interrupts */
902 DPRINTF(Kvm, "handleKvmExitHalt\n");
903 ++numHalt;
904
905 // Suspend the thread until the next interrupt arrives
906 thread->suspend();
907
908 // This is actually ignored since the thread is suspended.
909 return 0;
910
911 case KVM_EXIT_MMIO:
912 _status = RunningServiceCompletion;
913 /* Service memory mapped IO requests */
914 DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
915 _kvmRun->mmio.is_write,
916 _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
917
918 ++numMMIO;
919 return doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
920 _kvmRun->mmio.len, _kvmRun->mmio.is_write);
921
922 case KVM_EXIT_IRQ_WINDOW_OPEN:
923 return handleKvmExitIRQWindowOpen();
924
925 case KVM_EXIT_FAIL_ENTRY:
926 return handleKvmExitFailEntry();
927
928 case KVM_EXIT_INTR:
929 /* KVM was interrupted by a signal, restart it in the next
930 * tick. */
931 return 0;
932
933 case KVM_EXIT_INTERNAL_ERROR:
934 panic("KVM: Internal error (suberror: %u)\n",
935 _kvmRun->internal.suberror);
936
937 default:
938 dump();
939 panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
940 }
941}
942
943Tick
944BaseKvmCPU::handleKvmExitIO()
945{
946 panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
947 _kvmRun->io.direction, _kvmRun->io.size,
948 _kvmRun->io.port, _kvmRun->io.count);
949}
950
951Tick
952BaseKvmCPU::handleKvmExitHypercall()
953{
954 panic("KVM: Unhandled hypercall\n");
955}
956
957Tick
958BaseKvmCPU::handleKvmExitIRQWindowOpen()
959{
960 warn("KVM: Unhandled IRQ window.\n");
961 return 0;
962}
963
964
965Tick
966BaseKvmCPU::handleKvmExitUnknown()
967{
968 dump();
969 panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
970 _kvmRun->hw.hardware_exit_reason);
971}
972
973Tick
974BaseKvmCPU::handleKvmExitException()
975{
976 dump();
977 panic("KVM: Got exception when starting vCPU "
978 "(exception: %u, error_code: %u)\n",
979 _kvmRun->ex.exception, _kvmRun->ex.error_code);
980}
981
982Tick
983BaseKvmCPU::handleKvmExitFailEntry()
984{
985 dump();
986 panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
987 _kvmRun->fail_entry.hardware_entry_failure_reason);
988}
989
990Tick
991BaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
992{
993 ThreadContext *tc(thread->getTC());
994 syncThreadContext();
995
998 mmio_req.setPhys(paddr, size, Request::UNCACHEABLE, dataMasterId());
996 Request mmio_req(paddr, size, Request::UNCACHEABLE, dataMasterId());
997 mmio_req.setThreadContext(tc->contextId(), 0);
999 // Some architectures do need to massage physical addresses a bit
1000 // before they are inserted into the memory system. This enables
1001 // APIC accesses on x86 and m5ops where supported through a MMIO
1002 // interface.
1003 BaseTLB::Mode tlb_mode(write ? BaseTLB::Write : BaseTLB::Read);
1004 Fault fault(tc->getDTBPtr()->finalizePhysical(&mmio_req, tc, tlb_mode));
1005 if (fault != NoFault)
1006 warn("Finalization of MMIO address failed: %s\n", fault->name());
1007
1008
1009 const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
1010 Packet pkt(&mmio_req, cmd);
1011 pkt.dataStatic(data);
1012
1013 if (mmio_req.isMmappedIpr()) {
1014 // We currently assume that there is no need to migrate to a
1015 // different event queue when doing IPRs. Currently, IPRs are
1016 // only used for m5ops, so it should be a valid assumption.
1017 const Cycles ipr_delay(write ?
1018 TheISA::handleIprWrite(tc, &pkt) :
1019 TheISA::handleIprRead(tc, &pkt));
1020 threadContextDirty = true;
1021 return clockPeriod() * ipr_delay;
1022 } else {
1023 // Temporarily lock and migrate to the event queue of the
1024 // VM. This queue is assumed to "own" all devices we need to
1025 // access if running in multi-core mode.
1026 EventQueue::ScopedMigration migrate(vm.eventQueue());
1027
1028 return dataPort.sendAtomic(&pkt);
1029 }
1030}
1031
1032void
1033BaseKvmCPU::setSignalMask(const sigset_t *mask)
1034{
1035 std::unique_ptr<struct kvm_signal_mask> kvm_mask;
1036
1037 if (mask) {
1038 kvm_mask.reset((struct kvm_signal_mask *)operator new(
1039 sizeof(struct kvm_signal_mask) + sizeof(*mask)));
1040 // The kernel and the user-space headers have different ideas
1041 // about the size of sigset_t. This seems like a massive hack,
1042 // but is actually what qemu does.
1043 assert(sizeof(*mask) >= 8);
1044 kvm_mask->len = 8;
1045 memcpy(kvm_mask->sigset, mask, kvm_mask->len);
1046 }
1047
1048 if (ioctl(KVM_SET_SIGNAL_MASK, (void *)kvm_mask.get()) == -1)
1049 panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
1050 errno);
1051}
1052
1053int
1054BaseKvmCPU::ioctl(int request, long p1) const
1055{
1056 if (vcpuFD == -1)
1057 panic("KVM: CPU ioctl called before initialization\n");
1058
1059 return ::ioctl(vcpuFD, request, p1);
1060}
1061
1062Tick
1063BaseKvmCPU::flushCoalescedMMIO()
1064{
1065 if (!mmioRing)
1066 return 0;
1067
1068 DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
1069
1070 // TODO: We might need to do synchronization when we start to
1071 // support multiple CPUs
1072 Tick ticks(0);
1073 while (mmioRing->first != mmioRing->last) {
1074 struct kvm_coalesced_mmio &ent(
1075 mmioRing->coalesced_mmio[mmioRing->first]);
1076
1077 DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
1078 ent.phys_addr, ent.len);
1079
1080 ++numCoalescedMMIO;
1081 ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
1082
1083 mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
1084 }
1085
1086 return ticks;
1087}
1088
1089/**
1090 * Dummy handler for KVM kick signals.
1091 *
1092 * @note This function is usually not called since the kernel doesn't
1093 * seem to deliver signals when the signal is only unmasked when
1094 * running in KVM. This doesn't matter though since we are only
1095 * interested in getting KVM to exit, which happens as expected. See
1096 * setupSignalHandler() and kvmRun() for details about KVM signal
1097 * handling.
1098 */
1099static void
1100onKickSignal(int signo, siginfo_t *si, void *data)
1101{
1102}
1103
1104void
1105BaseKvmCPU::setupSignalHandler()
1106{
1107 struct sigaction sa;
1108
1109 memset(&sa, 0, sizeof(sa));
1110 sa.sa_sigaction = onKickSignal;
1111 sa.sa_flags = SA_SIGINFO | SA_RESTART;
1112 if (sigaction(KVM_KICK_SIGNAL, &sa, NULL) == -1)
1113 panic("KVM: Failed to setup vCPU timer signal handler\n");
1114
1115 sigset_t sigset;
1116 if (pthread_sigmask(SIG_BLOCK, NULL, &sigset) == -1)
1117 panic("KVM: Failed get signal mask\n");
1118
1119 // Request KVM to setup the same signal mask as we're currently
1120 // running with except for the KVM control signal. We'll sometimes
1121 // need to raise the KVM_KICK_SIGNAL to cause immediate exits from
1122 // KVM after servicing IO requests. See kvmRun().
1123 sigdelset(&sigset, KVM_KICK_SIGNAL);
1124 setSignalMask(&sigset);
1125
1126 // Mask our control signals so they aren't delivered unless we're
1127 // actually executing inside KVM.
1128 sigaddset(&sigset, KVM_KICK_SIGNAL);
1129 if (pthread_sigmask(SIG_SETMASK, &sigset, NULL) == -1)
1130 panic("KVM: Failed mask the KVM control signals\n");
1131}
1132
1133bool
1134BaseKvmCPU::discardPendingSignal(int signum) const
1135{
1136 int discardedSignal;
1137
1138 // Setting the timeout to zero causes sigtimedwait to return
1139 // immediately.
1140 struct timespec timeout;
1141 timeout.tv_sec = 0;
1142 timeout.tv_nsec = 0;
1143
1144 sigset_t sigset;
1145 sigemptyset(&sigset);
1146 sigaddset(&sigset, signum);
1147
1148 do {
1149 discardedSignal = sigtimedwait(&sigset, NULL, &timeout);
1150 } while (discardedSignal == -1 && errno == EINTR);
1151
1152 if (discardedSignal == signum)
1153 return true;
1154 else if (discardedSignal == -1 && errno == EAGAIN)
1155 return false;
1156 else
1157 panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
1158 discardedSignal, errno);
1159}
1160
1161void
1162BaseKvmCPU::setupCounters()
1163{
1164 DPRINTF(Kvm, "Attaching cycle counter...\n");
1165 PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
1166 PERF_COUNT_HW_CPU_CYCLES);
1167 cfgCycles.disabled(true)
1168 .pinned(true);
1169
1170 // Try to exclude the host. We set both exclude_hv and
1171 // exclude_host since different architectures use slightly
1172 // different APIs in the kernel.
1173 cfgCycles.exclude_hv(true)
1174 .exclude_host(true);
1175
1176 if (perfControlledByTimer) {
1177 // We need to configure the cycles counter to send overflows
1178 // since we are going to use it to trigger timer signals that
1179 // trap back into m5 from KVM. In practice, this means that we
1180 // need to set some non-zero sample period that gets
1181 // overridden when the timer is armed.
1182 cfgCycles.wakeupEvents(1)
1183 .samplePeriod(42);
1184 }
1185
1186 hwCycles.attach(cfgCycles,
1187 0); // TID (0 => currentThread)
1188
1189 setupInstCounter();
1190}
1191
1192bool
1193BaseKvmCPU::tryDrain()
1194{
1195 if (!drainManager)
1196 return false;
1197
1198 if (!archIsDrained()) {
1199 DPRINTF(Drain, "tryDrain: Architecture code is not ready.\n");
1200 return false;
1201 }
1202
1203 if (_status == Idle || _status == Running) {
1204 DPRINTF(Drain,
1205 "tryDrain: CPU transitioned into the Idle state, drain done\n");
1206 drainManager->signalDrainDone();
1207 drainManager = NULL;
1208 return true;
1209 } else {
1210 DPRINTF(Drain, "tryDrain: CPU not ready.\n");
1211 return false;
1212 }
1213}
1214
1215void
1216BaseKvmCPU::ioctlRun()
1217{
1218 if (ioctl(KVM_RUN) == -1) {
1219 if (errno != EINTR)
1220 panic("KVM: Failed to start virtual CPU (errno: %i)\n",
1221 errno);
1222 }
1223}
1224
1225void
1226BaseKvmCPU::setupInstStop()
1227{
1228 if (comInstEventQueue[0]->empty()) {
1229 setupInstCounter(0);
1230 } else {
1231 const uint64_t next(comInstEventQueue[0]->nextTick());
1232
1233 assert(next > ctrInsts);
1234 setupInstCounter(next - ctrInsts);
1235 }
1236}
1237
1238void
1239BaseKvmCPU::setupInstCounter(uint64_t period)
1240{
1241 // No need to do anything if we aren't attaching for the first
1242 // time or the period isn't changing.
1243 if (period == activeInstPeriod && hwInstructions.attached())
1244 return;
1245
1246 PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
1247 PERF_COUNT_HW_INSTRUCTIONS);
1248
1249 // Try to exclude the host. We set both exclude_hv and
1250 // exclude_host since different architectures use slightly
1251 // different APIs in the kernel.
1252 cfgInstructions.exclude_hv(true)
1253 .exclude_host(true);
1254
1255 if (period) {
1256 // Setup a sampling counter if that has been requested.
1257 cfgInstructions.wakeupEvents(1)
1258 .samplePeriod(period);
1259 }
1260
1261 // We need to detach and re-attach the counter to reliably change
1262 // sampling settings. See PerfKvmCounter::period() for details.
1263 if (hwInstructions.attached())
1264 hwInstructions.detach();
1265 assert(hwCycles.attached());
1266 hwInstructions.attach(cfgInstructions,
1267 0, // TID (0 => currentThread)
1268 hwCycles);
1269
1270 if (period)
1271 hwInstructions.enableSignals(KVM_KICK_SIGNAL);
1272
1273 activeInstPeriod = period;
1274}
998 // Some architectures do need to massage physical addresses a bit
999 // before they are inserted into the memory system. This enables
1000 // APIC accesses on x86 and m5ops where supported through a MMIO
1001 // interface.
1002 BaseTLB::Mode tlb_mode(write ? BaseTLB::Write : BaseTLB::Read);
1003 Fault fault(tc->getDTBPtr()->finalizePhysical(&mmio_req, tc, tlb_mode));
1004 if (fault != NoFault)
1005 warn("Finalization of MMIO address failed: %s\n", fault->name());
1006
1007
1008 const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
1009 Packet pkt(&mmio_req, cmd);
1010 pkt.dataStatic(data);
1011
1012 if (mmio_req.isMmappedIpr()) {
1013 // We currently assume that there is no need to migrate to a
1014 // different event queue when doing IPRs. Currently, IPRs are
1015 // only used for m5ops, so it should be a valid assumption.
1016 const Cycles ipr_delay(write ?
1017 TheISA::handleIprWrite(tc, &pkt) :
1018 TheISA::handleIprRead(tc, &pkt));
1019 threadContextDirty = true;
1020 return clockPeriod() * ipr_delay;
1021 } else {
1022 // Temporarily lock and migrate to the event queue of the
1023 // VM. This queue is assumed to "own" all devices we need to
1024 // access if running in multi-core mode.
1025 EventQueue::ScopedMigration migrate(vm.eventQueue());
1026
1027 return dataPort.sendAtomic(&pkt);
1028 }
1029}
1030
1031void
1032BaseKvmCPU::setSignalMask(const sigset_t *mask)
1033{
1034 std::unique_ptr<struct kvm_signal_mask> kvm_mask;
1035
1036 if (mask) {
1037 kvm_mask.reset((struct kvm_signal_mask *)operator new(
1038 sizeof(struct kvm_signal_mask) + sizeof(*mask)));
1039 // The kernel and the user-space headers have different ideas
1040 // about the size of sigset_t. This seems like a massive hack,
1041 // but is actually what qemu does.
1042 assert(sizeof(*mask) >= 8);
1043 kvm_mask->len = 8;
1044 memcpy(kvm_mask->sigset, mask, kvm_mask->len);
1045 }
1046
1047 if (ioctl(KVM_SET_SIGNAL_MASK, (void *)kvm_mask.get()) == -1)
1048 panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
1049 errno);
1050}
1051
1052int
1053BaseKvmCPU::ioctl(int request, long p1) const
1054{
1055 if (vcpuFD == -1)
1056 panic("KVM: CPU ioctl called before initialization\n");
1057
1058 return ::ioctl(vcpuFD, request, p1);
1059}
1060
1061Tick
1062BaseKvmCPU::flushCoalescedMMIO()
1063{
1064 if (!mmioRing)
1065 return 0;
1066
1067 DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
1068
1069 // TODO: We might need to do synchronization when we start to
1070 // support multiple CPUs
1071 Tick ticks(0);
1072 while (mmioRing->first != mmioRing->last) {
1073 struct kvm_coalesced_mmio &ent(
1074 mmioRing->coalesced_mmio[mmioRing->first]);
1075
1076 DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
1077 ent.phys_addr, ent.len);
1078
1079 ++numCoalescedMMIO;
1080 ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
1081
1082 mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
1083 }
1084
1085 return ticks;
1086}
1087
1088/**
1089 * Dummy handler for KVM kick signals.
1090 *
1091 * @note This function is usually not called since the kernel doesn't
1092 * seem to deliver signals when the signal is only unmasked when
1093 * running in KVM. This doesn't matter though since we are only
1094 * interested in getting KVM to exit, which happens as expected. See
1095 * setupSignalHandler() and kvmRun() for details about KVM signal
1096 * handling.
1097 */
1098static void
1099onKickSignal(int signo, siginfo_t *si, void *data)
1100{
1101}
1102
1103void
1104BaseKvmCPU::setupSignalHandler()
1105{
1106 struct sigaction sa;
1107
1108 memset(&sa, 0, sizeof(sa));
1109 sa.sa_sigaction = onKickSignal;
1110 sa.sa_flags = SA_SIGINFO | SA_RESTART;
1111 if (sigaction(KVM_KICK_SIGNAL, &sa, NULL) == -1)
1112 panic("KVM: Failed to setup vCPU timer signal handler\n");
1113
1114 sigset_t sigset;
1115 if (pthread_sigmask(SIG_BLOCK, NULL, &sigset) == -1)
1116 panic("KVM: Failed get signal mask\n");
1117
1118 // Request KVM to setup the same signal mask as we're currently
1119 // running with except for the KVM control signal. We'll sometimes
1120 // need to raise the KVM_KICK_SIGNAL to cause immediate exits from
1121 // KVM after servicing IO requests. See kvmRun().
1122 sigdelset(&sigset, KVM_KICK_SIGNAL);
1123 setSignalMask(&sigset);
1124
1125 // Mask our control signals so they aren't delivered unless we're
1126 // actually executing inside KVM.
1127 sigaddset(&sigset, KVM_KICK_SIGNAL);
1128 if (pthread_sigmask(SIG_SETMASK, &sigset, NULL) == -1)
1129 panic("KVM: Failed mask the KVM control signals\n");
1130}
1131
1132bool
1133BaseKvmCPU::discardPendingSignal(int signum) const
1134{
1135 int discardedSignal;
1136
1137 // Setting the timeout to zero causes sigtimedwait to return
1138 // immediately.
1139 struct timespec timeout;
1140 timeout.tv_sec = 0;
1141 timeout.tv_nsec = 0;
1142
1143 sigset_t sigset;
1144 sigemptyset(&sigset);
1145 sigaddset(&sigset, signum);
1146
1147 do {
1148 discardedSignal = sigtimedwait(&sigset, NULL, &timeout);
1149 } while (discardedSignal == -1 && errno == EINTR);
1150
1151 if (discardedSignal == signum)
1152 return true;
1153 else if (discardedSignal == -1 && errno == EAGAIN)
1154 return false;
1155 else
1156 panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
1157 discardedSignal, errno);
1158}
1159
1160void
1161BaseKvmCPU::setupCounters()
1162{
1163 DPRINTF(Kvm, "Attaching cycle counter...\n");
1164 PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
1165 PERF_COUNT_HW_CPU_CYCLES);
1166 cfgCycles.disabled(true)
1167 .pinned(true);
1168
1169 // Try to exclude the host. We set both exclude_hv and
1170 // exclude_host since different architectures use slightly
1171 // different APIs in the kernel.
1172 cfgCycles.exclude_hv(true)
1173 .exclude_host(true);
1174
1175 if (perfControlledByTimer) {
1176 // We need to configure the cycles counter to send overflows
1177 // since we are going to use it to trigger timer signals that
1178 // trap back into m5 from KVM. In practice, this means that we
1179 // need to set some non-zero sample period that gets
1180 // overridden when the timer is armed.
1181 cfgCycles.wakeupEvents(1)
1182 .samplePeriod(42);
1183 }
1184
1185 hwCycles.attach(cfgCycles,
1186 0); // TID (0 => currentThread)
1187
1188 setupInstCounter();
1189}
1190
1191bool
1192BaseKvmCPU::tryDrain()
1193{
1194 if (!drainManager)
1195 return false;
1196
1197 if (!archIsDrained()) {
1198 DPRINTF(Drain, "tryDrain: Architecture code is not ready.\n");
1199 return false;
1200 }
1201
1202 if (_status == Idle || _status == Running) {
1203 DPRINTF(Drain,
1204 "tryDrain: CPU transitioned into the Idle state, drain done\n");
1205 drainManager->signalDrainDone();
1206 drainManager = NULL;
1207 return true;
1208 } else {
1209 DPRINTF(Drain, "tryDrain: CPU not ready.\n");
1210 return false;
1211 }
1212}
1213
1214void
1215BaseKvmCPU::ioctlRun()
1216{
1217 if (ioctl(KVM_RUN) == -1) {
1218 if (errno != EINTR)
1219 panic("KVM: Failed to start virtual CPU (errno: %i)\n",
1220 errno);
1221 }
1222}
1223
1224void
1225BaseKvmCPU::setupInstStop()
1226{
1227 if (comInstEventQueue[0]->empty()) {
1228 setupInstCounter(0);
1229 } else {
1230 const uint64_t next(comInstEventQueue[0]->nextTick());
1231
1232 assert(next > ctrInsts);
1233 setupInstCounter(next - ctrInsts);
1234 }
1235}
1236
1237void
1238BaseKvmCPU::setupInstCounter(uint64_t period)
1239{
1240 // No need to do anything if we aren't attaching for the first
1241 // time or the period isn't changing.
1242 if (period == activeInstPeriod && hwInstructions.attached())
1243 return;
1244
1245 PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
1246 PERF_COUNT_HW_INSTRUCTIONS);
1247
1248 // Try to exclude the host. We set both exclude_hv and
1249 // exclude_host since different architectures use slightly
1250 // different APIs in the kernel.
1251 cfgInstructions.exclude_hv(true)
1252 .exclude_host(true);
1253
1254 if (period) {
1255 // Setup a sampling counter if that has been requested.
1256 cfgInstructions.wakeupEvents(1)
1257 .samplePeriod(period);
1258 }
1259
1260 // We need to detach and re-attach the counter to reliably change
1261 // sampling settings. See PerfKvmCounter::period() for details.
1262 if (hwInstructions.attached())
1263 hwInstructions.detach();
1264 assert(hwCycles.attached());
1265 hwInstructions.attach(cfgInstructions,
1266 0, // TID (0 => currentThread)
1267 hwCycles);
1268
1269 if (period)
1270 hwInstructions.enableSignals(KVM_KICK_SIGNAL);
1271
1272 activeInstPeriod = period;
1273}