在虚拟化场景下,遇到复杂的case,可能不知道如何处理。learn from native可能是一个突破口。何为native呢?本文指的是非虚拟化场景下,该case的行为(读者需要清楚:什么operation由硬件完成,什么operation由软件完成)。

读者可能会觉得上面的话很抽象,本文将以一个例子阐述该思想。

1. Background(behavior in native)

读者需要阅读Notes about instruction boundaries

If more than one exception or interrupt is pending at an instruction boundary, the processor services them in a predictable order. Table 6-2 shows the priority among classes of exception and interrupt sources.

The processor first services a pending exception or interrupt from the class which has the highest priority, transferring execution to the first instruction of the handler. Lower priority exceptions are discarded; lower priority interrupts are held pending. Discarded exceptions are re-generated when the interrupt handler returns execution to the point in the program or task where the exceptions and/or interrupts occurred.

SDM对于Simultaneous Exceptions and Interrupts 给出了描述。接下来将以一个具体的例子阐述相关知识点。

在native环境下,假设当前CPU会执行rdmsr指令,rdmsr指令的执行时间为5个cycle,并且rdsmr指令会产生#GP。当CPU执行rdmsr到第3个cycle时,外部设备向该CPU发送了一个Maskable Hardware Interrupt。那么,接下来的硬件行为是什么呢?

当CPU执行完rdmsr指令后,由于Maskable Hardware Interrupt的优先级高于#GP,因此CPU会丢弃#GP,优先处理Maskable Hardware Interrupt。当Maskable Hardware Interrupt处理完之后,硬件会re-generate #GP。

2. Is Simultaneous Exceptions and Interrupts?(behavior in virtualization)

假设在虚拟化场景下:

  1. 当前CPU只运行一个vCPU thread
  2. 当前CPU的LAPIC pass-thru给vCPU
  3. 在root mode下,hv会关中断
  4. 在non-root mode下,当vCPU执行rdmsr时,会发生VM Exit,hv将为vCPU注入#GP
  5. 在root下,当hv为vCPU注入#GP时,外部设备向该CPU发送了一个Maskable Hardware Interrupt

那么,读者可以尝试回答如下问题:

在guest看来,Maskable Hardware Interrupt和#GP是Simultaneous Exceptions and Interrupts吗?

实验结果如下:当进入non-root mode后,vCPU会先处理#GP,然后处理Maskable Hardware Interrupt。由此可见,在guest看来,Maskable Hardware Interrupt和#GP不是Simultaneous Exceptions and Interrupts。

为什么?此时,learn from native的方案就派上用场了。在native环境下,Maskable Hardware Interrupt和#GP pending at an instruction boundary时,硬件才会将Maskable Hardware Interrupt和#GP当作Simultaneous Exceptions and Interrupts。在我们的这个例子中,当guest执行完rdmsr指令后,根据instruction boundary,以guest的视角来看,硬件会立刻为其注入#GP,而Maskable Hardware Interrupt是在guest执行完rdmsr指令后产生的,因此,在guest看来,Maskable Hardware Interrupt和#GP不是Simultaneous Exceptions and Interrupts。

3. Rethinking

假设在虚拟化场景下:

  1. 当前CPU只运行一个vCPU thread
  2. 当前CPU的LAPIC pass-thru给vCPU
  3. 在non-root mode下,当vCPU执行rdmsr时(执行时间为5个cycle),会发生VM Exit,hv将为vCPU注入#GP
  4. 在non-root mode下,当vCPU执行rdmsr到第3个cycle时时,外部设备向该CPU发送了一个Maskable Hardware Interrupt

那么,读者可以尝试回答如下问题:

在guest看来,Maskable Hardware Interrupt和#GP是Simultaneous Exceptions and Interrupts吗?

利用learn from native的方案可知,在guest看来,Maskable Hardware Interrupt和#GP是Simultaneous Exceptions and Interrupts。

问题又来了,在虚拟化环境下,是如何保证Discarded exceptions are re-generated when the interrupt handler returns execution to the point in the program or task where the exceptions and/or interrupts occurred?

在non-root mode下,当vCPU处理完Maskable Hardware Interrupt后,RIP寄存器会保证vCPU再执行一次rdmsr指令,那么,就会发生VM Exit,hv会给vCPU 注入#GP。