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