VirtualBox

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

Last change on this file since 71289 was 70779, checked in by vboxsync, 7 years ago

scm again

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