VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/USBProxyService.cpp@ 48817

Last change on this file since 48817 was 41528, checked in by vboxsync, 13 years ago

Main/HostUSBDevice(all platforms)+USBProxyService: redo USB locking, fixes major regression, added lots of assertions to catch locking flaws early, whitespace cleanup
Main/Machine: small USB locking fix to be consistent with the remaining code
Main/Host+glue/AutoLock: replace USB list lock by host lock, small numbering cleanup
Main/Console: redo USB locking, do less in USB callbacks/EMT (addresses long standing todo items), eliminate unsafe iterator parameters

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 37.7 KB
Line 
1/* $Id: USBProxyService.cpp 41528 2012-05-31 16:48:33Z vboxsync $ */
2/** @file
3 * VirtualBox USB Proxy Service (base) class.
4 */
5
6/*
7 * Copyright (C) 2006-2012 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#include "USBProxyService.h"
19#include "HostUSBDeviceImpl.h"
20#include "HostImpl.h"
21#include "MachineImpl.h"
22#include "VirtualBoxImpl.h"
23
24#include "AutoCaller.h"
25#include "Logging.h"
26
27#include <VBox/com/array.h>
28#include <VBox/err.h>
29#include <iprt/asm.h>
30#include <iprt/semaphore.h>
31#include <iprt/thread.h>
32#include <iprt/mem.h>
33#include <iprt/string.h>
34
35
36/**
37 * Initialize data members.
38 */
39USBProxyService::USBProxyService(Host *aHost)
40 : mHost(aHost), mThread(NIL_RTTHREAD), mTerminate(false), mLastError(VINF_SUCCESS), mDevices()
41{
42 LogFlowThisFunc(("aHost=%p\n", aHost));
43}
44
45
46/**
47 * Stub needed as long as the class isn't virtual
48 */
49HRESULT USBProxyService::init(void)
50{
51 return S_OK;
52}
53
54
55/**
56 * Empty destructor.
57 */
58USBProxyService::~USBProxyService()
59{
60 LogFlowThisFunc(("\n"));
61 Assert(mThread == NIL_RTTHREAD);
62 mDevices.clear();
63 mTerminate = true;
64 mHost = NULL;
65}
66
67
68/**
69 * Query if the service is active and working.
70 *
71 * @returns true if the service is up running.
72 * @returns false if the service isn't running.
73 */
74bool USBProxyService::isActive(void)
75{
76 return mThread != NIL_RTTHREAD;
77}
78
79
80/**
81 * Get last error.
82 * Can be used to check why the proxy !isActive() upon construction.
83 *
84 * @returns VBox status code.
85 */
86int USBProxyService::getLastError(void)
87{
88 return mLastError;
89}
90
91
92/**
93 * Get last error message.
94 * Can be used to check why the proxy !isActive() upon construction as an
95 * extension to getLastError(). May return a NULL error.
96 *
97 * @param
98 * @returns VBox status code.
99 */
100HRESULT USBProxyService::getLastErrorMessage(BSTR *aError)
101{
102 AssertPtrReturn(aError, E_POINTER);
103 mLastErrorMessage.cloneTo(aError);
104 return S_OK;
105}
106
107
108/**
109 * We're using the Host object lock.
110 *
111 * This is just a temporary measure until all the USB refactoring is
112 * done, probably... For now it help avoiding deadlocks we don't have
113 * time to fix.
114 *
115 * @returns Lock handle.
116 */
117RWLockHandle *USBProxyService::lockHandle() const
118{
119 return mHost->lockHandle();
120}
121
122
123/**
124 * Gets the collection of USB devices, slave of Host::USBDevices.
125 *
126 * This is an interface for the HostImpl::USBDevices property getter.
127 *
128 *
129 * @param aUSBDevices Where to store the pointer to the collection.
130 *
131 * @returns COM status code.
132 *
133 * @remarks The caller must own the write lock of the host object.
134 */
135HRESULT USBProxyService::getDeviceCollection(ComSafeArrayOut(IHostUSBDevice *, aUSBDevices))
136{
137 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
138 CheckComArgOutSafeArrayPointerValid(aUSBDevices);
139
140 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
141
142 SafeIfaceArray<IHostUSBDevice> Collection(mDevices);
143 Collection.detachTo(ComSafeArrayOutArg(aUSBDevices));
144
145 return S_OK;
146}
147
148
149/**
150 * Request capture of a specific device.
151 *
152 * This is in an interface for SessionMachine::CaptureUSBDevice(), which is
153 * an internal worker used by Console::AttachUSBDevice() from the VM process.
154 *
155 * When the request is completed, SessionMachine::onUSBDeviceAttach() will
156 * be called for the given machine object.
157 *
158 *
159 * @param aMachine The machine to attach the device to.
160 * @param aId The UUID of the USB device to capture and attach.
161 *
162 * @returns COM status code and error info.
163 *
164 * @remarks This method may operate synchronously as well as asynchronously. In the
165 * former case it will temporarily abandon locks because of IPC.
166 */
167HRESULT USBProxyService::captureDeviceForVM(SessionMachine *aMachine, IN_GUID aId)
168{
169 ComAssertRet(aMachine, E_INVALIDARG);
170 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
171
172 /*
173 * Translate the device id into a device object.
174 */
175 ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId);
176 if (pHostDevice.isNull())
177 return setError(E_INVALIDARG,
178 tr("The USB device with UUID {%RTuuid} is not currently attached to the host"), Guid(aId).raw());
179
180 /*
181 * Try to capture the device
182 */
183 alock.release();
184 return pHostDevice->requestCaptureForVM(aMachine, true /* aSetError */);
185}
186
187
188/**
189 * Notification from VM process about USB device detaching progress.
190 *
191 * This is in an interface for SessionMachine::DetachUSBDevice(), which is
192 * an internal worker used by Console::DetachUSBDevice() from the VM process.
193 *
194 * @param aMachine The machine which is sending the notification.
195 * @param aId The UUID of the USB device is concerns.
196 * @param aDone \a false for the pre-action notification (necessary
197 * for advancing the device state to avoid confusing
198 * the guest).
199 * \a true for the post-action notification. The device
200 * will be subjected to all filters except those of
201 * of \a Machine.
202 *
203 * @returns COM status code.
204 *
205 * @remarks When \a aDone is \a true this method may end up doing IPC to other
206 * VMs when running filters. In these cases it will temporarily
207 * abandon its locks.
208 */
209HRESULT USBProxyService::detachDeviceFromVM(SessionMachine *aMachine, IN_GUID aId, bool aDone)
210{
211 LogFlowThisFunc(("aMachine=%p{%s} aId={%RTuuid} aDone=%RTbool\n",
212 aMachine,
213 aMachine->getName().c_str(),
214 Guid(aId).raw(),
215 aDone));
216
217 // get a list of all running machines while we're outside the lock
218 // (getOpenedMachines requests locks which are incompatible with the lock of the machines list)
219 SessionMachinesList llOpenedMachines;
220 mHost->parent()->getOpenedMachines(llOpenedMachines);
221
222 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
223
224 ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId);
225 ComAssertRet(!pHostDevice.isNull(), E_FAIL);
226 AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
227
228 /*
229 * Work the state machine.
230 */
231 LogFlowThisFunc(("id={%RTuuid} state=%s aDone=%RTbool name={%s}\n",
232 pHostDevice->getId().raw(), pHostDevice->getStateName(), aDone, pHostDevice->getName().c_str()));
233 bool fRunFilters = false;
234 HRESULT hrc = pHostDevice->onDetachFromVM(aMachine, aDone, &fRunFilters);
235
236 /*
237 * Run filters if necessary.
238 */
239 if ( SUCCEEDED(hrc)
240 && fRunFilters)
241 {
242 Assert(aDone && pHostDevice->getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->getMachine().isNull());
243 devLock.release();
244 alock.release();
245 HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine);
246 ComAssertComRC(hrc2);
247 }
248 return hrc;
249}
250
251
252/**
253 * Apply filters for the machine to all eligible USB devices.
254 *
255 * This is in an interface for SessionMachine::CaptureUSBDevice(), which
256 * is an internal worker used by Console::AutoCaptureUSBDevices() from the
257 * VM process at VM startup.
258 *
259 * Matching devices will be attached to the VM and may result IPC back
260 * to the VM process via SessionMachine::onUSBDeviceAttach() depending
261 * on whether the device needs to be captured or not. If capture is
262 * required, SessionMachine::onUSBDeviceAttach() will be called
263 * asynchronously by the USB proxy service thread.
264 *
265 * @param aMachine The machine to capture devices for.
266 *
267 * @returns COM status code, perhaps with error info.
268 *
269 * @remarks Temporarily locks this object, the machine object and some USB
270 * device, and the called methods will lock similar objects.
271 */
272HRESULT USBProxyService::autoCaptureDevicesForVM(SessionMachine *aMachine)
273{
274 LogFlowThisFunc(("aMachine=%p{%s}\n",
275 aMachine,
276 aMachine->getName().c_str()));
277
278 /*
279 * Make a copy of the list because we cannot hold the lock protecting it.
280 * (This will not make copies of any HostUSBDevice objects, only reference them.)
281 */
282 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
283 HostUSBDeviceList ListCopy = mDevices;
284 alock.release();
285
286 for (HostUSBDeviceList::iterator it = ListCopy.begin();
287 it != ListCopy.end();
288 ++it)
289 {
290 ComObjPtr<HostUSBDevice> device = *it;
291 AutoReadLock devLock(device COMMA_LOCKVAL_SRC_POS);
292 if ( device->getUnistate() == kHostUSBDeviceState_HeldByProxy
293 || device->getUnistate() == kHostUSBDeviceState_Unused
294 || device->getUnistate() == kHostUSBDeviceState_Capturable)
295 {
296 devLock.release();
297 runMachineFilters(aMachine, device);
298 }
299 }
300
301 return S_OK;
302}
303
304
305/**
306 * Detach all USB devices currently attached to a VM.
307 *
308 * This is in an interface for SessionMachine::DetachAllUSBDevices(), which
309 * is an internal worker used by Console::powerDown() from the VM process
310 * at VM startup, and SessionMachine::uninit() at VM abend.
311 *
312 * This is, like #detachDeviceFromVM(), normally a two stage journey
313 * where \a aDone indicates where we are. In addition we may be called
314 * to clean up VMs that have abended, in which case there will be no
315 * preparatory call. Filters will be applied to the devices in the final
316 * call with the risk that we have to do some IPC when attaching them
317 * to other VMs.
318 *
319 * @param aMachine The machine to detach devices from.
320 *
321 * @returns COM status code, perhaps with error info.
322 *
323 * @remarks Write locks the host object and may temporarily abandon
324 * its locks to perform IPC.
325 */
326HRESULT USBProxyService::detachAllDevicesFromVM(SessionMachine *aMachine, bool aDone, bool aAbnormal)
327{
328 // get a list of all running machines while we're outside the lock
329 // (getOpenedMachines requests locks which are incompatible with the host object lock)
330 SessionMachinesList llOpenedMachines;
331 mHost->parent()->getOpenedMachines(llOpenedMachines);
332
333 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
334
335 /*
336 * Make a copy of the device list (not the HostUSBDevice objects, just
337 * the list) since we may end up performing IPC and temporarily have
338 * to abandon locks when applying filters.
339 */
340 HostUSBDeviceList ListCopy = mDevices;
341
342 for (HostUSBDeviceList::iterator it = ListCopy.begin();
343 it != ListCopy.end();
344 ++it)
345 {
346 ComObjPtr<HostUSBDevice> pHostDevice = *it;
347 AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
348 if (pHostDevice->getMachine() == aMachine)
349 {
350 /*
351 * Same procedure as in detachUSBDevice().
352 */
353 bool fRunFilters = false;
354 HRESULT hrc = pHostDevice->onDetachFromVM(aMachine, aDone, &fRunFilters, aAbnormal);
355 if ( SUCCEEDED(hrc)
356 && fRunFilters)
357 {
358 Assert(aDone && pHostDevice->getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->getMachine().isNull());
359 devLock.release();
360 alock.release();
361 HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine);
362 ComAssertComRC(hrc2);
363 alock.acquire();
364 }
365 }
366 }
367
368 return S_OK;
369}
370
371
372/**
373 * Runs all the filters on the specified device.
374 *
375 * All filters mean global and active VM, with the exception of those
376 * belonging to \a aMachine. If a global ignore filter matched or if
377 * none of the filters matched, the device will be released back to
378 * the host.
379 *
380 * The device calling us here will be in the HeldByProxy, Unused, or
381 * Capturable state. The caller is aware that locks held might have
382 * to be abandond because of IPC and that the device might be in
383 * almost any state upon return.
384 *
385 *
386 * @returns COM status code (only parameter & state checks will fail).
387 * @param aDevice The USB device to apply filters to.
388 * @param aIgnoreMachine The machine to ignore filters from (we've just
389 * detached the device from this machine).
390 *
391 * @note The caller is expected to own no locks.
392 */
393HRESULT USBProxyService::runAllFiltersOnDevice(ComObjPtr<HostUSBDevice> &aDevice,
394 SessionMachinesList &llOpenedMachines,
395 SessionMachine *aIgnoreMachine)
396{
397 LogFlowThisFunc(("{%s} ignoring=%p\n", aDevice->getName().c_str(), aIgnoreMachine));
398
399 /*
400 * Verify preconditions.
401 */
402 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
403 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), E_FAIL);
404 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
405 AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
406 AssertMsgReturn(aDevice->isCapturableOrHeld(), ("{%s} %s\n", aDevice->getName().c_str(), aDevice->getStateName()), E_FAIL);
407
408 /*
409 * Get the lists we'll iterate.
410 */
411 Host::USBDeviceFilterList globalFilters;
412
413 mHost->getUSBFilters(&globalFilters);
414
415 /*
416 * Run global filters filters first.
417 */
418 bool fHoldIt = false;
419 for (Host::USBDeviceFilterList::const_iterator it = globalFilters.begin();
420 it != globalFilters.end();
421 ++it)
422 {
423 AutoWriteLock filterLock(*it COMMA_LOCKVAL_SRC_POS);
424 const HostUSBDeviceFilter::Data &data = (*it)->getData();
425 if (aDevice->isMatch(data))
426 {
427 USBDeviceFilterAction_T action = USBDeviceFilterAction_Null;
428 (*it)->COMGETTER(Action)(&action);
429 if (action == USBDeviceFilterAction_Ignore)
430 {
431 /*
432 * Release the device to the host and we're done.
433 */
434 filterLock.release();
435 devLock.release();
436 alock.release();
437 aDevice->requestReleaseToHost();
438 return S_OK;
439 }
440 if (action == USBDeviceFilterAction_Hold)
441 {
442 /*
443 * A device held by the proxy needs to be subjected
444 * to the machine filters.
445 */
446 fHoldIt = true;
447 break;
448 }
449 AssertMsgFailed(("action=%d\n", action));
450 }
451 }
452 globalFilters.clear();
453
454 /*
455 * Run the per-machine filters.
456 */
457 for (SessionMachinesList::const_iterator it = llOpenedMachines.begin();
458 it != llOpenedMachines.end();
459 ++it)
460 {
461 ComObjPtr<SessionMachine> pMachine = *it;
462
463 /* Skip the machine the device was just detached from. */
464 if ( aIgnoreMachine
465 && pMachine == aIgnoreMachine)
466 continue;
467
468 /* runMachineFilters takes care of checking the machine state. */
469 devLock.release();
470 alock.release();
471 if (runMachineFilters(pMachine, aDevice))
472 {
473 LogFlowThisFunc(("{%s} attached to %p\n", aDevice->getName().c_str(), (void *)pMachine));
474 return S_OK;
475 }
476 alock.acquire();
477 devLock.acquire();
478 }
479
480 /*
481 * No matching machine, so request hold or release depending
482 * on global filter match.
483 */
484 devLock.release();
485 alock.release();
486 if (fHoldIt)
487 aDevice->requestHold();
488 else
489 aDevice->requestReleaseToHost();
490 return S_OK;
491}
492
493
494/**
495 * Runs the USB filters of the machine on the device.
496 *
497 * If a match is found we will request capture for VM. This may cause
498 * us to temporary abandon locks while doing IPC.
499 *
500 * @param aMachine Machine whose filters are to be run.
501 * @param aDevice The USB device in question.
502 * @returns @c true if the device has been or is being attached to the VM, @c false otherwise.
503 *
504 * @note Locks several objects temporarily for reading or writing.
505 */
506bool USBProxyService::runMachineFilters(SessionMachine *aMachine, ComObjPtr<HostUSBDevice> &aDevice)
507{
508 LogFlowThisFunc(("{%s} aMachine=%p \n", aDevice->getName().c_str(), aMachine));
509
510 /*
511 * Validate preconditions.
512 */
513 AssertReturn(aMachine, false);
514 AssertReturn(!isWriteLockOnCurrentThread(), false);
515 AssertReturn(!aMachine->isWriteLockOnCurrentThread(), false);
516 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
517 /* Let HostUSBDevice::requestCaptureToVM() validate the state. */
518
519 /*
520 * Do the job.
521 */
522 ULONG ulMaskedIfs;
523 if (aMachine->hasMatchingUSBFilter(aDevice, &ulMaskedIfs))
524 {
525 /* try to capture the device */
526 HRESULT hrc = aDevice->requestCaptureForVM(aMachine, false /* aSetError */, ulMaskedIfs);
527 return SUCCEEDED(hrc)
528 || hrc == E_UNEXPECTED /* bad device state, give up */;
529 }
530
531 return false;
532}
533
534
535/**
536 * A filter was inserted / loaded.
537 *
538 * @param aFilter Pointer to the inserted filter.
539 * @return ID of the inserted filter
540 */
541void *USBProxyService::insertFilter(PCUSBFILTER aFilter)
542{
543 // return non-NULL to fake success.
544 NOREF(aFilter);
545 return (void *)1;
546}
547
548
549/**
550 * A filter was removed.
551 *
552 * @param aId ID of the filter to remove
553 */
554void USBProxyService::removeFilter(void *aId)
555{
556 NOREF(aId);
557}
558
559
560/**
561 * A VM is trying to capture a device, do necessary preparations.
562 *
563 * @returns VBox status code.
564 * @param aDevice The device in question.
565 */
566int USBProxyService::captureDevice(HostUSBDevice *aDevice)
567{
568 NOREF(aDevice);
569 return VERR_NOT_IMPLEMENTED;
570}
571
572
573/**
574 * Notification that an async captureDevice() operation completed.
575 *
576 * This is used by the proxy to release temporary filters.
577 *
578 * @returns VBox status code.
579 * @param aDevice The device in question.
580 * @param aSuccess Whether it succeeded or failed.
581 */
582void USBProxyService::captureDeviceCompleted(HostUSBDevice *aDevice, bool aSuccess)
583{
584 NOREF(aDevice);
585 NOREF(aSuccess);
586}
587
588
589/**
590 * The device is going to be detached from a VM.
591 *
592 * @param aDevice The device in question.
593 *
594 * @todo unused
595 */
596void USBProxyService::detachingDevice(HostUSBDevice *aDevice)
597{
598 NOREF(aDevice);
599}
600
601
602/**
603 * A VM is releasing a device back to the host.
604 *
605 * @returns VBox status code.
606 * @param aDevice The device in question.
607 */
608int USBProxyService::releaseDevice(HostUSBDevice *aDevice)
609{
610 NOREF(aDevice);
611 return VERR_NOT_IMPLEMENTED;
612}
613
614
615/**
616 * Notification that an async releaseDevice() operation completed.
617 *
618 * This is used by the proxy to release temporary filters.
619 *
620 * @returns VBox status code.
621 * @param aDevice The device in question.
622 * @param aSuccess Whether it succeeded or failed.
623 */
624void USBProxyService::releaseDeviceCompleted(HostUSBDevice *aDevice, bool aSuccess)
625{
626 NOREF(aDevice);
627 NOREF(aSuccess);
628}
629
630
631// Internals
632/////////////////////////////////////////////////////////////////////////////
633
634
635/**
636 * Starts the service.
637 *
638 * @returns VBox status.
639 */
640int USBProxyService::start(void)
641{
642 int rc = VINF_SUCCESS;
643 if (mThread == NIL_RTTHREAD)
644 {
645 /*
646 * Force update before starting the poller thread.
647 */
648 rc = wait(0);
649 if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED || RT_SUCCESS(rc))
650 {
651 processChanges();
652
653 /*
654 * Create the poller thread which will look for changes.
655 */
656 mTerminate = false;
657 rc = RTThreadCreate(&mThread, USBProxyService::serviceThread, this,
658 0, RTTHREADTYPE_INFREQUENT_POLLER, RTTHREADFLAGS_WAITABLE, "USBPROXY");
659 AssertRC(rc);
660 if (RT_SUCCESS(rc))
661 LogFlowThisFunc(("started mThread=%RTthrd\n", mThread));
662 else
663 mThread = NIL_RTTHREAD;
664 }
665 mLastError = rc;
666 }
667 else
668 LogFlowThisFunc(("already running, mThread=%RTthrd\n", mThread));
669 return rc;
670}
671
672
673/**
674 * Stops the service.
675 *
676 * @returns VBox status.
677 */
678int USBProxyService::stop(void)
679{
680 int rc = VINF_SUCCESS;
681 if (mThread != NIL_RTTHREAD)
682 {
683 /*
684 * Mark the thread for termination and kick it.
685 */
686 ASMAtomicXchgSize(&mTerminate, true);
687 rc = interruptWait();
688 AssertRC(rc);
689
690 /*
691 * Wait for the thread to finish and then update the state.
692 */
693 rc = RTThreadWait(mThread, 60000, NULL);
694 if (rc == VERR_INVALID_HANDLE)
695 rc = VINF_SUCCESS;
696 if (RT_SUCCESS(rc))
697 {
698 LogFlowThisFunc(("stopped mThread=%RTthrd\n", mThread));
699 mThread = NIL_RTTHREAD;
700 mTerminate = false;
701 }
702 else
703 {
704 AssertRC(rc);
705 mLastError = rc;
706 }
707 }
708 else
709 LogFlowThisFunc(("not active\n"));
710
711 return rc;
712}
713
714
715/**
716 * The service thread created by start().
717 *
718 * @param Thread The thread handle.
719 * @param pvUser Pointer to the USBProxyService instance.
720 */
721/*static*/ DECLCALLBACK(int) USBProxyService::serviceThread(RTTHREAD /* Thread */, void *pvUser)
722{
723 USBProxyService *pThis = (USBProxyService *)pvUser;
724 LogFlowFunc(("pThis=%p\n", pThis));
725 pThis->serviceThreadInit();
726 int rc = VINF_SUCCESS;
727
728 /*
729 * Processing loop.
730 */
731 for (;;)
732 {
733 rc = pThis->wait(RT_INDEFINITE_WAIT);
734 if (RT_FAILURE(rc) && rc != VERR_INTERRUPTED && rc != VERR_TIMEOUT)
735 break;
736 if (pThis->mTerminate)
737 break;
738 pThis->processChanges();
739 }
740
741 pThis->serviceThreadTerm();
742 LogFlowFunc(("returns %Rrc\n", rc));
743 return rc;
744}
745
746
747/**
748 * First call made on the service thread, use it to do
749 * thread initialization.
750 *
751 * The default implementation in USBProxyService just a dummy stub.
752 */
753void USBProxyService::serviceThreadInit(void)
754{
755}
756
757
758/**
759 * Last call made on the service thread, use it to do
760 * thread termination.
761 */
762void USBProxyService::serviceThreadTerm(void)
763{
764}
765
766
767/**
768 * Wait for a change in the USB devices attached to the host.
769 *
770 * The default implementation in USBProxyService just a dummy stub.
771 *
772 * @returns VBox status code. VERR_INTERRUPTED and VERR_TIMEOUT are considered
773 * harmless, while all other error status are fatal.
774 * @param aMillies Number of milliseconds to wait.
775 */
776int USBProxyService::wait(RTMSINTERVAL aMillies)
777{
778 return RTThreadSleep(RT_MIN(aMillies, 250));
779}
780
781
782/**
783 * Interrupt any wait() call in progress.
784 *
785 * The default implementation in USBProxyService just a dummy stub.
786 *
787 * @returns VBox status.
788 */
789int USBProxyService::interruptWait(void)
790{
791 return VERR_NOT_IMPLEMENTED;
792}
793
794
795/**
796 * Sort a list of USB devices.
797 *
798 * @returns Pointer to the head of the sorted doubly linked list.
799 * @param aDevices Head pointer (can be both singly and doubly linked list).
800 */
801static PUSBDEVICE sortDevices(PUSBDEVICE pDevices)
802{
803 PUSBDEVICE pHead = NULL;
804 PUSBDEVICE pTail = NULL;
805 while (pDevices)
806 {
807 /* unlink head */
808 PUSBDEVICE pDev = pDevices;
809 pDevices = pDev->pNext;
810 if (pDevices)
811 pDevices->pPrev = NULL;
812
813 /* find location. */
814 PUSBDEVICE pCur = pTail;
815 while ( pCur
816 && HostUSBDevice::compare(pCur, pDev) > 0)
817 pCur = pCur->pPrev;
818
819 /* insert (after pCur) */
820 pDev->pPrev = pCur;
821 if (pCur)
822 {
823 pDev->pNext = pCur->pNext;
824 pCur->pNext = pDev;
825 if (pDev->pNext)
826 pDev->pNext->pPrev = pDev;
827 else
828 pTail = pDev;
829 }
830 else
831 {
832 pDev->pNext = pHead;
833 if (pHead)
834 pHead->pPrev = pDev;
835 else
836 pTail = pDev;
837 pHead = pDev;
838 }
839 }
840
841 LogFlowFuncLeave();
842 return pHead;
843}
844
845
846/**
847 * Process any relevant changes in the attached USB devices.
848 *
849 * Except for the first call, this is always running on the service thread.
850 */
851void USBProxyService::processChanges(void)
852{
853 LogFlowThisFunc(("\n"));
854
855 /*
856 * Get the sorted list of USB devices.
857 */
858 PUSBDEVICE pDevices = getDevices();
859 pDevices = sortDevices(pDevices);
860
861 // get a list of all running machines while we're outside the lock
862 // (getOpenedMachines requests higher priority locks)
863 SessionMachinesList llOpenedMachines;
864 mHost->parent()->getOpenedMachines(llOpenedMachines);
865
866 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
867
868 /*
869 * Compare previous list with the new list of devices
870 * and merge in any changes while notifying Host.
871 */
872 HostUSBDeviceList::iterator it = this->mDevices.begin();
873 while ( it != mDevices.end()
874 || pDevices)
875 {
876 ComObjPtr<HostUSBDevice> pHostDevice;
877
878 if (it != mDevices.end())
879 pHostDevice = *it;
880
881 /*
882 * Assert that the object is still alive (we still reference it in
883 * the collection and we're the only one who calls uninit() on it.
884 */
885 AutoCaller devCaller(pHostDevice.isNull() ? NULL : pHostDevice);
886 AssertComRC(devCaller.rc());
887
888 /*
889 * Lock the device object since we will read/write its
890 * properties. All Host callbacks also imply the object is locked.
891 */
892 AutoWriteLock devLock(pHostDevice.isNull() ? NULL : pHostDevice
893 COMMA_LOCKVAL_SRC_POS);
894
895 /*
896 * Compare.
897 */
898 int iDiff;
899 if (pHostDevice.isNull())
900 iDiff = 1;
901 else
902 {
903 if (!pDevices)
904 iDiff = -1;
905 else
906 iDiff = pHostDevice->compare(pDevices);
907 }
908 if (!iDiff)
909 {
910 /*
911 * The device still there, update the state and move on. The PUSBDEVICE
912 * structure is eaten by updateDeviceState / HostUSBDevice::updateState().
913 */
914 PUSBDEVICE pCur = pDevices;
915 pDevices = pDevices->pNext;
916 pCur->pPrev = pCur->pNext = NULL;
917
918 bool fRunFilters = false;
919 SessionMachine *pIgnoreMachine = NULL;
920 devLock.release();
921 alock.release();
922 if (updateDeviceState(pHostDevice, pCur, &fRunFilters, &pIgnoreMachine))
923 deviceChanged(pHostDevice,
924 (fRunFilters ? &llOpenedMachines : NULL),
925 pIgnoreMachine);
926 alock.acquire();
927 it++;
928 }
929 else
930 {
931 if (iDiff > 0)
932 {
933 /*
934 * Head of pDevices was attached.
935 */
936 PUSBDEVICE pNew = pDevices;
937 pDevices = pDevices->pNext;
938 pNew->pPrev = pNew->pNext = NULL;
939
940 ComObjPtr<HostUSBDevice> NewObj;
941 NewObj.createObject();
942 NewObj->init(pNew, this);
943 Log(("USBProxyService::processChanges: attached %p {%s} %s / %p:{.idVendor=%#06x, .idProduct=%#06x, .pszProduct=\"%s\", .pszManufacturer=\"%s\"}\n",
944 (HostUSBDevice *)NewObj,
945 NewObj->getName().c_str(),
946 NewObj->getStateName(),
947 pNew,
948 pNew->idVendor,
949 pNew->idProduct,
950 pNew->pszProduct,
951 pNew->pszManufacturer));
952
953 mDevices.insert(it, NewObj);
954
955 devLock.release();
956 alock.release();
957 deviceAdded(NewObj, llOpenedMachines, pNew);
958 alock.acquire();
959 }
960 else
961 {
962 /*
963 * Check if the device was actually detached or logically detached
964 * as the result of a re-enumeration.
965 */
966 if (!pHostDevice->wasActuallyDetached())
967 it++;
968 else
969 {
970 it = mDevices.erase(it);
971 devLock.release();
972 alock.release();
973 deviceRemoved(pHostDevice);
974 Log(("USBProxyService::processChanges: detached %p {%s}\n",
975 (HostUSBDevice *)pHostDevice,
976 pHostDevice->getName().c_str()));
977
978 /* from now on, the object is no more valid,
979 * uninitialize to avoid abuse */
980 devCaller.release();
981 pHostDevice->uninit();
982 alock.acquire();
983 }
984 }
985 }
986 } /* while */
987
988 LogFlowThisFunc(("returns void\n"));
989}
990
991
992/**
993 * Get a list of USB device currently attached to the host.
994 *
995 * The default implementation in USBProxyService just a dummy stub.
996 *
997 * @returns Pointer to a list of USB devices.
998 * The list nodes are freed individually by calling freeDevice().
999 */
1000PUSBDEVICE USBProxyService::getDevices(void)
1001{
1002 return NULL;
1003}
1004
1005
1006/**
1007 * Performs the required actions when a device has been added.
1008 *
1009 * This means things like running filters and subsequent capturing and
1010 * VM attaching. This may result in IPC and temporary lock abandonment.
1011 *
1012 * @param aDevice The device in question.
1013 * @param aUSBDevice The USB device structure.
1014 */
1015void USBProxyService::deviceAdded(ComObjPtr<HostUSBDevice> &aDevice,
1016 SessionMachinesList &llOpenedMachines,
1017 PUSBDEVICE aUSBDevice)
1018{
1019 /*
1020 * Validate preconditions.
1021 */
1022 AssertReturnVoid(!isWriteLockOnCurrentThread());
1023 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
1024 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
1025 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
1026 (HostUSBDevice *)aDevice,
1027 aDevice->getName().c_str(),
1028 aDevice->getStateName(),
1029 aDevice->getId().raw()));
1030
1031 /*
1032 * Run filters on the device.
1033 */
1034 if (aDevice->isCapturableOrHeld())
1035 {
1036 devLock.release();
1037 HRESULT rc = runAllFiltersOnDevice(aDevice, llOpenedMachines, NULL /* aIgnoreMachine */);
1038 AssertComRC(rc);
1039 }
1040
1041 NOREF(aUSBDevice);
1042}
1043
1044
1045/**
1046 * Remove device notification hook for the OS specific code.
1047 *
1048 * This is means things like
1049 *
1050 * @param aDevice The device in question.
1051 */
1052void USBProxyService::deviceRemoved(ComObjPtr<HostUSBDevice> &aDevice)
1053{
1054 /*
1055 * Validate preconditions.
1056 */
1057 AssertReturnVoid(!isWriteLockOnCurrentThread());
1058 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
1059 AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
1060 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
1061 (HostUSBDevice *)aDevice,
1062 aDevice->getName().c_str(),
1063 aDevice->getStateName(),
1064 aDevice->getId().raw()));
1065
1066 /*
1067 * Detach the device from any machine currently using it,
1068 * reset all data and uninitialize the device object.
1069 */
1070 devLock.release();
1071 aDevice->onPhysicalDetached();
1072}
1073
1074
1075/**
1076 * Implement fake capture, ++.
1077 *
1078 * @returns true if there is a state change.
1079 * @param pDevice The device in question.
1080 * @param pUSBDevice The USB device structure for the last enumeration.
1081 * @param aRunFilters Whether or not to run filters.
1082 */
1083bool USBProxyService::updateDeviceStateFake(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters, SessionMachine **aIgnoreMachine)
1084{
1085 *aRunFilters = false;
1086 *aIgnoreMachine = NULL;
1087 AssertReturn(aDevice, false);
1088 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
1089
1090 /*
1091 * Just hand it to the device, it knows best what needs to be done.
1092 */
1093 return aDevice->updateStateFake(aUSBDevice, aRunFilters, aIgnoreMachine);
1094}
1095
1096
1097/**
1098 * Updates the device state.
1099 *
1100 * This is responsible for calling HostUSBDevice::updateState().
1101 *
1102 * @returns true if there is a state change.
1103 * @param aDevice The device in question.
1104 * @param aUSBDevice The USB device structure for the last enumeration.
1105 * @param aRunFilters Whether or not to run filters.
1106 * @param aIgnoreMachine Machine to ignore when running filters.
1107 */
1108bool USBProxyService::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters, SessionMachine **aIgnoreMachine)
1109{
1110 AssertReturn(aDevice, false);
1111 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
1112
1113 return aDevice->updateState(aUSBDevice, aRunFilters, aIgnoreMachine);
1114}
1115
1116
1117/**
1118 * Handle a device which state changed in some significant way.
1119 *
1120 * This means things like running filters and subsequent capturing and
1121 * VM attaching. This may result in IPC and temporary lock abandonment.
1122 *
1123 * @param aDevice The device.
1124 * @param pllOpenedMachines list of running session machines (VirtualBox::getOpenedMachines()); if NULL, we don't run filters
1125 * @param aIgnoreMachine Machine to ignore when running filters.
1126 */
1127void USBProxyService::deviceChanged(ComObjPtr<HostUSBDevice> &aDevice, SessionMachinesList *pllOpenedMachines, SessionMachine *aIgnoreMachine)
1128{
1129 /*
1130 * Validate preconditions.
1131 */
1132 AssertReturnVoid(!isWriteLockOnCurrentThread());
1133 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
1134 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
1135 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid} aRunFilters=%RTbool aIgnoreMachine=%p\n",
1136 (HostUSBDevice *)aDevice,
1137 aDevice->getName().c_str(),
1138 aDevice->getStateName(),
1139 aDevice->getId().raw(),
1140 (pllOpenedMachines != NULL), // used to be "bool aRunFilters"
1141 aIgnoreMachine));
1142 devLock.release();
1143
1144 /*
1145 * Run filters if requested to do so.
1146 */
1147 if (pllOpenedMachines)
1148 {
1149 HRESULT rc = runAllFiltersOnDevice(aDevice, *pllOpenedMachines, aIgnoreMachine);
1150 AssertComRC(rc);
1151 }
1152}
1153
1154
1155
1156/**
1157 * Free all the members of a USB device returned by getDevice().
1158 *
1159 * @param pDevice Pointer to the device.
1160 */
1161/*static*/ void
1162USBProxyService::freeDeviceMembers(PUSBDEVICE pDevice)
1163{
1164 RTStrFree((char *)pDevice->pszManufacturer);
1165 pDevice->pszManufacturer = NULL;
1166 RTStrFree((char *)pDevice->pszProduct);
1167 pDevice->pszProduct = NULL;
1168 RTStrFree((char *)pDevice->pszSerialNumber);
1169 pDevice->pszSerialNumber = NULL;
1170
1171 RTStrFree((char *)pDevice->pszAddress);
1172 pDevice->pszAddress = NULL;
1173#ifdef RT_OS_WINDOWS
1174 RTStrFree(pDevice->pszAltAddress);
1175 pDevice->pszAltAddress = NULL;
1176 RTStrFree(pDevice->pszHubName);
1177 pDevice->pszHubName = NULL;
1178#elif defined(RT_OS_SOLARIS)
1179 RTStrFree(pDevice->pszDevicePath);
1180 pDevice->pszDevicePath = NULL;
1181#endif
1182}
1183
1184
1185/**
1186 * Free one USB device returned by getDevice().
1187 *
1188 * @param pDevice Pointer to the device.
1189 */
1190/*static*/ void
1191USBProxyService::freeDevice(PUSBDEVICE pDevice)
1192{
1193 freeDeviceMembers(pDevice);
1194 RTMemFree(pDevice);
1195}
1196
1197
1198/**
1199 * Initializes a filter with the data from the specified device.
1200 *
1201 * @param aFilter The filter to fill.
1202 * @param aDevice The device to fill it with.
1203 */
1204/*static*/ void
1205USBProxyService::initFilterFromDevice(PUSBFILTER aFilter, HostUSBDevice *aDevice)
1206{
1207 PCUSBDEVICE pDev = aDevice->mUsb;
1208 int vrc;
1209
1210 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_VENDOR_ID, pDev->idVendor, true); AssertRC(vrc);
1211 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_PRODUCT_ID, pDev->idProduct, true); AssertRC(vrc);
1212 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_REV, pDev->bcdDevice, true); AssertRC(vrc);
1213 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_CLASS, pDev->bDeviceClass, true); AssertRC(vrc);
1214 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_SUB_CLASS, pDev->bDeviceSubClass, true); AssertRC(vrc);
1215 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_PROTOCOL, pDev->bDeviceProtocol, true); AssertRC(vrc);
1216 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_PORT, pDev->bPort, true); AssertRC(vrc);
1217 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_BUS, pDev->bBus, true); AssertRC(vrc);
1218 if (pDev->pszSerialNumber)
1219 {
1220 vrc = USBFilterSetStringExact(aFilter, USBFILTERIDX_SERIAL_NUMBER_STR, pDev->pszSerialNumber, true);
1221 AssertRC(vrc);
1222 }
1223 if (pDev->pszProduct)
1224 {
1225 vrc = USBFilterSetStringExact(aFilter, USBFILTERIDX_PRODUCT_STR, pDev->pszProduct, true);
1226 AssertRC(vrc);
1227 }
1228 if (pDev->pszManufacturer)
1229 {
1230 vrc = USBFilterSetStringExact(aFilter, USBFILTERIDX_MANUFACTURER_STR, pDev->pszManufacturer, true);
1231 AssertRC(vrc);
1232 }
1233}
1234
1235
1236/**
1237 * Searches the list of devices (mDevices) for the given device.
1238 *
1239 *
1240 * @returns Smart pointer to the device on success, NULL otherwise.
1241 * @param aId The UUID of the device we're looking for.
1242 */
1243ComObjPtr<HostUSBDevice> USBProxyService::findDeviceById(IN_GUID aId)
1244{
1245 Guid Id(aId);
1246 ComObjPtr<HostUSBDevice> Dev;
1247 for (HostUSBDeviceList::iterator it = mDevices.begin();
1248 it != mDevices.end();
1249 ++it)
1250 if ((*it)->getId() == Id)
1251 {
1252 Dev = (*it);
1253 break;
1254 }
1255
1256 return Dev;
1257}
1258
1259/*static*/
1260HRESULT USBProxyService::setError(HRESULT aResultCode, const char *aText, ...)
1261{
1262 va_list va;
1263 va_start(va, aText);
1264 HRESULT rc = VirtualBoxBase::setErrorInternal(aResultCode,
1265 COM_IIDOF(IHost),
1266 "USBProxyService",
1267 Utf8StrFmt(aText, va),
1268 false /* aWarning*/,
1269 true /* aLogIt*/);
1270 va_end(va);
1271 return rc;
1272}
1273
1274/* vi: set tabstop=4 shiftwidth=4 expandtab: */
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