timekeeping.txt 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. Timekeeping Virtualization for X86-Based Architectures
  2. Zachary Amsden <zamsden@redhat.com>
  3. Copyright (c) 2010, Red Hat. All rights reserved.
  4. 1) Overview
  5. 2) Timing Devices
  6. 3) TSC Hardware
  7. 4) Virtualization Problems
  8. =========================================================================
  9. 1) Overview
  10. One of the most complicated parts of the X86 platform, and specifically,
  11. the virtualization of this platform is the plethora of timing devices available
  12. and the complexity of emulating those devices. In addition, virtualization of
  13. time introduces a new set of challenges because it introduces a multiplexed
  14. division of time beyond the control of the guest CPU.
  15. First, we will describe the various timekeeping hardware available, then
  16. present some of the problems which arise and solutions available, giving
  17. specific recommendations for certain classes of KVM guests.
  18. The purpose of this document is to collect data and information relevant to
  19. timekeeping which may be difficult to find elsewhere, specifically,
  20. information relevant to KVM and hardware-based virtualization.
  21. =========================================================================
  22. 2) Timing Devices
  23. First we discuss the basic hardware devices available. TSC and the related
  24. KVM clock are special enough to warrant a full exposition and are described in
  25. the following section.
  26. 2.1) i8254 - PIT
  27. One of the first timer devices available is the programmable interrupt timer,
  28. or PIT. The PIT has a fixed frequency 1.193182 MHz base clock and three
  29. channels which can be programmed to deliver periodic or one-shot interrupts.
  30. These three channels can be configured in different modes and have individual
  31. counters. Channel 1 and 2 were not available for general use in the original
  32. IBM PC, and historically were connected to control RAM refresh and the PC
  33. speaker. Now the PIT is typically integrated as part of an emulated chipset
  34. and a separate physical PIT is not used.
  35. The PIT uses I/O ports 0x40 - 0x43. Access to the 16-bit counters is done
  36. using single or multiple byte access to the I/O ports. There are 6 modes
  37. available, but not all modes are available to all timers, as only timer 2
  38. has a connected gate input, required for modes 1 and 5. The gate line is
  39. controlled by port 61h, bit 0, as illustrated in the following diagram.
  40. -------------- ----------------
  41. | | | |
  42. | 1.1932 MHz |---------->| CLOCK OUT | ---------> IRQ 0
  43. | Clock | | | |
  44. -------------- | +->| GATE TIMER 0 |
  45. | ----------------
  46. |
  47. | ----------------
  48. | | |
  49. |------>| CLOCK OUT | ---------> 66.3 KHZ DRAM
  50. | | | (aka /dev/null)
  51. | +->| GATE TIMER 1 |
  52. | ----------------
  53. |
  54. | ----------------
  55. | | |
  56. |------>| CLOCK OUT | ---------> Port 61h, bit 5
  57. | | |
  58. Port 61h, bit 0 ---------->| GATE TIMER 2 | \_.---- ____
  59. ---------------- _| )--|LPF|---Speaker
  60. / *---- \___/
  61. Port 61h, bit 1 -----------------------------------/
  62. The timer modes are now described.
  63. Mode 0: Single Timeout. This is a one-shot software timeout that counts down
  64. when the gate is high (always true for timers 0 and 1). When the count
  65. reaches zero, the output goes high.
  66. Mode 1: Triggered One-shot. The output is initially set high. When the gate
  67. line is set high, a countdown is initiated (which does not stop if the gate is
  68. lowered), during which the output is set low. When the count reaches zero,
  69. the output goes high.
  70. Mode 2: Rate Generator. The output is initially set high. When the countdown
  71. reaches 1, the output goes low for one count and then returns high. The value
  72. is reloaded and the countdown automatically resumes. If the gate line goes
  73. low, the count is halted. If the output is low when the gate is lowered, the
  74. output automatically goes high (this only affects timer 2).
  75. Mode 3: Square Wave. This generates a high / low square wave. The count
  76. determines the length of the pulse, which alternates between high and low
  77. when zero is reached. The count only proceeds when gate is high and is
  78. automatically reloaded on reaching zero. The count is decremented twice at
  79. each clock to generate a full high / low cycle at the full periodic rate.
  80. If the count is even, the clock remains high for N/2 counts and low for N/2
  81. counts; if the clock is odd, the clock is high for (N+1)/2 counts and low
  82. for (N-1)/2 counts. Only even values are latched by the counter, so odd
  83. values are not observed when reading. This is the intended mode for timer 2,
  84. which generates sine-like tones by low-pass filtering the square wave output.
  85. Mode 4: Software Strobe. After programming this mode and loading the counter,
  86. the output remains high until the counter reaches zero. Then the output
  87. goes low for 1 clock cycle and returns high. The counter is not reloaded.
  88. Counting only occurs when gate is high.
  89. Mode 5: Hardware Strobe. After programming and loading the counter, the
  90. output remains high. When the gate is raised, a countdown is initiated
  91. (which does not stop if the gate is lowered). When the counter reaches zero,
  92. the output goes low for 1 clock cycle and then returns high. The counter is
  93. not reloaded.
  94. In addition to normal binary counting, the PIT supports BCD counting. The
  95. command port, 0x43 is used to set the counter and mode for each of the three
  96. timers.
  97. PIT commands, issued to port 0x43, using the following bit encoding:
  98. Bit 7-4: Command (See table below)
  99. Bit 3-1: Mode (000 = Mode 0, 101 = Mode 5, 11X = undefined)
  100. Bit 0 : Binary (0) / BCD (1)
  101. Command table:
  102. 0000 - Latch Timer 0 count for port 0x40
  103. sample and hold the count to be read in port 0x40;
  104. additional commands ignored until counter is read;
  105. mode bits ignored.
  106. 0001 - Set Timer 0 LSB mode for port 0x40
  107. set timer to read LSB only and force MSB to zero;
  108. mode bits set timer mode
  109. 0010 - Set Timer 0 MSB mode for port 0x40
  110. set timer to read MSB only and force LSB to zero;
  111. mode bits set timer mode
  112. 0011 - Set Timer 0 16-bit mode for port 0x40
  113. set timer to read / write LSB first, then MSB;
  114. mode bits set timer mode
  115. 0100 - Latch Timer 1 count for port 0x41 - as described above
  116. 0101 - Set Timer 1 LSB mode for port 0x41 - as described above
  117. 0110 - Set Timer 1 MSB mode for port 0x41 - as described above
  118. 0111 - Set Timer 1 16-bit mode for port 0x41 - as described above
  119. 1000 - Latch Timer 2 count for port 0x42 - as described above
  120. 1001 - Set Timer 2 LSB mode for port 0x42 - as described above
  121. 1010 - Set Timer 2 MSB mode for port 0x42 - as described above
  122. 1011 - Set Timer 2 16-bit mode for port 0x42 as described above
  123. 1101 - General counter latch
  124. Latch combination of counters into corresponding ports
  125. Bit 3 = Counter 2
  126. Bit 2 = Counter 1
  127. Bit 1 = Counter 0
  128. Bit 0 = Unused
  129. 1110 - Latch timer status
  130. Latch combination of counter mode into corresponding ports
  131. Bit 3 = Counter 2
  132. Bit 2 = Counter 1
  133. Bit 1 = Counter 0
  134. The output of ports 0x40-0x42 following this command will be:
  135. Bit 7 = Output pin
  136. Bit 6 = Count loaded (0 if timer has expired)
  137. Bit 5-4 = Read / Write mode
  138. 01 = MSB only
  139. 10 = LSB only
  140. 11 = LSB / MSB (16-bit)
  141. Bit 3-1 = Mode
  142. Bit 0 = Binary (0) / BCD mode (1)
  143. 2.2) RTC
  144. The second device which was available in the original PC was the MC146818 real
  145. time clock. The original device is now obsolete, and usually emulated by the
  146. system chipset, sometimes by an HPET and some frankenstein IRQ routing.
  147. The RTC is accessed through CMOS variables, which uses an index register to
  148. control which bytes are read. Since there is only one index register, read
  149. of the CMOS and read of the RTC require lock protection (in addition, it is
  150. dangerous to allow userspace utilities such as hwclock to have direct RTC
  151. access, as they could corrupt kernel reads and writes of CMOS memory).
  152. The RTC generates an interrupt which is usually routed to IRQ 8. The interrupt
  153. can function as a periodic timer, an additional once a day alarm, and can issue
  154. interrupts after an update of the CMOS registers by the MC146818 is complete.
  155. The type of interrupt is signalled in the RTC status registers.
  156. The RTC will update the current time fields by battery power even while the
  157. system is off. The current time fields should not be read while an update is
  158. in progress, as indicated in the status register.
  159. The clock uses a 32.768kHz crystal, so bits 6-4 of register A should be
  160. programmed to a 32kHz divider if the RTC is to count seconds.
  161. This is the RAM map originally used for the RTC/CMOS:
  162. Location Size Description
  163. ------------------------------------------
  164. 00h byte Current second (BCD)
  165. 01h byte Seconds alarm (BCD)
  166. 02h byte Current minute (BCD)
  167. 03h byte Minutes alarm (BCD)
  168. 04h byte Current hour (BCD)
  169. 05h byte Hours alarm (BCD)
  170. 06h byte Current day of week (BCD)
  171. 07h byte Current day of month (BCD)
  172. 08h byte Current month (BCD)
  173. 09h byte Current year (BCD)
  174. 0Ah byte Register A
  175. bit 7 = Update in progress
  176. bit 6-4 = Divider for clock
  177. 000 = 4.194 MHz
  178. 001 = 1.049 MHz
  179. 010 = 32 kHz
  180. 10X = test modes
  181. 110 = reset / disable
  182. 111 = reset / disable
  183. bit 3-0 = Rate selection for periodic interrupt
  184. 000 = periodic timer disabled
  185. 001 = 3.90625 uS
  186. 010 = 7.8125 uS
  187. 011 = .122070 mS
  188. 100 = .244141 mS
  189. ...
  190. 1101 = 125 mS
  191. 1110 = 250 mS
  192. 1111 = 500 mS
  193. 0Bh byte Register B
  194. bit 7 = Run (0) / Halt (1)
  195. bit 6 = Periodic interrupt enable
  196. bit 5 = Alarm interrupt enable
  197. bit 4 = Update-ended interrupt enable
  198. bit 3 = Square wave interrupt enable
  199. bit 2 = BCD calendar (0) / Binary (1)
  200. bit 1 = 12-hour mode (0) / 24-hour mode (1)
  201. bit 0 = 0 (DST off) / 1 (DST enabled)
  202. OCh byte Register C (read only)
  203. bit 7 = interrupt request flag (IRQF)
  204. bit 6 = periodic interrupt flag (PF)
  205. bit 5 = alarm interrupt flag (AF)
  206. bit 4 = update interrupt flag (UF)
  207. bit 3-0 = reserved
  208. ODh byte Register D (read only)
  209. bit 7 = RTC has power
  210. bit 6-0 = reserved
  211. 32h byte Current century BCD (*)
  212. (*) location vendor specific and now determined from ACPI global tables
  213. 2.3) APIC
  214. On Pentium and later processors, an on-board timer is available to each CPU
  215. as part of the Advanced Programmable Interrupt Controller. The APIC is
  216. accessed through memory-mapped registers and provides interrupt service to each
  217. CPU, used for IPIs and local timer interrupts.
  218. Although in theory the APIC is a safe and stable source for local interrupts,
  219. in practice, many bugs and glitches have occurred due to the special nature of
  220. the APIC CPU-local memory-mapped hardware. Beware that CPU errata may affect
  221. the use of the APIC and that workarounds may be required. In addition, some of
  222. these workarounds pose unique constraints for virtualization - requiring either
  223. extra overhead incurred from extra reads of memory-mapped I/O or additional
  224. functionality that may be more computationally expensive to implement.
  225. Since the APIC is documented quite well in the Intel and AMD manuals, we will
  226. avoid repetition of the detail here. It should be pointed out that the APIC
  227. timer is programmed through the LVT (local vector timer) register, is capable
  228. of one-shot or periodic operation, and is based on the bus clock divided down
  229. by the programmable divider register.
  230. 2.4) HPET
  231. HPET is quite complex, and was originally intended to replace the PIT / RTC
  232. support of the X86 PC. It remains to be seen whether that will be the case, as
  233. the de facto standard of PC hardware is to emulate these older devices. Some
  234. systems designated as legacy free may support only the HPET as a hardware timer
  235. device.
  236. The HPET spec is rather loose and vague, requiring at least 3 hardware timers,
  237. but allowing implementation freedom to support many more. It also imposes no
  238. fixed rate on the timer frequency, but does impose some extremal values on
  239. frequency, error and slew.
  240. In general, the HPET is recommended as a high precision (compared to PIT /RTC)
  241. time source which is independent of local variation (as there is only one HPET
  242. in any given system). The HPET is also memory-mapped, and its presence is
  243. indicated through ACPI tables by the BIOS.
  244. Detailed specification of the HPET is beyond the current scope of this
  245. document, as it is also very well documented elsewhere.
  246. 2.5) Offboard Timers
  247. Several cards, both proprietary (watchdog boards) and commonplace (e1000) have
  248. timing chips built into the cards which may have registers which are accessible
  249. to kernel or user drivers. To the author's knowledge, using these to generate
  250. a clocksource for a Linux or other kernel has not yet been attempted and is in
  251. general frowned upon as not playing by the agreed rules of the game. Such a
  252. timer device would require additional support to be virtualized properly and is
  253. not considered important at this time as no known operating system does this.
  254. =========================================================================
  255. 3) TSC Hardware
  256. The TSC or time stamp counter is relatively simple in theory; it counts
  257. instruction cycles issued by the processor, which can be used as a measure of
  258. time. In practice, due to a number of problems, it is the most complicated
  259. timekeeping device to use.
  260. The TSC is represented internally as a 64-bit MSR which can be read with the
  261. RDMSR, RDTSC, or RDTSCP (when available) instructions. In the past, hardware
  262. limitations made it possible to write the TSC, but generally on old hardware it
  263. was only possible to write the low 32-bits of the 64-bit counter, and the upper
  264. 32-bits of the counter were cleared. Now, however, on Intel processors family
  265. 0Fh, for models 3, 4 and 6, and family 06h, models e and f, this restriction
  266. has been lifted and all 64-bits are writable. On AMD systems, the ability to
  267. write the TSC MSR is not an architectural guarantee.
  268. The TSC is accessible from CPL-0 and conditionally, for CPL > 0 software by
  269. means of the CR4.TSD bit, which when enabled, disables CPL > 0 TSC access.
  270. Some vendors have implemented an additional instruction, RDTSCP, which returns
  271. atomically not just the TSC, but an indicator which corresponds to the
  272. processor number. This can be used to index into an array of TSC variables to
  273. determine offset information in SMP systems where TSCs are not synchronized.
  274. The presence of this instruction must be determined by consulting CPUID feature
  275. bits.
  276. Both VMX and SVM provide extension fields in the virtualization hardware which
  277. allows the guest visible TSC to be offset by a constant. Newer implementations
  278. promise to allow the TSC to additionally be scaled, but this hardware is not
  279. yet widely available.
  280. 3.1) TSC synchronization
  281. The TSC is a CPU-local clock in most implementations. This means, on SMP
  282. platforms, the TSCs of different CPUs may start at different times depending
  283. on when the CPUs are powered on. Generally, CPUs on the same die will share
  284. the same clock, however, this is not always the case.
  285. The BIOS may attempt to resynchronize the TSCs during the poweron process and
  286. the operating system or other system software may attempt to do this as well.
  287. Several hardware limitations make the problem worse - if it is not possible to
  288. write the full 64-bits of the TSC, it may be impossible to match the TSC in
  289. newly arriving CPUs to that of the rest of the system, resulting in
  290. unsynchronized TSCs. This may be done by BIOS or system software, but in
  291. practice, getting a perfectly synchronized TSC will not be possible unless all
  292. values are read from the same clock, which generally only is possible on single
  293. socket systems or those with special hardware support.
  294. 3.2) TSC and CPU hotplug
  295. As touched on already, CPUs which arrive later than the boot time of the system
  296. may not have a TSC value that is synchronized with the rest of the system.
  297. Either system software, BIOS, or SMM code may actually try to establish the TSC
  298. to a value matching the rest of the system, but a perfect match is usually not
  299. a guarantee. This can have the effect of bringing a system from a state where
  300. TSC is synchronized back to a state where TSC synchronization flaws, however
  301. small, may be exposed to the OS and any virtualization environment.
  302. 3.3) TSC and multi-socket / NUMA
  303. Multi-socket systems, especially large multi-socket systems are likely to have
  304. individual clocksources rather than a single, universally distributed clock.
  305. Since these clocks are driven by different crystals, they will not have
  306. perfectly matched frequency, and temperature and electrical variations will
  307. cause the CPU clocks, and thus the TSCs to drift over time. Depending on the
  308. exact clock and bus design, the drift may or may not be fixed in absolute
  309. error, and may accumulate over time.
  310. In addition, very large systems may deliberately slew the clocks of individual
  311. cores. This technique, known as spread-spectrum clocking, reduces EMI at the
  312. clock frequency and harmonics of it, which may be required to pass FCC
  313. standards for telecommunications and computer equipment.
  314. It is recommended not to trust the TSCs to remain synchronized on NUMA or
  315. multiple socket systems for these reasons.
  316. 3.4) TSC and C-states
  317. C-states, or idling states of the processor, especially C1E and deeper sleep
  318. states may be problematic for TSC as well. The TSC may stop advancing in such
  319. a state, resulting in a TSC which is behind that of other CPUs when execution
  320. is resumed. Such CPUs must be detected and flagged by the operating system
  321. based on CPU and chipset identifications.
  322. The TSC in such a case may be corrected by catching it up to a known external
  323. clocksource.
  324. 3.5) TSC frequency change / P-states
  325. To make things slightly more interesting, some CPUs may change frequency. They
  326. may or may not run the TSC at the same rate, and because the frequency change
  327. may be staggered or slewed, at some points in time, the TSC rate may not be
  328. known other than falling within a range of values. In this case, the TSC will
  329. not be a stable time source, and must be calibrated against a known, stable,
  330. external clock to be a usable source of time.
  331. Whether the TSC runs at a constant rate or scales with the P-state is model
  332. dependent and must be determined by inspecting CPUID, chipset or vendor
  333. specific MSR fields.
  334. In addition, some vendors have known bugs where the P-state is actually
  335. compensated for properly during normal operation, but when the processor is
  336. inactive, the P-state may be raised temporarily to service cache misses from
  337. other processors. In such cases, the TSC on halted CPUs could advance faster
  338. than that of non-halted processors. AMD Turion processors are known to have
  339. this problem.
  340. 3.6) TSC and STPCLK / T-states
  341. External signals given to the processor may also have the effect of stopping
  342. the TSC. This is typically done for thermal emergency power control to prevent
  343. an overheating condition, and typically, there is no way to detect that this
  344. condition has happened.
  345. 3.7) TSC virtualization - VMX
  346. VMX provides conditional trapping of RDTSC, RDMSR, WRMSR and RDTSCP
  347. instructions, which is enough for full virtualization of TSC in any manner. In
  348. addition, VMX allows passing through the host TSC plus an additional TSC_OFFSET
  349. field specified in the VMCS. Special instructions must be used to read and
  350. write the VMCS field.
  351. 3.8) TSC virtualization - SVM
  352. SVM provides conditional trapping of RDTSC, RDMSR, WRMSR and RDTSCP
  353. instructions, which is enough for full virtualization of TSC in any manner. In
  354. addition, SVM allows passing through the host TSC plus an additional offset
  355. field specified in the SVM control block.
  356. 3.9) TSC feature bits in Linux
  357. In summary, there is no way to guarantee the TSC remains in perfect
  358. synchronization unless it is explicitly guaranteed by the architecture. Even
  359. if so, the TSCs in multi-sockets or NUMA systems may still run independently
  360. despite being locally consistent.
  361. The following feature bits are used by Linux to signal various TSC attributes,
  362. but they can only be taken to be meaningful for UP or single node systems.
  363. X86_FEATURE_TSC : The TSC is available in hardware
  364. X86_FEATURE_RDTSCP : The RDTSCP instruction is available
  365. X86_FEATURE_CONSTANT_TSC : The TSC rate is unchanged with P-states
  366. X86_FEATURE_NONSTOP_TSC : The TSC does not stop in C-states
  367. X86_FEATURE_TSC_RELIABLE : TSC sync checks are skipped (VMware)
  368. 4) Virtualization Problems
  369. Timekeeping is especially problematic for virtualization because a number of
  370. challenges arise. The most obvious problem is that time is now shared between
  371. the host and, potentially, a number of virtual machines. Thus the virtual
  372. operating system does not run with 100% usage of the CPU, despite the fact that
  373. it may very well make that assumption. It may expect it to remain true to very
  374. exacting bounds when interrupt sources are disabled, but in reality only its
  375. virtual interrupt sources are disabled, and the machine may still be preempted
  376. at any time. This causes problems as the passage of real time, the injection
  377. of machine interrupts and the associated clock sources are no longer completely
  378. synchronized with real time.
  379. This same problem can occur on native hardware to a degree, as SMM mode may
  380. steal cycles from the naturally on X86 systems when SMM mode is used by the
  381. BIOS, but not in such an extreme fashion. However, the fact that SMM mode may
  382. cause similar problems to virtualization makes it a good justification for
  383. solving many of these problems on bare metal.
  384. 4.1) Interrupt clocking
  385. One of the most immediate problems that occurs with legacy operating systems
  386. is that the system timekeeping routines are often designed to keep track of
  387. time by counting periodic interrupts. These interrupts may come from the PIT
  388. or the RTC, but the problem is the same: the host virtualization engine may not
  389. be able to deliver the proper number of interrupts per second, and so guest
  390. time may fall behind. This is especially problematic if a high interrupt rate
  391. is selected, such as 1000 HZ, which is unfortunately the default for many Linux
  392. guests.
  393. There are three approaches to solving this problem; first, it may be possible
  394. to simply ignore it. Guests which have a separate time source for tracking
  395. 'wall clock' or 'real time' may not need any adjustment of their interrupts to
  396. maintain proper time. If this is not sufficient, it may be necessary to inject
  397. additional interrupts into the guest in order to increase the effective
  398. interrupt rate. This approach leads to complications in extreme conditions,
  399. where host load or guest lag is too much to compensate for, and thus another
  400. solution to the problem has risen: the guest may need to become aware of lost
  401. ticks and compensate for them internally. Although promising in theory, the
  402. implementation of this policy in Linux has been extremely error prone, and a
  403. number of buggy variants of lost tick compensation are distributed across
  404. commonly used Linux systems.
  405. Windows uses periodic RTC clocking as a means of keeping time internally, and
  406. thus requires interrupt slewing to keep proper time. It does use a low enough
  407. rate (ed: is it 18.2 Hz?) however that it has not yet been a problem in
  408. practice.
  409. 4.2) TSC sampling and serialization
  410. As the highest precision time source available, the cycle counter of the CPU
  411. has aroused much interest from developers. As explained above, this timer has
  412. many problems unique to its nature as a local, potentially unstable and
  413. potentially unsynchronized source. One issue which is not unique to the TSC,
  414. but is highlighted because of its very precise nature is sampling delay. By
  415. definition, the counter, once read is already old. However, it is also
  416. possible for the counter to be read ahead of the actual use of the result.
  417. This is a consequence of the superscalar execution of the instruction stream,
  418. which may execute instructions out of order. Such execution is called
  419. non-serialized. Forcing serialized execution is necessary for precise
  420. measurement with the TSC, and requires a serializing instruction, such as CPUID
  421. or an MSR read.
  422. Since CPUID may actually be virtualized by a trap and emulate mechanism, this
  423. serialization can pose a performance issue for hardware virtualization. An
  424. accurate time stamp counter reading may therefore not always be available, and
  425. it may be necessary for an implementation to guard against "backwards" reads of
  426. the TSC as seen from other CPUs, even in an otherwise perfectly synchronized
  427. system.
  428. 4.3) Timespec aliasing
  429. Additionally, this lack of serialization from the TSC poses another challenge
  430. when using results of the TSC when measured against another time source. As
  431. the TSC is much higher precision, many possible values of the TSC may be read
  432. while another clock is still expressing the same value.
  433. That is, you may read (T,T+10) while external clock C maintains the same value.
  434. Due to non-serialized reads, you may actually end up with a range which
  435. fluctuates - from (T-1.. T+10). Thus, any time calculated from a TSC, but
  436. calibrated against an external value may have a range of valid values.
  437. Re-calibrating this computation may actually cause time, as computed after the
  438. calibration, to go backwards, compared with time computed before the
  439. calibration.
  440. This problem is particularly pronounced with an internal time source in Linux,
  441. the kernel time, which is expressed in the theoretically high resolution
  442. timespec - but which advances in much larger granularity intervals, sometimes
  443. at the rate of jiffies, and possibly in catchup modes, at a much larger step.
  444. This aliasing requires care in the computation and recalibration of kvmclock
  445. and any other values derived from TSC computation (such as TSC virtualization
  446. itself).
  447. 4.4) Migration
  448. Migration of a virtual machine raises problems for timekeeping in two ways.
  449. First, the migration itself may take time, during which interrupts cannot be
  450. delivered, and after which, the guest time may need to be caught up. NTP may
  451. be able to help to some degree here, as the clock correction required is
  452. typically small enough to fall in the NTP-correctable window.
  453. An additional concern is that timers based off the TSC (or HPET, if the raw bus
  454. clock is exposed) may now be running at different rates, requiring compensation
  455. in some way in the hypervisor by virtualizing these timers. In addition,
  456. migrating to a faster machine may preclude the use of a passthrough TSC, as a
  457. faster clock cannot be made visible to a guest without the potential of time
  458. advancing faster than usual. A slower clock is less of a problem, as it can
  459. always be caught up to the original rate. KVM clock avoids these problems by
  460. simply storing multipliers and offsets against the TSC for the guest to convert
  461. back into nanosecond resolution values.
  462. 4.5) Scheduling
  463. Since scheduling may be based on precise timing and firing of interrupts, the
  464. scheduling algorithms of an operating system may be adversely affected by
  465. virtualization. In theory, the effect is random and should be universally
  466. distributed, but in contrived as well as real scenarios (guest device access,
  467. causes of virtualization exits, possible context switch), this may not always
  468. be the case. The effect of this has not been well studied.
  469. In an attempt to work around this, several implementations have provided a
  470. paravirtualized scheduler clock, which reveals the true amount of CPU time for
  471. which a virtual machine has been running.
  472. 4.6) Watchdogs
  473. Watchdog timers, such as the lock detector in Linux may fire accidentally when
  474. running under hardware virtualization due to timer interrupts being delayed or
  475. misinterpretation of the passage of real time. Usually, these warnings are
  476. spurious and can be ignored, but in some circumstances it may be necessary to
  477. disable such detection.
  478. 4.7) Delays and precision timing
  479. Precise timing and delays may not be possible in a virtualized system. This
  480. can happen if the system is controlling physical hardware, or issues delays to
  481. compensate for slower I/O to and from devices. The first issue is not solvable
  482. in general for a virtualized system; hardware control software can't be
  483. adequately virtualized without a full real-time operating system, which would
  484. require an RT aware virtualization platform.
  485. The second issue may cause performance problems, but this is unlikely to be a
  486. significant issue. In many cases these delays may be eliminated through
  487. configuration or paravirtualization.
  488. 4.8) Covert channels and leaks
  489. In addition to the above problems, time information will inevitably leak to the
  490. guest about the host in anything but a perfect implementation of virtualized
  491. time. This may allow the guest to infer the presence of a hypervisor (as in a
  492. red-pill type detection), and it may allow information to leak between guests
  493. by using CPU utilization itself as a signalling channel. Preventing such
  494. problems would require completely isolated virtual time which may not track
  495. real time any longer. This may be useful in certain security or QA contexts,
  496. but in general isn't recommended for real-world deployment scenarios.