VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/PDMBlkCache.cpp@ 42062

Last change on this file since 42062 was 40806, checked in by vboxsync, 13 years ago

RTSpinlock: Redid the interface, eliminating NoInts and Tmp. Whether a spinlock is interrupt safe or not is now defined at creation time, preventing stupid bugs arrising from calling the wrong acquire and/or release methods somewhere. The saved flags are stored in the spinlock strucutre, eliminating the annoying Tmp variable. Needs testing on each platform before fixing the build burn.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 98.5 KB
Line 
1/* $Id: PDMBlkCache.cpp 40806 2012-04-06 21:05:19Z vboxsync $ */
2/** @file
3 * PDM Block Cache.
4 */
5
6/*
7 * Copyright (C) 2006-2008 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_pdm_block_cache PDM Block Cache - The I/O cache
19 * This component implements an I/O cache based on the 2Q cache algorithm.
20 */
21
22/*******************************************************************************
23* Header Files *
24*******************************************************************************/
25#define LOG_GROUP LOG_GROUP_PDM_BLK_CACHE
26#include "PDMInternal.h"
27#include <iprt/asm.h>
28#include <iprt/mem.h>
29#include <iprt/path.h>
30#include <iprt/string.h>
31#include <VBox/log.h>
32#include <VBox/vmm/stam.h>
33#include <VBox/vmm/uvm.h>
34#include <VBox/vmm/vm.h>
35
36#include "PDMBlkCacheInternal.h"
37
38#ifdef VBOX_STRICT
39# define PDMACFILECACHE_IS_CRITSECT_OWNER(Cache) \
40 do \
41 { \
42 AssertMsg(RTCritSectIsOwner(&Cache->CritSect), \
43 ("Thread does not own critical section\n"));\
44 } while(0)
45
46# define PDMACFILECACHE_EP_IS_SEMRW_WRITE_OWNER(pEpCache) \
47 do \
48 { \
49 AssertMsg(RTSemRWIsWriteOwner(pEpCache->SemRWEntries), \
50 ("Thread is not exclusive owner of the per endpoint RW semaphore\n")); \
51 } while(0)
52
53# define PDMACFILECACHE_EP_IS_SEMRW_READ_OWNER(pEpCache) \
54 do \
55 { \
56 AssertMsg(RTSemRWIsReadOwner(pEpCache->SemRWEntries), \
57 ("Thread is not read owner of the per endpoint RW semaphore\n")); \
58 } while(0)
59
60#else
61# define PDMACFILECACHE_IS_CRITSECT_OWNER(Cache) do { } while(0)
62# define PDMACFILECACHE_EP_IS_SEMRW_WRITE_OWNER(pEpCache) do { } while(0)
63# define PDMACFILECACHE_EP_IS_SEMRW_READ_OWNER(pEpCache) do { } while(0)
64#endif
65
66#define PDM_BLK_CACHE_SAVED_STATE_VERSION 1
67
68/*******************************************************************************
69* Internal Functions *
70*******************************************************************************/
71
72static PPDMBLKCACHEENTRY pdmBlkCacheEntryAlloc(PPDMBLKCACHE pBlkCache,
73 uint64_t off, size_t cbData, uint8_t *pbBuffer);
74static bool pdmBlkCacheAddDirtyEntry(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEENTRY pEntry);
75
76/**
77 * Decrement the reference counter of the given cache entry.
78 *
79 * @returns nothing.
80 * @param pEntry The entry to release.
81 */
82DECLINLINE(void) pdmBlkCacheEntryRelease(PPDMBLKCACHEENTRY pEntry)
83{
84 AssertMsg(pEntry->cRefs > 0, ("Trying to release a not referenced entry\n"));
85 ASMAtomicDecU32(&pEntry->cRefs);
86}
87
88/**
89 * Increment the reference counter of the given cache entry.
90 *
91 * @returns nothing.
92 * @param pEntry The entry to reference.
93 */
94DECLINLINE(void) pdmBlkCacheEntryRef(PPDMBLKCACHEENTRY pEntry)
95{
96 ASMAtomicIncU32(&pEntry->cRefs);
97}
98
99#ifdef VBOX_STRICT
100static void pdmBlkCacheValidate(PPDMBLKCACHEGLOBAL pCache)
101{
102 /* Amount of cached data should never exceed the maximum amount. */
103 AssertMsg(pCache->cbCached <= pCache->cbMax,
104 ("Current amount of cached data exceeds maximum\n"));
105
106 /* The amount of cached data in the LRU and FRU list should match cbCached */
107 AssertMsg(pCache->LruRecentlyUsedIn.cbCached + pCache->LruFrequentlyUsed.cbCached == pCache->cbCached,
108 ("Amount of cached data doesn't match\n"));
109
110 AssertMsg(pCache->LruRecentlyUsedOut.cbCached <= pCache->cbRecentlyUsedOutMax,
111 ("Paged out list exceeds maximum\n"));
112}
113#endif
114
115DECLINLINE(void) pdmBlkCacheLockEnter(PPDMBLKCACHEGLOBAL pCache)
116{
117 RTCritSectEnter(&pCache->CritSect);
118#ifdef VBOX_STRICT
119 pdmBlkCacheValidate(pCache);
120#endif
121}
122
123DECLINLINE(void) pdmBlkCacheLockLeave(PPDMBLKCACHEGLOBAL pCache)
124{
125#ifdef VBOX_STRICT
126 pdmBlkCacheValidate(pCache);
127#endif
128 RTCritSectLeave(&pCache->CritSect);
129}
130
131DECLINLINE(void) pdmBlkCacheSub(PPDMBLKCACHEGLOBAL pCache, uint32_t cbAmount)
132{
133 PDMACFILECACHE_IS_CRITSECT_OWNER(pCache);
134 pCache->cbCached -= cbAmount;
135}
136
137DECLINLINE(void) pdmBlkCacheAdd(PPDMBLKCACHEGLOBAL pCache, uint32_t cbAmount)
138{
139 PDMACFILECACHE_IS_CRITSECT_OWNER(pCache);
140 pCache->cbCached += cbAmount;
141}
142
143DECLINLINE(void) pdmBlkCacheListAdd(PPDMBLKLRULIST pList, uint32_t cbAmount)
144{
145 pList->cbCached += cbAmount;
146}
147
148DECLINLINE(void) pdmBlkCacheListSub(PPDMBLKLRULIST pList, uint32_t cbAmount)
149{
150 pList->cbCached -= cbAmount;
151}
152
153#ifdef PDMACFILECACHE_WITH_LRULIST_CHECKS
154/**
155 * Checks consistency of a LRU list.
156 *
157 * @returns nothing
158 * @param pList The LRU list to check.
159 * @param pNotInList Element which is not allowed to occur in the list.
160 */
161static void pdmBlkCacheCheckList(PPDMBLKLRULIST pList, PPDMBLKCACHEENTRY pNotInList)
162{
163 PPDMBLKCACHEENTRY pCurr = pList->pHead;
164
165 /* Check that there are no double entries and no cycles in the list. */
166 while (pCurr)
167 {
168 PPDMBLKCACHEENTRY pNext = pCurr->pNext;
169
170 while (pNext)
171 {
172 AssertMsg(pCurr != pNext,
173 ("Entry %#p is at least two times in list %#p or there is a cycle in the list\n",
174 pCurr, pList));
175 pNext = pNext->pNext;
176 }
177
178 AssertMsg(pCurr != pNotInList, ("Not allowed entry %#p is in list\n", pCurr));
179
180 if (!pCurr->pNext)
181 AssertMsg(pCurr == pList->pTail, ("End of list reached but last element is not list tail\n"));
182
183 pCurr = pCurr->pNext;
184 }
185}
186#endif
187
188/**
189 * Unlinks a cache entry from the LRU list it is assigned to.
190 *
191 * @returns nothing.
192 * @param pEntry The entry to unlink.
193 */
194static void pdmBlkCacheEntryRemoveFromList(PPDMBLKCACHEENTRY pEntry)
195{
196 PPDMBLKLRULIST pList = pEntry->pList;
197 PPDMBLKCACHEENTRY pPrev, pNext;
198
199 LogFlowFunc((": Deleting entry %#p from list %#p\n", pEntry, pList));
200
201 AssertPtr(pList);
202
203#ifdef PDMACFILECACHE_WITH_LRULIST_CHECKS
204 pdmBlkCacheCheckList(pList, NULL);
205#endif
206
207 pPrev = pEntry->pPrev;
208 pNext = pEntry->pNext;
209
210 AssertMsg(pEntry != pPrev, ("Entry links to itself as previous element\n"));
211 AssertMsg(pEntry != pNext, ("Entry links to itself as next element\n"));
212
213 if (pPrev)
214 pPrev->pNext = pNext;
215 else
216 {
217 pList->pHead = pNext;
218
219 if (pNext)
220 pNext->pPrev = NULL;
221 }
222
223 if (pNext)
224 pNext->pPrev = pPrev;
225 else
226 {
227 pList->pTail = pPrev;
228
229 if (pPrev)
230 pPrev->pNext = NULL;
231 }
232
233 pEntry->pList = NULL;
234 pEntry->pPrev = NULL;
235 pEntry->pNext = NULL;
236 pdmBlkCacheListSub(pList, pEntry->cbData);
237#ifdef PDMACFILECACHE_WITH_LRULIST_CHECKS
238 pdmBlkCacheCheckList(pList, pEntry);
239#endif
240}
241
242/**
243 * Adds a cache entry to the given LRU list unlinking it from the currently
244 * assigned list if needed.
245 *
246 * @returns nothing.
247 * @param pList List to the add entry to.
248 * @param pEntry Entry to add.
249 */
250static void pdmBlkCacheEntryAddToList(PPDMBLKLRULIST pList, PPDMBLKCACHEENTRY pEntry)
251{
252 LogFlowFunc((": Adding entry %#p to list %#p\n", pEntry, pList));
253#ifdef PDMACFILECACHE_WITH_LRULIST_CHECKS
254 pdmBlkCacheCheckList(pList, NULL);
255#endif
256
257 /* Remove from old list if needed */
258 if (pEntry->pList)
259 pdmBlkCacheEntryRemoveFromList(pEntry);
260
261 pEntry->pNext = pList->pHead;
262 if (pList->pHead)
263 pList->pHead->pPrev = pEntry;
264 else
265 {
266 Assert(!pList->pTail);
267 pList->pTail = pEntry;
268 }
269
270 pEntry->pPrev = NULL;
271 pList->pHead = pEntry;
272 pdmBlkCacheListAdd(pList, pEntry->cbData);
273 pEntry->pList = pList;
274#ifdef PDMACFILECACHE_WITH_LRULIST_CHECKS
275 pdmBlkCacheCheckList(pList, NULL);
276#endif
277}
278
279/**
280 * Destroys a LRU list freeing all entries.
281 *
282 * @returns nothing
283 * @param pList Pointer to the LRU list to destroy.
284 *
285 * @note The caller must own the critical section of the cache.
286 */
287static void pdmBlkCacheDestroyList(PPDMBLKLRULIST pList)
288{
289 while (pList->pHead)
290 {
291 PPDMBLKCACHEENTRY pEntry = pList->pHead;
292
293 pList->pHead = pEntry->pNext;
294
295 AssertMsg(!(pEntry->fFlags & (PDMBLKCACHE_ENTRY_IO_IN_PROGRESS | PDMBLKCACHE_ENTRY_IS_DIRTY)),
296 ("Entry is dirty and/or still in progress fFlags=%#x\n", pEntry->fFlags));
297
298 RTMemPageFree(pEntry->pbData, pEntry->cbData);
299 RTMemFree(pEntry);
300 }
301}
302
303/**
304 * Tries to remove the given amount of bytes from a given list in the cache
305 * moving the entries to one of the given ghosts lists
306 *
307 * @returns Amount of data which could be freed.
308 * @param pCache Pointer to the global cache data.
309 * @param cbData The amount of the data to free.
310 * @param pListSrc The source list to evict data from.
311 * @param pGhostListSrc The ghost list removed entries should be moved to
312 * NULL if the entry should be freed.
313 * @param fReuseBuffer Flag whether a buffer should be reused if it has the same size
314 * @param ppbBuf Where to store the address of the buffer if an entry with the
315 * same size was found and fReuseBuffer is true.
316 *
317 * @note This function may return fewer bytes than requested because entries
318 * may be marked as non evictable if they are used for I/O at the
319 * moment.
320 */
321static size_t pdmBlkCacheEvictPagesFrom(PPDMBLKCACHEGLOBAL pCache, size_t cbData,
322 PPDMBLKLRULIST pListSrc, PPDMBLKLRULIST pGhostListDst,
323 bool fReuseBuffer, uint8_t **ppbBuffer)
324{
325 size_t cbEvicted = 0;
326
327 PDMACFILECACHE_IS_CRITSECT_OWNER(pCache);
328
329 AssertMsg(cbData > 0, ("Evicting 0 bytes not possible\n"));
330 AssertMsg( !pGhostListDst
331 || (pGhostListDst == &pCache->LruRecentlyUsedOut),
332 ("Destination list must be NULL or the recently used but paged out list\n"));
333
334 if (fReuseBuffer)
335 {
336 AssertPtr(ppbBuffer);
337 *ppbBuffer = NULL;
338 }
339
340 /* Start deleting from the tail. */
341 PPDMBLKCACHEENTRY pEntry = pListSrc->pTail;
342
343 while ((cbEvicted < cbData) && pEntry)
344 {
345 PPDMBLKCACHEENTRY pCurr = pEntry;
346
347 pEntry = pEntry->pPrev;
348
349 /* We can't evict pages which are currently in progress or dirty but not in progress */
350 if ( !(pCurr->fFlags & PDMBLKCACHE_NOT_EVICTABLE)
351 && (ASMAtomicReadU32(&pCurr->cRefs) == 0))
352 {
353 /* Ok eviction candidate. Grab the endpoint semaphore and check again
354 * because somebody else might have raced us. */
355 PPDMBLKCACHE pBlkCache = pCurr->pBlkCache;
356 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
357
358 if (!(pCurr->fFlags & PDMBLKCACHE_NOT_EVICTABLE)
359 && (ASMAtomicReadU32(&pCurr->cRefs) == 0))
360 {
361 LogFlow(("Evicting entry %#p (%u bytes)\n", pCurr, pCurr->cbData));
362
363 if (fReuseBuffer && pCurr->cbData == cbData)
364 {
365 STAM_COUNTER_INC(&pCache->StatBuffersReused);
366 *ppbBuffer = pCurr->pbData;
367 }
368 else if (pCurr->pbData)
369 RTMemPageFree(pCurr->pbData, pCurr->cbData);
370
371 pCurr->pbData = NULL;
372 cbEvicted += pCurr->cbData;
373
374 pdmBlkCacheEntryRemoveFromList(pCurr);
375 pdmBlkCacheSub(pCache, pCurr->cbData);
376
377 if (pGhostListDst)
378 {
379 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
380
381 PPDMBLKCACHEENTRY pGhostEntFree = pGhostListDst->pTail;
382
383 /* We have to remove the last entries from the paged out list. */
384 while ( pGhostListDst->cbCached + pCurr->cbData > pCache->cbRecentlyUsedOutMax
385 && pGhostEntFree)
386 {
387 PPDMBLKCACHEENTRY pFree = pGhostEntFree;
388 PPDMBLKCACHE pBlkCacheFree = pFree->pBlkCache;
389
390 pGhostEntFree = pGhostEntFree->pPrev;
391
392 RTSemRWRequestWrite(pBlkCacheFree->SemRWEntries, RT_INDEFINITE_WAIT);
393
394 if (ASMAtomicReadU32(&pFree->cRefs) == 0)
395 {
396 pdmBlkCacheEntryRemoveFromList(pFree);
397
398 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
399 RTAvlrU64Remove(pBlkCacheFree->pTree, pFree->Core.Key);
400 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
401
402 RTMemFree(pFree);
403 }
404
405 RTSemRWReleaseWrite(pBlkCacheFree->SemRWEntries);
406 }
407
408 if (pGhostListDst->cbCached + pCurr->cbData > pCache->cbRecentlyUsedOutMax)
409 {
410 /* Couldn't remove enough entries. Delete */
411 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
412 RTAvlrU64Remove(pCurr->pBlkCache->pTree, pCurr->Core.Key);
413 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
414
415 RTMemFree(pCurr);
416 }
417 else
418 pdmBlkCacheEntryAddToList(pGhostListDst, pCurr);
419 }
420 else
421 {
422 /* Delete the entry from the AVL tree it is assigned to. */
423 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
424 RTAvlrU64Remove(pCurr->pBlkCache->pTree, pCurr->Core.Key);
425 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
426
427 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
428 RTMemFree(pCurr);
429 }
430 }
431
432 }
433 else
434 LogFlow(("Entry %#p (%u bytes) is still in progress and can't be evicted\n", pCurr, pCurr->cbData));
435 }
436
437 return cbEvicted;
438}
439
440static bool pdmBlkCacheReclaim(PPDMBLKCACHEGLOBAL pCache, size_t cbData, bool fReuseBuffer, uint8_t **ppbBuffer)
441{
442 size_t cbRemoved = 0;
443
444 if ((pCache->cbCached + cbData) < pCache->cbMax)
445 return true;
446 else if ((pCache->LruRecentlyUsedIn.cbCached + cbData) > pCache->cbRecentlyUsedInMax)
447 {
448 /* Try to evict as many bytes as possible from A1in */
449 cbRemoved = pdmBlkCacheEvictPagesFrom(pCache, cbData, &pCache->LruRecentlyUsedIn,
450 &pCache->LruRecentlyUsedOut, fReuseBuffer, ppbBuffer);
451
452 /*
453 * If it was not possible to remove enough entries
454 * try the frequently accessed cache.
455 */
456 if (cbRemoved < cbData)
457 {
458 Assert(!fReuseBuffer || !*ppbBuffer); /* It is not possible that we got a buffer with the correct size but we didn't freed enough data. */
459
460 /*
461 * If we removed something we can't pass the reuse buffer flag anymore because
462 * we don't need to evict that much data
463 */
464 if (!cbRemoved)
465 cbRemoved += pdmBlkCacheEvictPagesFrom(pCache, cbData, &pCache->LruFrequentlyUsed,
466 NULL, fReuseBuffer, ppbBuffer);
467 else
468 cbRemoved += pdmBlkCacheEvictPagesFrom(pCache, cbData - cbRemoved, &pCache->LruFrequentlyUsed,
469 NULL, false, NULL);
470 }
471 }
472 else
473 {
474 /* We have to remove entries from frequently access list. */
475 cbRemoved = pdmBlkCacheEvictPagesFrom(pCache, cbData, &pCache->LruFrequentlyUsed,
476 NULL, fReuseBuffer, ppbBuffer);
477 }
478
479 LogFlowFunc((": removed %u bytes, requested %u\n", cbRemoved, cbData));
480 return (cbRemoved >= cbData);
481}
482
483DECLINLINE(int) pdmBlkCacheEnqueue(PPDMBLKCACHE pBlkCache, uint64_t off, size_t cbXfer, PPDMBLKCACHEIOXFER pIoXfer)
484{
485 int rc = VINF_SUCCESS;
486
487 LogFlowFunc(("%s: Enqueuing hIoXfer=%#p enmXferDir=%d\n",
488 __FUNCTION__, pIoXfer, pIoXfer->enmXferDir));
489
490 switch (pBlkCache->enmType)
491 {
492 case PDMBLKCACHETYPE_DEV:
493 {
494 rc = pBlkCache->u.Dev.pfnXferEnqueue(pBlkCache->u.Dev.pDevIns,
495 pIoXfer->enmXferDir,
496 off, cbXfer,
497 &pIoXfer->SgBuf, pIoXfer);
498 break;
499 }
500 case PDMBLKCACHETYPE_DRV:
501 {
502 rc = pBlkCache->u.Drv.pfnXferEnqueue(pBlkCache->u.Drv.pDrvIns,
503 pIoXfer->enmXferDir,
504 off, cbXfer,
505 &pIoXfer->SgBuf, pIoXfer);
506 break;
507 }
508 case PDMBLKCACHETYPE_USB:
509 {
510 rc = pBlkCache->u.Usb.pfnXferEnqueue(pBlkCache->u.Usb.pUsbIns,
511 pIoXfer->enmXferDir,
512 off, cbXfer,
513 &pIoXfer->SgBuf, pIoXfer);
514 break;
515 }
516 case PDMBLKCACHETYPE_INTERNAL:
517 {
518 rc = pBlkCache->u.Int.pfnXferEnqueue(pBlkCache->u.Int.pvUser,
519 pIoXfer->enmXferDir,
520 off, cbXfer,
521 &pIoXfer->SgBuf, pIoXfer);
522 break;
523 }
524 default:
525 AssertMsgFailed(("Unknown block cache type!\n"));
526 }
527
528 LogFlowFunc(("%s: returns rc=%Rrc\n", __FUNCTION__, rc));
529 return rc;
530}
531
532/**
533 * Initiates a read I/O task for the given entry.
534 *
535 * @returns VBox status code.
536 * @param pEntry The entry to fetch the data to.
537 */
538static int pdmBlkCacheEntryReadFromMedium(PPDMBLKCACHEENTRY pEntry)
539{
540 PPDMBLKCACHE pBlkCache = pEntry->pBlkCache;
541 LogFlowFunc((": Reading data into cache entry %#p\n", pEntry));
542
543 /* Make sure no one evicts the entry while it is accessed. */
544 pEntry->fFlags |= PDMBLKCACHE_ENTRY_IO_IN_PROGRESS;
545
546 PPDMBLKCACHEIOXFER pIoXfer = (PPDMBLKCACHEIOXFER)RTMemAllocZ(sizeof(PDMBLKCACHEIOXFER));
547 if (RT_UNLIKELY(!pIoXfer))
548 return VERR_NO_MEMORY;
549
550 AssertMsg(pEntry->pbData, ("Entry is in ghost state\n"));
551
552 pIoXfer->fIoCache = true;
553 pIoXfer->pEntry = pEntry;
554 pIoXfer->SgSeg.pvSeg = pEntry->pbData;
555 pIoXfer->SgSeg.cbSeg = pEntry->cbData;
556 pIoXfer->enmXferDir = PDMBLKCACHEXFERDIR_READ;
557 RTSgBufInit(&pIoXfer->SgBuf, &pIoXfer->SgSeg, 1);
558
559 return pdmBlkCacheEnqueue(pBlkCache, pEntry->Core.Key, pEntry->cbData, pIoXfer);
560}
561
562/**
563 * Initiates a write I/O task for the given entry.
564 *
565 * @returns nothing.
566 * @param pEntry The entry to read the data from.
567 */
568static int pdmBlkCacheEntryWriteToMedium(PPDMBLKCACHEENTRY pEntry)
569{
570 PPDMBLKCACHE pBlkCache = pEntry->pBlkCache;
571 LogFlowFunc((": Writing data from cache entry %#p\n", pEntry));
572
573 /* Make sure no one evicts the entry while it is accessed. */
574 pEntry->fFlags |= PDMBLKCACHE_ENTRY_IO_IN_PROGRESS;
575
576 PPDMBLKCACHEIOXFER pIoXfer = (PPDMBLKCACHEIOXFER)RTMemAllocZ(sizeof(PDMBLKCACHEIOXFER));
577 if (RT_UNLIKELY(!pIoXfer))
578 return VERR_NO_MEMORY;
579
580 AssertMsg(pEntry->pbData, ("Entry is in ghost state\n"));
581
582 pIoXfer->fIoCache = true;
583 pIoXfer->pEntry = pEntry;
584 pIoXfer->SgSeg.pvSeg = pEntry->pbData;
585 pIoXfer->SgSeg.cbSeg = pEntry->cbData;
586 pIoXfer->enmXferDir = PDMBLKCACHEXFERDIR_WRITE;
587 RTSgBufInit(&pIoXfer->SgBuf, &pIoXfer->SgSeg, 1);
588
589 return pdmBlkCacheEnqueue(pBlkCache, pEntry->Core.Key, pEntry->cbData, pIoXfer);
590}
591
592/**
593 * Passthrough a part of a request directly to the I/O manager
594 * handling the endpoint.
595 *
596 * @returns VBox status code.
597 * @param pEndpoint The endpoint.
598 * @param pTask The task.
599 * @param pIoMemCtx The I/O memory context to use.
600 * @param offStart Offset to start transfer from.
601 * @param cbData Amount of data to transfer.
602 * @param enmTransferType The transfer type (read/write)
603 */
604static int pdmBlkCacheRequestPassthrough(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEREQ pReq,
605 PRTSGBUF pSgBuf, uint64_t offStart, size_t cbData,
606 PDMBLKCACHEXFERDIR enmXferDir)
607{
608
609 PPDMBLKCACHEIOXFER pIoXfer = (PPDMBLKCACHEIOXFER)RTMemAllocZ(sizeof(PDMBLKCACHEIOXFER));
610 if (RT_UNLIKELY(!pIoXfer))
611 return VERR_NO_MEMORY;
612
613 ASMAtomicIncU32(&pReq->cXfersPending);
614 pIoXfer->fIoCache = false;
615 pIoXfer->pReq = pReq;
616 pIoXfer->enmXferDir = enmXferDir;
617 if (pSgBuf)
618 {
619 RTSgBufClone(&pIoXfer->SgBuf, pSgBuf);
620 RTSgBufAdvance(pSgBuf, cbData);
621 }
622
623 return pdmBlkCacheEnqueue(pBlkCache, offStart, cbData, pIoXfer);
624}
625
626/**
627 * Commit a single dirty entry to the endpoint
628 *
629 * @returns nothing
630 * @param pEntry The entry to commit.
631 */
632static void pdmBlkCacheEntryCommit(PPDMBLKCACHEENTRY pEntry)
633{
634 AssertMsg( (pEntry->fFlags & PDMBLKCACHE_ENTRY_IS_DIRTY)
635 && !(pEntry->fFlags & PDMBLKCACHE_ENTRY_IO_IN_PROGRESS),
636 ("Invalid flags set for entry %#p\n", pEntry));
637
638 pdmBlkCacheEntryWriteToMedium(pEntry);
639}
640
641/**
642 * Commit all dirty entries for a single endpoint.
643 *
644 * @returns nothing.
645 * @param pBlkCache The endpoint cache to commit.
646 */
647static void pdmBlkCacheCommit(PPDMBLKCACHE pBlkCache)
648{
649 uint32_t cbCommitted = 0;
650
651 /* Return if the cache was suspended. */
652 if (pBlkCache->fSuspended)
653 return;
654
655 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
656
657 /* The list is moved to a new header to reduce locking overhead. */
658 RTLISTANCHOR ListDirtyNotCommitted;
659
660 RTListInit(&ListDirtyNotCommitted);
661 RTSpinlockAcquire(pBlkCache->LockList);
662 RTListMove(&ListDirtyNotCommitted, &pBlkCache->ListDirtyNotCommitted);
663 RTSpinlockRelease(pBlkCache->LockList);
664
665 if (!RTListIsEmpty(&ListDirtyNotCommitted))
666 {
667 PPDMBLKCACHEENTRY pEntry = RTListGetFirst(&ListDirtyNotCommitted, PDMBLKCACHEENTRY, NodeNotCommitted);
668
669 while (!RTListNodeIsLast(&ListDirtyNotCommitted, &pEntry->NodeNotCommitted))
670 {
671 PPDMBLKCACHEENTRY pNext = RTListNodeGetNext(&pEntry->NodeNotCommitted, PDMBLKCACHEENTRY,
672 NodeNotCommitted);
673 pdmBlkCacheEntryCommit(pEntry);
674 cbCommitted += pEntry->cbData;
675 RTListNodeRemove(&pEntry->NodeNotCommitted);
676 pEntry = pNext;
677 }
678
679 /* Commit the last endpoint */
680 Assert(RTListNodeIsLast(&ListDirtyNotCommitted, &pEntry->NodeNotCommitted));
681 pdmBlkCacheEntryCommit(pEntry);
682 cbCommitted += pEntry->cbData;
683 RTListNodeRemove(&pEntry->NodeNotCommitted);
684 AssertMsg(RTListIsEmpty(&ListDirtyNotCommitted),
685 ("Committed all entries but list is not empty\n"));
686 }
687
688 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
689 AssertMsg(pBlkCache->pCache->cbDirty >= cbCommitted,
690 ("Number of committed bytes exceeds number of dirty bytes\n"));
691 uint32_t cbDirtyOld = ASMAtomicSubU32(&pBlkCache->pCache->cbDirty, cbCommitted);
692
693 /* Reset the commit timer if we don't have any dirty bits. */
694 if ( !(cbDirtyOld - cbCommitted)
695 && pBlkCache->pCache->u32CommitTimeoutMs != 0)
696 TMTimerStop(pBlkCache->pCache->pTimerCommit);
697}
698
699/**
700 * Commit all dirty entries in the cache.
701 *
702 * @returns nothing.
703 * @param pCache The global cache instance.
704 */
705static void pdmBlkCacheCommitDirtyEntries(PPDMBLKCACHEGLOBAL pCache)
706{
707 bool fCommitInProgress = ASMAtomicXchgBool(&pCache->fCommitInProgress, true);
708
709 if (!fCommitInProgress)
710 {
711 pdmBlkCacheLockEnter(pCache);
712 Assert(!RTListIsEmpty(&pCache->ListUsers));
713
714 PPDMBLKCACHE pBlkCache = RTListGetFirst(&pCache->ListUsers, PDMBLKCACHE, NodeCacheUser);
715 AssertPtr(pBlkCache);
716
717 while (!RTListNodeIsLast(&pCache->ListUsers, &pBlkCache->NodeCacheUser))
718 {
719 pdmBlkCacheCommit(pBlkCache);
720
721 pBlkCache = RTListNodeGetNext(&pBlkCache->NodeCacheUser, PDMBLKCACHE,
722 NodeCacheUser);
723 }
724
725 /* Commit the last endpoint */
726 Assert(RTListNodeIsLast(&pCache->ListUsers, &pBlkCache->NodeCacheUser));
727 pdmBlkCacheCommit(pBlkCache);
728
729 pdmBlkCacheLockLeave(pCache);
730 ASMAtomicWriteBool(&pCache->fCommitInProgress, false);
731 }
732}
733
734/**
735 * Adds the given entry as a dirty to the cache.
736 *
737 * @returns Flag whether the amount of dirty bytes in the cache exceeds the threshold
738 * @param pBlkCache The endpoint cache the entry belongs to.
739 * @param pEntry The entry to add.
740 */
741static bool pdmBlkCacheAddDirtyEntry(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEENTRY pEntry)
742{
743 bool fDirtyBytesExceeded = false;
744 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
745
746 /* If the commit timer is disabled we commit right away. */
747 if (pCache->u32CommitTimeoutMs == 0)
748 {
749 pEntry->fFlags |= PDMBLKCACHE_ENTRY_IS_DIRTY;
750 pdmBlkCacheEntryCommit(pEntry);
751 }
752 else if (!(pEntry->fFlags & PDMBLKCACHE_ENTRY_IS_DIRTY))
753 {
754 pEntry->fFlags |= PDMBLKCACHE_ENTRY_IS_DIRTY;
755
756 RTSpinlockAcquire(pBlkCache->LockList);
757 RTListAppend(&pBlkCache->ListDirtyNotCommitted, &pEntry->NodeNotCommitted);
758 RTSpinlockRelease(pBlkCache->LockList);
759
760 uint32_t cbDirty = ASMAtomicAddU32(&pCache->cbDirty, pEntry->cbData);
761
762 /* Prevent committing if the VM was suspended. */
763 if (RT_LIKELY(!ASMAtomicReadBool(&pCache->fIoErrorVmSuspended)))
764 fDirtyBytesExceeded = (cbDirty + pEntry->cbData >= pCache->cbCommitDirtyThreshold);
765 else if (!cbDirty && pCache->u32CommitTimeoutMs > 0)
766 {
767 /* Arm the commit timer. */
768 TMTimerSetMillies(pCache->pTimerCommit, pCache->u32CommitTimeoutMs);
769 }
770 }
771
772 return fDirtyBytesExceeded;
773}
774
775static PPDMBLKCACHE pdmR3BlkCacheFindById(PPDMBLKCACHEGLOBAL pBlkCacheGlobal, const char *pcszId)
776{
777 bool fFound = false;
778 PPDMBLKCACHE pBlkCache = NULL;
779
780 RTListForEach(&pBlkCacheGlobal->ListUsers, pBlkCache, PDMBLKCACHE, NodeCacheUser)
781 {
782 if (!RTStrCmp(pBlkCache->pszId, pcszId))
783 {
784 fFound = true;
785 break;
786 }
787 }
788
789 return fFound ? pBlkCache : NULL;
790}
791
792/**
793 * Commit timer callback.
794 */
795static DECLCALLBACK(void) pdmBlkCacheCommitTimerCallback(PVM pVM, PTMTIMER pTimer, void *pvUser)
796{
797 PPDMBLKCACHEGLOBAL pCache = (PPDMBLKCACHEGLOBAL)pvUser;
798 NOREF(pVM); NOREF(pTimer);
799
800 LogFlowFunc(("Commit interval expired, commiting dirty entries\n"));
801
802 if ( ASMAtomicReadU32(&pCache->cbDirty) > 0
803 && !ASMAtomicReadBool(&pCache->fIoErrorVmSuspended))
804 pdmBlkCacheCommitDirtyEntries(pCache);
805
806 LogFlowFunc(("Entries committed, going to sleep\n"));
807}
808
809static DECLCALLBACK(int) pdmR3BlkCacheSaveExec(PVM pVM, PSSMHANDLE pSSM)
810{
811 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
812
813 AssertPtr(pBlkCacheGlobal);
814
815 pdmBlkCacheLockEnter(pBlkCacheGlobal);
816
817 SSMR3PutU32(pSSM, pBlkCacheGlobal->cRefs);
818
819 /* Go through the list and save all dirty entries. */
820 PPDMBLKCACHE pBlkCache;
821 RTListForEach(&pBlkCacheGlobal->ListUsers, pBlkCache, PDMBLKCACHE, NodeCacheUser)
822 {
823 uint32_t cEntries = 0;
824 PPDMBLKCACHEENTRY pEntry;
825
826 RTSemRWRequestRead(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
827 SSMR3PutU32(pSSM, (uint32_t)strlen(pBlkCache->pszId));
828 SSMR3PutStrZ(pSSM, pBlkCache->pszId);
829
830 /* Count the number of entries to safe. */
831 RTListForEach(&pBlkCache->ListDirtyNotCommitted, pEntry, PDMBLKCACHEENTRY, NodeNotCommitted)
832 {
833 cEntries++;
834 }
835
836 SSMR3PutU32(pSSM, cEntries);
837
838 /* Walk the list of all dirty entries and save them. */
839 RTListForEach(&pBlkCache->ListDirtyNotCommitted, pEntry, PDMBLKCACHEENTRY, NodeNotCommitted)
840 {
841 /* A few sanity checks. */
842 AssertMsg(!pEntry->cRefs, ("The entry is still referenced\n"));
843 AssertMsg(pEntry->fFlags & PDMBLKCACHE_ENTRY_IS_DIRTY, ("Entry is not dirty\n"));
844 AssertMsg(!(pEntry->fFlags & ~PDMBLKCACHE_ENTRY_IS_DIRTY), ("Invalid flags set\n"));
845 AssertMsg(!pEntry->pWaitingHead && !pEntry->pWaitingTail, ("There are waiting requests\n"));
846 AssertMsg( pEntry->pList == &pBlkCacheGlobal->LruRecentlyUsedIn
847 || pEntry->pList == &pBlkCacheGlobal->LruFrequentlyUsed,
848 ("Invalid list\n"));
849 AssertMsg(pEntry->cbData == pEntry->Core.KeyLast - pEntry->Core.Key + 1,
850 ("Size and range do not match\n"));
851
852 /* Save */
853 SSMR3PutU64(pSSM, pEntry->Core.Key);
854 SSMR3PutU32(pSSM, pEntry->cbData);
855 SSMR3PutMem(pSSM, pEntry->pbData, pEntry->cbData);
856 }
857
858 RTSemRWReleaseRead(pBlkCache->SemRWEntries);
859 }
860
861 pdmBlkCacheLockLeave(pBlkCacheGlobal);
862
863 /* Terminator */
864 return SSMR3PutU32(pSSM, UINT32_MAX);
865}
866
867static DECLCALLBACK(int) pdmR3BlkCacheLoadExec(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
868{
869 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
870 uint32_t cRefs;
871
872 NOREF(uPass);
873 AssertPtr(pBlkCacheGlobal);
874
875 pdmBlkCacheLockEnter(pBlkCacheGlobal);
876
877 if (uVersion != PDM_BLK_CACHE_SAVED_STATE_VERSION)
878 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
879
880 SSMR3GetU32(pSSM, &cRefs);
881
882 /*
883 * Fewer users in the saved state than in the current VM are allowed
884 * because that means that there are only new ones which don't have any saved state
885 * which can get lost.
886 * More saved entries that current ones are not allowed because this could result in
887 * lost data.
888 */
889 int rc = VINF_SUCCESS;
890 if (cRefs <= pBlkCacheGlobal->cRefs)
891 {
892 char *pszId = NULL;
893
894 while ( cRefs > 0
895 && RT_SUCCESS(rc))
896 {
897 PPDMBLKCACHE pBlkCache = NULL;
898 uint32_t cbId = 0;
899
900 SSMR3GetU32(pSSM, &cbId);
901 Assert(cbId > 0);
902
903 cbId++; /* Include terminator */
904 pszId = (char *)RTMemAllocZ(cbId * sizeof(char));
905 if (!pszId)
906 {
907 rc = VERR_NO_MEMORY;
908 break;
909 }
910
911 rc = SSMR3GetStrZ(pSSM, pszId, cbId);
912 AssertRC(rc);
913
914 /* Search for the block cache with the provided id. */
915 pBlkCache = pdmR3BlkCacheFindById(pBlkCacheGlobal, pszId);
916 if (!pBlkCache)
917 {
918 rc = SSMR3SetCfgError(pSSM, RT_SRC_POS,
919 N_("The VM is missing a block device. Please make sure the source and target VMs have compatible storage configurations"));
920 break;
921 }
922
923 RTStrFree(pszId);
924 pszId = NULL;
925
926 /* Get the entries */
927 uint32_t cEntries;
928 SSMR3GetU32(pSSM, &cEntries);
929
930 while (cEntries > 0)
931 {
932 PPDMBLKCACHEENTRY pEntry;
933 uint64_t off;
934 uint32_t cbEntry;
935
936 SSMR3GetU64(pSSM, &off);
937 SSMR3GetU32(pSSM, &cbEntry);
938
939 pEntry = pdmBlkCacheEntryAlloc(pBlkCache, off, cbEntry, NULL);
940 if (!pEntry)
941 {
942 rc = VERR_NO_MEMORY;
943 break;
944 }
945
946 rc = SSMR3GetMem(pSSM, pEntry->pbData, cbEntry);
947 if (RT_FAILURE(rc))
948 {
949 RTMemFree(pEntry->pbData);
950 RTMemFree(pEntry);
951 break;
952 }
953
954 /* Insert into the tree. */
955 bool fInserted = RTAvlrU64Insert(pBlkCache->pTree, &pEntry->Core);
956 Assert(fInserted); NOREF(fInserted);
957
958 /* Add to the dirty list. */
959 pdmBlkCacheAddDirtyEntry(pBlkCache, pEntry);
960 pdmBlkCacheEntryAddToList(&pBlkCacheGlobal->LruRecentlyUsedIn, pEntry);
961 pdmBlkCacheAdd(pBlkCacheGlobal, cbEntry);
962 pdmBlkCacheEntryRelease(pEntry);
963 cEntries--;
964 }
965
966 cRefs--;
967 }
968
969 if (pszId)
970 RTStrFree(pszId);
971 }
972 else
973 rc = SSMR3SetCfgError(pSSM, RT_SRC_POS,
974 N_("The VM is missing a block device. Please make sure the source and target VMs have compatible storage configurations"));
975
976 pdmBlkCacheLockLeave(pBlkCacheGlobal);
977
978 if (RT_SUCCESS(rc))
979 {
980 uint32_t u32 = 0;
981 rc = SSMR3GetU32(pSSM, &u32);
982 if (RT_SUCCESS(rc))
983 AssertMsgReturn(u32 == UINT32_MAX, ("%#x\n", u32), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
984 }
985
986 return rc;
987}
988
989int pdmR3BlkCacheInit(PVM pVM)
990{
991 int rc = VINF_SUCCESS;
992 PUVM pUVM = pVM->pUVM;
993 PPDMBLKCACHEGLOBAL pBlkCacheGlobal;
994
995 LogFlowFunc((": pVM=%p\n", pVM));
996
997 VM_ASSERT_EMT(pVM);
998
999 PCFGMNODE pCfgRoot = CFGMR3GetRoot(pVM);
1000 PCFGMNODE pCfgBlkCache = CFGMR3GetChild(CFGMR3GetChild(pCfgRoot, "PDM"), "BlkCache");
1001
1002 pBlkCacheGlobal = (PPDMBLKCACHEGLOBAL)RTMemAllocZ(sizeof(PDMBLKCACHEGLOBAL));
1003 if (!pBlkCacheGlobal)
1004 return VERR_NO_MEMORY;
1005
1006 RTListInit(&pBlkCacheGlobal->ListUsers);
1007 pBlkCacheGlobal->pVM = pVM;
1008 pBlkCacheGlobal->cRefs = 0;
1009 pBlkCacheGlobal->cbCached = 0;
1010 pBlkCacheGlobal->fCommitInProgress = false;
1011
1012 /* Initialize members */
1013 pBlkCacheGlobal->LruRecentlyUsedIn.pHead = NULL;
1014 pBlkCacheGlobal->LruRecentlyUsedIn.pTail = NULL;
1015 pBlkCacheGlobal->LruRecentlyUsedIn.cbCached = 0;
1016
1017 pBlkCacheGlobal->LruRecentlyUsedOut.pHead = NULL;
1018 pBlkCacheGlobal->LruRecentlyUsedOut.pTail = NULL;
1019 pBlkCacheGlobal->LruRecentlyUsedOut.cbCached = 0;
1020
1021 pBlkCacheGlobal->LruFrequentlyUsed.pHead = NULL;
1022 pBlkCacheGlobal->LruFrequentlyUsed.pTail = NULL;
1023 pBlkCacheGlobal->LruFrequentlyUsed.cbCached = 0;
1024
1025 do
1026 {
1027 rc = CFGMR3QueryU32Def(pCfgBlkCache, "CacheSize", &pBlkCacheGlobal->cbMax, 5 * _1M);
1028 AssertLogRelRCBreak(rc);
1029 LogFlowFunc(("Maximum number of bytes cached %u\n", pBlkCacheGlobal->cbMax));
1030
1031 pBlkCacheGlobal->cbRecentlyUsedInMax = (pBlkCacheGlobal->cbMax / 100) * 25; /* 25% of the buffer size */
1032 pBlkCacheGlobal->cbRecentlyUsedOutMax = (pBlkCacheGlobal->cbMax / 100) * 50; /* 50% of the buffer size */
1033 LogFlowFunc(("cbRecentlyUsedInMax=%u cbRecentlyUsedOutMax=%u\n",
1034 pBlkCacheGlobal->cbRecentlyUsedInMax, pBlkCacheGlobal->cbRecentlyUsedOutMax));
1035
1036 /** @todo r=aeichner: Experiment to find optimal default values */
1037 rc = CFGMR3QueryU32Def(pCfgBlkCache, "CacheCommitIntervalMs", &pBlkCacheGlobal->u32CommitTimeoutMs, 10000 /* 10sec */);
1038 AssertLogRelRCBreak(rc);
1039 rc = CFGMR3QueryU32Def(pCfgBlkCache, "CacheCommitThreshold", &pBlkCacheGlobal->cbCommitDirtyThreshold, pBlkCacheGlobal->cbMax / 2);
1040 AssertLogRelRCBreak(rc);
1041 } while (0);
1042
1043 if (RT_SUCCESS(rc))
1044 {
1045 STAMR3Register(pVM, &pBlkCacheGlobal->cbMax,
1046 STAMTYPE_U32, STAMVISIBILITY_ALWAYS,
1047 "/PDM/BlkCache/cbMax",
1048 STAMUNIT_BYTES,
1049 "Maximum cache size");
1050 STAMR3Register(pVM, &pBlkCacheGlobal->cbCached,
1051 STAMTYPE_U32, STAMVISIBILITY_ALWAYS,
1052 "/PDM/BlkCache/cbCached",
1053 STAMUNIT_BYTES,
1054 "Currently used cache");
1055 STAMR3Register(pVM, &pBlkCacheGlobal->LruRecentlyUsedIn.cbCached,
1056 STAMTYPE_U32, STAMVISIBILITY_ALWAYS,
1057 "/PDM/BlkCache/cbCachedMruIn",
1058 STAMUNIT_BYTES,
1059 "Number of bytes cached in MRU list");
1060 STAMR3Register(pVM, &pBlkCacheGlobal->LruRecentlyUsedOut.cbCached,
1061 STAMTYPE_U32, STAMVISIBILITY_ALWAYS,
1062 "/PDM/BlkCache/cbCachedMruOut",
1063 STAMUNIT_BYTES,
1064 "Number of bytes cached in FRU list");
1065 STAMR3Register(pVM, &pBlkCacheGlobal->LruFrequentlyUsed.cbCached,
1066 STAMTYPE_U32, STAMVISIBILITY_ALWAYS,
1067 "/PDM/BlkCache/cbCachedFru",
1068 STAMUNIT_BYTES,
1069 "Number of bytes cached in FRU ghost list");
1070
1071#ifdef VBOX_WITH_STATISTICS
1072 STAMR3Register(pVM, &pBlkCacheGlobal->cHits,
1073 STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
1074 "/PDM/BlkCache/CacheHits",
1075 STAMUNIT_COUNT, "Number of hits in the cache");
1076 STAMR3Register(pVM, &pBlkCacheGlobal->cPartialHits,
1077 STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
1078 "/PDM/BlkCache/CachePartialHits",
1079 STAMUNIT_COUNT, "Number of partial hits in the cache");
1080 STAMR3Register(pVM, &pBlkCacheGlobal->cMisses,
1081 STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
1082 "/PDM/BlkCache/CacheMisses",
1083 STAMUNIT_COUNT, "Number of misses when accessing the cache");
1084 STAMR3Register(pVM, &pBlkCacheGlobal->StatRead,
1085 STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
1086 "/PDM/BlkCache/CacheRead",
1087 STAMUNIT_BYTES, "Number of bytes read from the cache");
1088 STAMR3Register(pVM, &pBlkCacheGlobal->StatWritten,
1089 STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
1090 "/PDM/BlkCache/CacheWritten",
1091 STAMUNIT_BYTES, "Number of bytes written to the cache");
1092 STAMR3Register(pVM, &pBlkCacheGlobal->StatTreeGet,
1093 STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS,
1094 "/PDM/BlkCache/CacheTreeGet",
1095 STAMUNIT_TICKS_PER_CALL, "Time taken to access an entry in the tree");
1096 STAMR3Register(pVM, &pBlkCacheGlobal->StatTreeInsert,
1097 STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS,
1098 "/PDM/BlkCache/CacheTreeInsert",
1099 STAMUNIT_TICKS_PER_CALL, "Time taken to insert an entry in the tree");
1100 STAMR3Register(pVM, &pBlkCacheGlobal->StatTreeRemove,
1101 STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS,
1102 "/PDM/BlkCache/CacheTreeRemove",
1103 STAMUNIT_TICKS_PER_CALL, "Time taken to remove an entry an the tree");
1104 STAMR3Register(pVM, &pBlkCacheGlobal->StatBuffersReused,
1105 STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
1106 "/PDM/BlkCache/CacheBuffersReused",
1107 STAMUNIT_COUNT, "Number of times a buffer could be reused");
1108#endif
1109
1110 /* Initialize the critical section */
1111 rc = RTCritSectInit(&pBlkCacheGlobal->CritSect);
1112 }
1113
1114 if (RT_SUCCESS(rc))
1115 {
1116 /* Create the commit timer */
1117 if (pBlkCacheGlobal->u32CommitTimeoutMs > 0)
1118 rc = TMR3TimerCreateInternal(pVM, TMCLOCK_REAL,
1119 pdmBlkCacheCommitTimerCallback,
1120 pBlkCacheGlobal,
1121 "BlkCache-Commit",
1122 &pBlkCacheGlobal->pTimerCommit);
1123
1124 if (RT_SUCCESS(rc))
1125 {
1126 /* Register saved state handler. */
1127 rc = SSMR3RegisterInternal(pVM, "pdmblkcache", 0, PDM_BLK_CACHE_SAVED_STATE_VERSION, pBlkCacheGlobal->cbMax,
1128 NULL, NULL, NULL,
1129 NULL, pdmR3BlkCacheSaveExec, NULL,
1130 NULL, pdmR3BlkCacheLoadExec, NULL);
1131 if (RT_SUCCESS(rc))
1132 {
1133 LogRel(("BlkCache: Cache successfully initialised. Cache size is %u bytes\n", pBlkCacheGlobal->cbMax));
1134 LogRel(("BlkCache: Cache commit interval is %u ms\n", pBlkCacheGlobal->u32CommitTimeoutMs));
1135 LogRel(("BlkCache: Cache commit threshold is %u bytes\n", pBlkCacheGlobal->cbCommitDirtyThreshold));
1136 pUVM->pdm.s.pBlkCacheGlobal = pBlkCacheGlobal;
1137 return VINF_SUCCESS;
1138 }
1139 }
1140
1141 RTCritSectDelete(&pBlkCacheGlobal->CritSect);
1142 }
1143
1144 if (pBlkCacheGlobal)
1145 RTMemFree(pBlkCacheGlobal);
1146
1147 LogFlowFunc((": returns rc=%Rrc\n", pVM, rc));
1148 return rc;
1149}
1150
1151void pdmR3BlkCacheTerm(PVM pVM)
1152{
1153 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
1154
1155 if (pBlkCacheGlobal)
1156 {
1157 /* Make sure no one else uses the cache now */
1158 pdmBlkCacheLockEnter(pBlkCacheGlobal);
1159
1160 /* Cleanup deleting all cache entries waiting for in progress entries to finish. */
1161 pdmBlkCacheDestroyList(&pBlkCacheGlobal->LruRecentlyUsedIn);
1162 pdmBlkCacheDestroyList(&pBlkCacheGlobal->LruRecentlyUsedOut);
1163 pdmBlkCacheDestroyList(&pBlkCacheGlobal->LruFrequentlyUsed);
1164
1165 pdmBlkCacheLockLeave(pBlkCacheGlobal);
1166
1167 RTCritSectDelete(&pBlkCacheGlobal->CritSect);
1168 RTMemFree(pBlkCacheGlobal);
1169 pVM->pUVM->pdm.s.pBlkCacheGlobal = NULL;
1170 }
1171}
1172
1173int pdmR3BlkCacheResume(PVM pVM)
1174{
1175 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
1176
1177 LogFlowFunc(("pVM=%#p\n", pVM));
1178
1179 if ( pBlkCacheGlobal
1180 && ASMAtomicXchgBool(&pBlkCacheGlobal->fIoErrorVmSuspended, false))
1181 {
1182 /* The VM was suspended because of an I/O error, commit all dirty entries. */
1183 pdmBlkCacheCommitDirtyEntries(pBlkCacheGlobal);
1184 }
1185
1186 return VINF_SUCCESS;
1187}
1188
1189static int pdmR3BlkCacheRetain(PVM pVM, PPPDMBLKCACHE ppBlkCache, const char *pcszId)
1190{
1191 int rc = VINF_SUCCESS;
1192 PPDMBLKCACHE pBlkCache = NULL;
1193 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
1194
1195 if (!pBlkCacheGlobal)
1196 return VERR_NOT_SUPPORTED;
1197
1198 /*
1199 * Check that no other user cache has the same id first,
1200 * Unique id's are necessary in case the state is saved.
1201 */
1202 pdmBlkCacheLockEnter(pBlkCacheGlobal);
1203
1204 pBlkCache = pdmR3BlkCacheFindById(pBlkCacheGlobal, pcszId);
1205
1206 if (!pBlkCache)
1207 {
1208 pBlkCache = (PPDMBLKCACHE)RTMemAllocZ(sizeof(PDMBLKCACHE));
1209
1210 if (pBlkCache)
1211 pBlkCache->pszId = RTStrDup(pcszId);
1212
1213 if ( pBlkCache
1214 && pBlkCache->pszId)
1215 {
1216 pBlkCache->fSuspended = false;
1217 pBlkCache->pCache = pBlkCacheGlobal;
1218 RTListInit(&pBlkCache->ListDirtyNotCommitted);
1219
1220 rc = RTSpinlockCreate(&pBlkCache->LockList, RTSPINLOCK_FLAGS_INTERRUPT_UNSAFE, "pdmR3BlkCacheRetain");
1221 if (RT_SUCCESS(rc))
1222 {
1223 rc = RTSemRWCreate(&pBlkCache->SemRWEntries);
1224 if (RT_SUCCESS(rc))
1225 {
1226 pBlkCache->pTree = (PAVLRU64TREE)RTMemAllocZ(sizeof(AVLRFOFFTREE));
1227 if (pBlkCache->pTree)
1228 {
1229#ifdef VBOX_WITH_STATISTICS
1230 STAMR3RegisterF(pBlkCacheGlobal->pVM, &pBlkCache->StatWriteDeferred,
1231 STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
1232 STAMUNIT_COUNT, "Number of deferred writes",
1233 "/PDM/BlkCache/%s/Cache/DeferredWrites", pBlkCache->pszId);
1234#endif
1235
1236 /* Add to the list of users. */
1237 pBlkCacheGlobal->cRefs++;
1238 RTListAppend(&pBlkCacheGlobal->ListUsers, &pBlkCache->NodeCacheUser);
1239 pdmBlkCacheLockLeave(pBlkCacheGlobal);
1240
1241 *ppBlkCache = pBlkCache;
1242 LogFlowFunc(("returns success\n"));
1243 return VINF_SUCCESS;
1244 }
1245 else
1246 rc = VERR_NO_MEMORY;
1247
1248 RTSemRWDestroy(pBlkCache->SemRWEntries);
1249 }
1250
1251 RTSpinlockDestroy(pBlkCache->LockList);
1252 }
1253
1254 RTStrFree(pBlkCache->pszId);
1255 }
1256 else
1257 rc = VERR_NO_MEMORY;
1258
1259 if (pBlkCache)
1260 RTMemFree(pBlkCache);
1261 }
1262 else
1263 rc = VERR_ALREADY_EXISTS;
1264
1265 pdmBlkCacheLockLeave(pBlkCacheGlobal);
1266
1267 LogFlowFunc(("Leave rc=%Rrc\n", rc));
1268 return rc;
1269}
1270
1271VMMR3DECL(int) PDMR3BlkCacheRetainDriver(PVM pVM, PPDMDRVINS pDrvIns, PPPDMBLKCACHE ppBlkCache,
1272 PFNPDMBLKCACHEXFERCOMPLETEDRV pfnXferComplete,
1273 PFNPDMBLKCACHEXFERENQUEUEDRV pfnXferEnqueue,
1274 PFNPDMBLKCACHEXFERENQUEUEDISCARDDRV pfnXferEnqueueDiscard,
1275 const char *pcszId)
1276{
1277 int rc = VINF_SUCCESS;
1278 PPDMBLKCACHE pBlkCache;
1279
1280 rc = pdmR3BlkCacheRetain(pVM, &pBlkCache, pcszId);
1281 if (RT_SUCCESS(rc))
1282 {
1283 pBlkCache->enmType = PDMBLKCACHETYPE_DRV;
1284 pBlkCache->u.Drv.pfnXferComplete = pfnXferComplete;
1285 pBlkCache->u.Drv.pfnXferEnqueue = pfnXferEnqueue;
1286 pBlkCache->u.Drv.pfnXferEnqueueDiscard = pfnXferEnqueueDiscard;
1287 pBlkCache->u.Drv.pDrvIns = pDrvIns;
1288 *ppBlkCache = pBlkCache;
1289 }
1290
1291 LogFlowFunc(("Leave rc=%Rrc\n", rc));
1292 return rc;
1293}
1294
1295VMMR3DECL(int) PDMR3BlkCacheRetainDevice(PVM pVM, PPDMDEVINS pDevIns, PPPDMBLKCACHE ppBlkCache,
1296 PFNPDMBLKCACHEXFERCOMPLETEDEV pfnXferComplete,
1297 PFNPDMBLKCACHEXFERENQUEUEDEV pfnXferEnqueue,
1298 PFNPDMBLKCACHEXFERENQUEUEDISCARDDEV pfnXferEnqueueDiscard,
1299 const char *pcszId)
1300{
1301 int rc = VINF_SUCCESS;
1302 PPDMBLKCACHE pBlkCache;
1303
1304 rc = pdmR3BlkCacheRetain(pVM, &pBlkCache, pcszId);
1305 if (RT_SUCCESS(rc))
1306 {
1307 pBlkCache->enmType = PDMBLKCACHETYPE_DEV;
1308 pBlkCache->u.Dev.pfnXferComplete = pfnXferComplete;
1309 pBlkCache->u.Dev.pfnXferEnqueue = pfnXferEnqueue;
1310 pBlkCache->u.Dev.pfnXferEnqueueDiscard = pfnXferEnqueueDiscard;
1311 pBlkCache->u.Dev.pDevIns = pDevIns;
1312 *ppBlkCache = pBlkCache;
1313 }
1314
1315 LogFlowFunc(("Leave rc=%Rrc\n", rc));
1316 return rc;
1317
1318}
1319
1320VMMR3DECL(int) PDMR3BlkCacheRetainUsb(PVM pVM, PPDMUSBINS pUsbIns, PPPDMBLKCACHE ppBlkCache,
1321 PFNPDMBLKCACHEXFERCOMPLETEUSB pfnXferComplete,
1322 PFNPDMBLKCACHEXFERENQUEUEUSB pfnXferEnqueue,
1323 PFNPDMBLKCACHEXFERENQUEUEDISCARDUSB pfnXferEnqueueDiscard,
1324 const char *pcszId)
1325{
1326 int rc = VINF_SUCCESS;
1327 PPDMBLKCACHE pBlkCache;
1328
1329 rc = pdmR3BlkCacheRetain(pVM, &pBlkCache, pcszId);
1330 if (RT_SUCCESS(rc))
1331 {
1332 pBlkCache->enmType = PDMBLKCACHETYPE_USB;
1333 pBlkCache->u.Usb.pfnXferComplete = pfnXferComplete;
1334 pBlkCache->u.Usb.pfnXferEnqueue = pfnXferEnqueue;
1335 pBlkCache->u.Usb.pfnXferEnqueueDiscard = pfnXferEnqueueDiscard;
1336 pBlkCache->u.Usb.pUsbIns = pUsbIns;
1337 *ppBlkCache = pBlkCache;
1338 }
1339
1340 LogFlowFunc(("Leave rc=%Rrc\n", rc));
1341 return rc;
1342
1343}
1344
1345VMMR3DECL(int) PDMR3BlkCacheRetainInt(PVM pVM, void *pvUser, PPPDMBLKCACHE ppBlkCache,
1346 PFNPDMBLKCACHEXFERCOMPLETEINT pfnXferComplete,
1347 PFNPDMBLKCACHEXFERENQUEUEINT pfnXferEnqueue,
1348 PFNPDMBLKCACHEXFERENQUEUEDISCARDINT pfnXferEnqueueDiscard,
1349 const char *pcszId)
1350{
1351 int rc = VINF_SUCCESS;
1352 PPDMBLKCACHE pBlkCache;
1353
1354 rc = pdmR3BlkCacheRetain(pVM, &pBlkCache, pcszId);
1355 if (RT_SUCCESS(rc))
1356 {
1357 pBlkCache->enmType = PDMBLKCACHETYPE_INTERNAL;
1358 pBlkCache->u.Int.pfnXferComplete = pfnXferComplete;
1359 pBlkCache->u.Int.pfnXferEnqueue = pfnXferEnqueue;
1360 pBlkCache->u.Int.pfnXferEnqueueDiscard = pfnXferEnqueueDiscard;
1361 pBlkCache->u.Int.pvUser = pvUser;
1362 *ppBlkCache = pBlkCache;
1363 }
1364
1365 LogFlowFunc(("Leave rc=%Rrc\n", rc));
1366 return rc;
1367
1368}
1369
1370/**
1371 * Callback for the AVL destroy routine. Frees a cache entry for this endpoint.
1372 *
1373 * @returns IPRT status code.
1374 * @param pNode The node to destroy.
1375 * @param pvUser Opaque user data.
1376 */
1377static int pdmBlkCacheEntryDestroy(PAVLRU64NODECORE pNode, void *pvUser)
1378{
1379 PPDMBLKCACHEENTRY pEntry = (PPDMBLKCACHEENTRY)pNode;
1380 PPDMBLKCACHEGLOBAL pCache = (PPDMBLKCACHEGLOBAL)pvUser;
1381 PPDMBLKCACHE pBlkCache = pEntry->pBlkCache;
1382
1383 while (ASMAtomicReadU32(&pEntry->fFlags) & PDMBLKCACHE_ENTRY_IO_IN_PROGRESS)
1384 {
1385 /* Leave the locks to let the I/O thread make progress but reference the entry to prevent eviction. */
1386 pdmBlkCacheEntryRef(pEntry);
1387 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
1388 pdmBlkCacheLockLeave(pCache);
1389
1390 RTThreadSleep(250);
1391
1392 /* Re-enter all locks */
1393 pdmBlkCacheLockEnter(pCache);
1394 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
1395 pdmBlkCacheEntryRelease(pEntry);
1396 }
1397
1398 AssertMsg(!(pEntry->fFlags & PDMBLKCACHE_ENTRY_IO_IN_PROGRESS),
1399 ("Entry is dirty and/or still in progress fFlags=%#x\n", pEntry->fFlags));
1400
1401 bool fUpdateCache = pEntry->pList == &pCache->LruFrequentlyUsed
1402 || pEntry->pList == &pCache->LruRecentlyUsedIn;
1403
1404 pdmBlkCacheEntryRemoveFromList(pEntry);
1405
1406 if (fUpdateCache)
1407 pdmBlkCacheSub(pCache, pEntry->cbData);
1408
1409 RTMemPageFree(pEntry->pbData, pEntry->cbData);
1410 RTMemFree(pEntry);
1411
1412 return VINF_SUCCESS;
1413}
1414
1415/**
1416 * Destroys all cache resources used by the given endpoint.
1417 *
1418 * @returns nothing.
1419 * @param pEndpoint The endpoint to the destroy.
1420 */
1421VMMR3DECL(void) PDMR3BlkCacheRelease(PPDMBLKCACHE pBlkCache)
1422{
1423 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
1424
1425 /*
1426 * Commit all dirty entries now (they are waited on for completion during the
1427 * destruction of the AVL tree below).
1428 * The exception is if the VM was paused because of an I/O error before.
1429 */
1430 if (!ASMAtomicReadBool(&pCache->fIoErrorVmSuspended))
1431 pdmBlkCacheCommit(pBlkCache);
1432
1433 /* Make sure nobody is accessing the cache while we delete the tree. */
1434 pdmBlkCacheLockEnter(pCache);
1435 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
1436 RTAvlrU64Destroy(pBlkCache->pTree, pdmBlkCacheEntryDestroy, pCache);
1437 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
1438
1439 RTSpinlockDestroy(pBlkCache->LockList);
1440
1441 pCache->cRefs--;
1442 RTListNodeRemove(&pBlkCache->NodeCacheUser);
1443
1444 pdmBlkCacheLockLeave(pCache);
1445
1446 RTSemRWDestroy(pBlkCache->SemRWEntries);
1447
1448#ifdef VBOX_WITH_STATISTICS
1449 STAMR3Deregister(pCache->pVM, &pBlkCache->StatWriteDeferred);
1450#endif
1451
1452 RTStrFree(pBlkCache->pszId);
1453 RTMemFree(pBlkCache);
1454}
1455
1456VMMR3DECL(void) PDMR3BlkCacheReleaseDevice(PVM pVM, PPDMDEVINS pDevIns)
1457{
1458 LogFlow(("%s: pDevIns=%p\n", __FUNCTION__, pDevIns));
1459
1460 /*
1461 * Validate input.
1462 */
1463 if (!pDevIns)
1464 return;
1465 VM_ASSERT_EMT(pVM);
1466
1467 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
1468 PPDMBLKCACHE pBlkCache, pBlkCacheNext;
1469
1470 /* Return silently if not supported. */
1471 if (!pBlkCacheGlobal)
1472 return;
1473
1474 pdmBlkCacheLockEnter(pBlkCacheGlobal);
1475
1476 RTListForEachSafe(&pBlkCacheGlobal->ListUsers, pBlkCache, pBlkCacheNext, PDMBLKCACHE, NodeCacheUser)
1477 {
1478 if ( pBlkCache->enmType == PDMBLKCACHETYPE_DEV
1479 && pBlkCache->u.Dev.pDevIns == pDevIns)
1480 PDMR3BlkCacheRelease(pBlkCache);
1481 }
1482
1483 pdmBlkCacheLockLeave(pBlkCacheGlobal);
1484}
1485
1486VMMR3DECL(void) PDMR3BlkCacheReleaseDriver(PVM pVM, PPDMDRVINS pDrvIns)
1487{
1488 LogFlow(("%s: pDrvIns=%p\n", __FUNCTION__, pDrvIns));
1489
1490 /*
1491 * Validate input.
1492 */
1493 if (!pDrvIns)
1494 return;
1495 VM_ASSERT_EMT(pVM);
1496
1497 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
1498 PPDMBLKCACHE pBlkCache, pBlkCacheNext;
1499
1500 /* Return silently if not supported. */
1501 if (!pBlkCacheGlobal)
1502 return;
1503
1504 pdmBlkCacheLockEnter(pBlkCacheGlobal);
1505
1506 RTListForEachSafe(&pBlkCacheGlobal->ListUsers, pBlkCache, pBlkCacheNext, PDMBLKCACHE, NodeCacheUser)
1507 {
1508 if ( pBlkCache->enmType == PDMBLKCACHETYPE_DRV
1509 && pBlkCache->u.Drv.pDrvIns == pDrvIns)
1510 PDMR3BlkCacheRelease(pBlkCache);
1511 }
1512
1513 pdmBlkCacheLockLeave(pBlkCacheGlobal);
1514}
1515
1516VMMR3DECL(void) PDMR3BlkCacheReleaseUsb(PVM pVM, PPDMUSBINS pUsbIns)
1517{
1518 LogFlow(("%s: pUsbIns=%p\n", __FUNCTION__, pUsbIns));
1519
1520 /*
1521 * Validate input.
1522 */
1523 if (!pUsbIns)
1524 return;
1525 VM_ASSERT_EMT(pVM);
1526
1527 PPDMBLKCACHEGLOBAL pBlkCacheGlobal = pVM->pUVM->pdm.s.pBlkCacheGlobal;
1528 PPDMBLKCACHE pBlkCache, pBlkCacheNext;
1529
1530 /* Return silently if not supported. */
1531 if (!pBlkCacheGlobal)
1532 return;
1533
1534 pdmBlkCacheLockEnter(pBlkCacheGlobal);
1535
1536 RTListForEachSafe(&pBlkCacheGlobal->ListUsers, pBlkCache, pBlkCacheNext, PDMBLKCACHE, NodeCacheUser)
1537 {
1538 if ( pBlkCache->enmType == PDMBLKCACHETYPE_USB
1539 && pBlkCache->u.Usb.pUsbIns == pUsbIns)
1540 PDMR3BlkCacheRelease(pBlkCache);
1541 }
1542
1543 pdmBlkCacheLockLeave(pBlkCacheGlobal);
1544}
1545
1546static PPDMBLKCACHEENTRY pdmBlkCacheGetCacheEntryByOffset(PPDMBLKCACHE pBlkCache, uint64_t off)
1547{
1548 STAM_PROFILE_ADV_START(&pBlkCache->pCache->StatTreeGet, Cache);
1549
1550 RTSemRWRequestRead(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
1551 PPDMBLKCACHEENTRY pEntry = (PPDMBLKCACHEENTRY)RTAvlrU64RangeGet(pBlkCache->pTree, off);
1552 if (pEntry)
1553 pdmBlkCacheEntryRef(pEntry);
1554 RTSemRWReleaseRead(pBlkCache->SemRWEntries);
1555
1556 STAM_PROFILE_ADV_STOP(&pBlkCache->pCache->StatTreeGet, Cache);
1557
1558 return pEntry;
1559}
1560
1561/**
1562 * Return the best fit cache entries for the given offset.
1563 *
1564 * @returns nothing.
1565 * @param pBlkCache The endpoint cache.
1566 * @param off The offset.
1567 * @param pEntryAbove Where to store the pointer to the best fit entry above the
1568 * the given offset. NULL if not required.
1569 */
1570static void pdmBlkCacheGetCacheBestFitEntryByOffset(PPDMBLKCACHE pBlkCache, uint64_t off,
1571 PPDMBLKCACHEENTRY *ppEntryAbove)
1572{
1573 STAM_PROFILE_ADV_START(&pBlkCache->pCache->StatTreeGet, Cache);
1574
1575 RTSemRWRequestRead(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
1576 if (ppEntryAbove)
1577 {
1578 *ppEntryAbove = (PPDMBLKCACHEENTRY)RTAvlrU64GetBestFit(pBlkCache->pTree, off, true /*fAbove*/);
1579 if (*ppEntryAbove)
1580 pdmBlkCacheEntryRef(*ppEntryAbove);
1581 }
1582
1583 RTSemRWReleaseRead(pBlkCache->SemRWEntries);
1584
1585 STAM_PROFILE_ADV_STOP(&pBlkCache->pCache->StatTreeGet, Cache);
1586}
1587
1588static void pdmBlkCacheInsertEntry(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEENTRY pEntry)
1589{
1590 STAM_PROFILE_ADV_START(&pBlkCache->pCache->StatTreeInsert, Cache);
1591 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
1592 bool fInserted = RTAvlrU64Insert(pBlkCache->pTree, &pEntry->Core);
1593 AssertMsg(fInserted, ("Node was not inserted into tree\n")); NOREF(fInserted);
1594 STAM_PROFILE_ADV_STOP(&pBlkCache->pCache->StatTreeInsert, Cache);
1595 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
1596}
1597
1598/**
1599 * Allocates and initializes a new entry for the cache.
1600 * The entry has a reference count of 1.
1601 *
1602 * @returns Pointer to the new cache entry or NULL if out of memory.
1603 * @param pBlkCache The cache the entry belongs to.
1604 * @param off Start offset.
1605 * @param cbData Size of the cache entry.
1606 * @param pbBuffer Pointer to the buffer to use.
1607 * NULL if a new buffer should be allocated.
1608 * The buffer needs to have the same size of the entry.
1609 */
1610static PPDMBLKCACHEENTRY pdmBlkCacheEntryAlloc(PPDMBLKCACHE pBlkCache,
1611 uint64_t off, size_t cbData, uint8_t *pbBuffer)
1612{
1613 AssertReturn(cbData <= UINT32_MAX, NULL);
1614 PPDMBLKCACHEENTRY pEntryNew = (PPDMBLKCACHEENTRY)RTMemAllocZ(sizeof(PDMBLKCACHEENTRY));
1615
1616 if (RT_UNLIKELY(!pEntryNew))
1617 return NULL;
1618
1619 pEntryNew->Core.Key = off;
1620 pEntryNew->Core.KeyLast = off + cbData - 1;
1621 pEntryNew->pBlkCache = pBlkCache;
1622 pEntryNew->fFlags = 0;
1623 pEntryNew->cRefs = 1; /* We are using it now. */
1624 pEntryNew->pList = NULL;
1625 pEntryNew->cbData = (uint32_t)cbData;
1626 pEntryNew->pWaitingHead = NULL;
1627 pEntryNew->pWaitingTail = NULL;
1628 if (pbBuffer)
1629 pEntryNew->pbData = pbBuffer;
1630 else
1631 pEntryNew->pbData = (uint8_t *)RTMemPageAlloc(cbData);
1632
1633 if (RT_UNLIKELY(!pEntryNew->pbData))
1634 {
1635 RTMemFree(pEntryNew);
1636 return NULL;
1637 }
1638
1639 return pEntryNew;
1640}
1641
1642/**
1643 * Checks that a set of flags is set/clear acquiring the R/W semaphore
1644 * in exclusive mode.
1645 *
1646 * @returns true if the flag in fSet is set and the one in fClear is clear.
1647 * false otherwise.
1648 * The R/W semaphore is only held if true is returned.
1649 *
1650 * @param pBlkCache The endpoint cache instance data.
1651 * @param pEntry The entry to check the flags for.
1652 * @param fSet The flag which is tested to be set.
1653 * @param fClear The flag which is tested to be clear.
1654 */
1655DECLINLINE(bool) pdmBlkCacheEntryFlagIsSetClearAcquireLock(PPDMBLKCACHE pBlkCache,
1656 PPDMBLKCACHEENTRY pEntry,
1657 uint32_t fSet, uint32_t fClear)
1658{
1659 uint32_t fFlags = ASMAtomicReadU32(&pEntry->fFlags);
1660 bool fPassed = ((fFlags & fSet) && !(fFlags & fClear));
1661
1662 if (fPassed)
1663 {
1664 /* Acquire the lock and check again because the completion callback might have raced us. */
1665 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
1666
1667 fFlags = ASMAtomicReadU32(&pEntry->fFlags);
1668 fPassed = ((fFlags & fSet) && !(fFlags & fClear));
1669
1670 /* Drop the lock if we didn't passed the test. */
1671 if (!fPassed)
1672 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
1673 }
1674
1675 return fPassed;
1676}
1677
1678/**
1679 * Adds a segment to the waiting list for a cache entry
1680 * which is currently in progress.
1681 *
1682 * @returns nothing.
1683 * @param pEntry The cache entry to add the segment to.
1684 * @param pSeg The segment to add.
1685 */
1686DECLINLINE(void) pdmBlkCacheEntryAddWaiter(PPDMBLKCACHEENTRY pEntry,
1687 PPDMBLKCACHEWAITER pWaiter)
1688{
1689 pWaiter->pNext = NULL;
1690
1691 if (pEntry->pWaitingHead)
1692 {
1693 AssertPtr(pEntry->pWaitingTail);
1694
1695 pEntry->pWaitingTail->pNext = pWaiter;
1696 pEntry->pWaitingTail = pWaiter;
1697 }
1698 else
1699 {
1700 Assert(!pEntry->pWaitingTail);
1701
1702 pEntry->pWaitingHead = pWaiter;
1703 pEntry->pWaitingTail = pWaiter;
1704 }
1705}
1706
1707/**
1708 * Add a buffer described by the I/O memory context
1709 * to the entry waiting for completion.
1710 *
1711 * @returns VBox status code.
1712 * @param pEntry The entry to add the buffer to.
1713 * @param pTask Task associated with the buffer.
1714 * @param pIoMemCtx The memory context to use.
1715 * @param offDiff Offset from the start of the buffer
1716 * in the entry.
1717 * @param cbData Amount of data to wait for onthis entry.
1718 * @param fWrite Flag whether the task waits because it wants to write
1719 * to the cache entry.
1720 */
1721static int pdmBlkCacheEntryWaitersAdd(PPDMBLKCACHEENTRY pEntry,
1722 PPDMBLKCACHEREQ pReq,
1723 PRTSGBUF pSgBuf, uint64_t offDiff,
1724 size_t cbData, bool fWrite)
1725{
1726 PPDMBLKCACHEWAITER pWaiter = (PPDMBLKCACHEWAITER)RTMemAllocZ(sizeof(PDMBLKCACHEWAITER));
1727 if (!pWaiter)
1728 return VERR_NO_MEMORY;
1729
1730 ASMAtomicIncU32(&pReq->cXfersPending);
1731 pWaiter->pReq = pReq;
1732 pWaiter->offCacheEntry = offDiff;
1733 pWaiter->cbTransfer = cbData;
1734 pWaiter->fWrite = fWrite;
1735 RTSgBufClone(&pWaiter->SgBuf, pSgBuf);
1736 RTSgBufAdvance(pSgBuf, cbData);
1737
1738 pdmBlkCacheEntryAddWaiter(pEntry, pWaiter);
1739
1740 return VINF_SUCCESS;
1741}
1742
1743/**
1744 * Calculate aligned offset and size for a new cache entry which do not
1745 * intersect with an already existing entry and the file end.
1746 *
1747 * @returns The number of bytes the entry can hold of the requested amount
1748 * of bytes.
1749 * @param pEndpoint The endpoint.
1750 * @param pBlkCache The endpoint cache.
1751 * @param off The start offset.
1752 * @param cb The number of bytes the entry needs to hold at
1753 * least.
1754 * @param pcbEntry Where to store the number of bytes the entry can hold.
1755 * Can be less than given because of other entries.
1756 */
1757static uint32_t pdmBlkCacheEntryBoundariesCalc(PPDMBLKCACHE pBlkCache,
1758 uint64_t off, uint32_t cb,
1759 uint32_t *pcbEntry)
1760{
1761 /* Get the best fit entries around the offset */
1762 PPDMBLKCACHEENTRY pEntryAbove = NULL;
1763 pdmBlkCacheGetCacheBestFitEntryByOffset(pBlkCache, off, &pEntryAbove);
1764
1765 /* Log the info */
1766 LogFlow(("%sest fit entry above off=%llu (BestFit=%llu BestFitEnd=%llu BestFitSize=%u)\n",
1767 pEntryAbove ? "B" : "No b",
1768 off,
1769 pEntryAbove ? pEntryAbove->Core.Key : 0,
1770 pEntryAbove ? pEntryAbove->Core.KeyLast : 0,
1771 pEntryAbove ? pEntryAbove->cbData : 0));
1772
1773 uint32_t cbNext;
1774 uint32_t cbInEntry;
1775 if ( pEntryAbove
1776 && off + cb > pEntryAbove->Core.Key)
1777 {
1778 cbInEntry = (uint32_t)(pEntryAbove->Core.Key - off);
1779 cbNext = (uint32_t)(pEntryAbove->Core.Key - off);
1780 }
1781 else
1782 {
1783 cbInEntry = cb;
1784 cbNext = cb;
1785 }
1786
1787 /* A few sanity checks */
1788 AssertMsg(!pEntryAbove || off + cbNext <= pEntryAbove->Core.Key,
1789 ("Aligned size intersects with another cache entry\n"));
1790 Assert(cbInEntry <= cbNext);
1791
1792 if (pEntryAbove)
1793 pdmBlkCacheEntryRelease(pEntryAbove);
1794
1795 LogFlow(("off=%llu cbNext=%u\n", off, cbNext));
1796
1797 *pcbEntry = cbNext;
1798
1799 return cbInEntry;
1800}
1801
1802/**
1803 * Create a new cache entry evicting data from the cache if required.
1804 *
1805 * @returns Pointer to the new cache entry or NULL
1806 * if not enough bytes could be evicted from the cache.
1807 * @param pEndpoint The endpoint.
1808 * @param pBlkCache The endpoint cache.
1809 * @param off The offset.
1810 * @param cb Number of bytes the cache entry should have.
1811 * @param pcbData Where to store the number of bytes the new
1812 * entry can hold. May be lower than actually requested
1813 * due to another entry intersecting the access range.
1814 */
1815static PPDMBLKCACHEENTRY pdmBlkCacheEntryCreate(PPDMBLKCACHE pBlkCache,
1816 uint64_t off, size_t cb,
1817 size_t *pcbData)
1818{
1819 uint32_t cbEntry = 0;
1820
1821 *pcbData = pdmBlkCacheEntryBoundariesCalc(pBlkCache, off, (uint32_t)cb, &cbEntry);
1822 AssertReturn(cb <= UINT32_MAX, NULL);
1823
1824 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
1825 pdmBlkCacheLockEnter(pCache);
1826
1827 PPDMBLKCACHEENTRY pEntryNew = NULL;
1828 uint8_t *pbBuffer = NULL;
1829 bool fEnough = pdmBlkCacheReclaim(pCache, cbEntry, true, &pbBuffer);
1830 if (fEnough)
1831 {
1832 LogFlow(("Evicted enough bytes (%u requested). Creating new cache entry\n", cbEntry));
1833
1834 pEntryNew = pdmBlkCacheEntryAlloc(pBlkCache, off, cbEntry, pbBuffer);
1835 if (RT_LIKELY(pEntryNew))
1836 {
1837 pdmBlkCacheEntryAddToList(&pCache->LruRecentlyUsedIn, pEntryNew);
1838 pdmBlkCacheAdd(pCache, cbEntry);
1839 pdmBlkCacheLockLeave(pCache);
1840
1841 pdmBlkCacheInsertEntry(pBlkCache, pEntryNew);
1842
1843 AssertMsg( (off >= pEntryNew->Core.Key)
1844 && (off + *pcbData <= pEntryNew->Core.KeyLast + 1),
1845 ("Overflow in calculation off=%llu\n", off));
1846 }
1847 else
1848 pdmBlkCacheLockLeave(pCache);
1849 }
1850 else
1851 pdmBlkCacheLockLeave(pCache);
1852
1853 return pEntryNew;
1854}
1855
1856static PPDMBLKCACHEREQ pdmBlkCacheReqAlloc(void *pvUser)
1857{
1858 PPDMBLKCACHEREQ pReq = (PPDMBLKCACHEREQ)RTMemAlloc(sizeof(PDMBLKCACHEREQ));
1859
1860 if (RT_LIKELY(pReq))
1861 {
1862 pReq->pvUser = pvUser;
1863 pReq->rcReq = VINF_SUCCESS;
1864 pReq->cXfersPending = 0;
1865 }
1866
1867 return pReq;
1868}
1869
1870static void pdmBlkCacheReqComplete(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEREQ pReq)
1871{
1872 switch (pBlkCache->enmType)
1873 {
1874 case PDMBLKCACHETYPE_DEV:
1875 {
1876 pBlkCache->u.Dev.pfnXferComplete(pBlkCache->u.Dev.pDevIns,
1877 pReq->pvUser, pReq->rcReq);
1878 break;
1879 }
1880 case PDMBLKCACHETYPE_DRV:
1881 {
1882 pBlkCache->u.Drv.pfnXferComplete(pBlkCache->u.Drv.pDrvIns,
1883 pReq->pvUser, pReq->rcReq);
1884 break;
1885 }
1886 case PDMBLKCACHETYPE_USB:
1887 {
1888 pBlkCache->u.Usb.pfnXferComplete(pBlkCache->u.Usb.pUsbIns,
1889 pReq->pvUser, pReq->rcReq);
1890 break;
1891 }
1892 case PDMBLKCACHETYPE_INTERNAL:
1893 {
1894 pBlkCache->u.Int.pfnXferComplete(pBlkCache->u.Int.pvUser,
1895 pReq->pvUser, pReq->rcReq);
1896 break;
1897 }
1898 default:
1899 AssertMsgFailed(("Unknown block cache type!\n"));
1900 }
1901
1902 RTMemFree(pReq);
1903}
1904
1905static bool pdmBlkCacheReqUpdate(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEREQ pReq,
1906 int rcReq, bool fCallHandler)
1907{
1908 if (RT_FAILURE(rcReq))
1909 ASMAtomicCmpXchgS32(&pReq->rcReq, rcReq, VINF_SUCCESS);
1910
1911 AssertMsg(pReq->cXfersPending > 0, ("No transfers are pending for this request\n"));
1912 uint32_t cXfersPending = ASMAtomicDecU32(&pReq->cXfersPending);
1913
1914 if (!cXfersPending)
1915 {
1916 if (fCallHandler)
1917 pdmBlkCacheReqComplete(pBlkCache, pReq);
1918 else
1919 RTMemFree(pReq);
1920 return true;
1921 }
1922
1923 LogFlowFunc(("pReq=%#p cXfersPending=%u\n", pReq, cXfersPending));
1924 return false;
1925}
1926
1927VMMR3DECL(int) PDMR3BlkCacheRead(PPDMBLKCACHE pBlkCache, uint64_t off,
1928 PCRTSGBUF pcSgBuf, size_t cbRead, void *pvUser)
1929{
1930 int rc = VINF_SUCCESS;
1931 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
1932 PPDMBLKCACHEENTRY pEntry;
1933 PPDMBLKCACHEREQ pReq;
1934
1935 LogFlowFunc((": pBlkCache=%#p{%s} off=%llu pcSgBuf=%#p cbRead=%u pvUser=%#p\n",
1936 pBlkCache, pBlkCache->pszId, off, pcSgBuf, cbRead, pvUser));
1937
1938 AssertPtrReturn(pBlkCache, VERR_INVALID_POINTER);
1939 AssertReturn(!pBlkCache->fSuspended, VERR_INVALID_STATE);
1940
1941 RTSGBUF SgBuf;
1942 RTSgBufClone(&SgBuf, pcSgBuf);
1943
1944 /* Allocate new request structure. */
1945 pReq = pdmBlkCacheReqAlloc(pvUser);
1946 if (RT_UNLIKELY(!pReq))
1947 return VERR_NO_MEMORY;
1948
1949 /* Increment data transfer counter to keep the request valid while we access it. */
1950 ASMAtomicIncU32(&pReq->cXfersPending);
1951
1952 while (cbRead)
1953 {
1954 size_t cbToRead;
1955
1956 pEntry = pdmBlkCacheGetCacheEntryByOffset(pBlkCache, off);
1957
1958 /*
1959 * If there is no entry we try to create a new one eviciting unused pages
1960 * if the cache is full. If this is not possible we will pass the request through
1961 * and skip the caching (all entries may be still in progress so they can't
1962 * be evicted)
1963 * If we have an entry it can be in one of the LRU lists where the entry
1964 * contains data (recently used or frequently used LRU) so we can just read
1965 * the data we need and put the entry at the head of the frequently used LRU list.
1966 * In case the entry is in one of the ghost lists it doesn't contain any data.
1967 * We have to fetch it again evicting pages from either T1 or T2 to make room.
1968 */
1969 if (pEntry)
1970 {
1971 uint64_t offDiff = off - pEntry->Core.Key;
1972
1973 AssertMsg(off >= pEntry->Core.Key,
1974 ("Overflow in calculation off=%llu OffsetAligned=%llu\n",
1975 off, pEntry->Core.Key));
1976
1977 AssertPtr(pEntry->pList);
1978
1979 cbToRead = RT_MIN(pEntry->cbData - offDiff, cbRead);
1980
1981 AssertMsg(off + cbToRead <= pEntry->Core.Key + pEntry->Core.KeyLast + 1,
1982 ("Buffer of cache entry exceeded off=%llu cbToRead=%d\n",
1983 off, cbToRead));
1984
1985 cbRead -= cbToRead;
1986
1987 if (!cbRead)
1988 STAM_COUNTER_INC(&pCache->cHits);
1989 else
1990 STAM_COUNTER_INC(&pCache->cPartialHits);
1991
1992 STAM_COUNTER_ADD(&pCache->StatRead, cbToRead);
1993
1994 /* Ghost lists contain no data. */
1995 if ( (pEntry->pList == &pCache->LruRecentlyUsedIn)
1996 || (pEntry->pList == &pCache->LruFrequentlyUsed))
1997 {
1998 if (pdmBlkCacheEntryFlagIsSetClearAcquireLock(pBlkCache, pEntry,
1999 PDMBLKCACHE_ENTRY_IO_IN_PROGRESS,
2000 PDMBLKCACHE_ENTRY_IS_DIRTY))
2001 {
2002 /* Entry didn't completed yet. Append to the list */
2003 pdmBlkCacheEntryWaitersAdd(pEntry, pReq,
2004 &SgBuf, offDiff, cbToRead,
2005 false /* fWrite */);
2006 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2007 }
2008 else
2009 {
2010 /* Read as much as we can from the entry. */
2011 RTSgBufCopyFromBuf(&SgBuf, pEntry->pbData + offDiff, cbToRead);
2012 }
2013
2014 /* Move this entry to the top position */
2015 if (pEntry->pList == &pCache->LruFrequentlyUsed)
2016 {
2017 pdmBlkCacheLockEnter(pCache);
2018 pdmBlkCacheEntryAddToList(&pCache->LruFrequentlyUsed, pEntry);
2019 pdmBlkCacheLockLeave(pCache);
2020 }
2021 /* Release the entry */
2022 pdmBlkCacheEntryRelease(pEntry);
2023 }
2024 else
2025 {
2026 uint8_t *pbBuffer = NULL;
2027
2028 LogFlow(("Fetching data for ghost entry %#p from file\n", pEntry));
2029
2030 pdmBlkCacheLockEnter(pCache);
2031 pdmBlkCacheEntryRemoveFromList(pEntry); /* Remove it before we remove data, otherwise it may get freed when evicting data. */
2032 bool fEnough = pdmBlkCacheReclaim(pCache, pEntry->cbData, true, &pbBuffer);
2033
2034 /* Move the entry to Am and fetch it to the cache. */
2035 if (fEnough)
2036 {
2037 pdmBlkCacheEntryAddToList(&pCache->LruFrequentlyUsed, pEntry);
2038 pdmBlkCacheAdd(pCache, pEntry->cbData);
2039 pdmBlkCacheLockLeave(pCache);
2040
2041 if (pbBuffer)
2042 pEntry->pbData = pbBuffer;
2043 else
2044 pEntry->pbData = (uint8_t *)RTMemPageAlloc(pEntry->cbData);
2045 AssertPtr(pEntry->pbData);
2046
2047 pdmBlkCacheEntryWaitersAdd(pEntry, pReq,
2048 &SgBuf, offDiff, cbToRead,
2049 false /* fWrite */);
2050 pdmBlkCacheEntryReadFromMedium(pEntry);
2051 /* Release the entry */
2052 pdmBlkCacheEntryRelease(pEntry);
2053 }
2054 else
2055 {
2056 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2057 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
2058 RTAvlrU64Remove(pBlkCache->pTree, pEntry->Core.Key);
2059 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
2060 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2061
2062 pdmBlkCacheLockLeave(pCache);
2063
2064 RTMemFree(pEntry);
2065
2066 pdmBlkCacheRequestPassthrough(pBlkCache, pReq,
2067 &SgBuf, off, cbToRead,
2068 PDMBLKCACHEXFERDIR_READ);
2069 }
2070 }
2071 }
2072 else
2073 {
2074#ifdef VBOX_WITH_IO_READ_CACHE
2075 /* No entry found for this offset. Create a new entry and fetch the data to the cache. */
2076 PPDMBLKCACHEENTRY pEntryNew = pdmBlkCacheEntryCreate(pBlkCache,
2077 off, cbRead,
2078 &cbToRead);
2079
2080 cbRead -= cbToRead;
2081
2082 if (pEntryNew)
2083 {
2084 if (!cbRead)
2085 STAM_COUNTER_INC(&pCache->cMisses);
2086 else
2087 STAM_COUNTER_INC(&pCache->cPartialHits);
2088
2089 pdmBlkCacheEntryWaitersAdd(pEntryNew, pReq,
2090 &SgBuf,
2091 off - pEntryNew->Core.Key,
2092 cbToRead,
2093 false /* fWrite */);
2094 pdmBlkCacheEntryReadFromMedium(pEntryNew);
2095 pdmBlkCacheEntryRelease(pEntryNew); /* it is protected by the I/O in progress flag now. */
2096 }
2097 else
2098 {
2099 /*
2100 * There is not enough free space in the cache.
2101 * Pass the request directly to the I/O manager.
2102 */
2103 LogFlow(("Couldn't evict %u bytes from the cache. Remaining request will be passed through\n", cbToRead));
2104
2105 pdmBlkCacheRequestPassthrough(pBlkCache, pReq,
2106 &SgBuf, off, cbToRead,
2107 PDMBLKCACHEXFERDIR_READ);
2108 }
2109#else
2110 /* Clip read size if necessary. */
2111 PPDMBLKCACHEENTRY pEntryAbove;
2112 pdmBlkCacheGetCacheBestFitEntryByOffset(pBlkCache, off, &pEntryAbove);
2113
2114 if (pEntryAbove)
2115 {
2116 if (off + cbRead > pEntryAbove->Core.Key)
2117 cbToRead = pEntryAbove->Core.Key - off;
2118 else
2119 cbToRead = cbRead;
2120
2121 pdmBlkCacheEntryRelease(pEntryAbove);
2122 }
2123 else
2124 cbToRead = cbRead;
2125
2126 cbRead -= cbToRead;
2127 pdmBlkCacheRequestPassthrough(pBlkCache, pReq,
2128 &SgBuf, off, cbToRead,
2129 PDMBLKCACHEXFERDIR_READ);
2130#endif
2131 }
2132 off += cbToRead;
2133 }
2134
2135 if (!pdmBlkCacheReqUpdate(pBlkCache, pReq, rc, false))
2136 rc = VINF_AIO_TASK_PENDING;
2137
2138 LogFlowFunc((": Leave rc=%Rrc\n", rc));
2139
2140 return rc;
2141}
2142
2143VMMR3DECL(int) PDMR3BlkCacheWrite(PPDMBLKCACHE pBlkCache, uint64_t off,
2144 PCRTSGBUF pcSgBuf, size_t cbWrite, void *pvUser)
2145{
2146 int rc = VINF_SUCCESS;
2147 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
2148 PPDMBLKCACHEENTRY pEntry;
2149 PPDMBLKCACHEREQ pReq;
2150
2151 LogFlowFunc((": pBlkCache=%#p{%s} off=%llu pcSgBuf=%#p cbWrite=%u pvUser=%#p\n",
2152 pBlkCache, pBlkCache->pszId, off, pcSgBuf, cbWrite, pvUser));
2153
2154 AssertPtrReturn(pBlkCache, VERR_INVALID_POINTER);
2155 AssertReturn(!pBlkCache->fSuspended, VERR_INVALID_STATE);
2156
2157 RTSGBUF SgBuf;
2158 RTSgBufClone(&SgBuf, pcSgBuf);
2159
2160 /* Allocate new request structure. */
2161 pReq = pdmBlkCacheReqAlloc(pvUser);
2162 if (RT_UNLIKELY(!pReq))
2163 return VERR_NO_MEMORY;
2164
2165 /* Increment data transfer counter to keep the request valid while we access it. */
2166 ASMAtomicIncU32(&pReq->cXfersPending);
2167
2168 while (cbWrite)
2169 {
2170 size_t cbToWrite;
2171
2172 pEntry = pdmBlkCacheGetCacheEntryByOffset(pBlkCache, off);
2173 if (pEntry)
2174 {
2175 /* Write the data into the entry and mark it as dirty */
2176 AssertPtr(pEntry->pList);
2177
2178 uint64_t offDiff = off - pEntry->Core.Key;
2179
2180 AssertMsg(off >= pEntry->Core.Key,
2181 ("Overflow in calculation off=%llu OffsetAligned=%llu\n",
2182 off, pEntry->Core.Key));
2183
2184 cbToWrite = RT_MIN(pEntry->cbData - offDiff, cbWrite);
2185 cbWrite -= cbToWrite;
2186
2187 if (!cbWrite)
2188 STAM_COUNTER_INC(&pCache->cHits);
2189 else
2190 STAM_COUNTER_INC(&pCache->cPartialHits);
2191
2192 STAM_COUNTER_ADD(&pCache->StatWritten, cbToWrite);
2193
2194 /* Ghost lists contain no data. */
2195 if ( (pEntry->pList == &pCache->LruRecentlyUsedIn)
2196 || (pEntry->pList == &pCache->LruFrequentlyUsed))
2197 {
2198 /* Check if the entry is dirty. */
2199 if (pdmBlkCacheEntryFlagIsSetClearAcquireLock(pBlkCache, pEntry,
2200 PDMBLKCACHE_ENTRY_IS_DIRTY,
2201 0))
2202 {
2203 /* If it is already dirty but not in progress just update the data. */
2204 if (!(pEntry->fFlags & PDMBLKCACHE_ENTRY_IO_IN_PROGRESS))
2205 RTSgBufCopyToBuf(&SgBuf, pEntry->pbData + offDiff, cbToWrite);
2206 else
2207 {
2208 /* The data isn't written to the file yet */
2209 pdmBlkCacheEntryWaitersAdd(pEntry, pReq,
2210 &SgBuf, offDiff, cbToWrite,
2211 true /* fWrite */);
2212 STAM_COUNTER_INC(&pBlkCache->StatWriteDeferred);
2213 }
2214
2215 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2216 }
2217 else /* Dirty bit not set */
2218 {
2219 /*
2220 * Check if a read is in progress for this entry.
2221 * We have to defer processing in that case.
2222 */
2223 if (pdmBlkCacheEntryFlagIsSetClearAcquireLock(pBlkCache, pEntry,
2224 PDMBLKCACHE_ENTRY_IO_IN_PROGRESS,
2225 0))
2226 {
2227 pdmBlkCacheEntryWaitersAdd(pEntry, pReq,
2228 &SgBuf, offDiff, cbToWrite,
2229 true /* fWrite */);
2230 STAM_COUNTER_INC(&pBlkCache->StatWriteDeferred);
2231 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2232 }
2233 else /* I/O in progress flag not set */
2234 {
2235 /* Write as much as we can into the entry and update the file. */
2236 RTSgBufCopyToBuf(&SgBuf, pEntry->pbData + offDiff, cbToWrite);
2237
2238 bool fCommit = pdmBlkCacheAddDirtyEntry(pBlkCache, pEntry);
2239 if (fCommit)
2240 pdmBlkCacheCommitDirtyEntries(pCache);
2241 }
2242 } /* Dirty bit not set */
2243
2244 /* Move this entry to the top position */
2245 if (pEntry->pList == &pCache->LruFrequentlyUsed)
2246 {
2247 pdmBlkCacheLockEnter(pCache);
2248 pdmBlkCacheEntryAddToList(&pCache->LruFrequentlyUsed, pEntry);
2249 pdmBlkCacheLockLeave(pCache);
2250 }
2251
2252 pdmBlkCacheEntryRelease(pEntry);
2253 }
2254 else /* Entry is on the ghost list */
2255 {
2256 uint8_t *pbBuffer = NULL;
2257
2258 pdmBlkCacheLockEnter(pCache);
2259 pdmBlkCacheEntryRemoveFromList(pEntry); /* Remove it before we remove data, otherwise it may get freed when evicting data. */
2260 bool fEnough = pdmBlkCacheReclaim(pCache, pEntry->cbData, true, &pbBuffer);
2261
2262 if (fEnough)
2263 {
2264 /* Move the entry to Am and fetch it to the cache. */
2265 pdmBlkCacheEntryAddToList(&pCache->LruFrequentlyUsed, pEntry);
2266 pdmBlkCacheAdd(pCache, pEntry->cbData);
2267 pdmBlkCacheLockLeave(pCache);
2268
2269 if (pbBuffer)
2270 pEntry->pbData = pbBuffer;
2271 else
2272 pEntry->pbData = (uint8_t *)RTMemPageAlloc(pEntry->cbData);
2273 AssertPtr(pEntry->pbData);
2274
2275 pdmBlkCacheEntryWaitersAdd(pEntry, pReq,
2276 &SgBuf, offDiff, cbToWrite,
2277 true /* fWrite */);
2278 STAM_COUNTER_INC(&pBlkCache->StatWriteDeferred);
2279 pdmBlkCacheEntryReadFromMedium(pEntry);
2280
2281 /* Release the reference. If it is still needed the I/O in progress flag should protect it now. */
2282 pdmBlkCacheEntryRelease(pEntry);
2283 }
2284 else
2285 {
2286 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2287 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
2288 RTAvlrU64Remove(pBlkCache->pTree, pEntry->Core.Key);
2289 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
2290 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2291
2292 pdmBlkCacheLockLeave(pCache);
2293
2294 RTMemFree(pEntry);
2295 pdmBlkCacheRequestPassthrough(pBlkCache, pReq,
2296 &SgBuf, off, cbToWrite,
2297 PDMBLKCACHEXFERDIR_WRITE);
2298 }
2299 }
2300 }
2301 else /* No entry found */
2302 {
2303 /*
2304 * No entry found. Try to create a new cache entry to store the data in and if that fails
2305 * write directly to the file.
2306 */
2307 PPDMBLKCACHEENTRY pEntryNew = pdmBlkCacheEntryCreate(pBlkCache,
2308 off, cbWrite,
2309 &cbToWrite);
2310
2311 cbWrite -= cbToWrite;
2312
2313 if (pEntryNew)
2314 {
2315 uint64_t offDiff = off - pEntryNew->Core.Key;
2316
2317 STAM_COUNTER_INC(&pCache->cHits);
2318
2319 /*
2320 * Check if it is possible to just write the data without waiting
2321 * for it to get fetched first.
2322 */
2323 if (!offDiff && pEntryNew->cbData == cbToWrite)
2324 {
2325 RTSgBufCopyToBuf(&SgBuf, pEntryNew->pbData, cbToWrite);
2326
2327 bool fCommit = pdmBlkCacheAddDirtyEntry(pBlkCache, pEntryNew);
2328 if (fCommit)
2329 pdmBlkCacheCommitDirtyEntries(pCache);
2330 STAM_COUNTER_ADD(&pCache->StatWritten, cbToWrite);
2331 }
2332 else
2333 {
2334 /* Defer the write and fetch the data from the endpoint. */
2335 pdmBlkCacheEntryWaitersAdd(pEntryNew, pReq,
2336 &SgBuf, offDiff, cbToWrite,
2337 true /* fWrite */);
2338 STAM_COUNTER_INC(&pBlkCache->StatWriteDeferred);
2339 pdmBlkCacheEntryReadFromMedium(pEntryNew);
2340 }
2341
2342 pdmBlkCacheEntryRelease(pEntryNew);
2343 }
2344 else
2345 {
2346 /*
2347 * There is not enough free space in the cache.
2348 * Pass the request directly to the I/O manager.
2349 */
2350 LogFlow(("Couldn't evict %u bytes from the cache. Remaining request will be passed through\n", cbToWrite));
2351
2352 STAM_COUNTER_INC(&pCache->cMisses);
2353
2354 pdmBlkCacheRequestPassthrough(pBlkCache, pReq,
2355 &SgBuf, off, cbToWrite,
2356 PDMBLKCACHEXFERDIR_WRITE);
2357 }
2358 }
2359
2360 off += cbToWrite;
2361 }
2362
2363 if (!pdmBlkCacheReqUpdate(pBlkCache, pReq, rc, false))
2364 rc = VINF_AIO_TASK_PENDING;
2365
2366 LogFlowFunc((": Leave rc=%Rrc\n", rc));
2367
2368 return rc;
2369}
2370
2371VMMR3DECL(int) PDMR3BlkCacheFlush(PPDMBLKCACHE pBlkCache, void *pvUser)
2372{
2373 int rc = VINF_SUCCESS;
2374 PPDMBLKCACHEREQ pReq;
2375
2376 LogFlowFunc((": pBlkCache=%#p{%s}\n", pBlkCache, pBlkCache->pszId));
2377
2378 AssertPtrReturn(pBlkCache, VERR_INVALID_POINTER);
2379 AssertReturn(!pBlkCache->fSuspended, VERR_INVALID_STATE);
2380
2381 /* Commit dirty entries in the cache. */
2382 pdmBlkCacheCommit(pBlkCache);
2383
2384 /* Allocate new request structure. */
2385 pReq = pdmBlkCacheReqAlloc(pvUser);
2386 if (RT_UNLIKELY(!pReq))
2387 return VERR_NO_MEMORY;
2388
2389 rc = pdmBlkCacheRequestPassthrough(pBlkCache, pReq, NULL, 0, 0,
2390 PDMBLKCACHEXFERDIR_FLUSH);
2391 AssertRC(rc);
2392
2393 LogFlowFunc((": Leave rc=%Rrc\n", rc));
2394 return VINF_AIO_TASK_PENDING;
2395}
2396
2397VMMR3DECL(int) PDMR3BlkCacheDiscard(PPDMBLKCACHE pBlkCache, PCRTRANGE paRanges,
2398 unsigned cRanges, void *pvUser)
2399{
2400 int rc = VINF_SUCCESS;
2401 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
2402 PPDMBLKCACHEENTRY pEntry;
2403 PPDMBLKCACHEREQ pReq;
2404
2405 LogFlowFunc((": pBlkCache=%#p{%s} paRanges=%#p cRanges=%u pvUser=%#p\n",
2406 pBlkCache, pBlkCache->pszId, paRanges, cRanges, pvUser));
2407
2408 AssertPtrReturn(pBlkCache, VERR_INVALID_POINTER);
2409 AssertReturn(!pBlkCache->fSuspended, VERR_INVALID_STATE);
2410
2411 /* Allocate new request structure. */
2412 pReq = pdmBlkCacheReqAlloc(pvUser);
2413 if (RT_UNLIKELY(!pReq))
2414 return VERR_NO_MEMORY;
2415
2416 /* Increment data transfer counter to keep the request valid while we access it. */
2417 ASMAtomicIncU32(&pReq->cXfersPending);
2418
2419 for (unsigned i = 0; i < cRanges; i++)
2420 {
2421 uint64_t offCur = paRanges[i].offStart;
2422 size_t cbLeft = paRanges[i].cbRange;
2423
2424 while (cbLeft)
2425 {
2426 size_t cbThisDiscard = 0;
2427
2428 pEntry = pdmBlkCacheGetCacheEntryByOffset(pBlkCache, offCur);
2429
2430 if (pEntry)
2431 {
2432 /* Write the data into the entry and mark it as dirty */
2433 AssertPtr(pEntry->pList);
2434
2435 uint64_t offDiff = offCur - pEntry->Core.Key;
2436
2437 AssertMsg(offCur >= pEntry->Core.Key,
2438 ("Overflow in calculation offCur=%llu OffsetAligned=%llu\n",
2439 offCur, pEntry->Core.Key));
2440
2441 cbThisDiscard = RT_MIN(pEntry->cbData - offDiff, cbLeft);
2442
2443 /* Ghost lists contain no data. */
2444 if ( (pEntry->pList == &pCache->LruRecentlyUsedIn)
2445 || (pEntry->pList == &pCache->LruFrequentlyUsed))
2446 {
2447 /* Check if the entry is dirty. */
2448 if (pdmBlkCacheEntryFlagIsSetClearAcquireLock(pBlkCache, pEntry,
2449 PDMBLKCACHE_ENTRY_IS_DIRTY,
2450 0))
2451 {
2452 /* If it is dirty but not yet in progress remove it. */
2453 if (!(pEntry->fFlags & PDMBLKCACHE_ENTRY_IO_IN_PROGRESS))
2454 {
2455 pdmBlkCacheLockEnter(pCache);
2456 pdmBlkCacheEntryRemoveFromList(pEntry);
2457
2458 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
2459 RTAvlrU64Remove(pBlkCache->pTree, pEntry->Core.Key);
2460 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
2461
2462 pdmBlkCacheLockLeave(pCache);
2463
2464 RTMemFree(pEntry);
2465 }
2466 else
2467 {
2468#if 0
2469 /* The data isn't written to the file yet */
2470 pdmBlkCacheEntryWaitersAdd(pEntry, pReq,
2471 &SgBuf, offDiff, cbToWrite,
2472 true /* fWrite */);
2473 STAM_COUNTER_INC(&pBlkCache->StatWriteDeferred);
2474#endif
2475 }
2476
2477 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2478 pdmBlkCacheEntryRelease(pEntry);
2479 }
2480 else /* Dirty bit not set */
2481 {
2482 /*
2483 * Check if a read is in progress for this entry.
2484 * We have to defer processing in that case.
2485 */
2486 if(pdmBlkCacheEntryFlagIsSetClearAcquireLock(pBlkCache, pEntry,
2487 PDMBLKCACHE_ENTRY_IO_IN_PROGRESS,
2488 0))
2489 {
2490#if 0
2491 pdmBlkCacheEntryWaitersAdd(pEntry, pReq,
2492 &SgBuf, offDiff, cbToWrite,
2493 true /* fWrite */);
2494#endif
2495 STAM_COUNTER_INC(&pBlkCache->StatWriteDeferred);
2496 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2497 pdmBlkCacheEntryRelease(pEntry);
2498 }
2499 else /* I/O in progress flag not set */
2500 {
2501 pdmBlkCacheLockEnter(pCache);
2502 pdmBlkCacheEntryRemoveFromList(pEntry);
2503
2504 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2505 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
2506 RTAvlrU64Remove(pBlkCache->pTree, pEntry->Core.Key);
2507 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
2508 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2509
2510 pdmBlkCacheLockLeave(pCache);
2511
2512 RTMemFree(pEntry);
2513 }
2514 } /* Dirty bit not set */
2515 }
2516 else /* Entry is on the ghost list just remove cache entry. */
2517 {
2518 pdmBlkCacheLockEnter(pCache);
2519 pdmBlkCacheEntryRemoveFromList(pEntry);
2520
2521 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2522 STAM_PROFILE_ADV_START(&pCache->StatTreeRemove, Cache);
2523 RTAvlrU64Remove(pBlkCache->pTree, pEntry->Core.Key);
2524 STAM_PROFILE_ADV_STOP(&pCache->StatTreeRemove, Cache);
2525 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2526
2527 pdmBlkCacheLockLeave(pCache);
2528
2529 RTMemFree(pEntry);
2530 }
2531 }
2532 /* else: no entry found. */
2533
2534 offCur += cbThisDiscard;
2535 cbLeft -= cbThisDiscard;
2536 }
2537 }
2538
2539 if (!pdmBlkCacheReqUpdate(pBlkCache, pReq, rc, false))
2540 rc = VINF_AIO_TASK_PENDING;
2541
2542 LogFlowFunc((": Leave rc=%Rrc\n", rc));
2543
2544 return rc;
2545}
2546
2547/**
2548 * Completes a task segment freeing all resources and completes the task handle
2549 * if everything was transferred.
2550 *
2551 * @returns Next task segment handle.
2552 * @param pTaskSeg Task segment to complete.
2553 * @param rc Status code to set.
2554 */
2555static PPDMBLKCACHEWAITER pdmBlkCacheWaiterComplete(PPDMBLKCACHE pBlkCache,
2556 PPDMBLKCACHEWAITER pWaiter,
2557 int rc)
2558{
2559 PPDMBLKCACHEWAITER pNext = pWaiter->pNext;
2560 PPDMBLKCACHEREQ pReq = pWaiter->pReq;
2561
2562 pdmBlkCacheReqUpdate(pBlkCache, pReq, rc, true);
2563
2564 RTMemFree(pWaiter);
2565
2566 return pNext;
2567}
2568
2569static void pdmBlkCacheIoXferCompleteEntry(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEIOXFER hIoXfer, int rcIoXfer)
2570{
2571 PPDMBLKCACHEENTRY pEntry = hIoXfer->pEntry;
2572 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
2573
2574 /* Reference the entry now as we are clearing the I/O in progress flag
2575 * which protected the entry till now. */
2576 pdmBlkCacheEntryRef(pEntry);
2577
2578 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2579 pEntry->fFlags &= ~PDMBLKCACHE_ENTRY_IO_IN_PROGRESS;
2580
2581 /* Process waiting segment list. The data in entry might have changed in-between. */
2582 bool fDirty = false;
2583 PPDMBLKCACHEWAITER pComplete = pEntry->pWaitingHead;
2584 PPDMBLKCACHEWAITER pCurr = pComplete;
2585
2586 AssertMsg((pCurr && pEntry->pWaitingTail) || (!pCurr && !pEntry->pWaitingTail),
2587 ("The list tail was not updated correctly\n"));
2588 pEntry->pWaitingTail = NULL;
2589 pEntry->pWaitingHead = NULL;
2590
2591 if (hIoXfer->enmXferDir == PDMBLKCACHEXFERDIR_WRITE)
2592 {
2593 /*
2594 * An error here is difficult to handle as the original request completed already.
2595 * The error is logged for now and the VM is paused.
2596 * If the user continues the entry is written again in the hope
2597 * the user fixed the problem and the next write succeeds.
2598 */
2599 if (RT_FAILURE(rcIoXfer))
2600 {
2601 LogRel(("I/O cache: Error while writing entry at offset %llu (%u bytes) to medium \"%s\" (rc=%Rrc)\n",
2602 pEntry->Core.Key, pEntry->cbData, pBlkCache->pszId, rcIoXfer));
2603
2604 if (!ASMAtomicXchgBool(&pCache->fIoErrorVmSuspended, true))
2605 {
2606 int rc = VMSetRuntimeError(pCache->pVM, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "BLKCACHE_IOERR",
2607 N_("The I/O cache encountered an error while updating data in medium \"%s\" (rc=%Rrc). "
2608 "Make sure there is enough free space on the disk and that the disk is working properly. "
2609 "Operation can be resumed afterwards"),
2610 pBlkCache->pszId, rcIoXfer);
2611 AssertRC(rc);
2612 }
2613
2614 /* Mark the entry as dirty again to get it added to the list later on. */
2615 fDirty = true;
2616 }
2617
2618 pEntry->fFlags &= ~PDMBLKCACHE_ENTRY_IS_DIRTY;
2619
2620 while (pCurr)
2621 {
2622 AssertMsg(pCurr->fWrite, ("Completed write entries should never have read tasks attached\n"));
2623
2624 RTSgBufCopyToBuf(&pCurr->SgBuf, pEntry->pbData + pCurr->offCacheEntry, pCurr->cbTransfer);
2625 fDirty = true;
2626 pCurr = pCurr->pNext;
2627 }
2628 }
2629 else
2630 {
2631 AssertMsg(hIoXfer->enmXferDir == PDMBLKCACHEXFERDIR_READ, ("Invalid transfer type\n"));
2632 AssertMsg(!(pEntry->fFlags & PDMBLKCACHE_ENTRY_IS_DIRTY),
2633 ("Invalid flags set\n"));
2634
2635 while (pCurr)
2636 {
2637 if (pCurr->fWrite)
2638 {
2639 RTSgBufCopyToBuf(&pCurr->SgBuf, pEntry->pbData + pCurr->offCacheEntry, pCurr->cbTransfer);
2640 fDirty = true;
2641 }
2642 else
2643 RTSgBufCopyFromBuf(&pCurr->SgBuf, pEntry->pbData + pCurr->offCacheEntry, pCurr->cbTransfer);
2644
2645 pCurr = pCurr->pNext;
2646 }
2647 }
2648
2649 bool fCommit = false;
2650 if (fDirty)
2651 fCommit = pdmBlkCacheAddDirtyEntry(pBlkCache, pEntry);
2652
2653 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2654
2655 /* Dereference so that it isn't protected anymore except we issued anyother write for it. */
2656 pdmBlkCacheEntryRelease(pEntry);
2657
2658 if (fCommit)
2659 pdmBlkCacheCommitDirtyEntries(pCache);
2660
2661 /* Complete waiters now. */
2662 while (pComplete)
2663 pComplete = pdmBlkCacheWaiterComplete(pBlkCache, pComplete, rcIoXfer);
2664}
2665
2666VMMR3DECL(void) PDMR3BlkCacheIoXferComplete(PPDMBLKCACHE pBlkCache, PPDMBLKCACHEIOXFER hIoXfer, int rcIoXfer)
2667{
2668 LogFlowFunc(("pBlkCache=%#p hIoXfer=%#p rcIoXfer=%Rrc\n", pBlkCache, hIoXfer, rcIoXfer));
2669
2670 if (hIoXfer->fIoCache)
2671 pdmBlkCacheIoXferCompleteEntry(pBlkCache, hIoXfer, rcIoXfer);
2672 else
2673 pdmBlkCacheReqUpdate(pBlkCache, hIoXfer->pReq, rcIoXfer, true);
2674 RTMemFree(hIoXfer);
2675}
2676
2677/**
2678 * Callback for the AVL do with all routine. Waits for a cachen entry to finish any pending I/O.
2679 *
2680 * @returns IPRT status code.
2681 * @param pNode The node to destroy.
2682 * @param pvUser Opaque user data.
2683 */
2684static int pdmBlkCacheEntryQuiesce(PAVLRU64NODECORE pNode, void *pvUser)
2685{
2686 PPDMBLKCACHEENTRY pEntry = (PPDMBLKCACHEENTRY)pNode;
2687 PPDMBLKCACHE pBlkCache = pEntry->pBlkCache;
2688 NOREF(pvUser);
2689
2690 while (ASMAtomicReadU32(&pEntry->fFlags) & PDMBLKCACHE_ENTRY_IO_IN_PROGRESS)
2691 {
2692 /* Leave the locks to let the I/O thread make progress but reference the entry to prevent eviction. */
2693 pdmBlkCacheEntryRef(pEntry);
2694 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2695
2696 RTThreadSleep(1);
2697
2698 /* Re-enter all locks and drop the reference. */
2699 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2700 pdmBlkCacheEntryRelease(pEntry);
2701 }
2702
2703 AssertMsg(!(pEntry->fFlags & PDMBLKCACHE_ENTRY_IO_IN_PROGRESS),
2704 ("Entry is dirty and/or still in progress fFlags=%#x\n", pEntry->fFlags));
2705
2706 return VINF_SUCCESS;
2707}
2708
2709VMMR3DECL(int) PDMR3BlkCacheSuspend(PPDMBLKCACHE pBlkCache)
2710{
2711 int rc = VINF_SUCCESS;
2712 LogFlowFunc(("pBlkCache=%#p\n", pBlkCache));
2713
2714 AssertPtrReturn(pBlkCache, VERR_INVALID_POINTER);
2715
2716 if (!ASMAtomicReadBool(&pBlkCache->pCache->fIoErrorVmSuspended))
2717 pdmBlkCacheCommit(pBlkCache); /* Can issue new I/O requests. */
2718 ASMAtomicXchgBool(&pBlkCache->fSuspended, true);
2719
2720 /* Wait for all I/O to complete. */
2721 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2722 rc = RTAvlrU64DoWithAll(pBlkCache->pTree, true, pdmBlkCacheEntryQuiesce, NULL);
2723 AssertRC(rc);
2724 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2725
2726 return rc;
2727}
2728
2729VMMR3DECL(int) PDMR3BlkCacheResume(PPDMBLKCACHE pBlkCache)
2730{
2731 LogFlowFunc(("pBlkCache=%#p\n", pBlkCache));
2732
2733 AssertPtrReturn(pBlkCache, VERR_INVALID_POINTER);
2734
2735 ASMAtomicXchgBool(&pBlkCache->fSuspended, false);
2736
2737 return VINF_SUCCESS;
2738}
2739
2740VMMR3DECL(int) PDMR3BlkCacheClear(PPDMBLKCACHE pBlkCache)
2741{
2742 int rc = VINF_SUCCESS;
2743 PPDMBLKCACHEGLOBAL pCache = pBlkCache->pCache;
2744
2745 /*
2746 * Commit all dirty entries now (they are waited on for completion during the
2747 * destruction of the AVL tree below).
2748 * The exception is if the VM was paused because of an I/O error before.
2749 */
2750 if (!ASMAtomicReadBool(&pCache->fIoErrorVmSuspended))
2751 pdmBlkCacheCommit(pBlkCache);
2752
2753 /* Make sure nobody is accessing the cache while we delete the tree. */
2754 pdmBlkCacheLockEnter(pCache);
2755 RTSemRWRequestWrite(pBlkCache->SemRWEntries, RT_INDEFINITE_WAIT);
2756 RTAvlrU64Destroy(pBlkCache->pTree, pdmBlkCacheEntryDestroy, pCache);
2757 RTSemRWReleaseWrite(pBlkCache->SemRWEntries);
2758
2759 pdmBlkCacheLockLeave(pCache);
2760 return rc;
2761}
2762
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette