summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/OVR_DeviceImpl.cpp
blob: 80dc7d29c4d644dae9fea580e467ea0b8391df9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/************************************************************************************

Filename    :   OVR_DeviceImpl.h
Content     :   Partial back-end independent implementation of Device interfaces
Created     :   October 10, 2012
Authors     :   Michael Antonov

Copyright   :   Copyright 2012 Oculus VR, Inc. All Rights reserved.

Use of this software is subject to the terms of the Oculus license
agreement provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.

*************************************************************************************/

#include "OVR_DeviceImpl.h"
#include "Kernel/OVR_Atomic.h"
#include "Kernel/OVR_Log.h"
#include "Kernel/OVR_System.h"

#include "OVR_DeviceImpl.h"
#include "OVR_SensorImpl.h"
#include "OVR_Profile.h"

namespace OVR {


//-------------------------------------------------------------------------------------
// ***** SharedLock

// This is a general purpose globally shared Lock implementation that should probably be
// moved to Kernel.
// May in theory busy spin-wait if we hit contention on first lock creation,
// but this shouldn't matter in practice since Lock* should be cached.


enum { LockInitMarker = 0xFFFFFFFF };

Lock* SharedLock::GetLockAddRef()
{
    int oldUseCount;

    do {
        oldUseCount = UseCount;
        if (oldUseCount == LockInitMarker)
            continue;

        if (oldUseCount == 0)
        {
            // Initialize marker
            if (AtomicOps<int>::CompareAndSet_Sync(&UseCount, 0, LockInitMarker))
            {
                Construct<Lock>(Buffer);
                do { }
                while (!AtomicOps<int>::CompareAndSet_Sync(&UseCount, LockInitMarker, 1));
                return toLock();
            }
            continue;
        }

    } while (!AtomicOps<int>::CompareAndSet_NoSync(&UseCount, oldUseCount, oldUseCount + 1));

    return toLock();
}

void SharedLock::ReleaseLock(Lock* plock)
{
    OVR_UNUSED(plock);
    OVR_ASSERT(plock == toLock());

    int oldUseCount;

    do {
        oldUseCount = UseCount;
        OVR_ASSERT(oldUseCount != LockInitMarker);

        if (oldUseCount == 1)
        {
            // Initialize marker
            if (AtomicOps<int>::CompareAndSet_Sync(&UseCount, 1, LockInitMarker))
            {
                Destruct<Lock>(toLock());

                do { }
                while (!AtomicOps<int>::CompareAndSet_Sync(&UseCount, LockInitMarker, 0));

                return;
            }
            continue;
        }

    } while (!AtomicOps<int>::CompareAndSet_NoSync(&UseCount, oldUseCount, oldUseCount - 1));
}



//-------------------------------------------------------------------------------------
// ***** MessageHandler

// Threading notes:
// The OnMessage() handler and SetMessageHandler are currently synchronized
// through a separately stored shared Lock object to avoid calling the handler 
// from background thread while it's being removed.

static SharedLock MessageHandlerSharedLock;


class MessageHandlerImpl
{
public:
    MessageHandlerImpl()
        : pLock(MessageHandlerSharedLock.GetLockAddRef())
    {
    }
    ~MessageHandlerImpl()
    {
        MessageHandlerSharedLock.ReleaseLock(pLock);
        pLock = 0;
    }

    static MessageHandlerImpl* FromHandler(MessageHandler* handler)
    { return (MessageHandlerImpl*)&handler->Internal; }
    static const MessageHandlerImpl* FromHandler(const MessageHandler* handler)
    { return (const MessageHandlerImpl*)&handler->Internal; }

    // This lock is held while calling a handler and when we are applied/
    // removed from a device.
    Lock*                     pLock;
    // List of device we are applied to.
    List<MessageHandlerRef>   UseList;
};


MessageHandlerRef::MessageHandlerRef(DeviceBase* device)
    : pLock(MessageHandlerSharedLock.GetLockAddRef()), pDevice(device), pHandler(0)
{
}

MessageHandlerRef::~MessageHandlerRef()
{
    {
        Lock::Locker lockScope(pLock);
        if (pHandler)
        {
            pHandler = 0;
            RemoveNode();
        }
    }
    MessageHandlerSharedLock.ReleaseLock(pLock);
    pLock = 0;
}

void MessageHandlerRef::SetHandler(MessageHandler* handler)
{    
    OVR_ASSERT(!handler ||
               MessageHandlerImpl::FromHandler(handler)->pLock == pLock);    
    Lock::Locker lockScope(pLock);
    SetHandler_NTS(handler);
}

void MessageHandlerRef::SetHandler_NTS(MessageHandler* handler)
{   
    if (pHandler != handler)
    {
        if (pHandler)
            RemoveNode();
        pHandler = handler;

        if (handler)
        {
            MessageHandlerImpl* handlerImpl = MessageHandlerImpl::FromHandler(handler);
            handlerImpl->UseList.PushBack(this);
        }
        // TBD: Call notifier on device?
    }
}


MessageHandler::MessageHandler()
{    
    OVR_COMPILER_ASSERT(sizeof(Internal) > sizeof(MessageHandlerImpl));
    Construct<MessageHandlerImpl>(Internal);
}

MessageHandler::~MessageHandler()
{
    MessageHandlerImpl* handlerImpl = MessageHandlerImpl::FromHandler(this);
    {
        Lock::Locker lockedScope(handlerImpl->pLock);
        OVR_ASSERT_LOG(handlerImpl->UseList.IsEmpty(),
            ("~MessageHandler %p - Handler still active; call RemoveHandlerFromDevices", this));
    }

    Destruct<MessageHandlerImpl>(handlerImpl);    
}

bool MessageHandler::IsHandlerInstalled() const
{
    const MessageHandlerImpl* handlerImpl = MessageHandlerImpl::FromHandler(this);    
    Lock::Locker lockedScope(handlerImpl->pLock);
    return handlerImpl->UseList.IsEmpty() != true;
}


void MessageHandler::RemoveHandlerFromDevices()
{
    MessageHandlerImpl* handlerImpl = MessageHandlerImpl::FromHandler(this);
    Lock::Locker lockedScope(handlerImpl->pLock);

    while(!handlerImpl->UseList.IsEmpty())
    {
        MessageHandlerRef* use = handlerImpl->UseList.GetFirst();
        use->SetHandler_NTS(0);
    }
}

Lock* MessageHandler::GetHandlerLock() const
{
    const MessageHandlerImpl* handlerImpl = MessageHandlerImpl::FromHandler(this);
    return handlerImpl->pLock;
}


//-------------------------------------------------------------------------------------
// ***** DeviceBase
   

// Delegate relevant implementation to DeviceRectord to avoid re-implementation in
// every derived Device.
void DeviceBase::AddRef()
{
    getDeviceCommon()->DeviceAddRef();
}
void DeviceBase::Release()
{
    getDeviceCommon()->DeviceRelease();
}
DeviceBase* DeviceBase::GetParent() const
{
    return getDeviceCommon()->pParent.GetPtr();
}
DeviceManager* DeviceBase::GetManager() const
{
    return getDeviceCommon()->pCreateDesc->GetManagerImpl();
}

void DeviceBase::SetMessageHandler(MessageHandler* handler)
{
    getDeviceCommon()->HandlerRef.SetHandler(handler);
}
MessageHandler* DeviceBase::GetMessageHandler() const
{
    return getDeviceCommon()->HandlerRef.GetHandler();
}

DeviceType DeviceBase::GetType() const
{
    return getDeviceCommon()->pCreateDesc->Type;
}

bool DeviceBase::GetDeviceInfo(DeviceInfo* info) const
{
    return getDeviceCommon()->pCreateDesc->GetDeviceInfo(info);
    //info->Name[0] = 0;
    //return false;
}

// returns the MessageHandler's lock
Lock* DeviceBase::GetHandlerLock() const
{
    return getDeviceCommon()->HandlerRef.GetLock();
}

// Derive DeviceManagerCreateDesc to provide abstract function implementation.
class DeviceManagerCreateDesc : public DeviceCreateDesc
{
public:
    DeviceManagerCreateDesc(DeviceFactory* factory)
        : DeviceCreateDesc(factory, Device_Manager) { }

    // We don't need there on Manager since it isn't assigned to DeviceHandle.
    virtual DeviceCreateDesc* Clone() const                        { return 0; }
    virtual MatchResult MatchDevice(const DeviceCreateDesc&,
                                    DeviceCreateDesc**) const      { return Match_None; }
    virtual DeviceBase* NewDeviceInstance()                        { return 0; }
    virtual bool        GetDeviceInfo(DeviceInfo*) const           { return false; }
};

//-------------------------------------------------------------------------------------
// ***** DeviceManagerImpl

DeviceManagerImpl::DeviceManagerImpl()
    : DeviceImpl<OVR::DeviceManager>(CreateManagerDesc(), 0)
      //,DeviceCreateDescList(pCreateDesc ? pCreateDesc->pLock : 0)
{
    if (pCreateDesc)
    {
        pCreateDesc->pLock->pManager = this;
    }
}

DeviceManagerImpl::~DeviceManagerImpl()
{
    // Shutdown must've been called.
    OVR_ASSERT(!pCreateDesc->pDevice);

    // Remove all factories
    while(!Factories.IsEmpty())
    {
        DeviceFactory* factory = Factories.GetFirst();
        factory->RemovedFromManager();
        factory->RemoveNode();
    }
}

DeviceCreateDesc* DeviceManagerImpl::CreateManagerDesc()
{
    DeviceCreateDesc* managerDesc = new DeviceManagerCreateDesc(0);
    if (managerDesc)
    {
        managerDesc->pLock = *new DeviceManagerLock;
    }
    return managerDesc;
}

bool DeviceManagerImpl::Initialize(DeviceBase* parent)
{
    OVR_UNUSED(parent);
    if (!pCreateDesc || !pCreateDesc->pLock)
		return false;

    pProfileManager = *ProfileManager::Create();

    return true;
}

void DeviceManagerImpl::Shutdown()
{
    // Remove all device descriptors from list while the lock is held.
    // Some descriptors may survive longer due to handles.    
    while(!Devices.IsEmpty())
    {     
        DeviceCreateDesc* devDesc = Devices.GetFirst();
        OVR_ASSERT(!devDesc->pDevice); // Manager shouldn't be dying while Device exists.
        devDesc->Enumerated = false;
        devDesc->RemoveNode();
        devDesc->pNext = devDesc->pPrev = 0;

        if (devDesc->HandleCount == 0)
        {
            delete devDesc;
        }
    }
    Devices.Clear();

    // These must've been cleared by caller.
    OVR_ASSERT(pCreateDesc->pDevice == 0);
    OVR_ASSERT(pCreateDesc->pLock->pManager == 0);

    pProfileManager.Clear();
}


// Callbacks for DeviceCreation/Release    
DeviceBase* DeviceManagerImpl::CreateDevice_MgrThread(DeviceCreateDesc* createDesc, DeviceBase* parent)
{
    // Calls to DeviceManagerImpl::CreateDevice are enqueued with wait while holding pManager,
    // so 'this' must remain valid.
    OVR_ASSERT(createDesc->pLock->pManager);    

    Lock::Locker devicesLock(GetLock());

    // If device already exists, just AddRef to it.
    if (createDesc->pDevice)
    {
        createDesc->pDevice->AddRef();
        return createDesc->pDevice;
    }

    if (!parent)
        parent = this;

    DeviceBase* device = createDesc->NewDeviceInstance();
    
    if (device)
    {
        if (device->getDeviceCommon()->Initialize(parent))
        {
           createDesc->pDevice = device;
        }
        else
        {
            // Don't go through Release() to avoid PushCall behaviour,
            // as it is not needed here.
            delete device;
            device = 0;
        }
    }
     
    return device;
}

Void DeviceManagerImpl::ReleaseDevice_MgrThread(DeviceBase* device)
{
    // descKeepAlive will keep ManagerLock object alive as well,
    // allowing us to exit gracefully.    
    Ptr<DeviceCreateDesc>  descKeepAlive;
    Lock::Locker           devicesLock(GetLock());
    DeviceCommon*          devCommon = device->getDeviceCommon();

    while(1)
    {
        UInt32 refCount = devCommon->RefCount;

        if (refCount > 1)
        {
            if (devCommon->RefCount.CompareAndSet_NoSync(refCount, refCount-1))
            {
                // We decreented from initial count higher then 1;
                // nothing else to do.
                return 0;
            }        
        }
        else if (devCommon->RefCount.CompareAndSet_NoSync(1, 0))
        {
            // { 1 -> 0 } decrement succeded. Destroy this device.
            break;
        }
    }

    // At this point, may be releasing the device manager itself.
    // This does not matter, however, since shutdown logic is the same
    // in both cases. DeviceManager::Shutdown with begin shutdown process for
    // the internal manager thread, which will eventually destroy itself.
    // TBD: Clean thread shutdown.
    descKeepAlive = devCommon->pCreateDesc;
    descKeepAlive->pDevice = 0;
    devCommon->Shutdown();
    delete device;
    return 0;
}



Void DeviceManagerImpl::EnumerateAllFactoryDevices()
{
    // 1. Mark matching devices as NOT enumerated.
    // 2. Call factory to enumerate all HW devices, adding any device that 
    //    was not matched.
    // 3. Remove non-matching devices.

    Lock::Locker deviceLock(GetLock());

    DeviceCreateDesc* devDesc, *nextdevDesc;

    // 1.
    for(devDesc = Devices.GetFirst();
        !Devices.IsNull(devDesc);  devDesc = devDesc->pNext)
    {
        //if (devDesc->pFactory == factory)
            devDesc->Enumerated = false;
    }
    
    // 2.
    DeviceFactory* factory = Factories.GetFirst();
    while(!Factories.IsNull(factory))
    {
        EnumerateFactoryDevices(factory);
        factory = factory->pNext;
    }

    
    // 3.
    for(devDesc = Devices.GetFirst();
        !Devices.IsNull(devDesc);  devDesc = nextdevDesc)
    {
        // In case 'devDesc' gets removed.
        nextdevDesc = devDesc->pNext; 

        // Note, device might be not enumerated since it is opened and
        // in use! Do NOT notify 'device removed' in this case (!AB)
        if (!devDesc->Enumerated)
        {
            // This deletes the devDesc for HandleCount == 0 due to Release in DeviceHandle.
            CallOnDeviceRemoved(devDesc);

            /*
            if (devDesc->HandleCount == 0)
            {                
                // Device must be dead if it ever existed, since it AddRefs to us.
                // ~DeviceCreateDesc removes its node from list.
                OVR_ASSERT(!devDesc->pDevice);
                delete devDesc;
            }
            */
        }
    }

    return 0;
}

Ptr<DeviceCreateDesc> DeviceManagerImpl::AddDevice_NeedsLock(
    const DeviceCreateDesc& createDesc)
{
    // If found, mark as enumerated and we are done.
    DeviceCreateDesc* descCandidate = 0;

    for(DeviceCreateDesc* devDesc = Devices.GetFirst();
        !Devices.IsNull(devDesc);  devDesc = devDesc->pNext)
    {
        DeviceCreateDesc::MatchResult mr = devDesc->MatchDevice(createDesc, &descCandidate);
        if (mr == DeviceCreateDesc::Match_Found)
        {
            devDesc->Enumerated = true;
            if (!devDesc->pDevice)
                CallOnDeviceAdded(devDesc);
            return devDesc;
        }
    }

    // Update candidate (this may involve writing fields to HMDDevice createDesc).
    if (descCandidate)
    {
        bool newDevice = false;
        if (descCandidate->UpdateMatchedCandidate(createDesc, &newDevice))
        {
            descCandidate->Enumerated = true;
            if (!descCandidate->pDevice || newDevice)
                CallOnDeviceAdded(descCandidate);
            return descCandidate;
        }
    }

    // If not found, add new device.
    //  - This stores a new descriptor with
    //    {pDevice = 0, HandleCount = 1, Enumerated = true}
    DeviceCreateDesc* desc = createDesc.Clone();
    desc->pLock = pCreateDesc->pLock;
    Devices.PushBack(desc);
    desc->Enumerated = true;

    CallOnDeviceAdded(desc);

    return desc;
}

Ptr<DeviceCreateDesc> DeviceManagerImpl::FindDevice(
    const String& path, 
    DeviceType deviceType)
{
    Lock::Locker deviceLock(GetLock());
    DeviceCreateDesc* devDesc;

    for (devDesc = Devices.GetFirst();
        !Devices.IsNull(devDesc);  devDesc = devDesc->pNext)
    {
        if ((deviceType == Device_None || deviceType == devDesc->Type) &&
            devDesc->MatchDevice(path))
            return devDesc;
    }
    return NULL;
}

Ptr<DeviceCreateDesc> DeviceManagerImpl::FindHIDDevice(const HIDDeviceDesc& hidDevDesc)
{
    Lock::Locker deviceLock(GetLock());
    DeviceCreateDesc* devDesc;
    
    for (devDesc = Devices.GetFirst();
        !Devices.IsNull(devDesc);  devDesc = devDesc->pNext)
    {
        if (devDesc->MatchHIDDevice(hidDevDesc))
            return devDesc;
    }
    return NULL;
}
  
void DeviceManagerImpl::DetectHIDDevice(const HIDDeviceDesc& hidDevDesc)
{
    Lock::Locker deviceLock(GetLock());
    DeviceFactory* factory = Factories.GetFirst();
    while(!Factories.IsNull(factory))
    {
        if (factory->DetectHIDDevice(this, hidDevDesc))
            break;
        factory = factory->pNext;
    }
    
}
    
// Enumerates devices for a particular factory.
Void DeviceManagerImpl::EnumerateFactoryDevices(DeviceFactory* factory)
{
       
    class FactoryEnumerateVisitor : public DeviceFactory::EnumerateVisitor
    {        
        DeviceManagerImpl* pManager;
        DeviceFactory*     pFactory;
    public:
        FactoryEnumerateVisitor(DeviceManagerImpl* manager, DeviceFactory* factory)
            : pManager(manager), pFactory(factory) { }

        virtual void Visit(const DeviceCreateDesc& createDesc)
        {
            pManager->AddDevice_NeedsLock(createDesc);
        }
    };

    FactoryEnumerateVisitor newDeviceVisitor(this, factory);
    factory->EnumerateDevices(newDeviceVisitor);


    return 0;
}


DeviceEnumerator<> DeviceManagerImpl::EnumerateDevicesEx(const DeviceEnumerationArgs& args)
{
    Lock::Locker deviceLock(GetLock());
    
    if (Devices.IsEmpty())
        return DeviceEnumerator<>();

    DeviceCreateDesc*  firstDeviceDesc = Devices.GetFirst();
    DeviceEnumerator<> e = enumeratorFromHandle(DeviceHandle(firstDeviceDesc), args);

    if (!args.MatchRule(firstDeviceDesc->Type, firstDeviceDesc->Enumerated))
    {
        e.Next();
    }
    
    return e;
}

//-------------------------------------------------------------------------------------
// ***** DeviceCommon

void DeviceCommon::DeviceAddRef()
{
    RefCount++;
}

void DeviceCommon::DeviceRelease()
{
    while(1)
    {
        UInt32 refCount = RefCount;
        OVR_ASSERT(refCount > 0);
        
        if (refCount == 1)
        {
            DeviceManagerImpl*  manager = pCreateDesc->GetManagerImpl();
            ThreadCommandQueue* queue   = manager->GetThreadQueue();

            // Enqueue ReleaseDevice for {1 -> 0} transition with no wait.
            // We pass our reference ownership into the queue to destroy.
            // It's in theory possible for another thread to re-steal our device reference,
            // but that is checked for atomically in DeviceManagerImpl::ReleaseDevice.
            if (!queue->PushCall(manager, &DeviceManagerImpl::ReleaseDevice_MgrThread,
                                          pCreateDesc->pDevice))
            {
                // PushCall shouldn't fail because background thread runs while manager is
                // alive and we are holding Manager alive through pParent chain.
                OVR_ASSERT(false);
            }

            // Warning! At his point everything, including manager, may be dead.
            break;
        }
        else if (RefCount.CompareAndSet_NoSync(refCount, refCount-1))
        {
            break;
        }
    }
}



//-------------------------------------------------------------------------------------
// ***** DeviceCreateDesc


void DeviceCreateDesc::AddRef()
{
    // Technically, HandleCount { 0 -> 1 } transition can only happen during Lock,
    // but we leave this to caller to worry about (happens during enumeration).
    HandleCount++;
}

void DeviceCreateDesc::Release()
{
    while(1)
    {
        UInt32 handleCount = HandleCount;
        // HandleCount must obviously be >= 1, since we are releasing it.
        OVR_ASSERT(handleCount > 0);

        // {1 -> 0} transition may cause us to be destroyed, so require a lock.
        if (handleCount == 1)
        {       
            Ptr<DeviceManagerLock>  lockKeepAlive;
            Lock::Locker            deviceLockScope(GetLock());

            if (!HandleCount.CompareAndSet_NoSync(handleCount, 0))
                continue;
            
            OVR_ASSERT(pDevice == 0);

            // Destroy *this if the manager was destroyed already, or Enumerated
            // is false (device no longer available).           
            if (!GetManagerImpl() || !Enumerated)
            {
                lockKeepAlive = pLock;

                // Remove from manager list (only matters for !Enumerated).
                if (pNext)
                {
                    RemoveNode();
                    pNext = pPrev = 0;
                }

                delete this;
            }

            // Available DeviceCreateDesc may survive with { HandleCount == 0 },
            // in case it might be enumerated again later.
            break;
        }
        else if (HandleCount.CompareAndSet_NoSync(handleCount, handleCount-1))
        {
            break;
        }
    }
}

HMDDevice* HMDDevice::Disconnect(SensorDevice* psensor)
{
    if (!psensor)
        return NULL;

    OVR::DeviceManager* manager = GetManager();
    if (manager)
    {
        //DeviceManagerImpl* mgrImpl = static_cast<DeviceManagerImpl*>(manager);
        Ptr<DeviceCreateDesc> desc = getDeviceCommon()->pCreateDesc;
        if (desc)
        {
            class Visitor : public DeviceFactory::EnumerateVisitor
            {
                Ptr<DeviceCreateDesc> Desc;
            public:
                Visitor(DeviceCreateDesc* desc) : Desc(desc) {}
                virtual void Visit(const DeviceCreateDesc& createDesc) 
                {
                    Lock::Locker lock(Desc->GetLock());
                    Desc->UpdateMatchedCandidate(createDesc);
                }
            } visitor(desc);
            //SensorDeviceImpl* sImpl = static_cast<SensorDeviceImpl*>(psensor);

            SensorDisplayInfoImpl displayInfo;

            if (psensor->GetFeatureReport(displayInfo.Buffer, SensorDisplayInfoImpl::PacketSize))
            {
                displayInfo.Unpack();

                // If we got display info, try to match / create HMDDevice as well
                // so that sensor settings give preference.
                if (displayInfo.DistortionType & SensorDisplayInfoImpl::Mask_BaseFmt)
                {
                    SensorDeviceImpl::EnumerateHMDFromSensorDisplayInfo(displayInfo, visitor);
                }
            }
        }
    }
    return this;
}

bool  HMDDevice::IsDisconnected() const
{
    OVR::HMDInfo info;
    GetDeviceInfo(&info);
    // if strlen(info.DisplayDeviceName) == 0 then
    // this HMD is 'fake' (created using sensor).
    return (strlen(info.DisplayDeviceName) == 0);
}


} // namespace OVR