VirtualBox

source: vbox/trunk/src/VBox/Devices/USB/VUSBReadAhead.cpp@ 59738

Last change on this file since 59738 was 59722, checked in by vboxsync, 9 years ago

VUSB: Some structural cleanup (#5 Optimize the allocation strategy a bit which will free URBs now which were not used for some time or are too big and just waste memory)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 15.8 KB
Line 
1/* $Id: VUSBReadAhead.cpp 59722 2016-02-18 13:11:07Z vboxsync $ */
2/** @file
3 * Virtual USB - Read-ahead buffering for periodic endpoints.
4 */
5
6/*
7 * Copyright (C) 2006-2015 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
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_VUSB
23#include <VBox/vmm/pdm.h>
24#include <VBox/vmm/vmapi.h>
25#include <VBox/err.h>
26#include <VBox/log.h>
27#include <iprt/alloc.h>
28#include <iprt/time.h>
29#include <iprt/thread.h>
30#include <iprt/semaphore.h>
31#include <iprt/string.h>
32#include <iprt/assert.h>
33#include <iprt/asm.h>
34#include <iprt/critsect.h>
35#include "VUSBInternal.h"
36
37
38/*********************************************************************************************************************************
39* Structures and Typedefs *
40*********************************************************************************************************************************/
41
42/**
43 * VUSB Readahead instance data.
44 */
45typedef struct VUSBREADAHEADINT
46{
47 /** Pointer to the device which the thread is for. */
48 PVUSBDEV pDev;
49 /** Pointer to the pipe which the thread is servicing. */
50 PVUSBPIPE pPipe;
51 /** A flag indicating a high-speed (vs. low/full-speed) endpoint. */
52 bool fHighSpeed;
53 /** A flag telling the thread to terminate. */
54 volatile bool fTerminate;
55 /** Maximum number of URBs to submit. */
56 uint32_t cUrbsMax;
57 /** The periodic read-ahead buffer thread. */
58 RTTHREAD hReadAheadThread;
59 /** Pointer to the first buffered URB. */
60 PVUSBURB pBuffUrbHead;
61 /** Pointer to the last buffered URB. */
62 PVUSBURB pBuffUrbTail;
63 /** Count of URBs in read-ahead buffer. */
64 uint32_t cBuffered;
65 /** Count of URBs submitted for read-ahead but not yet reaped. */
66 uint32_t cSubmitted;
67 /** Critical section to serialize access the buffered URB list. */
68 RTCRITSECT CritSectBuffUrbList;
69} VUSBREADAHEADINT, *PVUSBREADAHEADINT;
70
71
72/*********************************************************************************************************************************
73* Implementation *
74*********************************************************************************************************************************/
75
76static PVUSBURB vusbDevNewIsocUrb(PVUSBDEV pDev, unsigned uEndPt, unsigned uInterval, unsigned uPktSize)
77{
78 PVUSBURB pUrb;
79 unsigned cPackets = 0;
80 uint32_t cbTotal = 0;
81 unsigned uNextIndex = 0;
82
83 Assert(pDev);
84 Assert(uEndPt);
85 Assert(uInterval);
86 Assert(uPktSize);
87
88 /* Calculate the amount of data needed, taking the endpoint's bInterval into account */
89 for (unsigned i = 0; i < 8; ++i)
90 {
91 if (i == uNextIndex)
92 {
93 cbTotal += uPktSize;
94 cPackets++;
95 uNextIndex += uInterval;
96 }
97 }
98 Assert(cbTotal <= 24576);
99
100 // @todo: What do we do if cPackets is 0?
101
102 /*
103 * Allocate and initialize the URB.
104 */
105 Assert(pDev->u8Address != VUSB_INVALID_ADDRESS);
106
107 PVUSBROOTHUB pRh = vusbDevGetRh(pDev);
108 if (!pRh)
109 /* can happen during disconnect */
110 return NULL;
111
112 pUrb = vusbRhNewUrb(pRh, pDev->u8Address, NULL, VUSBXFERTYPE_ISOC, VUSBDIRECTION_IN, cbTotal, 1, "prab");
113 if (!pUrb)
114 /* not much we can do here... */
115 return NULL;
116
117 pUrb->EndPt = uEndPt;
118 pUrb->fShortNotOk = false;
119 pUrb->enmStatus = VUSBSTATUS_OK;
120
121 /* Set up the individual packets, again with bInterval in mind */
122 pUrb->cIsocPkts = 8;
123 unsigned off = 0;
124 uNextIndex = 0;
125 for (unsigned i = 0; i < 8; i++)
126 {
127 pUrb->aIsocPkts[i].enmStatus = VUSBSTATUS_NOT_ACCESSED;
128 pUrb->aIsocPkts[i].off = off;
129 if (i == uNextIndex) // skip unused packets
130 {
131 pUrb->aIsocPkts[i].cb = uPktSize;
132 off += uPktSize;
133 uNextIndex += uInterval;
134 }
135 else
136 pUrb->aIsocPkts[i].cb = 0;
137 }
138 Assert(off == cbTotal);
139 return pUrb;
140}
141
142/**
143 * Thread function for performing read-ahead buffering of periodic input.
144 *
145 * This thread keeps a buffer (queue) filled with data read from a periodic
146 * input endpoint.
147 *
148 * The problem: In the EHCI emulation, there is a very short period between the
149 * time when the guest can schedule a request and the time when it expects the results.
150 * This leads to many dropped URBs because by the time we get the data from the host,
151 * the guest already gave up and moved on.
152 *
153 * The solution: For periodic transfers, we know the worst-case bandwidth. We can
154 * read ahead and buffer a few milliseconds worth of data. That way data is available
155 * by the time the guest asks for it and we can deliver it immediately.
156 *
157 * @returns success indicator.
158 * @param Thread This thread.
159 * @param pvUser Pointer to a VUSBREADAHEADARGS structure.
160 */
161static DECLCALLBACK(int) vusbDevReadAheadThread(RTTHREAD Thread, void *pvUser)
162{
163 PVUSBREADAHEADINT pThis = (PVUSBREADAHEADINT)pvUser;
164 PVUSBPIPE pPipe;
165 PCVUSBDESCENDPOINT pDesc;
166 PVUSBURB pUrb;
167 int rc = VINF_SUCCESS;
168 unsigned max_pkt_size, mult, interval;
169
170 LogFlow(("vusb: periodic read-ahead buffer thread started\n"));
171 Assert(pThis);
172 Assert(pThis->pPipe && pThis->pDev);
173
174 pPipe = pThis->pPipe;
175 pDesc = &pPipe->in->Core;
176 Assert(pDesc);
177
178 Assert(!pThis->cSubmitted && !pThis->cBuffered);
179
180 /* Figure out the maximum bandwidth we might need */
181 if (pThis->fHighSpeed)
182 {
183 /* High-speed endpoint */
184 Assert((pDesc->wMaxPacketSize & 0x1fff) == pDesc->wMaxPacketSize);
185 Assert(pDesc->bInterval <= 16);
186 interval = pDesc->bInterval ? 1 << (pDesc->bInterval - 1) : 1;
187 max_pkt_size = pDesc->wMaxPacketSize & 0x7ff;
188 mult = ((pDesc->wMaxPacketSize & 0x1800) >> 11) + 1;
189 }
190 else
191 {
192 /* Full- or low-speed endpoint */
193 Assert((pDesc->wMaxPacketSize & 0x7ff) == pDesc->wMaxPacketSize);
194 interval = pDesc->bInterval;
195 max_pkt_size = pDesc->wMaxPacketSize;
196 mult = 1;
197 }
198 Log(("vusb: interval=%u, max pkt size=%u, multiplier=%u\n", interval, max_pkt_size, mult));
199
200 /*
201 * Submit new URBs in a loop unless the buffer is too full (paused VM etc.). Note that we only
202 * queue the URBs here, they are reaped on a different thread.
203 */
204 while (!pThis->fTerminate)
205 {
206 while (pThis->cSubmitted < pThis->cUrbsMax && pThis->cBuffered < pThis->cUrbsMax)
207 {
208 pUrb = vusbDevNewIsocUrb(pThis->pDev, pDesc->bEndpointAddress & 0xF, interval, max_pkt_size * mult);
209 if (!pUrb) {
210 /* Happens if device was unplugged. */
211 Log(("vusb: read-ahead thread failed to allocate new URB; exiting\n"));
212 vusbReadAheadStop(pThis);
213 break;
214 }
215
216 Assert(pUrb->enmState == VUSBURBSTATE_ALLOCATED);
217
218 pUrb->pVUsb->pvReadAhead = pvUser;
219 pUrb->enmState = VUSBURBSTATE_IN_FLIGHT;
220 rc = vusbUrbQueueAsyncRh(pUrb);
221 if (RT_FAILURE(rc))
222 {
223 /* Happens if device was unplugged. */
224 Log(("vusb: read-ahead thread failed to queue URB with %Rrc; exiting\n", rc));
225 pThis->cUrbsMax = pThis->cSubmitted;
226 pUrb->pVUsb->pfnFree(pUrb);
227 break;
228 }
229 else
230 ASMAtomicIncU32(&pThis->cSubmitted);
231 }
232 RTThreadSleep(1);
233 }
234 LogFlow(("vusb: periodic read-ahead buffer thread exiting\n"));
235
236 /* wait until there are no more submitted packets */
237 while (pThis->cSubmitted > 0)
238 {
239 Log2(("vusbDevReadAheadThread: still %u packets submitted, waiting before terminating...\n", pThis->cSubmitted));
240 RTThreadSleep(1);
241 }
242
243 RTCritSectEnter(&pThis->CritSectBuffUrbList);
244 /*
245 * Free all still buffered URBs because another endpoint with a different packet size
246 * and complete different data formats might be served later.
247 */
248 while (pThis->pBuffUrbHead)
249 {
250 PVUSBURB pBufferedUrb = pThis->pBuffUrbHead;
251
252 pThis->pBuffUrbHead = (PVUSBURB)pBufferedUrb->pVUsb->pvReadAhead;
253 pBufferedUrb->pVUsb->pfnFree(pBufferedUrb);
254 }
255
256 RTCritSectLeave(&pThis->CritSectBuffUrbList);
257 RTCritSectDelete(&pThis->CritSectBuffUrbList);
258 RTMemTmpFree(pThis);
259
260 return rc;
261}
262
263/**
264 * Completes a read-ahead URB. This function does *not* free the URB but puts
265 * it on a queue instead. The URB is only freed when the guest asks for the data
266 * (by reading on the buffered pipe) or when the pipe/device is torn down.
267 */
268void vusbUrbCompletionReadAhead(PVUSBURB pUrb)
269{
270 Assert(pUrb);
271 Assert(pUrb->pVUsb->pvReadAhead);
272 PVUSBREADAHEADINT pThis = (PVUSBREADAHEADINT)pUrb->pVUsb->pvReadAhead;
273 PVUSBPIPE pPipe = pThis->pPipe;
274 Assert(pPipe);
275
276 RTCritSectEnter(&pThis->CritSectBuffUrbList);
277 pUrb->pVUsb->pvReadAhead = NULL;
278 if (pThis->pBuffUrbHead == NULL)
279 {
280 // The queue is empty, this is easy
281 Assert(!pThis->pBuffUrbTail);
282 pThis->pBuffUrbTail = pThis->pBuffUrbHead = pUrb;
283 }
284 else
285 {
286 // Some URBs are queued already
287 Assert(pThis->pBuffUrbTail);
288 Assert(!pThis->pBuffUrbTail->pVUsb->pvReadAhead);
289 pThis->pBuffUrbTail->pVUsb->pvReadAhead = pUrb;
290 pThis->pBuffUrbTail = pUrb;
291 }
292 ASMAtomicDecU32(&pThis->cSubmitted);
293 ++pThis->cBuffered;
294 RTCritSectLeave(&pThis->CritSectBuffUrbList);
295}
296
297/**
298 * Process a submit of an input URB on a pipe with read-ahead buffering. Instead
299 * of passing the URB to the proxy, we use previously read data stored in the
300 * read-ahead buffer, immediately complete the input URB and free the buffered URB.
301 *
302 * @param pUrb The URB submitted by HC
303 * @param hReadAhead The read-ahead buffering instance
304 *
305 * @return int Status code
306 */
307int vusbUrbSubmitBufferedRead(PVUSBURB pUrb, VUSBREADAHEAD hReadAhead)
308{
309 PVUSBREADAHEADINT pThis = hReadAhead;
310 PVUSBURB pBufferedUrb;
311 Assert(pUrb && pThis);
312
313 RTCritSectEnter(&pThis->CritSectBuffUrbList);
314 pBufferedUrb = pThis->pBuffUrbHead;
315 if (pBufferedUrb)
316 {
317 unsigned cbTotal;
318
319 // There's a URB available in the read-ahead buffer; use it
320 pThis->pBuffUrbHead = (PVUSBURB)pBufferedUrb->pVUsb->pvReadAhead;
321 if (pThis->pBuffUrbHead == NULL)
322 pThis->pBuffUrbTail = NULL;
323
324 --pThis->cBuffered;
325 RTCritSectLeave(&pThis->CritSectBuffUrbList);
326
327 // Make sure the buffered URB is what we expect
328 Assert(pUrb->enmType == pBufferedUrb->enmType);
329 Assert(pUrb->EndPt == pBufferedUrb->EndPt);
330 Assert(pUrb->enmDir == pBufferedUrb->enmDir);
331
332 pUrb->enmState = VUSBURBSTATE_REAPED;
333 pUrb->enmStatus = pBufferedUrb->enmStatus;
334 cbTotal = 0;
335 // Copy status and data received from the device
336 for (unsigned i = 0; i < pUrb->cIsocPkts; ++i)
337 {
338 unsigned off, len;
339
340 off = pBufferedUrb->aIsocPkts[i].off;
341 len = pBufferedUrb->aIsocPkts[i].cb;
342 pUrb->aIsocPkts[i].cb = len;
343 pUrb->aIsocPkts[i].off = off;
344 pUrb->aIsocPkts[i].enmStatus = pBufferedUrb->aIsocPkts[i].enmStatus;
345 cbTotal += len;
346 //Assert(pUrb->pVUsb->cbDataAllocated >= cbTotal); /* Not publicly available anymore. */
347 memcpy(&pUrb->abData[off], &pBufferedUrb->abData[off], len);
348 }
349 // Give back the data to the HC right away and then free the buffered URB
350 vusbUrbCompletionRh(pUrb);
351 // This assertion is wrong as the URB could be re-allocated in the meantime by the EMT (race)
352 // Assert(pUrb->enmState == VUSBURBSTATE_FREE);
353 Assert(pBufferedUrb->enmState == VUSBURBSTATE_REAPED);
354 LogFlow(("%s: vusbUrbSubmitBufferedRead: Freeing buffered URB\n", pBufferedUrb->pszDesc));
355 pBufferedUrb->pVUsb->pfnFree(pBufferedUrb);
356 // This assertion is wrong as the URB could be re-allocated in the meantime by the EMT (race)
357 // Assert(pBufferedUrb->enmState == VUSBURBSTATE_FREE);
358 }
359 else
360 {
361 RTCritSectLeave(&pThis->CritSectBuffUrbList);
362 // No URB on hand. Either we exhausted the buffer (shouldn't happen!) or the guest simply
363 // asked for data too soon. Pretend that the device didn't deliver any data.
364 pUrb->enmState = VUSBURBSTATE_REAPED;
365 pUrb->enmStatus = VUSBSTATUS_DATA_UNDERRUN;
366 for (unsigned i = 0; i < pUrb->cIsocPkts; ++i)
367 {
368 pUrb->aIsocPkts[i].cb = 0;
369 pUrb->aIsocPkts[i].enmStatus = VUSBSTATUS_NOT_ACCESSED;
370 }
371 vusbUrbCompletionRh(pUrb);
372 // This assertion is wrong as the URB could be re-allocated in the meantime by the EMT (race)
373 // Assert(pUrb->enmState == VUSBURBSTATE_FREE);
374 LogFlow(("vusbUrbSubmitBufferedRead: No buffered URB available!\n"));
375 }
376 return VINF_SUCCESS;
377}
378
379/* Read-ahead start/stop functions, used primarily to keep the PVUSBREADAHEADARGS struct private to this module. */
380
381VUSBREADAHEAD vusbReadAheadStart(PVUSBDEV pDev, PVUSBPIPE pPipe)
382{
383 int rc;
384 PVUSBREADAHEADINT pThis = (PVUSBREADAHEADINT)RTMemTmpAlloc(sizeof(VUSBREADAHEADINT));
385
386 if (pThis)
387 {
388 PVUSBROOTHUB pRh = vusbDevGetRh(pDev);
389 pThis->pDev = pDev;
390 pThis->pPipe = pPipe;
391 pThis->fTerminate = false;
392 pThis->fHighSpeed = pRh && ((pRh->fHcVersions & VUSB_STDVER_20) != 0);
393 pThis->cUrbsMax = 120;
394 pThis->pBuffUrbHead = NULL;
395 pThis->pBuffUrbTail = NULL;
396 pThis->cBuffered = 0;
397 pThis->cSubmitted = 0;
398 rc = RTCritSectInit(&pThis->CritSectBuffUrbList);
399 if (RT_SUCCESS(rc))
400 {
401 if (pThis->fHighSpeed)
402 rc = RTThreadCreate(&pThis->hReadAheadThread, vusbDevReadAheadThread, pThis, 0, RTTHREADTYPE_IO, 0 /* fFlags */, "USBISOC");
403 else
404 rc = VERR_VUSB_DEVICE_NOT_ATTACHED; // No buffering for low/full-speed devices at the moment, needs testing.
405 if (RT_SUCCESS(rc))
406 {
407 Log(("vusb: created isochronous read-ahead thread\n"));
408 return pThis;
409 }
410 else
411 Log(("vusb: isochronous read-ahead thread creation failed, rc=%d\n", rc));
412
413 rc = RTCritSectDelete(&pThis->CritSectBuffUrbList);
414 AssertRC(rc);
415 }
416
417 RTMemTmpFree(pThis);
418 }
419
420 /* If thread creation failed for any reason, simply fall back to standard processing. */
421 return NULL;
422}
423
424void vusbReadAheadStop(VUSBREADAHEAD hReadAhead)
425{
426 PVUSBREADAHEADINT pThis = hReadAhead;
427 Log(("vusb: terminating read-ahead thread for endpoint\n"));
428 ASMAtomicXchgBool(&pThis->fTerminate, true);
429}
430
431/*
432 * Local Variables:
433 * mode: c
434 * c-file-style: "bsd"
435 * c-basic-offset: 4
436 * tab-width: 4
437 * indent-tabs-mode: s
438 * End:
439 */
440
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