VirtualBox

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

Last change on this file since 50778 was 50453, checked in by vboxsync, 11 years ago

USB/ReadAhead: Don't keep the buffered URBs around when the buffer thread is terminated, later buffering might have a different packet size

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

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