VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/PGMPool.cpp@ 50653

Last change on this file since 50653 was 45808, checked in by vboxsync, 11 years ago

VMM,DevVGA: Don't resolve RC symbols when HM is enabled (part 1).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 52.3 KB
Line 
1/* $Id: PGMPool.cpp 45808 2013-04-29 12:41:07Z vboxsync $ */
2/** @file
3 * PGM Shadow Page Pool.
4 */
5
6/*
7 * Copyright (C) 2006-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @page pg_pgm_pool PGM Shadow Page Pool
19 *
20 * Motivations:
21 * -# Relationship between shadow page tables and physical guest pages. This
22 * should allow us to skip most of the global flushes now following access
23 * handler changes. The main expense is flushing shadow pages.
24 * -# Limit the pool size if necessary (default is kind of limitless).
25 * -# Allocate shadow pages from RC. We use to only do this in SyncCR3.
26 * -# Required for 64-bit guests.
27 * -# Combining the PD cache and page pool in order to simplify caching.
28 *
29 *
30 * @section sec_pgm_pool_outline Design Outline
31 *
32 * The shadow page pool tracks pages used for shadowing paging structures (i.e.
33 * page tables, page directory, page directory pointer table and page map
34 * level-4). Each page in the pool has an unique identifier. This identifier is
35 * used to link a guest physical page to a shadow PT. The identifier is a
36 * non-zero value and has a relativly low max value - say 14 bits. This makes it
37 * possible to fit it into the upper bits of the of the aHCPhys entries in the
38 * ram range.
39 *
40 * By restricting host physical memory to the first 48 bits (which is the
41 * announced physical memory range of the K8L chip (scheduled for 2008)), we
42 * can safely use the upper 16 bits for shadow page ID and reference counting.
43 *
44 * Update: The 48 bit assumption will be lifted with the new physical memory
45 * management (PGMPAGE), so we won't have any trouble when someone stuffs 2TB
46 * into a box in some years.
47 *
48 * Now, it's possible for a page to be aliased, i.e. mapped by more than one PT
49 * or PD. This is solved by creating a list of physical cross reference extents
50 * when ever this happens. Each node in the list (extent) is can contain 3 page
51 * pool indexes. The list it self is chained using indexes into the paPhysExt
52 * array.
53 *
54 *
55 * @section sec_pgm_pool_life Life Cycle of a Shadow Page
56 *
57 * -# The SyncPT function requests a page from the pool.
58 * The request includes the kind of page it is (PT/PD, PAE/legacy), the
59 * address of the page it's shadowing, and more.
60 * -# The pool responds to the request by allocating a new page.
61 * When the cache is enabled, it will first check if it's in the cache.
62 * Should the pool be exhausted, one of two things can be done:
63 * -# Flush the whole pool and current CR3.
64 * -# Use the cache to find a page which can be flushed (~age).
65 * -# The SyncPT function will sync one or more pages and insert it into the
66 * shadow PD.
67 * -# The SyncPage function may sync more pages on a later \#PFs.
68 * -# The page is freed / flushed in SyncCR3 (perhaps) and some other cases.
69 * When caching is enabled, the page isn't flush but remains in the cache.
70 *
71 *
72 * @section sec_pgm_pool_impl Monitoring
73 *
74 * We always monitor PAGE_SIZE chunks of memory. When we've got multiple shadow
75 * pages for the same PAGE_SIZE of guest memory (PAE and mixed PD/PT) the pages
76 * sharing the monitor get linked using the iMonitoredNext/Prev. The head page
77 * is the pvUser to the access handlers.
78 *
79 *
80 * @section sec_pgm_pool_impl Implementation
81 *
82 * The pool will take pages from the MM page pool. The tracking data
83 * (attributes, bitmaps and so on) are allocated from the hypervisor heap. The
84 * pool content can be accessed both by using the page id and the physical
85 * address (HC). The former is managed by means of an array, the latter by an
86 * offset based AVL tree.
87 *
88 * Flushing of a pool page means that we iterate the content (we know what kind
89 * it is) and updates the link information in the ram range.
90 *
91 * ...
92 */
93
94
95/*******************************************************************************
96* Header Files *
97*******************************************************************************/
98#define LOG_GROUP LOG_GROUP_PGM_POOL
99#include <VBox/vmm/pgm.h>
100#include <VBox/vmm/mm.h>
101#include "PGMInternal.h"
102#include <VBox/vmm/vm.h>
103#include <VBox/vmm/uvm.h>
104#include "PGMInline.h"
105
106#include <VBox/log.h>
107#include <VBox/err.h>
108#include <iprt/asm.h>
109#include <iprt/string.h>
110#include <VBox/dbg.h>
111
112
113/*******************************************************************************
114* Internal Functions *
115*******************************************************************************/
116static DECLCALLBACK(int) pgmR3PoolAccessHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser);
117#ifdef VBOX_WITH_DEBUGGER
118static FNDBGCCMD pgmR3PoolCmdCheck;
119#endif
120
121#ifdef VBOX_WITH_DEBUGGER
122/** Command descriptors. */
123static const DBGCCMD g_aCmds[] =
124{
125 /* pszCmd, cArgsMin, cArgsMax, paArgDesc, cArgDescs, fFlags, pfnHandler pszSyntax, ....pszDescription */
126 { "pgmpoolcheck", 0, 0, NULL, 0, 0, pgmR3PoolCmdCheck, "", "Check the pgm pool pages." },
127};
128#endif
129
130/**
131 * Initializes the pool
132 *
133 * @returns VBox status code.
134 * @param pVM Pointer to the VM.
135 */
136int pgmR3PoolInit(PVM pVM)
137{
138 int rc;
139
140 AssertCompile(NIL_PGMPOOL_IDX == 0);
141 /* pPage->cLocked is an unsigned byte. */
142 AssertCompile(VMM_MAX_CPU_COUNT <= 255);
143
144 /*
145 * Query Pool config.
146 */
147 PCFGMNODE pCfg = CFGMR3GetChild(CFGMR3GetRoot(pVM), "/PGM/Pool");
148
149 /* Default pgm pool size is 1024 pages (4MB). */
150 uint16_t cMaxPages = 1024;
151
152 /* Adjust it up relative to the RAM size, using the nested paging formula. */
153 uint64_t cbRam;
154 rc = CFGMR3QueryU64Def(CFGMR3GetRoot(pVM), "RamSize", &cbRam, 0); AssertRCReturn(rc, rc);
155 uint64_t u64MaxPages = (cbRam >> 9)
156 + (cbRam >> 18)
157 + (cbRam >> 27)
158 + 32 * PAGE_SIZE;
159 u64MaxPages >>= PAGE_SHIFT;
160 if (u64MaxPages > PGMPOOL_IDX_LAST)
161 cMaxPages = PGMPOOL_IDX_LAST;
162 else
163 cMaxPages = (uint16_t)u64MaxPages;
164
165 /** @cfgm{/PGM/Pool/MaxPages, uint16_t, #pages, 16, 0x3fff, F(ram-size)}
166 * The max size of the shadow page pool in pages. The pool will grow dynamically
167 * up to this limit.
168 */
169 rc = CFGMR3QueryU16Def(pCfg, "MaxPages", &cMaxPages, cMaxPages);
170 AssertLogRelRCReturn(rc, rc);
171 AssertLogRelMsgReturn(cMaxPages <= PGMPOOL_IDX_LAST && cMaxPages >= RT_ALIGN(PGMPOOL_IDX_FIRST, 16),
172 ("cMaxPages=%u (%#x)\n", cMaxPages, cMaxPages), VERR_INVALID_PARAMETER);
173 cMaxPages = RT_ALIGN(cMaxPages, 16);
174 if (cMaxPages > PGMPOOL_IDX_LAST)
175 cMaxPages = PGMPOOL_IDX_LAST;
176 LogRel(("PGMPool: cMaxPages=%u (u64MaxPages=%llu)\n", cMaxPages, u64MaxPages));
177
178 /** todo:
179 * We need to be much more careful with our allocation strategy here.
180 * For nested paging we don't need pool user info nor extents at all, but
181 * we can't check for nested paging here (too early during init to get a
182 * confirmation it can be used). The default for large memory configs is a
183 * bit large for shadow paging, so I've restricted the extent maximum to 8k
184 * (8k * 16 = 128k of hyper heap).
185 *
186 * Also when large page support is enabled, we typically don't need so much,
187 * although that depends on the availability of 2 MB chunks on the host.
188 */
189
190 /** @cfgm{/PGM/Pool/MaxUsers, uint16_t, #users, MaxUsers, 32K, MaxPages*2}
191 * The max number of shadow page user tracking records. Each shadow page has
192 * zero of other shadow pages (or CR3s) that references it, or uses it if you
193 * like. The structures describing these relationships are allocated from a
194 * fixed sized pool. This configuration variable defines the pool size.
195 */
196 uint16_t cMaxUsers;
197 rc = CFGMR3QueryU16Def(pCfg, "MaxUsers", &cMaxUsers, cMaxPages * 2);
198 AssertLogRelRCReturn(rc, rc);
199 AssertLogRelMsgReturn(cMaxUsers >= cMaxPages && cMaxPages <= _32K,
200 ("cMaxUsers=%u (%#x)\n", cMaxUsers, cMaxUsers), VERR_INVALID_PARAMETER);
201
202 /** @cfgm{/PGM/Pool/MaxPhysExts, uint16_t, #extents, 16, MaxPages * 2, MIN(MaxPages*2,8192)}
203 * The max number of extents for tracking aliased guest pages.
204 */
205 uint16_t cMaxPhysExts;
206 rc = CFGMR3QueryU16Def(pCfg, "MaxPhysExts", &cMaxPhysExts,
207 RT_MIN(cMaxPages * 2, 8192 /* 8Ki max as this eat too much hyper heap */));
208 AssertLogRelRCReturn(rc, rc);
209 AssertLogRelMsgReturn(cMaxPhysExts >= 16 && cMaxPhysExts <= PGMPOOL_IDX_LAST,
210 ("cMaxPhysExts=%u (%#x)\n", cMaxPhysExts, cMaxPhysExts), VERR_INVALID_PARAMETER);
211
212 /** @cfgm{/PGM/Pool/ChacheEnabled, bool, true}
213 * Enables or disabling caching of shadow pages. Caching means that we will try
214 * reuse shadow pages instead of recreating them everything SyncCR3, SyncPT or
215 * SyncPage requests one. When reusing a shadow page, we can save time
216 * reconstructing it and it's children.
217 */
218 bool fCacheEnabled;
219 rc = CFGMR3QueryBoolDef(pCfg, "CacheEnabled", &fCacheEnabled, true);
220 AssertLogRelRCReturn(rc, rc);
221
222 LogRel(("pgmR3PoolInit: cMaxPages=%#RX16 cMaxUsers=%#RX16 cMaxPhysExts=%#RX16 fCacheEnable=%RTbool\n",
223 cMaxPages, cMaxUsers, cMaxPhysExts, fCacheEnabled));
224
225 /*
226 * Allocate the data structures.
227 */
228 uint32_t cb = RT_OFFSETOF(PGMPOOL, aPages[cMaxPages]);
229 cb += cMaxUsers * sizeof(PGMPOOLUSER);
230 cb += cMaxPhysExts * sizeof(PGMPOOLPHYSEXT);
231 PPGMPOOL pPool;
232 rc = MMR3HyperAllocOnceNoRel(pVM, cb, 0, MM_TAG_PGM_POOL, (void **)&pPool);
233 if (RT_FAILURE(rc))
234 return rc;
235 pVM->pgm.s.pPoolR3 = pPool;
236 pVM->pgm.s.pPoolR0 = MMHyperR3ToR0(pVM, pPool);
237 pVM->pgm.s.pPoolRC = MMHyperR3ToRC(pVM, pPool);
238
239 /*
240 * Initialize it.
241 */
242 pPool->pVMR3 = pVM;
243 pPool->pVMR0 = pVM->pVMR0;
244 pPool->pVMRC = pVM->pVMRC;
245 pPool->cMaxPages = cMaxPages;
246 pPool->cCurPages = PGMPOOL_IDX_FIRST;
247 pPool->iUserFreeHead = 0;
248 pPool->cMaxUsers = cMaxUsers;
249 PPGMPOOLUSER paUsers = (PPGMPOOLUSER)&pPool->aPages[pPool->cMaxPages];
250 pPool->paUsersR3 = paUsers;
251 pPool->paUsersR0 = MMHyperR3ToR0(pVM, paUsers);
252 pPool->paUsersRC = MMHyperR3ToRC(pVM, paUsers);
253 for (unsigned i = 0; i < cMaxUsers; i++)
254 {
255 paUsers[i].iNext = i + 1;
256 paUsers[i].iUser = NIL_PGMPOOL_IDX;
257 paUsers[i].iUserTable = 0xfffffffe;
258 }
259 paUsers[cMaxUsers - 1].iNext = NIL_PGMPOOL_USER_INDEX;
260 pPool->iPhysExtFreeHead = 0;
261 pPool->cMaxPhysExts = cMaxPhysExts;
262 PPGMPOOLPHYSEXT paPhysExts = (PPGMPOOLPHYSEXT)&paUsers[cMaxUsers];
263 pPool->paPhysExtsR3 = paPhysExts;
264 pPool->paPhysExtsR0 = MMHyperR3ToR0(pVM, paPhysExts);
265 pPool->paPhysExtsRC = MMHyperR3ToRC(pVM, paPhysExts);
266 for (unsigned i = 0; i < cMaxPhysExts; i++)
267 {
268 paPhysExts[i].iNext = i + 1;
269 paPhysExts[i].aidx[0] = NIL_PGMPOOL_IDX;
270 paPhysExts[i].apte[0] = NIL_PGMPOOL_PHYSEXT_IDX_PTE;
271 paPhysExts[i].aidx[1] = NIL_PGMPOOL_IDX;
272 paPhysExts[i].apte[1] = NIL_PGMPOOL_PHYSEXT_IDX_PTE;
273 paPhysExts[i].aidx[2] = NIL_PGMPOOL_IDX;
274 paPhysExts[i].apte[2] = NIL_PGMPOOL_PHYSEXT_IDX_PTE;
275 }
276 paPhysExts[cMaxPhysExts - 1].iNext = NIL_PGMPOOL_PHYSEXT_INDEX;
277 for (unsigned i = 0; i < RT_ELEMENTS(pPool->aiHash); i++)
278 pPool->aiHash[i] = NIL_PGMPOOL_IDX;
279 pPool->iAgeHead = NIL_PGMPOOL_IDX;
280 pPool->iAgeTail = NIL_PGMPOOL_IDX;
281 pPool->fCacheEnabled = fCacheEnabled;
282 pPool->pfnAccessHandlerR3 = pgmR3PoolAccessHandler;
283 pPool->pszAccessHandler = "Guest Paging Access Handler";
284 pPool->HCPhysTree = 0;
285
286 /*
287 * The NIL entry.
288 */
289 Assert(NIL_PGMPOOL_IDX == 0);
290 pPool->aPages[NIL_PGMPOOL_IDX].enmKind = PGMPOOLKIND_INVALID;
291 pPool->aPages[NIL_PGMPOOL_IDX].idx = NIL_PGMPOOL_IDX;
292 pPool->aPages[NIL_PGMPOOL_IDX].Core.Key = NIL_RTHCPHYS;
293 pPool->aPages[NIL_PGMPOOL_IDX].GCPhys = NIL_RTGCPHYS;
294 pPool->aPages[NIL_PGMPOOL_IDX].iNext = NIL_PGMPOOL_IDX;
295 /* pPool->aPages[NIL_PGMPOOL_IDX].cLocked = INT32_MAX; - test this out... */
296 pPool->aPages[NIL_PGMPOOL_IDX].pvPageR3 = 0;
297 pPool->aPages[NIL_PGMPOOL_IDX].iUserHead = NIL_PGMPOOL_USER_INDEX;
298 pPool->aPages[NIL_PGMPOOL_IDX].iModifiedNext = NIL_PGMPOOL_IDX;
299 pPool->aPages[NIL_PGMPOOL_IDX].iModifiedPrev = NIL_PGMPOOL_IDX;
300 pPool->aPages[NIL_PGMPOOL_IDX].iMonitoredNext = NIL_PGMPOOL_IDX;
301 pPool->aPages[NIL_PGMPOOL_IDX].iMonitoredNext = NIL_PGMPOOL_IDX;
302 pPool->aPages[NIL_PGMPOOL_IDX].iAgeNext = NIL_PGMPOOL_IDX;
303 pPool->aPages[NIL_PGMPOOL_IDX].iAgePrev = NIL_PGMPOOL_IDX;
304
305 Assert(pPool->aPages[NIL_PGMPOOL_IDX].idx == NIL_PGMPOOL_IDX);
306 Assert(pPool->aPages[NIL_PGMPOOL_IDX].GCPhys == NIL_RTGCPHYS);
307 Assert(!pPool->aPages[NIL_PGMPOOL_IDX].fSeenNonGlobal);
308 Assert(!pPool->aPages[NIL_PGMPOOL_IDX].fMonitored);
309 Assert(!pPool->aPages[NIL_PGMPOOL_IDX].fCached);
310 Assert(!pPool->aPages[NIL_PGMPOOL_IDX].fZeroed);
311 Assert(!pPool->aPages[NIL_PGMPOOL_IDX].fReusedFlushPending);
312
313#ifdef VBOX_WITH_STATISTICS
314 /*
315 * Register statistics.
316 */
317 STAM_REG(pVM, &pPool->cCurPages, STAMTYPE_U16, "/PGM/Pool/cCurPages", STAMUNIT_PAGES, "Current pool size.");
318 STAM_REG(pVM, &pPool->cMaxPages, STAMTYPE_U16, "/PGM/Pool/cMaxPages", STAMUNIT_PAGES, "Max pool size.");
319 STAM_REG(pVM, &pPool->cUsedPages, STAMTYPE_U16, "/PGM/Pool/cUsedPages", STAMUNIT_PAGES, "The number of pages currently in use.");
320 STAM_REG(pVM, &pPool->cUsedPagesHigh, STAMTYPE_U16_RESET, "/PGM/Pool/cUsedPagesHigh", STAMUNIT_PAGES, "The high watermark for cUsedPages.");
321 STAM_REG(pVM, &pPool->StatAlloc, STAMTYPE_PROFILE_ADV, "/PGM/Pool/Alloc", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmPoolAlloc.");
322 STAM_REG(pVM, &pPool->StatClearAll, STAMTYPE_PROFILE, "/PGM/Pool/ClearAll", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmR3PoolClearAll.");
323 STAM_REG(pVM, &pPool->StatR3Reset, STAMTYPE_PROFILE, "/PGM/Pool/R3Reset", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmR3PoolReset.");
324 STAM_REG(pVM, &pPool->StatFlushPage, STAMTYPE_PROFILE, "/PGM/Pool/FlushPage", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmPoolFlushPage.");
325 STAM_REG(pVM, &pPool->StatFree, STAMTYPE_PROFILE, "/PGM/Pool/Free", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmPoolFree.");
326 STAM_REG(pVM, &pPool->StatForceFlushPage, STAMTYPE_COUNTER, "/PGM/Pool/FlushForce", STAMUNIT_OCCURENCES, "Counting explicit flushes by PGMPoolFlushPage().");
327 STAM_REG(pVM, &pPool->StatForceFlushDirtyPage, STAMTYPE_COUNTER, "/PGM/Pool/FlushForceDirty", STAMUNIT_OCCURENCES, "Counting explicit flushes of dirty pages by PGMPoolFlushPage().");
328 STAM_REG(pVM, &pPool->StatForceFlushReused, STAMTYPE_COUNTER, "/PGM/Pool/FlushReused", STAMUNIT_OCCURENCES, "Counting flushes for reused pages.");
329 STAM_REG(pVM, &pPool->StatZeroPage, STAMTYPE_PROFILE, "/PGM/Pool/ZeroPage", STAMUNIT_TICKS_PER_CALL, "Profiling time spent zeroing pages. Overlaps with Alloc.");
330 STAM_REG(pVM, &pPool->cMaxUsers, STAMTYPE_U16, "/PGM/Pool/Track/cMaxUsers", STAMUNIT_COUNT, "Max user tracking records.");
331 STAM_REG(pVM, &pPool->cPresent, STAMTYPE_U32, "/PGM/Pool/Track/cPresent", STAMUNIT_COUNT, "Number of present page table entries.");
332 STAM_REG(pVM, &pPool->StatTrackDeref, STAMTYPE_PROFILE, "/PGM/Pool/Track/Deref", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmPoolTrackDeref.");
333 STAM_REG(pVM, &pPool->StatTrackFlushGCPhysPT, STAMTYPE_PROFILE, "/PGM/Pool/Track/FlushGCPhysPT", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmPoolTrackFlushGCPhysPT.");
334 STAM_REG(pVM, &pPool->StatTrackFlushGCPhysPTs, STAMTYPE_PROFILE, "/PGM/Pool/Track/FlushGCPhysPTs", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmPoolTrackFlushGCPhysPTs.");
335 STAM_REG(pVM, &pPool->StatTrackFlushGCPhysPTsSlow, STAMTYPE_PROFILE, "/PGM/Pool/Track/FlushGCPhysPTsSlow", STAMUNIT_TICKS_PER_CALL, "Profiling of pgmPoolTrackFlushGCPhysPTsSlow.");
336 STAM_REG(pVM, &pPool->StatTrackFlushEntry, STAMTYPE_COUNTER, "/PGM/Pool/Track/Entry/Flush", STAMUNIT_COUNT, "Nr of flushed entries.");
337 STAM_REG(pVM, &pPool->StatTrackFlushEntryKeep, STAMTYPE_COUNTER, "/PGM/Pool/Track/Entry/Update", STAMUNIT_COUNT, "Nr of updated entries.");
338 STAM_REG(pVM, &pPool->StatTrackFreeUpOneUser, STAMTYPE_COUNTER, "/PGM/Pool/Track/FreeUpOneUser", STAMUNIT_TICKS_PER_CALL, "The number of times we were out of user tracking records.");
339 STAM_REG(pVM, &pPool->StatTrackDerefGCPhys, STAMTYPE_PROFILE, "/PGM/Pool/Track/DrefGCPhys", STAMUNIT_TICKS_PER_CALL, "Profiling deref activity related tracking GC physical pages.");
340 STAM_REG(pVM, &pPool->StatTrackLinearRamSearches, STAMTYPE_COUNTER, "/PGM/Pool/Track/LinearRamSearches", STAMUNIT_OCCURENCES, "The number of times we had to do linear ram searches.");
341 STAM_REG(pVM, &pPool->StamTrackPhysExtAllocFailures,STAMTYPE_COUNTER, "/PGM/Pool/Track/PhysExtAllocFailures", STAMUNIT_OCCURENCES, "The number of failing pgmPoolTrackPhysExtAlloc calls.");
342 STAM_REG(pVM, &pPool->StatMonitorRZ, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/RZ", STAMUNIT_TICKS_PER_CALL, "Profiling the RC/R0 access handler.");
343 STAM_REG(pVM, &pPool->StatMonitorRZEmulateInstr, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/EmulateInstr", STAMUNIT_OCCURENCES, "Times we've failed interpreting the instruction.");
344 STAM_REG(pVM, &pPool->StatMonitorRZFlushPage, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/RZ/FlushPage", STAMUNIT_TICKS_PER_CALL, "Profiling the pgmPoolFlushPage calls made from the RC/R0 access handler.");
345 STAM_REG(pVM, &pPool->StatMonitorRZFlushReinit, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/FlushReinit", STAMUNIT_OCCURENCES, "Times we've detected a page table reinit.");
346 STAM_REG(pVM, &pPool->StatMonitorRZFlushModOverflow,STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/FlushOverflow", STAMUNIT_OCCURENCES, "Counting flushes for pages that are modified too often.");
347 STAM_REG(pVM, &pPool->StatMonitorRZFork, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/Fork", STAMUNIT_OCCURENCES, "Times we've detected fork().");
348 STAM_REG(pVM, &pPool->StatMonitorRZHandled, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/RZ/Handled", STAMUNIT_TICKS_PER_CALL, "Profiling the RC/R0 access we've handled (except REP STOSD).");
349 STAM_REG(pVM, &pPool->StatMonitorRZIntrFailPatch1, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/IntrFailPatch1", STAMUNIT_OCCURENCES, "Times we've failed interpreting a patch code instruction.");
350 STAM_REG(pVM, &pPool->StatMonitorRZIntrFailPatch2, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/IntrFailPatch2", STAMUNIT_OCCURENCES, "Times we've failed interpreting a patch code instruction during flushing.");
351 STAM_REG(pVM, &pPool->StatMonitorRZRepPrefix, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/RepPrefix", STAMUNIT_OCCURENCES, "The number of times we've seen rep prefixes we can't handle.");
352 STAM_REG(pVM, &pPool->StatMonitorRZRepStosd, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/RZ/RepStosd", STAMUNIT_TICKS_PER_CALL, "Profiling the REP STOSD cases we've handled.");
353 STAM_REG(pVM, &pPool->StatMonitorRZFaultPT, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/Fault/PT", STAMUNIT_OCCURENCES, "Nr of handled PT faults.");
354 STAM_REG(pVM, &pPool->StatMonitorRZFaultPD, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/Fault/PD", STAMUNIT_OCCURENCES, "Nr of handled PD faults.");
355 STAM_REG(pVM, &pPool->StatMonitorRZFaultPDPT, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/Fault/PDPT", STAMUNIT_OCCURENCES, "Nr of handled PDPT faults.");
356 STAM_REG(pVM, &pPool->StatMonitorRZFaultPML4, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/RZ/Fault/PML4", STAMUNIT_OCCURENCES, "Nr of handled PML4 faults.");
357 STAM_REG(pVM, &pPool->StatMonitorR3, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/R3", STAMUNIT_TICKS_PER_CALL, "Profiling the R3 access handler.");
358 STAM_REG(pVM, &pPool->StatMonitorR3EmulateInstr, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/EmulateInstr", STAMUNIT_OCCURENCES, "Times we've failed interpreting the instruction.");
359 STAM_REG(pVM, &pPool->StatMonitorR3FlushPage, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/R3/FlushPage", STAMUNIT_TICKS_PER_CALL, "Profiling the pgmPoolFlushPage calls made from the R3 access handler.");
360 STAM_REG(pVM, &pPool->StatMonitorR3FlushReinit, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/FlushReinit", STAMUNIT_OCCURENCES, "Times we've detected a page table reinit.");
361 STAM_REG(pVM, &pPool->StatMonitorR3FlushModOverflow,STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/FlushOverflow", STAMUNIT_OCCURENCES, "Counting flushes for pages that are modified too often.");
362 STAM_REG(pVM, &pPool->StatMonitorR3Fork, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/Fork", STAMUNIT_OCCURENCES, "Times we've detected fork().");
363 STAM_REG(pVM, &pPool->StatMonitorR3Handled, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/R3/Handled", STAMUNIT_TICKS_PER_CALL, "Profiling the R3 access we've handled (except REP STOSD).");
364 STAM_REG(pVM, &pPool->StatMonitorR3RepPrefix, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/RepPrefix", STAMUNIT_OCCURENCES, "The number of times we've seen rep prefixes we can't handle.");
365 STAM_REG(pVM, &pPool->StatMonitorR3RepStosd, STAMTYPE_PROFILE, "/PGM/Pool/Monitor/R3/RepStosd", STAMUNIT_TICKS_PER_CALL, "Profiling the REP STOSD cases we've handled.");
366 STAM_REG(pVM, &pPool->StatMonitorR3FaultPT, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/Fault/PT", STAMUNIT_OCCURENCES, "Nr of handled PT faults.");
367 STAM_REG(pVM, &pPool->StatMonitorR3FaultPD, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/Fault/PD", STAMUNIT_OCCURENCES, "Nr of handled PD faults.");
368 STAM_REG(pVM, &pPool->StatMonitorR3FaultPDPT, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/Fault/PDPT", STAMUNIT_OCCURENCES, "Nr of handled PDPT faults.");
369 STAM_REG(pVM, &pPool->StatMonitorR3FaultPML4, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/Fault/PML4", STAMUNIT_OCCURENCES, "Nr of handled PML4 faults.");
370 STAM_REG(pVM, &pPool->StatMonitorR3Async, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/R3/Async", STAMUNIT_OCCURENCES, "Times we're called in an async thread and need to flush.");
371 STAM_REG(pVM, &pPool->cModifiedPages, STAMTYPE_U16, "/PGM/Pool/Monitor/cModifiedPages", STAMUNIT_PAGES, "The current cModifiedPages value.");
372 STAM_REG(pVM, &pPool->cModifiedPagesHigh, STAMTYPE_U16_RESET, "/PGM/Pool/Monitor/cModifiedPagesHigh", STAMUNIT_PAGES, "The high watermark for cModifiedPages.");
373 STAM_REG(pVM, &pPool->StatResetDirtyPages, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/Dirty/Resets", STAMUNIT_OCCURENCES, "Times we've called pgmPoolResetDirtyPages (and there were dirty page).");
374 STAM_REG(pVM, &pPool->StatDirtyPage, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/Dirty/Pages", STAMUNIT_OCCURENCES, "Times we've called pgmPoolAddDirtyPage.");
375 STAM_REG(pVM, &pPool->StatDirtyPageDupFlush, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/Dirty/FlushDup", STAMUNIT_OCCURENCES, "Times we've had to flush duplicates for dirty page management.");
376 STAM_REG(pVM, &pPool->StatDirtyPageOverFlowFlush, STAMTYPE_COUNTER, "/PGM/Pool/Monitor/Dirty/FlushOverflow",STAMUNIT_OCCURENCES, "Times we've had to flush because of overflow.");
377 STAM_REG(pVM, &pPool->StatCacheHits, STAMTYPE_COUNTER, "/PGM/Pool/Cache/Hits", STAMUNIT_OCCURENCES, "The number of pgmPoolAlloc calls satisfied by the cache.");
378 STAM_REG(pVM, &pPool->StatCacheMisses, STAMTYPE_COUNTER, "/PGM/Pool/Cache/Misses", STAMUNIT_OCCURENCES, "The number of pgmPoolAlloc calls not statisfied by the cache.");
379 STAM_REG(pVM, &pPool->StatCacheKindMismatches, STAMTYPE_COUNTER, "/PGM/Pool/Cache/KindMismatches", STAMUNIT_OCCURENCES, "The number of shadow page kind mismatches. (Better be low, preferably 0!)");
380 STAM_REG(pVM, &pPool->StatCacheFreeUpOne, STAMTYPE_COUNTER, "/PGM/Pool/Cache/FreeUpOne", STAMUNIT_OCCURENCES, "The number of times the cache was asked to free up a page.");
381 STAM_REG(pVM, &pPool->StatCacheCacheable, STAMTYPE_COUNTER, "/PGM/Pool/Cache/Cacheable", STAMUNIT_OCCURENCES, "The number of cacheable allocations.");
382 STAM_REG(pVM, &pPool->StatCacheUncacheable, STAMTYPE_COUNTER, "/PGM/Pool/Cache/Uncacheable", STAMUNIT_OCCURENCES, "The number of uncacheable allocations.");
383#endif /* VBOX_WITH_STATISTICS */
384
385#ifdef VBOX_WITH_DEBUGGER
386 /*
387 * Debugger commands.
388 */
389 static bool s_fRegisteredCmds = false;
390 if (!s_fRegisteredCmds)
391 {
392 rc = DBGCRegisterCommands(&g_aCmds[0], RT_ELEMENTS(g_aCmds));
393 if (RT_SUCCESS(rc))
394 s_fRegisteredCmds = true;
395 }
396#endif
397
398 return VINF_SUCCESS;
399}
400
401
402/**
403 * Relocate the page pool data.
404 *
405 * @param pVM Pointer to the VM.
406 */
407void pgmR3PoolRelocate(PVM pVM)
408{
409 pVM->pgm.s.pPoolRC = MMHyperR3ToRC(pVM, pVM->pgm.s.pPoolR3);
410 pVM->pgm.s.pPoolR3->pVMRC = pVM->pVMRC;
411 pVM->pgm.s.pPoolR3->paUsersRC = MMHyperR3ToRC(pVM, pVM->pgm.s.pPoolR3->paUsersR3);
412 pVM->pgm.s.pPoolR3->paPhysExtsRC = MMHyperR3ToRC(pVM, pVM->pgm.s.pPoolR3->paPhysExtsR3);
413
414 if (!HMIsEnabled(pVM))
415 {
416 int rc = PDMR3LdrGetSymbolRC(pVM, NULL, "pgmPoolAccessHandler", &pVM->pgm.s.pPoolR3->pfnAccessHandlerRC);
417 AssertReleaseRC(rc);
418 }
419
420 /* init order hack. */
421 if (!pVM->pgm.s.pPoolR3->pfnAccessHandlerR0)
422 {
423 int rc = PDMR3LdrGetSymbolR0(pVM, NULL, "pgmPoolAccessHandler", &pVM->pgm.s.pPoolR3->pfnAccessHandlerR0);
424 AssertReleaseRC(rc);
425 }
426}
427
428
429/**
430 * Grows the shadow page pool.
431 *
432 * I.e. adds more pages to it, assuming that hasn't reached cMaxPages yet.
433 *
434 * @returns VBox status code.
435 * @param pVM Pointer to the VM.
436 */
437VMMR3DECL(int) PGMR3PoolGrow(PVM pVM)
438{
439 PPGMPOOL pPool = pVM->pgm.s.pPoolR3;
440 AssertReturn(pPool->cCurPages < pPool->cMaxPages, VERR_PGM_POOL_MAXED_OUT_ALREADY);
441
442 /* With 32-bit guests and no EPT, the CR3 limits the root pages to low
443 (below 4 GB) memory. */
444 /** @todo change the pool to handle ROOT page allocations specially when
445 * required. */
446 bool fCanUseHighMemory = HMIsNestedPagingActive(pVM)
447 && HMGetShwPagingMode(pVM) == PGMMODE_EPT;
448
449 pgmLock(pVM);
450
451 /*
452 * How much to grow it by?
453 */
454 uint32_t cPages = pPool->cMaxPages - pPool->cCurPages;
455 cPages = RT_MIN(PGMPOOL_CFG_MAX_GROW, cPages);
456 LogFlow(("PGMR3PoolGrow: Growing the pool by %d (%#x) pages. fCanUseHighMemory=%RTbool\n", cPages, cPages, fCanUseHighMemory));
457
458 for (unsigned i = pPool->cCurPages; cPages-- > 0; i++)
459 {
460 PPGMPOOLPAGE pPage = &pPool->aPages[i];
461
462 if (fCanUseHighMemory)
463 pPage->pvPageR3 = MMR3PageAlloc(pVM);
464 else
465 pPage->pvPageR3 = MMR3PageAllocLow(pVM);
466 if (!pPage->pvPageR3)
467 {
468 Log(("We're out of memory!! i=%d fCanUseHighMemory=%RTbool\n", i, fCanUseHighMemory));
469 pgmUnlock(pVM);
470 return i ? VINF_SUCCESS : VERR_NO_PAGE_MEMORY;
471 }
472 pPage->Core.Key = MMPage2Phys(pVM, pPage->pvPageR3);
473 AssertFatal(pPage->Core.Key < _4G || fCanUseHighMemory);
474 pPage->GCPhys = NIL_RTGCPHYS;
475 pPage->enmKind = PGMPOOLKIND_FREE;
476 pPage->idx = pPage - &pPool->aPages[0];
477 LogFlow(("PGMR3PoolGrow: insert page #%#x - %RHp\n", pPage->idx, pPage->Core.Key));
478 pPage->iNext = pPool->iFreeHead;
479 pPage->iUserHead = NIL_PGMPOOL_USER_INDEX;
480 pPage->iModifiedNext = NIL_PGMPOOL_IDX;
481 pPage->iModifiedPrev = NIL_PGMPOOL_IDX;
482 pPage->iMonitoredNext = NIL_PGMPOOL_IDX;
483 pPage->iMonitoredNext = NIL_PGMPOOL_IDX;
484 pPage->iAgeNext = NIL_PGMPOOL_IDX;
485 pPage->iAgePrev = NIL_PGMPOOL_IDX;
486 /* commit it */
487 bool fRc = RTAvloHCPhysInsert(&pPool->HCPhysTree, &pPage->Core); Assert(fRc); NOREF(fRc);
488 pPool->iFreeHead = i;
489 pPool->cCurPages = i + 1;
490 }
491
492 pgmUnlock(pVM);
493 Assert(pPool->cCurPages <= pPool->cMaxPages);
494 return VINF_SUCCESS;
495}
496
497
498
499/**
500 * Worker used by pgmR3PoolAccessHandler when it's invoked by an async thread.
501 *
502 * @param pPool The pool.
503 * @param pPage The page.
504 */
505static DECLCALLBACK(void) pgmR3PoolFlushReusedPage(PPGMPOOL pPool, PPGMPOOLPAGE pPage)
506{
507 /* for the present this should be safe enough I think... */
508 pgmLock(pPool->pVMR3);
509 if ( pPage->fReusedFlushPending
510 && pPage->enmKind != PGMPOOLKIND_FREE)
511 pgmPoolFlushPage(pPool, pPage);
512 pgmUnlock(pPool->pVMR3);
513}
514
515
516/**
517 * \#PF Handler callback for PT write accesses.
518 *
519 * The handler can not raise any faults, it's mainly for monitoring write access
520 * to certain pages.
521 *
522 * @returns VINF_SUCCESS if the handler has carried out the operation.
523 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
524 * @param pVM Pointer to the VM.
525 * @param GCPhys The physical address the guest is writing to.
526 * @param pvPhys The HC mapping of that address.
527 * @param pvBuf What the guest is reading/writing.
528 * @param cbBuf How much it's reading/writing.
529 * @param enmAccessType The access type.
530 * @param pvUser User argument.
531 */
532static DECLCALLBACK(int) pgmR3PoolAccessHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf,
533 PGMACCESSTYPE enmAccessType, void *pvUser)
534{
535 STAM_PROFILE_START(&pVM->pgm.s.pPoolR3->StatMonitorR3, a);
536 PPGMPOOL pPool = pVM->pgm.s.pPoolR3;
537 PPGMPOOLPAGE pPage = (PPGMPOOLPAGE)pvUser;
538 PVMCPU pVCpu = VMMGetCpu(pVM);
539 LogFlow(("pgmR3PoolAccessHandler: GCPhys=%RGp %p:{.Core=%RHp, .idx=%d, .GCPhys=%RGp, .enmType=%d}\n",
540 GCPhys, pPage, pPage->Core.Key, pPage->idx, pPage->GCPhys, pPage->enmKind));
541
542 NOREF(pvBuf); NOREF(enmAccessType);
543
544 /*
545 * We don't have to be very sophisticated about this since there are relativly few calls here.
546 * However, we must try our best to detect any non-cpu accesses (disk / networking).
547 *
548 * Just to make life more interesting, we'll have to deal with the async threads too.
549 * We cannot flush a page if we're in an async thread because of REM notifications.
550 */
551 pgmLock(pVM);
552 if (PHYS_PAGE_ADDRESS(GCPhys) != PHYS_PAGE_ADDRESS(pPage->GCPhys))
553 {
554 /* Pool page changed while we were waiting for the lock; ignore. */
555 Log(("CPU%d: pgmR3PoolAccessHandler pgm pool page for %RGp changed (to %RGp) while waiting!\n", pVCpu->idCpu, PHYS_PAGE_ADDRESS(GCPhys), PHYS_PAGE_ADDRESS(pPage->GCPhys)));
556 pgmUnlock(pVM);
557 return VINF_PGM_HANDLER_DO_DEFAULT;
558 }
559
560 Assert(pPage->enmKind != PGMPOOLKIND_FREE);
561
562 /* @todo this code doesn't make any sense. remove the if (!pVCpu) block */
563 if (!pVCpu) /** @todo This shouldn't happen any longer, all access handlers will be called on an EMT. All ring-3 handlers, except MMIO, already own the PGM lock. @bugref{3170} */
564 {
565 Log(("pgmR3PoolAccessHandler: async thread, requesting EMT to flush the page: %p:{.Core=%RHp, .idx=%d, .GCPhys=%RGp, .enmType=%d}\n",
566 pPage, pPage->Core.Key, pPage->idx, pPage->GCPhys, pPage->enmKind));
567 STAM_COUNTER_INC(&pPool->StatMonitorR3Async);
568 if (!pPage->fReusedFlushPending)
569 {
570 pgmUnlock(pVM);
571 int rc = VMR3ReqCallVoidNoWait(pPool->pVMR3, VMCPUID_ANY, (PFNRT)pgmR3PoolFlushReusedPage, 2, pPool, pPage);
572 AssertRCReturn(rc, rc);
573 pgmLock(pVM);
574 pPage->fReusedFlushPending = true;
575 pPage->cModifications += 0x1000;
576 }
577
578 pgmPoolMonitorChainChanging(pVCpu, pPool, pPage, GCPhys, pvPhys, 0 /* unknown write size */);
579 /** @todo r=bird: making unsafe assumption about not crossing entries here! */
580 while (cbBuf > 4)
581 {
582 cbBuf -= 4;
583 pvPhys = (uint8_t *)pvPhys + 4;
584 GCPhys += 4;
585 pgmPoolMonitorChainChanging(pVCpu, pPool, pPage, GCPhys, pvPhys, 0 /* unknown write size */);
586 }
587 STAM_PROFILE_STOP(&pPool->StatMonitorR3, a);
588 }
589 else if ( ( pPage->cModifications < 96 /* it's cheaper here. */
590 || pgmPoolIsPageLocked(pPage)
591 )
592 && cbBuf <= 4)
593 {
594 /* Clear the shadow entry. */
595 if (!pPage->cModifications++)
596 pgmPoolMonitorModifiedInsert(pPool, pPage);
597 /** @todo r=bird: making unsafe assumption about not crossing entries here! */
598 pgmPoolMonitorChainChanging(pVCpu, pPool, pPage, GCPhys, pvPhys, 0 /* unknown write size */);
599 STAM_PROFILE_STOP(&pPool->StatMonitorR3, a);
600 }
601 else
602 {
603 pgmPoolMonitorChainFlush(pPool, pPage); /* ASSUME that VERR_PGM_POOL_CLEARED can be ignored here and that FFs will deal with it in due time. */
604 STAM_PROFILE_STOP_EX(&pPool->StatMonitorR3, &pPool->StatMonitorR3FlushPage, a);
605 }
606 pgmUnlock(pVM);
607 return VINF_PGM_HANDLER_DO_DEFAULT;
608}
609
610
611/**
612 * Rendezvous callback used by pgmR3PoolClearAll that clears all shadow pages
613 * and all modification counters.
614 *
615 * This is only called on one of the EMTs while the other ones are waiting for
616 * it to complete this function.
617 *
618 * @returns VINF_SUCCESS (VBox strict status code).
619 * @param pVM Pointer to the VM.
620 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
621 * @param fpvFlushRemTlb When not NULL, we'll flush the REM TLB as well.
622 * (This is the pvUser, so it has to be void *.)
623 *
624 */
625DECLCALLBACK(VBOXSTRICTRC) pgmR3PoolClearAllRendezvous(PVM pVM, PVMCPU pVCpu, void *fpvFlushRemTbl)
626{
627 PPGMPOOL pPool = pVM->pgm.s.CTX_SUFF(pPool);
628 STAM_PROFILE_START(&pPool->StatClearAll, c);
629 NOREF(pVCpu);
630
631 pgmLock(pVM);
632 Log(("pgmR3PoolClearAllRendezvous: cUsedPages=%d fpvFlushRemTbl=%RTbool\n", pPool->cUsedPages, !!fpvFlushRemTbl));
633
634 /*
635 * Iterate all the pages until we've encountered all that are in use.
636 * This is a simple but not quite optimal solution.
637 */
638 unsigned cModifiedPages = 0; NOREF(cModifiedPages);
639 unsigned cLeft = pPool->cUsedPages;
640 uint32_t iPage = pPool->cCurPages;
641 while (--iPage >= PGMPOOL_IDX_FIRST)
642 {
643 PPGMPOOLPAGE pPage = &pPool->aPages[iPage];
644 if (pPage->GCPhys != NIL_RTGCPHYS)
645 {
646 switch (pPage->enmKind)
647 {
648 /*
649 * We only care about shadow page tables that reference physical memory
650 */
651#ifdef PGM_WITH_LARGE_PAGES
652 case PGMPOOLKIND_EPT_PD_FOR_PHYS: /* Large pages reference 2 MB of physical memory, so we must clear them. */
653 if (pPage->cPresent)
654 {
655 PX86PDPAE pShwPD = (PX86PDPAE)PGMPOOL_PAGE_2_PTR_V2(pPool->CTX_SUFF(pVM), pVCpu, pPage);
656 for (unsigned i = 0; i < RT_ELEMENTS(pShwPD->a); i++)
657 {
658 if ( pShwPD->a[i].n.u1Present
659 && pShwPD->a[i].b.u1Size)
660 {
661 Assert(!(pShwPD->a[i].u & PGM_PDFLAGS_MAPPING));
662 pShwPD->a[i].u = 0;
663 Assert(pPage->cPresent);
664 pPage->cPresent--;
665 }
666 }
667 if (pPage->cPresent == 0)
668 pPage->iFirstPresent = NIL_PGMPOOL_PRESENT_INDEX;
669 }
670 goto default_case;
671
672 case PGMPOOLKIND_PAE_PD_PHYS: /* Large pages reference 2 MB of physical memory, so we must clear them. */
673 if (pPage->cPresent)
674 {
675 PEPTPD pShwPD = (PEPTPD)PGMPOOL_PAGE_2_PTR_V2(pPool->CTX_SUFF(pVM), pVCpu, pPage);
676 for (unsigned i = 0; i < RT_ELEMENTS(pShwPD->a); i++)
677 {
678 Assert((pShwPD->a[i].u & UINT64_C(0xfff0000000000f80)) == 0);
679 if ( pShwPD->a[i].n.u1Present
680 && pShwPD->a[i].b.u1Size)
681 {
682 Assert(!(pShwPD->a[i].u & PGM_PDFLAGS_MAPPING));
683 pShwPD->a[i].u = 0;
684 Assert(pPage->cPresent);
685 pPage->cPresent--;
686 }
687 }
688 if (pPage->cPresent == 0)
689 pPage->iFirstPresent = NIL_PGMPOOL_PRESENT_INDEX;
690 }
691 goto default_case;
692#endif /* PGM_WITH_LARGE_PAGES */
693
694 case PGMPOOLKIND_32BIT_PT_FOR_32BIT_PT:
695 case PGMPOOLKIND_32BIT_PT_FOR_32BIT_4MB:
696 case PGMPOOLKIND_PAE_PT_FOR_32BIT_PT:
697 case PGMPOOLKIND_PAE_PT_FOR_32BIT_4MB:
698 case PGMPOOLKIND_PAE_PT_FOR_PAE_PT:
699 case PGMPOOLKIND_PAE_PT_FOR_PAE_2MB:
700 case PGMPOOLKIND_32BIT_PT_FOR_PHYS:
701 case PGMPOOLKIND_PAE_PT_FOR_PHYS:
702 case PGMPOOLKIND_EPT_PT_FOR_PHYS:
703 {
704 if (pPage->cPresent)
705 {
706 void *pvShw = PGMPOOL_PAGE_2_PTR_V2(pPool->CTX_SUFF(pVM), pVCpu, pPage);
707 STAM_PROFILE_START(&pPool->StatZeroPage, z);
708#if 0
709 /* Useful check for leaking references; *very* expensive though. */
710 switch (pPage->enmKind)
711 {
712 case PGMPOOLKIND_PAE_PT_FOR_32BIT_PT:
713 case PGMPOOLKIND_PAE_PT_FOR_32BIT_4MB:
714 case PGMPOOLKIND_PAE_PT_FOR_PAE_PT:
715 case PGMPOOLKIND_PAE_PT_FOR_PAE_2MB:
716 case PGMPOOLKIND_PAE_PT_FOR_PHYS:
717 {
718 bool fFoundFirst = false;
719 PPGMSHWPTPAE pPT = (PPGMSHWPTPAE)pvShw;
720 for (unsigned ptIndex = 0; ptIndex < RT_ELEMENTS(pPT->a); ptIndex++)
721 {
722 if (pPT->a[ptIndex].u)
723 {
724 if (!fFoundFirst)
725 {
726 AssertFatalMsg(pPage->iFirstPresent <= ptIndex, ("ptIndex = %d first present = %d\n", ptIndex, pPage->iFirstPresent));
727 if (pPage->iFirstPresent != ptIndex)
728 Log(("ptIndex = %d first present = %d\n", ptIndex, pPage->iFirstPresent));
729 fFoundFirst = true;
730 }
731 if (PGMSHWPTEPAE_IS_P(pPT->a[ptIndex]))
732 {
733 pgmPoolTracDerefGCPhysHint(pPool, pPage, PGMSHWPTEPAE_GET_HCPHYS(pPT->a[ptIndex]), NIL_RTGCPHYS);
734 if (pPage->iFirstPresent == ptIndex)
735 pPage->iFirstPresent = NIL_PGMPOOL_PRESENT_INDEX;
736 }
737 }
738 }
739 AssertFatalMsg(pPage->cPresent == 0, ("cPresent = %d pPage = %RGv\n", pPage->cPresent, pPage->GCPhys));
740 break;
741 }
742 default:
743 break;
744 }
745#endif
746 ASMMemZeroPage(pvShw);
747 STAM_PROFILE_STOP(&pPool->StatZeroPage, z);
748 pPage->cPresent = 0;
749 pPage->iFirstPresent = NIL_PGMPOOL_PRESENT_INDEX;
750 }
751 }
752 /* fall thru */
753
754#ifdef PGM_WITH_LARGE_PAGES
755 default_case:
756#endif
757 default:
758 Assert(!pPage->cModifications || ++cModifiedPages);
759 Assert(pPage->iModifiedNext == NIL_PGMPOOL_IDX || pPage->cModifications);
760 Assert(pPage->iModifiedPrev == NIL_PGMPOOL_IDX || pPage->cModifications);
761 pPage->iModifiedNext = NIL_PGMPOOL_IDX;
762 pPage->iModifiedPrev = NIL_PGMPOOL_IDX;
763 pPage->cModifications = 0;
764 break;
765
766 }
767 if (!--cLeft)
768 break;
769 }
770 }
771
772#ifndef DEBUG_michael
773 AssertMsg(cModifiedPages == pPool->cModifiedPages, ("%d != %d\n", cModifiedPages, pPool->cModifiedPages));
774#endif
775 pPool->iModifiedHead = NIL_PGMPOOL_IDX;
776 pPool->cModifiedPages = 0;
777
778 /*
779 * Clear all the GCPhys links and rebuild the phys ext free list.
780 */
781 for (PPGMRAMRANGE pRam = pPool->CTX_SUFF(pVM)->pgm.s.CTX_SUFF(pRamRangesX);
782 pRam;
783 pRam = pRam->CTX_SUFF(pNext))
784 {
785 iPage = pRam->cb >> PAGE_SHIFT;
786 while (iPage-- > 0)
787 PGM_PAGE_SET_TRACKING(pVM, &pRam->aPages[iPage], 0);
788 }
789
790 pPool->iPhysExtFreeHead = 0;
791 PPGMPOOLPHYSEXT paPhysExts = pPool->CTX_SUFF(paPhysExts);
792 const unsigned cMaxPhysExts = pPool->cMaxPhysExts;
793 for (unsigned i = 0; i < cMaxPhysExts; i++)
794 {
795 paPhysExts[i].iNext = i + 1;
796 paPhysExts[i].aidx[0] = NIL_PGMPOOL_IDX;
797 paPhysExts[i].apte[0] = NIL_PGMPOOL_PHYSEXT_IDX_PTE;
798 paPhysExts[i].aidx[1] = NIL_PGMPOOL_IDX;
799 paPhysExts[i].apte[1] = NIL_PGMPOOL_PHYSEXT_IDX_PTE;
800 paPhysExts[i].aidx[2] = NIL_PGMPOOL_IDX;
801 paPhysExts[i].apte[2] = NIL_PGMPOOL_PHYSEXT_IDX_PTE;
802 }
803 paPhysExts[cMaxPhysExts - 1].iNext = NIL_PGMPOOL_PHYSEXT_INDEX;
804
805
806#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
807 /* Reset all dirty pages to reactivate the page monitoring. */
808 /* Note: we must do this *after* clearing all page references and shadow page tables as there might be stale references to
809 * recently removed MMIO ranges around that might otherwise end up asserting in pgmPoolTracDerefGCPhysHint
810 */
811 for (unsigned i = 0; i < RT_ELEMENTS(pPool->aDirtyPages); i++)
812 {
813 PPGMPOOLPAGE pPage;
814 unsigned idxPage;
815
816 if (pPool->aDirtyPages[i].uIdx == NIL_PGMPOOL_IDX)
817 continue;
818
819 idxPage = pPool->aDirtyPages[i].uIdx;
820 AssertRelease(idxPage != NIL_PGMPOOL_IDX);
821 pPage = &pPool->aPages[idxPage];
822 Assert(pPage->idx == idxPage);
823 Assert(pPage->iMonitoredNext == NIL_PGMPOOL_IDX && pPage->iMonitoredPrev == NIL_PGMPOOL_IDX);
824
825 AssertMsg(pPage->fDirty, ("Page %RGp (slot=%d) not marked dirty!", pPage->GCPhys, i));
826
827 Log(("Reactivate dirty page %RGp\n", pPage->GCPhys));
828
829 /* First write protect the page again to catch all write accesses. (before checking for changes -> SMP) */
830 int rc = PGMHandlerPhysicalReset(pVM, pPage->GCPhys & PAGE_BASE_GC_MASK);
831 AssertRCSuccess(rc);
832 pPage->fDirty = false;
833
834 pPool->aDirtyPages[i].uIdx = NIL_PGMPOOL_IDX;
835 }
836
837 /* Clear all dirty pages. */
838 pPool->idxFreeDirtyPage = 0;
839 pPool->cDirtyPages = 0;
840#endif
841
842 /* Clear the PGM_SYNC_CLEAR_PGM_POOL flag on all VCPUs to prevent redundant flushes. */
843 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
844 pVM->aCpus[idCpu].pgm.s.fSyncFlags &= ~PGM_SYNC_CLEAR_PGM_POOL;
845
846 /* Flush job finished. */
847 VM_FF_CLEAR(pVM, VM_FF_PGM_POOL_FLUSH_PENDING);
848 pPool->cPresent = 0;
849 pgmUnlock(pVM);
850
851 PGM_INVL_ALL_VCPU_TLBS(pVM);
852
853 if (fpvFlushRemTbl)
854 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
855 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
856
857 STAM_PROFILE_STOP(&pPool->StatClearAll, c);
858 return VINF_SUCCESS;
859}
860
861
862/**
863 * Clears the shadow page pool.
864 *
865 * @param pVM Pointer to the VM.
866 * @param fFlushRemTlb When set, the REM TLB is scheduled for flushing as
867 * well.
868 */
869void pgmR3PoolClearAll(PVM pVM, bool fFlushRemTlb)
870{
871 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PoolClearAllRendezvous, &fFlushRemTlb);
872 AssertRC(rc);
873}
874
875
876/**
877 * Protect all pgm pool page table entries to monitor writes
878 *
879 * @param pVM Pointer to the VM.
880 *
881 * @remarks ASSUMES the caller will flush all TLBs!!
882 */
883void pgmR3PoolWriteProtectPages(PVM pVM)
884{
885 PGM_LOCK_ASSERT_OWNER(pVM);
886 PPGMPOOL pPool = pVM->pgm.s.CTX_SUFF(pPool);
887 unsigned cLeft = pPool->cUsedPages;
888 unsigned iPage = pPool->cCurPages;
889 while (--iPage >= PGMPOOL_IDX_FIRST)
890 {
891 PPGMPOOLPAGE pPage = &pPool->aPages[iPage];
892 if ( pPage->GCPhys != NIL_RTGCPHYS
893 && pPage->cPresent)
894 {
895 union
896 {
897 void *pv;
898 PX86PT pPT;
899 PPGMSHWPTPAE pPTPae;
900 PEPTPT pPTEpt;
901 } uShw;
902 uShw.pv = PGMPOOL_PAGE_2_PTR(pVM, pPage);
903
904 switch (pPage->enmKind)
905 {
906 /*
907 * We only care about shadow page tables.
908 */
909 case PGMPOOLKIND_32BIT_PT_FOR_32BIT_PT:
910 case PGMPOOLKIND_32BIT_PT_FOR_32BIT_4MB:
911 case PGMPOOLKIND_32BIT_PT_FOR_PHYS:
912 for (unsigned iShw = 0; iShw < RT_ELEMENTS(uShw.pPT->a); iShw++)
913 {
914 if (uShw.pPT->a[iShw].n.u1Present)
915 uShw.pPT->a[iShw].n.u1Write = 0;
916 }
917 break;
918
919 case PGMPOOLKIND_PAE_PT_FOR_32BIT_PT:
920 case PGMPOOLKIND_PAE_PT_FOR_32BIT_4MB:
921 case PGMPOOLKIND_PAE_PT_FOR_PAE_PT:
922 case PGMPOOLKIND_PAE_PT_FOR_PAE_2MB:
923 case PGMPOOLKIND_PAE_PT_FOR_PHYS:
924 for (unsigned iShw = 0; iShw < RT_ELEMENTS(uShw.pPTPae->a); iShw++)
925 {
926 if (PGMSHWPTEPAE_IS_P(uShw.pPTPae->a[iShw]))
927 PGMSHWPTEPAE_SET_RO(uShw.pPTPae->a[iShw]);
928 }
929 break;
930
931 case PGMPOOLKIND_EPT_PT_FOR_PHYS:
932 for (unsigned iShw = 0; iShw < RT_ELEMENTS(uShw.pPTEpt->a); iShw++)
933 {
934 if (uShw.pPTEpt->a[iShw].n.u1Present)
935 uShw.pPTEpt->a[iShw].n.u1Write = 0;
936 }
937 break;
938
939 default:
940 break;
941 }
942 if (!--cLeft)
943 break;
944 }
945 }
946}
947
948#ifdef VBOX_WITH_DEBUGGER
949/**
950 * @callback_method_impl{FNDBGCCMD, The '.pgmpoolcheck' command.}
951 */
952static DECLCALLBACK(int) pgmR3PoolCmdCheck(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PUVM pUVM, PCDBGCVAR paArgs, unsigned cArgs)
953{
954 DBGC_CMDHLP_REQ_UVM_RET(pCmdHlp, pCmd, pUVM);
955 PVM pVM = pUVM->pVM;
956 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
957 DBGC_CMDHLP_ASSERT_PARSER_RET(pCmdHlp, pCmd, -1, cArgs == 0);
958 uint32_t cErrors = 0;
959 NOREF(paArgs);
960
961 PPGMPOOL pPool = pVM->pgm.s.CTX_SUFF(pPool);
962 for (unsigned i = 0; i < pPool->cCurPages; i++)
963 {
964 PPGMPOOLPAGE pPage = &pPool->aPages[i];
965 bool fFirstMsg = true;
966
967 /* Todo: cover other paging modes too. */
968 if (pPage->enmKind == PGMPOOLKIND_PAE_PT_FOR_PAE_PT)
969 {
970 PPGMSHWPTPAE pShwPT = (PPGMSHWPTPAE)PGMPOOL_PAGE_2_PTR(pPool->CTX_SUFF(pVM), pPage);
971 {
972 PX86PTPAE pGstPT;
973 PGMPAGEMAPLOCK LockPage;
974 int rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, pPage->GCPhys, (const void **)&pGstPT, &LockPage); AssertReleaseRC(rc);
975
976 /* Check if any PTEs are out of sync. */
977 for (unsigned j = 0; j < RT_ELEMENTS(pShwPT->a); j++)
978 {
979 if (PGMSHWPTEPAE_IS_P(pShwPT->a[j]))
980 {
981 RTHCPHYS HCPhys = NIL_RTHCPHYS;
982 rc = PGMPhysGCPhys2HCPhys(pPool->CTX_SUFF(pVM), pGstPT->a[j].u & X86_PTE_PAE_PG_MASK, &HCPhys);
983 if ( rc != VINF_SUCCESS
984 || PGMSHWPTEPAE_GET_HCPHYS(pShwPT->a[j]) != HCPhys)
985 {
986 if (fFirstMsg)
987 {
988 DBGCCmdHlpPrintf(pCmdHlp, "Check pool page %RGp\n", pPage->GCPhys);
989 fFirstMsg = false;
990 }
991 DBGCCmdHlpPrintf(pCmdHlp, "Mismatch HCPhys: rc=%Rrc idx=%d guest %RX64 shw=%RX64 vs %RHp\n", rc, j, pGstPT->a[j].u, PGMSHWPTEPAE_GET_LOG(pShwPT->a[j]), HCPhys);
992 cErrors++;
993 }
994 else if ( PGMSHWPTEPAE_IS_RW(pShwPT->a[j])
995 && !pGstPT->a[j].n.u1Write)
996 {
997 if (fFirstMsg)
998 {
999 DBGCCmdHlpPrintf(pCmdHlp, "Check pool page %RGp\n", pPage->GCPhys);
1000 fFirstMsg = false;
1001 }
1002 DBGCCmdHlpPrintf(pCmdHlp, "Mismatch r/w gst/shw: idx=%d guest %RX64 shw=%RX64 vs %RHp\n", j, pGstPT->a[j].u, PGMSHWPTEPAE_GET_LOG(pShwPT->a[j]), HCPhys);
1003 cErrors++;
1004 }
1005 }
1006 }
1007 PGMPhysReleasePageMappingLock(pVM, &LockPage);
1008 }
1009
1010 /* Make sure this page table can't be written to from any shadow mapping. */
1011 RTHCPHYS HCPhysPT = NIL_RTHCPHYS;
1012 int rc = PGMPhysGCPhys2HCPhys(pPool->CTX_SUFF(pVM), pPage->GCPhys, &HCPhysPT);
1013 AssertMsgRC(rc, ("PGMPhysGCPhys2HCPhys failed with rc=%d for %RGp\n", rc, pPage->GCPhys));
1014 if (rc == VINF_SUCCESS)
1015 {
1016 for (unsigned j = 0; j < pPool->cCurPages; j++)
1017 {
1018 PPGMPOOLPAGE pTempPage = &pPool->aPages[j];
1019
1020 if (pTempPage->enmKind == PGMPOOLKIND_PAE_PT_FOR_PAE_PT)
1021 {
1022 PPGMSHWPTPAE pShwPT2 = (PPGMSHWPTPAE)PGMPOOL_PAGE_2_PTR(pPool->CTX_SUFF(pVM), pTempPage);
1023
1024 for (unsigned k = 0; k < RT_ELEMENTS(pShwPT->a); k++)
1025 {
1026 if ( PGMSHWPTEPAE_IS_P_RW(pShwPT2->a[k])
1027# ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
1028 && !pPage->fDirty
1029# endif
1030 && PGMSHWPTEPAE_GET_HCPHYS(pShwPT2->a[k]) == HCPhysPT)
1031 {
1032 if (fFirstMsg)
1033 {
1034 DBGCCmdHlpPrintf(pCmdHlp, "Check pool page %RGp\n", pPage->GCPhys);
1035 fFirstMsg = false;
1036 }
1037 DBGCCmdHlpPrintf(pCmdHlp, "Mismatch: r/w: GCPhys=%RGp idx=%d shw %RX64 %RX64\n", pTempPage->GCPhys, k, PGMSHWPTEPAE_GET_LOG(pShwPT->a[k]), PGMSHWPTEPAE_GET_LOG(pShwPT2->a[k]));
1038 cErrors++;
1039 }
1040 }
1041 }
1042 }
1043 }
1044 }
1045 }
1046 if (cErrors > 0)
1047 return DBGCCmdHlpFail(pCmdHlp, pCmd, "Found %#x errors", cErrors);
1048 return VINF_SUCCESS;
1049}
1050#endif /* VBOX_WITH_DEBUGGER */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use