summaryrefslogtreecommitdiff
path: root/mobicore/MobiCoreDriverLib/Daemon/Device/MobiCoreDevice.cpp
blob: 3e86dcbcd51cf5e12580fbde3d377855cefc9c10 (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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
/*
 * Copyright (c) 2013-2014 TRUSTONIC LIMITED
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the TRUSTONIC LIMITED nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include <cstdlib>
#include <pthread.h>
#include <assert.h>
#include "McTypes.h"

#include "DeviceScheduler.h"
#include "DeviceIrqHandler.h"
#include "Connection.h"
#include "TrustletSession.h"

#include "MobiCoreDevice.h"
#include "Mci/mci.h"
#include "mcLoadFormat.h"


#include "log.h"
#include "public/MobiCoreDevice.h"



//------------------------------------------------------------------------------
MobiCoreDevice::MobiCoreDevice()
{
    nq = NULL;
    mcFlags = NULL;
    mcVersionInfo = NULL;
    mcFault = false;
    mciReused = false;
    mcpMessage = NULL;
}

//------------------------------------------------------------------------------
MobiCoreDevice::~MobiCoreDevice()
{
    mciReused = false;
    mcFault = false;
    delete mcVersionInfo;
    mcVersionInfo = NULL;
    mcFlags = NULL;
    nq = NULL;
}

//------------------------------------------------------------------------------
TrustletSession *MobiCoreDevice::getTrustletSession(
    uint32_t sessionId
) {
    for (trustletSessionIterator_t iterator = trustletSessions.begin();
         iterator != trustletSessions.end();
         ++iterator)
    {
        TrustletSession *session = *iterator;
        if (session->sessionId == sessionId) {
            return session;
        }
    }
    return NULL;
}


//------------------------------------------------------------------------------
//Connection *MobiCoreDevice::getSessionConnection(
//    uint32_t sessionId,
//    notification_t *notification
//) {
//    Connection *con = NULL;
//
//    mutex_tslist.lock();
//    TrustletSession *session = getTrustletSession(sessionId);
//    if (session != NULL)
//    {
//        con = session->notificationConnection;
//        if (con == NULL)
//        {
//            session->queueNotification(notification);
//        }
//    }
//    mutex_tslist.unlock();
//
//    return con;
//}


//------------------------------------------------------------------------------
TrustletSession* MobiCoreDevice::findSession(
    Connection *deviceConnection,
    uint32_t sessionId
) {
    mutex_tslist.lock();
    TrustletSession *session = getTrustletSession(sessionId);
    if (session == NULL)
    {
        LOG_E("no session found with id %03x", sessionId);
    }
    else
    {
        // check is connection own this session
        if (session->deviceConnection != deviceConnection)
        {
            LOG_E("connection does not own session id %03x", sessionId);
            session = NULL;
        }
    }
    mutex_tslist.unlock();
    return session;
}


//------------------------------------------------------------------------------
bool MobiCoreDevice::open(
    Connection *connection
) {
    // Link this device to the connection
    connection->connectionData = this;
    return true;
}

//------------------------------------------------------------------------------
// send a close session message. Used in three cases:
// 1) during init to tell SWd to invalidate this session, if it is still open
//    from a prev Daemon instance
// 2) normal session close
// 3) close all session when Daemon terminates
mcResult_t MobiCoreDevice::sendSessionCloseCmd(
    uint32_t sessionId
) {
    // Write MCP close message to buffer
    mcpMessage->cmdClose.cmdHeader.cmdId = MC_MCP_CMD_CLOSE_SESSION;
    mcpMessage->cmdClose.sessionId = sessionId;

    mcResult_t mcRet = mshNotifyAndWait();
    if (mcRet != MC_MCP_RET_OK)
    {
        LOG_E("mshNotifyAndWait failed for CLOSE_SESSION, code %d.", mcRet);
        return mcRet;
    }

    // Check if the command response ID is correct
    if ((MC_MCP_CMD_CLOSE_SESSION | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) {
        LOG_E("invalid MCP response for CLOSE_SESSION");
        return MC_DRV_ERR_DAEMON_MCI_ERROR;
    }

    // Read MC answer from MCP buffer
    mcRet = mcpMessage->rspOpen.rspHeader.result;

    return mcRet;
}

//------------------------------------------------------------------------------
// internal API to close a session
mcResult_t MobiCoreDevice::closeSessionInternal(
    TrustletSession *session
) {
    LOG_I("closing session %03x", session->sessionId);

    mcResult_t mcRet = sendSessionCloseCmd(session->sessionId);
    switch(mcRet){
        case MC_MCP_RET_OK:
            return mcRet;
        case MC_MCP_RET_ERR_CLOSE_TASK_FAILED:
            LOG_I("sendSessionCloseCmd failed");
        break;
        default:
            LOG_E("sendSessionCloseCmd error %d", mcRet);
        break;
    }
//    // clean session WSM
//    LOG_I("unlocking session buffers!");
//    CWsm_ptr pWsm = session->popBulkBuff();
//    while (pWsm)
//    {
//        unlockWsmL2(pWsm->handle);
//        delete pWsm;
//        pWsm = session->popBulkBuff();
//    }

    return MAKE_MC_DRV_MCP_ERROR(mcRet);
}

//------------------------------------------------------------------------------
/**
 * Close device.
 *
 * Removes all sessions to a connection. Though, clientLib rejects the closeDevice()
 * command if still sessions connected to the device, this is needed to clean up all
 * sessions if client dies.
 */
void MobiCoreDevice::close(
    Connection *connection
) {
    // static mutex is the the same for each thread. So this serializes
    // multiple connections failing at the same time.
    static CMutex mutex;
    // Enter critical section
    mutex.lock();

    // 1. Iterate through device session to find connection
    // 2. Decide what to do with open Trustlet sessions
    // 3. Remove & delete deviceSession from vector

    // iterating over the list in reverse order, as the LIFO approach may
    // avoid some quirks. The assumption is that a driver is opened before a
    // TA, so we want to terminate the TA first and then the driver. This may
    // make this a bit easier for everbody.

    // Cannot lock list as we need to receive notifications, but it may change, so search under lock
    trustletSessionList_t sessions_list;
    mutex_tslist.lock();
    for (trustletSessionList_t::reverse_iterator revIt = trustletSessions.rbegin(); revIt != trustletSessions.rend(); revIt++)
    {
        if ((*revIt)->deviceConnection == connection) {
            LOG_I("MobiCoreDevice::close found a session %p", *revIt);

            sessions_list.push_back(*revIt);
            break;
        }
    }
    mutex_tslist.unlock();

    for (trustletSessionList_t::iterator it = sessions_list.begin(); it != sessions_list.end(); it++) {
        mcResult_t mcRet = closeSession(connection, (*it)->sessionId);
        if (mcRet != MC_MCP_RET_OK) {
            LOG_I("device closeSession failed for %p with %d", *it, mcRet);
        }
    }

    connection->connectionData = NULL;

    // Leave critical section
    mutex.unlock();
}


//------------------------------------------------------------------------------
void MobiCoreDevice::start(void)
{
    LOG_I("Starting DeviceIrqHandler...");
    // Start the irq handling thread
    DeviceIrqHandler::start("DevIrqHandler");

    if (schedulerAvailable())
    {
        LOG_I("Starting DeviceScheduler...");
        // Start the scheduling handling thread
        DeviceScheduler::start();
    }
    else
    {
        LOG_I("No DeviceScheduler available.");
    }

    LOG_I("Starting TAExitHandler...");
    TAExitHandler::start("TAExitHandler");

    if (mciReused)
    {
        // Remove all pending sessions. In <t-base-301, there is a maximum of 32 sessions.
        // Few sessions in the start are reserved by the system.
#define LOG_SOURCE_TASK_SHIFT      8
        for (int sessionNumber = 3; sessionNumber<32; sessionNumber++) {
            int sessionId = ((sessionNumber<<LOG_SOURCE_TASK_SHIFT)+1);
            LOG_I("invalidating session %03x", sessionId);
            mcResult_t mcRet = sendSessionCloseCmd(sessionId);
            if (mcRet != MC_MCP_RET_OK) {
                LOG_I("sendSessionCloseCmd error %d", mcRet);
            }
        }
    }

    return;
}


//------------------------------------------------------------------------------
void MobiCoreDevice::signalMcpNotification(void)
{
    mcpSessionNotification.signal();
}


//------------------------------------------------------------------------------
bool MobiCoreDevice::waitMcpNotification(void)
{
    int counter = 5; // retry 5 times
    while (1)
	{
        // In case of fault just return, nothing to do here
        if (mcFault)
		{
            return false;
        }
        // Wait 10 seconds for notification
        if ( mcpSessionNotification.wait(10) )
		{
			break; // seem we got one.
        }
        // No MCP answer received and mobicore halted, dump mobicore status
        // then throw exception
        LOG_I("No MCP answer received in 2 seconds.");
        if (getMobicoreStatus() == MC_STATUS_HALT)
		{
            dumpMobicoreStatus();
            mcFault = true;
            return false;
        }

        counter--;
        if (counter < 1)
		{
            mcFault = true;
            return false;
        }
    } // while(1)

    // Check healthiness state of the device
	if (DeviceIrqHandler::isExiting() || 
		DeviceScheduler::isExiting() ||
		TAExitHandler::isExiting())
	{
        LOG_I("waitMcpNotification(): Threads state:");
        LOG_I("Irq handler : %s", (DeviceIrqHandler::isExiting()==true)?"running":"exit");
        LOG_I("Scheduler   : %s", (DeviceScheduler::isExiting()==true)?"running":"exit");
        LOG_I("Exit handler: %s", (TAExitHandler::isExiting()==true)?"running":"exit");
        
        //There is no CThread::wait() so no need to wake up
        LOG_I("waitMcpNotification(): IrqHandler thread should exit automatically");
        
        DeviceScheduler::terminate();
        //Cancel waiting just in case.
        DeviceScheduler::wakeup();
        LOG_I("waitMcpNotification(): terminate Scheduler  thread");
    
        TAExitHandler::terminate();
        //Cancel waiting just in case.
        TAExitHandler::wakeup();
        LOG_I("waitMcpNotification(): terminate Exit handler thread");

        DeviceIrqHandler::join();
        LOG_I("waitMcpNotification(): IrqHandler joined");
        LOG_E("IrqHandler thread died!");

        DeviceScheduler::join();
        LOG_I("waitMcpNotification(): Scheduler Joined");
        LOG_E("Scheduler thread died!");

        TAExitHandler::join();
        LOG_I("waitMcpNotification(): Exit handler Joined");
        LOG_E("TAExitHandler thread died!");

        return false;
    }
    return true;
}


//------------------------------------------------------------------------------
mcResult_t MobiCoreDevice::mshNotifyAndWait()
{
    // Notify MC about the availability of a new command inside the MCP buffer
    notify(SID_MCP);

    // Wait till response from MSH is available
    if (!waitMcpNotification())
    {
        LOG_E("waiting for MCP notification failed");
        return MC_DRV_ERR_DAEMON_MCI_ERROR;
    }

    return MC_DRV_OK;
}

//------------------------------------------------------------------------------
mcResult_t MobiCoreDevice::openSession(
    Connection                      *deviceConnection,
    loadDataOpenSession_ptr         pLoadDataOpenSession,
    uint32_t                        tciHandle,
    uint32_t                        tciLen,
    uint32_t                        tciOffset,
    mcDrvRspOpenSessionPayload_ptr  pRspOpenSessionPayload)
{
    do {
        uint64_t tci = 0;
        uint32_t len = 0;

        if (tciHandle != 0 && tciLen != 0) {
            // Check if we have a cont WSM or normal one
            if (findContiguousWsm(tciHandle,
                                  deviceConnection->socketDescriptor, &tci, &len)) {
                mcpMessage->cmdOpen.wsmTypeTci = WSM_CONTIGUOUS;
            mcpMessage->cmdOpen.adrTciBuffer = tci;
                mcpMessage->cmdOpen.ofsTciBuffer = 0;
            } else if ((tci = findWsmL2(tciHandle, deviceConnection->socketDescriptor))) {
                // We don't actually care about the len as the L2 table mapping is done
                // // and the TL will segfault if it's trying to access non-allocated memory
                len = tciLen;
                mcpMessage->cmdOpen.wsmTypeTci = WSM_L2;
            mcpMessage->cmdOpen.adrTciBuffer = tci;
                mcpMessage->cmdOpen.ofsTciBuffer = tciOffset;
            } else {
                LOG_E("Failed to find contiguous WSM %u", tciHandle);
                return MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND;
            }

            if (!lockWsmL2(tciHandle)) {
                LOG_E("Failed to lock contiguous WSM %u", tciHandle);
                return MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND;
            }
        } else if (tciHandle == 0 && tciLen == 0) {
            mcpMessage->cmdOpen.wsmTypeTci = WSM_INVALID;
            mcpMessage->cmdOpen.adrTciBuffer = (uint32_t)(tci);
            mcpMessage->cmdOpen.ofsTciBuffer = tciOffset;
        }

        if ((tciHandle != 0 && tciLen == 0) || tciLen > len) {
            LOG_E("Invalid TCI len from client - %u, tciHandle %d, Wsm len found %u",
                  tciLen, tciHandle, len);
            return MC_DRV_ERR_TCI_GREATER_THAN_WSM;
        }

        // Write MCP open message to buffer
        mcpMessage->cmdOpen.cmdHeader.cmdId = MC_MCP_CMD_OPEN_SESSION;
        mcpMessage->cmdOpen.uuid = pLoadDataOpenSession->tlHeader->mclfHeaderV2.uuid;
        mcpMessage->cmdOpen.lenTciBuffer = tciLen;
        LOG_I(" Using phys=%#llx, len=%d as TCI buffer", (uint64_t)tci, tciLen);

        // check if load data is provided
        mcpMessage->cmdOpen.wsmTypeLoadData = WSM_L2;
        mcpMessage->cmdOpen.adrLoadData = pLoadDataOpenSession->baseAddr;
        mcpMessage->cmdOpen.ofsLoadData = pLoadDataOpenSession->offs;
        mcpMessage->cmdOpen.lenLoadData = pLoadDataOpenSession->len;
        memcpy(&mcpMessage->cmdOpen.tlHeader, pLoadDataOpenSession->tlHeader, sizeof(*pLoadDataOpenSession->tlHeader));

        // Clear the notifications queue. We asume the race condition we have
        // seen in openSession never happens elsewhere
        notifications = std::queue<notification_t>();

        mcResult_t mcRet = mshNotifyAndWait();
        if (mcRet != MC_MCP_RET_OK)
        {
            LOG_E("mshNotifyAndWait failed for OPEN_SESSION, code %d.", mcRet);
            // Here Mobicore can be considered dead.
            if ((tciHandle != 0) && (tciLen != 0))
            {
                unlockWsmL2(tciHandle);
            }
            return mcRet;
        }

        // Check if the command response ID is correct
        if ((MC_MCP_CMD_OPEN_SESSION | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) {
            LOG_E("CMD_OPEN_SESSION got invalid MCP command response(0x%X)", mcpMessage->rspHeader.rspId);
            // Something is messing with our MCI memory, we cannot know if the Trustlet was loaded.
            // Had in been loaded, we are loosing track of it here.
            if (tciHandle != 0 && tciLen != 0) {
                unlockWsmL2(tciHandle);
            }
            return MC_DRV_ERR_DAEMON_MCI_ERROR;
        }

        mcRet = mcpMessage->rspOpen.rspHeader.result;

        if (mcRet != MC_MCP_RET_OK) {
            LOG_E("MCP OPEN returned code %d.", mcRet);
            if (tciHandle != 0 && tciLen != 0) {
                unlockWsmL2(tciHandle);
            }
            return MAKE_MC_DRV_MCP_ERROR(mcRet);
        }

        LOG_I(" After MCP OPEN, we have %d queued notifications",
              notifications.size());
        // Read MC answer from MCP buffer
        TrustletSession *trustletSession = new TrustletSession(
            deviceConnection,
            mcpMessage->rspOpen.sessionId);

        // Security TODO: device connection peer has to match the NQ connection peer
    	// The check here is not 100% correct
        pRspOpenSessionPayload->sessionId = trustletSession->sessionId;
        pRspOpenSessionPayload->deviceSessionId = (uint32_t)((uintptr_t)trustletSession & UINT_MAX);
        pRspOpenSessionPayload->sessionMagic = trustletSession->sessionMagic;

        trustletSession->gp_level=((mclfHeaderV24_ptr)&pLoadDataOpenSession->tlHeader->mclfHeaderV2)->gp_level;
        LOG_I(" Trusted App has gp_level %d",trustletSession->gp_level);
        trustletSession->sessionState = TrustletSession::TS_TA_RUNNING;

        mutex_tslist.lock();
        trustletSessions.push_back(trustletSession);
        mutex_tslist.unlock();

        if (tciHandle != 0 && tciLen != 0) {
            trustletSession->addBulkBuff(new CWsm(NULL, pLoadDataOpenSession->len, tciHandle, 0));
        }

        // We have some queued notifications and we need to send them to them
        // trustlet session
        while (!notifications.empty()) {
            trustletSession->queueNotification(&notifications.front());
            notifications.pop();
        }

    } while (0);
    return MC_DRV_OK;
}

mcResult_t MobiCoreDevice::checkLoad(
    loadDataOpenSession_ptr         pLoadDataOpenSession,
    mcDrvRspOpenSessionPayload_ptr  /*pRspOpenSessionPayload*/)
{
    do {
        // Write MCP open message to buffer
        mcpMessage->cmdCheckLoad.cmdHeader.cmdId = MC_MCP_CMD_CHECK_LOAD_TA;
        mcpMessage->cmdCheckLoad.uuid = pLoadDataOpenSession->tlHeader->mclfHeaderV2.uuid;

        // check if load data is provided
        mcpMessage->cmdCheckLoad.wsmTypeLoadData = WSM_L2;
        mcpMessage->cmdCheckLoad.adrLoadData = pLoadDataOpenSession->baseAddr;
        mcpMessage->cmdCheckLoad.ofsLoadData = pLoadDataOpenSession->offs;
        mcpMessage->cmdCheckLoad.lenLoadData = pLoadDataOpenSession->len;
        memcpy(&mcpMessage->cmdCheckLoad.tlHeader, pLoadDataOpenSession->tlHeader, sizeof(*pLoadDataOpenSession->tlHeader));

        // Clear the notifications queue. We asume the race condition we have
        // seen in openSession never happens elsewhere
        notifications = std::queue<notification_t>();

        mcResult_t mcRet = mshNotifyAndWait();
        if (mcRet != MC_MCP_RET_OK)
        {
            LOG_E("mshNotifyAndWait failed for CHECK_LOAD_TA, code %d.", mcRet);
            // Here Mobicore can be considered dead.
            return mcRet;
        }

        // Check if the command response ID is correct
        if ((MC_MCP_CMD_CHECK_LOAD_TA | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) {
            LOG_E("CMD_OPEN_SESSION got invalid MCP command response(0x%X)", mcpMessage->rspHeader.rspId);
            // Something is messing with our MCI memory, we cannot know if the Trustlet was loaded.
            // Had in been loaded, we are loosing track of it here.

            return MC_DRV_ERR_DAEMON_MCI_ERROR;
        }

        mcRet = mcpMessage->rspCheckLoad.rspHeader.result;

        if (mcRet != MC_MCP_RET_OK) {
            LOG_E("MCP CHECK_LOAD returned code %d.", mcRet);
            return MAKE_MC_DRV_MCP_ERROR(mcRet);
        }
        return MC_DRV_OK;

    } while (0);
    return MC_DRV_ERR_UNKNOWN;
}



//------------------------------------------------------------------------------
TrustletSession *MobiCoreDevice::registerTrustletConnection(
    Connection                    *connection,
    MC_DRV_CMD_NQ_CONNECT_struct *cmdNqConnect
)
{
    LOG_I(" Registering notification socket with Service session %03x.",
          cmdNqConnect->sessionId);
    LOG_V("  Searching sessionId %03x with sessionMagic %d",
          cmdNqConnect->sessionId,
          cmdNqConnect->sessionMagic);


    for (trustletSessionIterator_t iterator = trustletSessions.begin();
         iterator != trustletSessions.end();
         ++iterator)
    {
        TrustletSession *session = *iterator;

        if (((uintptr_t)session & UINT_MAX) != cmdNqConnect->deviceSessionId) {
            continue;
        }

        if ( (session->sessionMagic != cmdNqConnect->sessionMagic)
                || (session->sessionId != cmdNqConnect->sessionId)) {
            continue;
        }

        session->notificationConnection = connection;

        LOG_I(" Found Service session, registered connection.");


        return session;
    }


    LOG_I("registerTrustletConnection(): search failed");
    return NULL;
}


//------------------------------------------------------------------------------
/**
 * Need connection as well as according session ID, so that a client can not
 * close sessions not belonging to him.
 */
mcResult_t MobiCoreDevice::closeSession(
    Connection  *deviceConnection,
    uint32_t    sessionId
) {
    TrustletSession *session = findSession(deviceConnection,sessionId);
    if (session == NULL) {
        LOG_E("cannot close session %03x", sessionId);
        return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION;
    }

    if (session->gp_level == 1) {
        mutex_connection.lock();
        LOG_I(" Closing GP TA session...");
        // Disconnect client from this session
        session->deviceConnection = NULL;
        // Free connection, i.e. close nq socket
        delete session->notificationConnection;
        session->notificationConnection = NULL;
        // If exit notification from task arrives during MCP_CLOSE,
        // Daemon can see that CA is already away
        session->sessionState = TrustletSession::TS_CLOSE_SEND;
        mutex_connection.unlock();
    }

    /* close session */
    mcResult_t mcRet = closeSessionInternal(session);

    if ((session->gp_level==1) && (mcRet == MAKE_MC_DRV_MCP_ERROR(MC_MCP_RET_ERR_CLOSE_TASK_FAILED))) {
        LOG_I(" Close session failed this time.");
        // We could have received a spurious notification of TA dead
        if (session->sessionState == TrustletSession::TS_TA_DEAD) {
            LOG_V(" TA died in the meantime, try closing again");
            // Try again
            mcRet = closeSessionInternal(session);
            assert(mcRet == MC_MCP_RET_OK);
        } else {
            // Clean up is deferred to handleTaExit()
            return MC_MCP_RET_OK;
        }
    }

    if (mcRet != MC_MCP_RET_OK) {
        LOG_E("closeSession failed with %d", mcRet);
        return MAKE_MC_DRV_MCP_ERROR(mcRet);
    }

    freeSession(session);

    return MC_MCP_RET_OK;
}


void MobiCoreDevice::freeSession(
        TrustletSession *session
) {
    // clean session WSM
    LOG_I("unlocking session buffers!");
    CWsm_ptr pWsm = session->popBulkBuff();
    while (pWsm)
    {
        unlockWsmL2(pWsm->handle);
        delete pWsm;
        pWsm = session->popBulkBuff();
    }

    // remove session from list.
    mutex_tslist.lock();
    trustletSessions.remove(session);
    mutex_tslist.unlock();
    delete session;
}


//------------------------------------------------------------------------------
void MobiCoreDevice::queueUnknownNotification(
     notification_t notification
) {
    notifications.push(notification);
}

//------------------------------------------------------------------------------
mcResult_t MobiCoreDevice::notify(
    Connection  *deviceConnection,
    uint32_t    sessionId
) {
    TrustletSession *session = findSession(deviceConnection,sessionId);
    if (session == NULL)
    {
        LOG_E("cannot notify session %03x", sessionId);
        return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION;
    }

    notify(sessionId);

    return MC_DRV_OK;
}

//------------------------------------------------------------------------------
mcResult_t MobiCoreDevice::mapBulk(
    Connection *deviceConnection,
    uint32_t  sessionId,
    uint32_t  handle,
    uint64_t  pAddrL2,
    uint32_t  offsetPayload,
    uint32_t  lenBulkMem,
    uint32_t  *secureVirtualAdr
) {
    TrustletSession *session = findSession(deviceConnection,sessionId);
    if (session == NULL) {
        LOG_E("cannot mapBulk on session %03x", sessionId);
        return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION;
    }

    // TODO-2012-09-06-haenellu: considernot ignoring the error case, ClientLib
    //                           does not allow this.
    session->addBulkBuff(
                new CWsm(NULL,
                lenBulkMem,
                handle,
                pAddrL2));

    // Write MCP map message to buffer
    mcpMessage->cmdMap.cmdHeader.cmdId = MC_MCP_CMD_MAP;
    mcpMessage->cmdMap.sessionId = sessionId;
    mcpMessage->cmdMap.wsmType = WSM_L2;
    mcpMessage->cmdMap.adrBuffer = pAddrL2;
    mcpMessage->cmdMap.ofsBuffer = offsetPayload;
    mcpMessage->cmdMap.lenBuffer = lenBulkMem;

    mcResult_t mcRet = mshNotifyAndWait();
    if (mcRet != MC_MCP_RET_OK)
    {
        LOG_E("mshNotifyAndWait failed for MAP, code %d.", mcRet);
        return mcRet;
    }

    // Check if the command response ID is correct
    if (mcpMessage->rspHeader.rspId != (MC_MCP_CMD_MAP | FLAG_RESPONSE)) {
        LOG_E("invalid MCP response for CMD_MAP");
        return MC_DRV_ERR_DAEMON_MCI_ERROR;
    }

    mcRet = mcpMessage->rspMap.rspHeader.result;

    if (mcRet != MC_MCP_RET_OK) {
        LOG_E("MCP MAP returned code %d.", mcRet);
        return MAKE_MC_DRV_MCP_ERROR(mcRet);
    }

    *secureVirtualAdr = mcpMessage->rspMap.secureVirtualAdr;
    return MC_DRV_OK;
}


//------------------------------------------------------------------------------
mcResult_t MobiCoreDevice::unmapBulk(
    Connection  *deviceConnection,
    uint32_t    sessionId,
    uint32_t    handle,
    uint32_t    secureVirtualAdr,
    uint32_t    lenBulkMem
) {
    TrustletSession *session = findSession(deviceConnection,sessionId);
    if (session == NULL) {
        LOG_E("cannot unmapBulk on session %03x", sessionId);
        return MC_DRV_ERR_DAEMON_UNKNOWN_SESSION;
    }

    if (!session->findBulkBuff(handle, lenBulkMem)) {
        LOG_E("cannot unmapBulk with handle=%d", handle);
        return MC_DRV_ERR_DAEMON_WSM_HANDLE_NOT_FOUND;
    }

    // Write MCP unmap command to buffer
    mcpMessage->cmdUnmap.cmdHeader.cmdId = MC_MCP_CMD_UNMAP;
    mcpMessage->cmdUnmap.sessionId = sessionId;
    mcpMessage->cmdUnmap.wsmType = WSM_L2;
    mcpMessage->cmdUnmap.secureVirtualAdr = secureVirtualAdr;
    mcpMessage->cmdUnmap.lenVirtualBuffer = lenBulkMem;

    mcResult_t mcRet = mshNotifyAndWait();
    if (mcRet != MC_MCP_RET_OK)
    {
        LOG_E("mshNotifyAndWait failed for UNMAP, code %d.", mcRet);
        return mcRet;
    }

    // Check if the command response ID is correct
    if (mcpMessage->rspHeader.rspId != (MC_MCP_CMD_UNMAP | FLAG_RESPONSE)) {
        LOG_E("invalid MCP response for OPEN_SESSION");
        return MC_DRV_ERR_DAEMON_MCI_ERROR;
    }

    mcRet = mcpMessage->rspUnmap.rspHeader.result;

    if (mcRet != MC_MCP_RET_OK) {
        LOG_E("MCP UNMAP returned code %d.", mcRet);
        return MAKE_MC_DRV_MCP_ERROR(mcRet);
    }

    // Just remove the buffer
    // TODO-2012-09-06-haenellu: Haven't we removed it already?
    if (!session->removeBulkBuff(handle))
    {
        LOG_I("unmapBulk(): no buffer found found with handle=%u", handle);
    }

    return MC_DRV_OK;
}

mcResult_t MobiCoreDevice::getMobiCoreVersion(
    mcDrvRspGetMobiCoreVersionPayload_ptr pRspGetMobiCoreVersionPayload
) {
    // retunt info it we have already fetched it before
    if (mcVersionInfo != NULL)
    {
        pRspGetMobiCoreVersionPayload->versionInfo = *mcVersionInfo;
        return MC_DRV_OK;
    }

    // Write MCP unmap command to buffer
    mcpMessage->cmdGetMobiCoreVersion.cmdHeader.cmdId = MC_MCP_CMD_GET_MOBICORE_VERSION;

    mcResult_t mcRet = mshNotifyAndWait();
    if (mcRet != MC_MCP_RET_OK)
    {
        LOG_E("mshNotifyAndWait failed for GET_MOBICORE_VERSION, code %d.", mcRet);
        return mcRet;
    }

    // Check if the command response ID is correct
    if ((MC_MCP_CMD_GET_MOBICORE_VERSION | FLAG_RESPONSE) != mcpMessage->rspHeader.rspId) {
        LOG_E("invalid MCP response for GET_MOBICORE_VERSION");
        return MC_DRV_ERR_DAEMON_MCI_ERROR;
    }

    mcRet = mcpMessage->rspGetMobiCoreVersion.rspHeader.result;

    if (mcRet != MC_MCP_RET_OK) {
        LOG_E("MC_MCP_CMD_GET_MOBICORE_VERSION error %d", mcRet);
        return MAKE_MC_DRV_MCP_ERROR(mcRet);
    }

    pRspGetMobiCoreVersionPayload->versionInfo = mcpMessage->rspGetMobiCoreVersion.versionInfo;

    // Store MobiCore info for future reference.
    mcVersionInfo = new mcVersionInfo_t();
    *mcVersionInfo = pRspGetMobiCoreVersionPayload->versionInfo;
    return MC_DRV_OK;
}

//------------------------------------------------------------------------------
mcResult_t MobiCoreDevice::loadToken(Connection        */*deviceConnection*/,
                                     loadTokenData_ptr pLoadTokenData)
{
    do {
        mcpMessage->cmdLoadToken.cmdHeader.cmdId = MC_MCP_CMD_LOAD_TOKEN;
        mcpMessage->cmdLoadToken.wsmTypeLoadData = WSM_L2;
        mcpMessage->cmdLoadToken.adrLoadData = (uint32_t) pLoadTokenData->addr;
        mcpMessage->cmdLoadToken.ofsLoadData = pLoadTokenData->offs;
        mcpMessage->cmdLoadToken.lenLoadData = pLoadTokenData->len;

        /* Clear the notifications queue. We asume the race condition we have
         * seen in openSession never happens elsewhere
         */
        notifications = std::queue<notification_t>();

        mcResult_t mcRet = mshNotifyAndWait();
        if (mcRet != MC_MCP_RET_OK)
        {
            LOG_E("mshNotifyAndWait failed for LOAD_TOKEN, code 0x%x.", mcRet);
            /* Here <t-base can be considered dead. */
            return mcRet;
        }

        /* Check if the command response ID is correct */
        if ((MC_MCP_CMD_LOAD_TOKEN | FLAG_RESPONSE) !=
            mcpMessage->rspHeader.rspId) {
            LOG_E("CMD_LOAD_TOKEN got invalid MCP command response(0x%X)",
                  mcpMessage->rspHeader.rspId);
            return MC_DRV_ERR_DAEMON_MCI_ERROR;
        }

        mcRet = mcpMessage->rspLoadToken.rspHeader.result;

        if (mcRet != MC_MCP_RET_OK) {
            LOG_E("MCP LOAD_TOKEN returned code 0x%x.", mcRet);
            return MAKE_MC_DRV_MCP_ERROR(mcRet);
        }

    } while (0);

    return MC_DRV_OK;
}