summaryrefslogtreecommitdiff
path: root/arch/arm/mach-tegra/nvrm/core/common/nvrm_transport.c
blob: ffc4f83196fc18123df4414a0b58a7a70a4f4bc9 (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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
/*
 * Copyright (c) 2010 NVIDIA Corporation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 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.
 *
 * Neither the name of the NVIDIA Corporation 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.
 *
 */

/** @file
 * @brief <b>NVIDIA Driver Development Kit:
 *          Transport API</b>
 *
 * @b Description: This is the implementation of Transport API, which
 * implements a simple means to pass messages across a port name regardless of
 * port exist in what processor (on same processor or other processor).
 */

#include "nvrm_transport.h"
#include "nvrm_xpc.h"
#include "nvrm_interrupt.h"
#include "nvrm_rpc.h"
#include "nvutil.h"
#include "nvassert.h"
#include "nvcommon.h"
#include "avp.h"

#define LOOPBACK_PROFILE 0

// indices where to save data for the loopback test
#define LOOP_CPU_SEND_INDEX 0
#define LOOP_AVP_ISR_INDEX  1
#define LOOP_AVP_RECV_INDEX 2
#define LOOP_AVP_SEND_INDEX 3
#define LOOP_CPU_ISR_INDEX  4
#define LOOP_CPU_RECV_INDEX 5

#define SEMAPHORE_BASED_MUTUAL_EXCLUSION 0

enum {MAX_INT_FOR_TRANSPORT = 2};

// Interrupt bit index in the interrupt controller relocation table.
enum {CPU_TRANSPORT_INT_OBE = 1};
enum {CPU_TRANSPORT_INT_IBF = 0};
enum {AVP_TRANSPORT_INT_OBE = 0};
enum {AVP_TRANSPORT_INT_IBF = 1};

// Some constraints parameter to develop the transport APIs.

// Maximum port name length
enum {MAX_PORT_NAME_LENGTH = 16};

// Maximum possible message length between the ports
#define  MAX_COMMAND_SIZE   16

// Message header size MessageCommand + port Name + message Length (24 Bytes)
enum {MESSAGE_HEADER_SIZE = 0x20};

// Maximum receive message queue depth
enum {MAX_MESSAGE_DEPTH = 30};

// Maximum time to wait for the response when open the port.
enum {MAX_OPEN_TIMEOUT_MS = 200};

// Try to resend the message after this time.
enum {MESSAGE_RETRY_AFTER_MS = 500 };

// Connection message transfer and response wait timeout.
enum {MAX_CONNECTION_TIMEOUT_MS = 500 };



// Transport Commands which uses to do the handshaking and message transfer
// between the processor. This commands are send to the remote processor
// when any type if transaction happens.
typedef enum
{
  TransportCmd_None = 0x0,

  // The first transport command from the cpu->avp will inform the
  // avp of size of the buffer.
  TransportCmd_SetBufferInfo,

  // Transport command for staring the connection process.
  TransportCmd_Connect,

  // Transport command for disconnecting the port and deleting the port entry.
  TransportCmd_Disconnect,

  // Transport command which used for normal message transfer to the port.
  TransportCmd_Message,

  // When a command requires a response, the value in the command field will
  // be changed by the called processor here to indicate that the response is ready.
  TransportCmd_Response,

  TransportCmd_Force32 = 0x7FFFFFFF

} TransportCmd;



// Ports (endpoint) state.
typedef enum
{
    // Port is opened only.
    PortState_Open = 0x1,

    // Port is waiting for connection.
    PortState_Waiting,

    // Port is connected.
    PortState_Connected,

    // Port has been disconnected from other side.  You can pop out messages
    // but you can't send anymore
    PortState_Disconnected,

    // Set to destroy when there is someone waiting for a connection, but
    // and a different thread calls to kill close the port.
    PortState_Destroy,

    PortState_Force32 = 0x7FFFFFFF
} PortState;



// Message list which will be queued in the port receive message queue.
typedef struct RmReceiveMessageRec
{
    // Length of message.
    NvU32 MessageLength;

    // Fixed size message buffer where the receiving message will be store.
    NvU8 MessageBuffer[MAX_MESSAGE_LENGTH];
} RmReceiveMessage;


// Combines the information for keeping the received messages to the
// corresponding ports.
typedef struct MessageQueueRec
{
    // Receive message Q details to receive the message.  We make the queue 1 extra bigger than the
    // requested size, and then we can do lockless updates because only the Recv function modifies
    // ReadIndex, and only the ISR modifies the WriteIndex
    RmReceiveMessage *pReceiveMsg;

    volatile NvU16 ReadIndex;
    volatile NvU16 WriteIndex;

    NvU16 QueueSize;

} MessageQueue;



// Combines all required information for the transport port.
// The port information  contains the state, recv message q, message depth and
// message length.
typedef struct NvRmTransportRec
{
    // Name of the port, 1 exra byte for NULL termination
    char PortName[MAX_PORT_NAME_LENGTH+1];

    // The state of port whether this is open or connected or waiting for
    // connection.
    PortState State;

    // Receive message Box which contains the receive messages for this port.
    MessageQueue RecvMessageQueue;

    // Semaphore which is signal after getting the message for that port.
    // This is the client passed semaphore.
    NvOsSemaphoreHandle hOnPushMsgSem;

    // Pointer to the partner port.  If the connect is to a remote partner,
    // then this pointer is NULL
    NvRmTransportHandle hConnectedPort;

    // If this is a remote connection, this holds the remote ports "name"
    NvU32               RemotePort;

    // save a copy of the rm handle.
    NvRmDeviceHandle hRmDevice; 

    struct NvRmTransportRec *pNext;

    // unlikely to be used members at the end
    
    // to be signalled when someone waits for a connector.
    NvOsSemaphoreHandle hOnConnectSem;

#if LOOPBACK_PROFILE
    NvBool              bLoopTest;
#endif

} NvRmTransport;



// Combines the common information for keeping the transport information and
// sending and receiving the messages.
typedef struct NvRmPrivPortsRec
{
    // Device handle.
    NvRmDeviceHandle hDevice;

    // List of port names of the open ports in the system.
    NvRmTransport   *pPortHead;

    // Mutex for transport
    NvOsMutexHandle mutex;

    NvRmMemHandle hMessageMem;
    void          *pTransmitMem;
    void          *pReceiveMem;
    NvU32         MessageMemPhysAddr;

    NvRmPrivXpcMessageHandle hXpc;

    // if a message comes in, but the receiver's queue is full,
    // then we don't clear the inbound message to allow another message
    // and set this flag.  We use 2 variables here, so we don't need a lock.
    volatile NvU8  ReceiveBackPressureOn;
    NvU8           ReceiveBackPressureOff;

#if LOOPBACK_PROFILE
    volatile NvU32 *pTimer;
#endif
} NvRmPrivPorts;


// !!! Fixme, this should be part of the rm handle.
static NvRmPrivPorts s_TransportInfo;

extern NvU32 NvRmAvpPrivGetUncachedAddress(NvU32 addr);

#define MESSAGE_QUEUE_SIZE_IN_BYTES ( sizeof(RmReceiveMessage) * (MAX_MESSAGE_DEPTH+1) )
static NvU32 s_RpcAvpQueue[ (MESSAGE_QUEUE_SIZE_IN_BYTES + 3) / 4 ];
static NvU32 s_RpcCpuQueue[ (MESSAGE_QUEUE_SIZE_IN_BYTES + 3) / 4 ];
static struct NvRmTransportRec s_RpcAvpPortStruct;
static struct NvRmTransportRec s_RpcCpuPortStruct;

static NvOsInterruptHandle s_TransportInterruptHandle = NULL;

static NvRmTransportHandle
FindPort(NvRmDeviceHandle hDevice, char *pPortName);

static NvError
NvRmPrivTransportSendMessage(NvRmDeviceHandle hDevice, NvU32 *message, NvU32 MessageLength);

static void HandleAVPResetMessage(NvRmDeviceHandle hDevice);

// expect caller to handle mutex
static char *NvRmPrivTransportUniqueName(void)
{
    static char UniqueName[] = "aaaaaaaa+";
    NvU32 len = 8;
    NvU32 i;

    // this will roll a new name until we hit zzzz:zzzz
    // it's not unbounded, but it is a lot of names...
    // Unique names end in a '+' which won't be allowed in supplied names, to avoid
    // collision.
    for (i=0; i < len; ++i)
    {
        ++UniqueName[i];
        if (UniqueName[i] != 'z')
        {
            break;
        }
        UniqueName[i] = 'a';

    }

    return UniqueName;
}


/* Returns NV_TRUE if the message was inserted ok
 *  Returns NV_FALSE if message was not inserted because the queue is already full

 */static NvBool
InsertMessage(NvRmTransportHandle hPort, const NvU8 *message, const NvU32 MessageSize)
{
    NvU32 index;
    NvU32 NextIndex;

    index = (NvU32)hPort->RecvMessageQueue.WriteIndex;
    NextIndex = index + 1;
    if (NextIndex == hPort->RecvMessageQueue.QueueSize)
        NextIndex = 0;

    // check for full condition
    if (NextIndex == hPort->RecvMessageQueue.ReadIndex)
        return NV_FALSE;

    // copy in the message
    NvOsMemcpy(hPort->RecvMessageQueue.pReceiveMsg[index].MessageBuffer,
               message,
               MessageSize);
    hPort->RecvMessageQueue.pReceiveMsg[index].MessageLength = MessageSize;

    hPort->RecvMessageQueue.WriteIndex = (NvU16)NextIndex;
    return NV_TRUE;
}


static void
ExtractMessage(NvRmTransportHandle hPort, NvU8 *message, NvU32 *pMessageSize, NvU32 MaxSize)
{
    NvU32 NextIndex;
    NvU32 index = (NvU32)hPort->RecvMessageQueue.ReadIndex;
    NvU32 size  = hPort->RecvMessageQueue.pReceiveMsg[index].MessageLength;

    NextIndex = index + 1;
    if (NextIndex == hPort->RecvMessageQueue.QueueSize)
        NextIndex = 0;

    NV_ASSERT(index != hPort->RecvMessageQueue.WriteIndex); // assert on empty condition
    NV_ASSERT(size <= MaxSize);

    *pMessageSize = size;

    // only do the copy and update if there is sufficient room, otherwise
    // the caller will propogate an error up.
    if (size > MaxSize)
    {
        return;
    }
    NvOsMemcpy(message,
               hPort->RecvMessageQueue.pReceiveMsg[index].MessageBuffer,
               size);

    hPort->RecvMessageQueue.ReadIndex = (NvU16)NextIndex;
}



static void *s_TmpIsrMsgBuffer;

/**
 * Connect message
 *  [ Transport Command ]
 *  [ Remote Handle ]
 *  [ Port Name ]
 *
 * Response:
 *   [ Remote Handle ] <- [ Local Handle ]
 */

static void
HandleConnectMessage(NvRmDeviceHandle hDevice, volatile NvU32 *pMessage)
{
    char PortName[MAX_PORT_NAME_LENGTH+1];
    NvU32 RemotePort;
    NvRmTransportHandle hPort;
    
    RemotePort = pMessage[1];
    NvOsMemcpy(PortName, (void*)&pMessage[2], MAX_PORT_NAME_LENGTH);
    PortName[MAX_PORT_NAME_LENGTH] = 0;

    // See if there is a local port with that name
    hPort = FindPort(hDevice, PortName);
    if (hPort && hPort->State == PortState_Waiting)
    {
        NvOsAtomicCompareExchange32((NvS32 *)&hPort->State, PortState_Waiting, PortState_Connected);
        if (hPort->State == PortState_Connected)
        {
            hPort->RemotePort = RemotePort;
            NvOsSemaphoreSignal(hPort->hOnConnectSem);
            pMessage[1] = (NvU32)hPort;
        }
        else
        {
            pMessage[1] = 0;
        }
    }
    else
    {
        pMessage[1] = 0;
    }
    pMessage[0] = TransportCmd_Response;
}



/**
 * Disconnect message
 *  [ Transport Command ]
 *  [ Local Handle ]
 *
 * Response:
 *   [ Local Handle ] <- 0 
 */
static void
HandleDisconnectMessage(NvRmDeviceHandle hDevice, volatile NvU32 *pMessage)
{
    NvRmTransportHandle hPort;
    hPort = (NvRmTransportHandle)pMessage[1];

    // !!! For sanity we should walk the list of open ports to make sure this is a valid port!
    if (hPort && hPort->State == PortState_Connected)
    {
        hPort->State = PortState_Disconnected;
        hPort->RemotePort = 0;
    }
    pMessage[1] = 0;
    pMessage[0] = TransportCmd_None;
}


/**
 * Disconnect message
 *  [ Transport Command ]
 *  [ Local Handle ]
 *  [ Message Length ]
 *  [ Message ]
 *
 * Response:
 *   [ Message Length ] <- NvSuccess 
 *   [ Transport Command ] <- When we can accept a new message
 */

static void
HandlePortMessage(NvRmDeviceHandle hDevice, volatile NvU32 *pMessage)
{
    NvRmTransportHandle hPort;
    NvU32               MessageLength;
    NvBool              bSuccess;

    hPort         = (NvRmTransportHandle)pMessage[1];
    MessageLength = pMessage[2];

#if LOOPBACK_PROFILE
    if (hPort && hPort->bLoopTest)
    {
# if NV_IS_AVP
        pMessage[LOOP_AVP_ISR_INDEX + 3] = *s_TransportInfo.pTimer;
# else
        pMessage[LOOP_CPU_ISR_INDEX + 3] = *s_TransportInfo.pTimer;
# endif
    }
#endif


    // !!! For sanity we should walk the list of open ports to make sure this is a valid port!
    // Queue the message even if in the open state as presumably this should only have happened if
    // due to a race condition with the transport connected messages.
    if (hPort && (hPort->State == PortState_Connected || hPort->State == PortState_Open))    
    {
        bSuccess = InsertMessage(hPort, (NvU8*)&pMessage[3], MessageLength);
        if (bSuccess)
        {
            if (hPort->hOnPushMsgSem)
                NvOsSemaphoreSignal(hPort->hOnPushMsgSem);
            pMessage[0] = TransportCmd_None;
        }
        else
        {
            ++s_TransportInfo.ReceiveBackPressureOn;
        }
    }
}

static void 
HandleAVPResetMessage(NvRmDeviceHandle hDevice)
{
    NvRmTransportHandle hPort;
    
    hPort = FindPort(hDevice,(char*)"RPC_CPU_PORT");
    if (hPort && (hPort->State == PortState_Connected || hPort->State == PortState_Open))
    {
        NvU32 message;
        message = NvRmMsg_AVP_Reset;
        InsertMessage(hPort, (NvU8*)&message, sizeof(NvU32));
        if (hPort->hOnPushMsgSem)
            NvOsSemaphoreSignal(hPort->hOnPushMsgSem);
        else
            NV_ASSERT(0);
    }
    else
        NV_ASSERT(0);

}


/**
 * Handle the Inbox full interrupt.
 */
static void
InboxFullIsr(void *args)
{
    NvRmDeviceHandle hDevice = (NvRmDeviceHandle)args;
    NvU32 MessageData;
    NvU32 MessageCommand;
    volatile NvU32 *pMessage;

    MessageData = NvRmPrivXpcGetMessage(s_TransportInfo.hXpc);
    if(MessageData == AVP_WDT_RESET)
    {
         HandleAVPResetMessage(hDevice);
         NvRmInterruptDone(s_TransportInterruptHandle);
         return;
    }
    // if we're on the AVP, the first message we get will configure the message info
    if (s_TransportInfo.MessageMemPhysAddr == 0)
    {
#if NV_IS_AVP
        MessageData = NvRmAvpPrivGetUncachedAddress(MessageData);
#else
        MessageData = MessageData;
#endif
        s_TransportInfo.MessageMemPhysAddr = MessageData;
        s_TransportInfo.pReceiveMem  = (void*)MessageData;
        s_TransportInfo.pTransmitMem = (void *) (MessageData + MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE);
        // ack the message and return.
        *(NvU32*)s_TransportInfo.pReceiveMem = TransportCmd_None;
        return;
    }

    // otherwise decode and dispatch the message.


    if (s_TransportInfo.pReceiveMem == NULL)
    {
        /* QT/EMUTRANS takes this path. */
        NvRmMemRead(s_TransportInfo.hMessageMem, MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE, s_TmpIsrMsgBuffer, MAX_MESSAGE_LENGTH);
        pMessage = s_TmpIsrMsgBuffer;
        NvRmMemWrite(s_TransportInfo.hMessageMem, MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE, s_TmpIsrMsgBuffer, 2*sizeof(NvU32));
    }
    else
    {
        pMessage = (NvU32*)s_TransportInfo.pReceiveMem;
    }

    MessageCommand = pMessage[0];

    switch (MessageCommand)
    {
    case  TransportCmd_Connect:
        HandleConnectMessage(hDevice, pMessage);
        break;
        
    case  TransportCmd_Disconnect:
        HandleDisconnectMessage(hDevice, pMessage);
        break;

    case TransportCmd_Message:
        HandlePortMessage(hDevice, pMessage);
        break;
            
    default:
        NV_ASSERT(0);
    }

    NvRmInterruptDone(s_TransportInterruptHandle);
}


/**
 * Handle the outbox empty interrupt.
 */
static void
OutboxEmptyIsr(void *args)
{
    // !!! This is not currently used... ignore for now.  Might be required if we find that we
    //     need to spin for long periods of time waiting for other end of the connection to consume
    //     messages.
    //
    NvRmInterruptDone(s_TransportInterruptHandle);
}

static void
NvRmPrivProcIdGetProcessorInfo(
    NvRmDeviceHandle hDevice,
    NvRmModuleID *pProcModuleId)
{
#if NV_IS_AVP
    *pProcModuleId = NvRmModuleID_Avp;
#else
    *pProcModuleId = NvRmModuleID_Cpu;
#endif
}

/**
 * Register for the transport interrupts.
 */
static NvError
RegisterTransportInterrupt(NvRmDeviceHandle hDevice)
{
    NvOsInterruptHandler DmaIntHandlers[MAX_INT_FOR_TRANSPORT];
    NvU32 IrqList[MAX_INT_FOR_TRANSPORT];
    NvRmModuleID ProcModuleId;

    if (s_TransportInterruptHandle)
    {
        return NvSuccess;
    }
    NvRmPrivProcIdGetProcessorInfo(hDevice, &ProcModuleId);

    if (ProcModuleId == NvRmModuleID_Cpu)
    {
        IrqList[0] = NvRmGetIrqForLogicalInterrupt(
            hDevice, NvRmModuleID_ResourceSema, CPU_TRANSPORT_INT_IBF);
        IrqList[1] = NvRmGetIrqForLogicalInterrupt(
            hDevice, NvRmModuleID_ResourceSema, CPU_TRANSPORT_INT_OBE);
    }
    else
    {
        IrqList[0] = NvRmGetIrqForLogicalInterrupt(
            hDevice, NvRmModuleID_ResourceSema, AVP_TRANSPORT_INT_IBF);
        IrqList[1] = NvRmGetIrqForLogicalInterrupt(
            hDevice, NvRmModuleID_ResourceSema, AVP_TRANSPORT_INT_OBE);
    }

    /* There is no need for registering the OutboxEmptyIsr, so we only register
     * one interrupt i.e. InboxFullIsr  */
    DmaIntHandlers[0] = InboxFullIsr;
    DmaIntHandlers[1] = OutboxEmptyIsr;
    return NvRmInterruptRegister(hDevice, 1, IrqList, DmaIntHandlers, 
            hDevice, &s_TransportInterruptHandle, NV_TRUE);
}

// allocate buffers to be used for sending/receiving messages.
static void
NvRmPrivTransportAllocBuffers(NvRmDeviceHandle hRmDevice)
{
#if !NV_IS_AVP
    // These buffers are always allocated on the CPU side.  We'll pass the address over the AVP
    //

    NvError Error = NvSuccess;
    NvRmMemHandle hNewMemHandle = NULL;

    // Create memory handle
    Error = NvRmMemHandleCreate(hRmDevice, &hNewMemHandle, (MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE)*2);
    if (Error)
        goto fail;

    // Allocates the memory from the Heap
    Error = NvRmMemAlloc(hNewMemHandle, NULL, 0,
                         XPC_MESSAGE_ALIGNMENT_SIZE, NvOsMemAttribute_Uncached);
    if (Error)
        goto fail;

    s_TransportInfo.MessageMemPhysAddr = NvRmMemPin(hNewMemHandle);

    // If it is success to create the memory handle.
    // We have to be able to get a mapping to this, because it is used at interrupt time!
    s_TransportInfo.hMessageMem = hNewMemHandle;
    Error = NvRmMemMap(hNewMemHandle, 0,
        (MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE)*2,
        NVOS_MEM_READ_WRITE,
        &s_TransportInfo.pTransmitMem);
    if (Error)
    {
        s_TransportInfo.pTransmitMem = NULL;
        s_TransportInfo.pReceiveMem = NULL;
    }
    else
    {
        s_TransportInfo.pReceiveMem  = (void *) (((NvUPtr)s_TransportInfo.pTransmitMem) + 
                                                              MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE);
    }

    s_TransportInfo.hMessageMem = hNewMemHandle;
    NvRmMemWr32(hNewMemHandle, 0, 0xdeadf00d); // set this non-zero to throttle messages to the avp till avp is ready.
    NvRmMemWr32(hNewMemHandle,  MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE, 0);

    NvRmPrivXpcSendMessage(s_TransportInfo.hXpc, s_TransportInfo.MessageMemPhysAddr);
    return;
    

fail:
    NvRmMemHandleFree(hNewMemHandle);
    s_TransportInfo.hMessageMem = NULL;
    return;
#else
    return;
#endif
}


static void
NvRmPrivTransportFreeBuffers(NvRmDeviceHandle hRmDevice)
{
#if !NV_IS_AVP
    NvRmMemHandleFree(s_TransportInfo.hMessageMem);
#endif
}

static volatile NvBool s_Transport_Inited = NV_FALSE;

/**
 * Initialize the transport structures, this is callled once
 * at NvRmOpen time.
 */
NvError NvRmTransportInit(NvRmDeviceHandle hRmDevice)
{
    NvError err;

    NvOsMemset(&s_TransportInfo, 0, sizeof(s_TransportInfo));
    s_TransportInfo.hDevice = hRmDevice;
   
    err = NvOsMutexCreate(&s_TransportInfo.mutex);
    if (err)
        goto fail;

#if !NVOS_IS_WINDOWS || NVOS_IS_WINDOWS_CE 
    err = NvRmPrivXpcCreate(hRmDevice, &s_TransportInfo.hXpc);
    if (err)
        goto fail;

    NvRmPrivTransportAllocBuffers(hRmDevice);
#endif

    if (1)  // Used in EMUTRANS mode where the buffers cannot be mapped.
    {
        s_TmpIsrMsgBuffer = NvOsAlloc(MAX_MESSAGE_LENGTH);
        if (!s_TmpIsrMsgBuffer)
            goto fail;
    }

#if LOOPBACK_PROFILE
    {
        NvU32             TimerAddr;
        NvU32             TimerSize;
        
        NvRmModuleGetBaseAddress(hRmDevice, NvRmModuleID_TimerUs, &TimerAddr, &TimerSize);
        // map the us counter
        err = NvRmPhysicalMemMap(TimerAddr, TimerSize, NVOS_MEM_READ_WRITE,
            NvOsMemAttribute_Uncached, (void*)&s_TransportInfo.pTimer);
        if (err)
            goto fail;
    }
    
#endif

#if !NVOS_IS_WINDOWS || NVOS_IS_WINDOWS_CE 
    err = RegisterTransportInterrupt(hRmDevice);
    if (err)
        goto fail;
#endif
    s_Transport_Inited = NV_TRUE;
    return NvSuccess;


fail:
#if !NVOS_IS_WINDOWS || NVOS_IS_WINDOWS_CE 
    NvRmPrivXpcDestroy(s_TransportInfo.hXpc);
    NvRmPrivTransportFreeBuffers(hRmDevice);
#endif
    NvOsFree(s_TmpIsrMsgBuffer);
    NvOsMutexDestroy(s_TransportInfo.mutex);
    return err;
}

/**
 * DeInitialize the transport structures.
 */
void NvRmTransportDeInit(NvRmDeviceHandle hRmDevice)
{
    // Unregister the interrupts.
#if !NVOS_IS_WINDOWS || NVOS_IS_WINDOWS_CE 
    NvRmPrivXpcDestroy(s_TransportInfo.hXpc);
    NvRmPrivTransportFreeBuffers(hRmDevice);
    NvRmInterruptUnregister(hRmDevice, s_TransportInterruptHandle);
    s_TransportInterruptHandle = NULL;
#endif
    NvOsFree(s_TmpIsrMsgBuffer);
    NvOsMutexDestroy(s_TransportInfo.mutex);
}


static void
InsertPort(NvRmDeviceHandle hDevice, NvRmTransportHandle hPort)
{
    hPort->pNext = s_TransportInfo.pPortHead;
    s_TransportInfo.pPortHead = hPort;
}


static NvRmTransportHandle
FindPort(NvRmDeviceHandle hDevice, char *pPortName)
{
    NvRmTransportHandle hPort = NULL;
    NvRmTransportHandle hIter = NULL;

    hIter = s_TransportInfo.pPortHead;
    while (hIter)
    {
        if ( NvOsStrcmp(pPortName, hIter->PortName) == 0)
        {
            hPort = hIter;
            break;
        }
        hIter = hIter->pNext;
    }

    return hPort;
}


// Remove the given hPort from the list of ports
static void
DeletePort(NvRmDeviceHandle hRmDevice, const NvRmTransportHandle hPort)
{
    // Pointer to the pointer alleviates all special cases in linked list walking.
    // I wish I was clever enough to have figured this out myself. 

    NvRmTransportHandle *hIter;

    hIter = &s_TransportInfo.pPortHead;
    while (*hIter)
    {
        if ( *hIter == hPort )
        {
            *hIter = (*hIter)->pNext;
            break;
        }
        hIter = &(*hIter)->pNext;
    }
}




/**
 * Open the port handle with a given port name. With the same name, only two
 * port can be open.
 * Thread Safety: It is done inside the function.
 */

NvError
NvRmTransportOpen(
    NvRmDeviceHandle hRmDevice,
    char *pPortName,
    NvOsSemaphoreHandle RecvMessageSemaphore,
    NvRmTransportHandle *phTransport)
{
    NvU32               PortNameLen;
    NvRmTransportHandle hPartner = NULL;
    NvRmTransportHandle hPort    = NULL;
    NvError             err      = NvError_InsufficientMemory;
    char                TmpName[MAX_PORT_NAME_LENGTH+1];

    while (!s_Transport_Inited) {
        // This can happen, if this API is called before avp init.
        NvOsSleepMS(500);
    }
    // Look and see if this port exists anywhere.
    if (pPortName == NULL)
    {
        NvOsMutexLock(s_TransportInfo.mutex);

        pPortName = NvRmPrivTransportUniqueName();
        PortNameLen = NvOsStrlen(pPortName);
        NvOsStrncpy(TmpName, pPortName, sizeof(TmpName) );
        pPortName = TmpName;

        NvOsMutexUnlock(s_TransportInfo.mutex);
    }
    else
    {
        PortNameLen = NvOsStrlen(pPortName);
        NV_ASSERT(PortNameLen <= MAX_PORT_NAME_LENGTH);
    }

    NvOsMutexLock(s_TransportInfo.mutex);
    hPartner = FindPort(hRmDevice, pPortName);

    if (hPartner && hPartner->hConnectedPort != NULL)
    {
        NvOsMutexUnlock(s_TransportInfo.mutex);
        return NvError_TransportPortAlreadyExist;
    }

    // check if this is one of the special RPC ports used by the rm
    if ( NvOsStrcmp(pPortName, "RPC_AVP_PORT") == 0)
    {        
        //If someone else wants to open this port
        //just return the one already created.        
        if (hPartner)
        {
            hPort = hPartner;
            goto success;
        }
        else
        {
            hPort = &s_RpcAvpPortStruct;
            hPort->RecvMessageQueue.pReceiveMsg = (void *)&s_RpcAvpQueue[0];
        }
    }
    else if (NvOsStrcmp(pPortName, "RPC_CPU_PORT") == 0)
    {
        hPort = &s_RpcCpuPortStruct;
        hPort->RecvMessageQueue.pReceiveMsg = (void *)&s_RpcCpuQueue[0];
    }
    else
    {
        // Create a new TransportPort
        hPort = NvOsAlloc( sizeof(*hPort) );
        if (!hPort)
            goto fail;

        NvOsMemset(hPort, 0, sizeof(*hPort) );

        // Allocate the receive queue
        hPort->RecvMessageQueue.pReceiveMsg = NvOsAlloc( sizeof(RmReceiveMessage) * (MAX_MESSAGE_DEPTH+1));
        if (!hPort->RecvMessageQueue.pReceiveMsg)
            goto fail;
    }

    NvOsStrncpy(hPort->PortName, pPortName, PortNameLen);
    hPort->State =  PortState_Open;
    hPort->hConnectedPort = hPartner;

    if (RecvMessageSemaphore)
    {
        err = NvOsSemaphoreClone(RecvMessageSemaphore, &hPort->hOnPushMsgSem);
        if (err)
            goto fail;
    }

    hPort->RecvMessageQueue.QueueSize = MAX_MESSAGE_DEPTH+1;
    hPort->hRmDevice = hRmDevice;

    if (hPort->hConnectedPort != NULL)
    {
        hPort->hConnectedPort->hConnectedPort = hPort;
    }
    InsertPort(hRmDevice, hPort);


    // !!! loopback info
#if LOOPBACK_PROFILE 
    if (NvOsStrcmp(hPort->PortName, "LOOPTEST") == 0)
        hPort->bLoopTest = 1;
#endif

success:
    NvOsMutexUnlock(s_TransportInfo.mutex);
    *phTransport = hPort;
    return NvSuccess;

fail:
    if (hPort)
    {
        NvOsFree(hPort->RecvMessageQueue.pReceiveMsg);
        NvOsSemaphoreDestroy(hPort->hOnPushMsgSem);
        NvOsFree(hPort);
        hPort = NULL;
    }
    NvOsMutexUnlock(s_TransportInfo.mutex);

    return err;
}


/**
 * Close the transport handle
 * Thread Safety: It is done inside the function.
 */
void NvRmTransportClose(NvRmTransportHandle hPort)
{
    NvU32 RemoteMessage[4];

    if (!hPort)
        return;

    // Look and see if this port exists anywhere.
    NV_ASSERT(hPort);

    
    NvOsMutexLock(s_TransportInfo.mutex);
    DeletePort(hPort->hRmDevice, hPort);  // unlink this port

    // Check if there is already a port waiting to connect, and if there is
    // switch the port state to _Destroy, and signal the waiters semaphore.
    // The "State" member is not protected by the mutex because it can be
    // updated by the ISR.
    while (hPort->State == PortState_Waiting)
    {
        NvOsAtomicCompareExchange32((NvS32*)&hPort->State, PortState_Waiting, PortState_Destroy);
        if (hPort->State == PortState_Destroy)
        {
            NvOsSemaphoreSignal(hPort->hOnConnectSem);

            // in this case, we can't complete the destroy, the signalled thread will
            // have to complete.  We just return now
            NvOsMutexUnlock(s_TransportInfo.mutex);
            return;
        }
    }

    if (hPort->hConnectedPort)
    {
        // unlink this port from the other side of the connection.
        hPort->hConnectedPort->hConnectedPort = NULL;
    }
    
    if (hPort->RemotePort)
    {
        RemoteMessage[0] = TransportCmd_Disconnect;
        RemoteMessage[1] = hPort->RemotePort;
        NvRmPrivTransportSendMessage(hPort->hRmDevice, RemoteMessage, 2*sizeof(NvU32));
    }

    NvOsSemaphoreDestroy(hPort->hOnPushMsgSem);


    if (hPort == &s_RpcAvpPortStruct ||
        hPort == &s_RpcCpuPortStruct)
    {
        // don't free these..
        NvOsMemset(hPort, 0, sizeof(*hPort));
    }
    else
    {
        NvOsFree(hPort->RecvMessageQueue.pReceiveMsg);
        NvOsFree(hPort);
    }

    NvOsMutexUnlock(s_TransportInfo.mutex);
}


/**
 * Wait for the connection to the other end.
 * Thread Safety: It is done inside the function.
 */
NvError
NvRmTransportWaitForConnect(
    NvRmTransportHandle hPort,
    NvU32 TimeoutMS)
{
    NvOsSemaphoreHandle hSem = NULL;
    NvError             err  = NvSuccess;

    NvOsMutexLock(s_TransportInfo.mutex);
    if (hPort->State != PortState_Open)
    {
        NvOsMutexUnlock(s_TransportInfo.mutex);
        err = NvError_TransportPortAlreadyExist;
        goto exit_gracefully;
    }

    err = NvOsSemaphoreCreate(&hSem, 0);
    if (err)
    {
        NvOsMutexUnlock(s_TransportInfo.mutex);
        goto exit_gracefully;
    }
    
    hPort->hOnConnectSem = hSem;
    hPort->State = PortState_Waiting;
    NvOsMutexUnlock(s_TransportInfo.mutex);

    err = NvOsSemaphoreWaitTimeout(hSem, TimeoutMS);
    if (err)
    {
        // we have to be careful here, the ISR _might_ happen just after the semaphore
        // times out.
        NvOsAtomicCompareExchange32((NvS32 *)&hPort->State, PortState_Waiting, PortState_Open);
        NV_ASSERT(hPort->State == PortState_Open || hPort->State == PortState_Connected);
        if (hPort->State == PortState_Connected)
        {
            err = NvSuccess;
        }
    }

    NvOsMutexLock(s_TransportInfo.mutex);
    hPort->hOnConnectSem = NULL;
    NvOsMutexUnlock(s_TransportInfo.mutex);

    if (hPort->State == PortState_Destroy)
    {
        // finish the destroy process
        NvRmTransportClose(hPort);
        err = NvError_TransportConnectionFailed;
    }

exit_gracefully:
    NvOsSemaphoreDestroy(hSem);
    return err;
}



static NvError
NvRmPrivTransportWaitResponse(NvRmDeviceHandle hDevice, NvU32 *response, NvU32 ResponseLength, NvU32 TimeoutMS)
{
    NvU32   CurrentTime;
    NvU32   StartTime;
    NvU32   Response;
    NvBool  GotResponse = NV_TRUE;
    NvError err         = NvError_Timeout;
    volatile NvU32 *pXpcMessage = (volatile NvU32*)s_TransportInfo.pTransmitMem;

    if (pXpcMessage == NULL)
    {
        if (!NV_IS_AVP)
        {
            Response = NvRmMemRd32(s_TransportInfo.hMessageMem, 0);
        } else
        {
            NV_ASSERT(0);
            return NvSuccess;
        }
    }
    else
    {
        Response = pXpcMessage[0];
    }

    if (Response != TransportCmd_Response)
    {
        GotResponse = NV_FALSE;

        // response is not back yet, so spin till its here.
        StartTime = NvOsGetTimeMS();
        CurrentTime = StartTime;
        while ( (CurrentTime - StartTime) < TimeoutMS )
        {
            if ( pXpcMessage && (pXpcMessage[0] == TransportCmd_Response) )
            {
                GotResponse = NV_TRUE;
                break;
            }
            else if ( !pXpcMessage )
            {
                NV_ASSERT(!"Invalid pXpcMessage pointer is accessed");
            }
            CurrentTime = NvOsGetTimeMS();
        }
    }
    
    if ( pXpcMessage && GotResponse )
    {
        err = NvSuccess;
        NvOsMemcpy(response, (void *)pXpcMessage, ResponseLength);
    }

    return err;
}


static NvError
NvRmPrivTransportSendMessage(NvRmDeviceHandle hDevice, NvU32 *message, NvU32 MessageLength)
{
    NvU32 ReadData;

    if (s_TransportInfo.pTransmitMem == NULL)
    {
        /* QT/EMUTRANS takes this code path */
        if (!NV_IS_AVP)
        {
            ReadData = NvRmMemRd32(s_TransportInfo.hMessageMem, 0);
        } else
        {
            NV_ASSERT(0);
            return NvSuccess;
        }
    }
    else
    {
        ReadData = ((NvU32*)s_TransportInfo.pTransmitMem)[0];
    }

    // Check for clear to send
    if ( ReadData != 0)
        return NvError_TransportMessageBoxFull;  // someone else is sending a message

    if (s_TransportInfo.pTransmitMem == NULL)
    {
        /* QT/EMUTRANS takes this code path */
        NvRmMemWrite(s_TransportInfo.hMessageMem, 0, message, MessageLength);
    }
    else
    {
        NvOsMemcpy(s_TransportInfo.pTransmitMem, message, MessageLength);
        NvOsFlushWriteCombineBuffer();
    }
    NvRmPrivXpcSendMessage(s_TransportInfo.hXpc, s_TransportInfo.MessageMemPhysAddr);
    return NvSuccess;
}

NvError
NvRmTransportSendMsgInLP0(NvRmTransportHandle hPort, void *pMessageBuffer, NvU32 MessageSize)
{
    NvU32 ReadData;
    NvU32 Message[3 + ((MAX_MESSAGE_LENGTH) / sizeof(NvU32))];

    NV_ASSERT(pMessageBuffer);

    Message[0] = TransportCmd_Message;
    Message[1] = hPort->RemotePort;
    Message[2] = MessageSize;
   
    if (MessageSize)
        NvOsMemcpy(&Message[3], pMessageBuffer, MessageSize);

    ReadData = ((NvU32*)s_TransportInfo.pTransmitMem)[0];
    
    // Check for clear to send
    if ( ReadData != 0)
        return NvError_TransportMessageBoxFull;  // someone else is sending a message

    NvOsMemcpy(s_TransportInfo.pTransmitMem, Message, MessageSize + 3*sizeof(NvU32));
    NvOsFlushWriteCombineBuffer();

    NvRmPrivXpcSendMessage(s_TransportInfo.hXpc, s_TransportInfo.MessageMemPhysAddr);
    return NvSuccess;
}

static void
NvRmPrivTransportClearSend(NvRmDeviceHandle hDevice)
{
    if (s_TransportInfo.pTransmitMem == NULL)
    {
        /* QT/EMUTRANS take this path */
        if (!NV_IS_AVP)
        {
            NvRmMemWr32(s_TransportInfo.hMessageMem, 0, TransportCmd_None);
        } else
        {
            NV_ASSERT(0);
        }
    }
    else
    {
        ((NvU32*)s_TransportInfo.pTransmitMem)[0] = TransportCmd_None;
    }
}

/**
 * Make the connection to the other end.
 * Thread Safety: It is done inside the function.
 */
NvError NvRmTransportConnect(NvRmTransportHandle hPort, NvU32 TimeoutMS)
{
    NvRmTransportHandle hPartnerPort;
    NvU32               StartTime;
    NvU32               CurrentTime;
    NvU32               ConnectMessage[ MAX_PORT_NAME_LENGTH/4 + 3];
    NvError             err;
    

    // Look and see if there is a local port with the same name that is currently waiting, if there is
    // mark both ports as connected.

    NV_ASSERT(hPort);
    NV_ASSERT(hPort->hRmDevice);
    NV_ASSERT(hPort->State == PortState_Open);


    StartTime = NvOsGetTimeMS();
    for (;;)
    {
        // Someone is waiting for a connection here locally.
        NvOsMutexLock(s_TransportInfo.mutex);

        hPartnerPort = hPort->hConnectedPort;
        if (hPartnerPort)
        {
            // Found a local connection
            if (hPartnerPort->State == PortState_Waiting)
            {

                hPartnerPort->State = PortState_Connected;
                hPartnerPort->hConnectedPort = hPort;

                hPort->State = PortState_Connected;
                NvOsSemaphoreSignal(hPartnerPort->hOnConnectSem);
                break;
            }
        }
        else if (s_TransportInfo.hMessageMem || s_TransportInfo.pReceiveMem)  // if no shared buffer, then we can't create a remote connection.
        {
            ConnectMessage[0] = TransportCmd_Connect;
            ConnectMessage[1] = (NvU32)hPort;
            NvOsMemcpy(&ConnectMessage[2], hPort->PortName, MAX_PORT_NAME_LENGTH);
            
            err = NvRmPrivTransportSendMessage(hPort->hRmDevice, ConnectMessage, sizeof(ConnectMessage));
            if (!err)
            {
                // should send back 2 words of data.  Give remote side 1000ms to respond, which should be about 100x more
                // than it needs.
                NvU32 WaitTime = NV_MAX(1000, TimeoutMS);
                if (TimeoutMS == NV_WAIT_INFINITE)
                    TimeoutMS = NV_WAIT_INFINITE;

                // !!! Note, we can do this without holding the mutex...
                err = NvRmPrivTransportWaitResponse(hPort->hRmDevice, ConnectMessage, 2*sizeof(NvU32), WaitTime);
                NvRmPrivTransportClearSend(hPort->hRmDevice);
                if (err)
                {
                    // the other side is not responding to messages, doh!
                    NvOsMutexUnlock(s_TransportInfo.mutex);
                    return NvError_TransportConnectionFailed;
                }

                // check the response
                hPort->RemotePort = ConnectMessage[1];
                if (hPort->RemotePort != 0)
                {
                    hPort->State = PortState_Connected;
                    break;
                }
            }
        }
        NvOsMutexUnlock(s_TransportInfo.mutex);
        NV_ASSERT(hPort->State == PortState_Open);  // it better still be open

        // Didn't find a connection, wait a few ms and then try again
        CurrentTime = NvOsGetTimeMS();
        if ( (CurrentTime - StartTime) > TimeoutMS )
            return NvError_Timeout;
        
        NvOsSleepMS(10);
    }

    NvOsMutexUnlock(s_TransportInfo.mutex);
    return NvSuccess;
}


/**
 * Set the queue depth and message size of the transport handle.
 * Thread Safety: It is done inside the function.
 */
NvError NvRmTransportSetQueueDepth(
    NvRmTransportHandle hPort,
    NvU32 MaxQueueDepth,
    NvU32 MaxMessageSize)
{
    RmReceiveMessage *pNewReceiveMsg = NULL;

    NV_ASSERT(hPort != NULL);
    NV_ASSERT(MaxQueueDepth != 0);
    NV_ASSERT(MaxMessageSize != 0);

    // You cannot change the queue after a connection has been opened
    NV_ASSERT(hPort->State == PortState_Open);

    // !!! FIXME
    // Xpc does not allow changing the base message size, so we can't change the message size here (yet!)
    // Once we have per port message buffers we can set this.
    NV_ASSERT(MaxMessageSize <= MAX_MESSAGE_LENGTH);

    // These are statically allocated ports, they cannot be modified!
    // !!! FIXME: this is just a sanity check.  Remove this and make it so that
    //            cpu/avp rpc doesn't call this function and just knows that the
    //            transport will give it a port with a large enough queue to support
    //            rpc, since rpc ports and queue are statically allocated this has to be true.
    if (hPort == &s_RpcAvpPortStruct ||
        hPort == &s_RpcCpuPortStruct)
    {
        if (MaxMessageSize <= MAX_MESSAGE_LENGTH &&
            MaxQueueDepth <= MAX_MESSAGE_DEPTH)
        {
            return NvSuccess;
        }
        
        NV_ASSERT(!" Illegal meesage length or queue depth. ");
    }

    // Freeing default allocated message queue.
    NvOsFree(hPort->RecvMessageQueue.pReceiveMsg);
    hPort->RecvMessageQueue.pReceiveMsg = NULL;
    // create a new message queue struct, one longer than requested on purpose.
    pNewReceiveMsg = NvOsAlloc( sizeof(RmReceiveMessage) * (MaxQueueDepth+1));
    if (pNewReceiveMsg == NULL)
        return NvError_InsufficientMemory;

    hPort->RecvMessageQueue.pReceiveMsg = pNewReceiveMsg;
    hPort->RecvMessageQueue.QueueSize = (NvU16)(MaxQueueDepth+1);

    return NvSuccess;
}


static NvError
NvRmPrivTransportSendRemoteMsg(
    NvRmTransportHandle hPort,
    void* pMessageBuffer,
    NvU32 MessageSize,
    NvU32 TimeoutMS)
{
    NvError err;
    NvU32 StartTime;
    NvU32 CurrentTime;
    NvU32 Message[3 + ((MAX_MESSAGE_LENGTH) / sizeof(NvU32))];

    NV_ASSERT((MAX_MESSAGE_LENGTH) >= MessageSize);

    StartTime = NvOsGetTimeMS();

    Message[0] = TransportCmd_Message;
    Message[1] = hPort->RemotePort;
    Message[2] = MessageSize;
   
    NvOsMemcpy(&Message[3], pMessageBuffer, MessageSize);

    for (;;)
    {
        NvOsMutexLock(s_TransportInfo.mutex);
        err = NvRmPrivTransportSendMessage(hPort->hRmDevice, Message, MessageSize + 3*sizeof(NvU32));
        NvOsMutexUnlock(s_TransportInfo.mutex);
        if (err == NvSuccess)
        {
            return NvSuccess;
        }

        // Sleep and then try again in a few ms to send again
        CurrentTime = NvOsGetTimeMS();
        if ( TimeoutMS != NV_WAIT_INFINITE && (CurrentTime - StartTime) > TimeoutMS )
            return NvError_Timeout;
        
        NvOsSleepMS(1); // try again later...
    }
}



static NvError
NvRmPrivTransportSendLocalMsg(
    NvRmTransportHandle hPort,
    void* pMessageBuffer,
    NvU32 MessageSize,
    NvU32 TimeoutMS)
{
    NvU32  CurrentTime;
    NvU32  StartTime;
    NvError err            = NvSuccess;

    NvRmTransportHandle hRemotePort;

    NvOsMutexLock(s_TransportInfo.mutex);
    hRemotePort = hPort->hConnectedPort;


    StartTime = NvOsGetTimeMS();

    for (;;)
    {
        // try to insert into the message into the receivers queue.
        NvBool bSuccess = InsertMessage(hRemotePort, (NvU8*)pMessageBuffer, MessageSize);
        if (bSuccess)
        {
            if (hRemotePort->hOnPushMsgSem)
                NvOsSemaphoreSignal(hRemotePort->hOnPushMsgSem);
            break;
        }
        
        // The destination port is full.
        if (TimeoutMS == 0)
        {
            err = NvError_TransportMessageBoxFull;
            break;
        }

        // The user wants a timeout, so we just sleep a short time so the
        // other thread can pop a message.  It would be better to use another semaphore
        // to indicate that the box is not full, but that just seems overkill since this
        // should rarely happen anyhow.
        // unlock the mutex, and wait a small amount of time.
        NvOsMutexUnlock(s_TransportInfo.mutex);

        NvOsSleepMS(1);
        NvOsMutexLock(s_TransportInfo.mutex);
        if (TimeoutMS != NV_WAIT_INFINITE)
        {
            // check for a timeout condition.
            CurrentTime = NvOsGetTimeMS();
            if ( (CurrentTime - StartTime) >= TimeoutMS)
            {
                err = NvError_Timeout;
                break;
            }
        }
    }
    NvOsMutexUnlock(s_TransportInfo.mutex);

    return err;
}


/**
 * Send the message to the other end port.
 * Thread Safety: It is done inside the function.
 */
NvError
NvRmTransportSendMsg(
    NvRmTransportHandle hPort,
    void* pMessageBuffer,
    NvU32 MessageSize,
    NvU32 TimeoutMS)
{
    NvError err;

    NV_ASSERT(hPort);
    NV_ASSERT(hPort->State == PortState_Connected);
    NV_ASSERT(pMessageBuffer);

#if LOOPBACK_PROFILE
    if (hPort->bLoopTest)
    {
# if NV_IS_AVP
        ((NvU32*)pMessageBuffer)[LOOP_AVP_SEND_INDEX] = *s_TransportInfo.pTimer;
# else
        ((NvU32*)pMessageBuffer)[LOOP_CPU_SEND_INDEX] = *s_TransportInfo.pTimer;
# endif
    }
#endif

    if (hPort->hConnectedPort)
    {
        err = NvRmPrivTransportSendLocalMsg(hPort, pMessageBuffer, MessageSize, TimeoutMS);
    }
    else if (hPort->State == PortState_Connected)
    {
        err = NvRmPrivTransportSendRemoteMsg(hPort, pMessageBuffer, MessageSize, TimeoutMS);
    }
    else
    {
        NV_ASSERT(0);  // someone did something naughty
        err = NvError_TransportNotConnected;
    }

    return err;
}



/**
 * Receive the message from the other end port.
 * Thread Safety: It is done inside the function.
 */
NvError
NvRmTransportRecvMsg(
    NvRmTransportHandle hPort,
    void* pMessageBuffer,
    NvU32 MaxSize,
    NvU32 *pMessageSize)
{
    NvU8 TmpMessage[MAX_MESSAGE_LENGTH];

    NV_ASSERT(hPort);
    NV_ASSERT( (hPort->State == PortState_Connected) || (hPort->State == PortState_Disconnected) );
    NV_ASSERT(pMessageBuffer);
    NV_ASSERT(pMessageSize);


    NvOsMutexLock(s_TransportInfo.mutex);
    if (hPort->RecvMessageQueue.ReadIndex == hPort->RecvMessageQueue.WriteIndex)
    {
        NvOsMutexUnlock(s_TransportInfo.mutex);
        return NvError_TransportMessageBoxEmpty;
    }
    
    ExtractMessage(hPort, (NvU8*)pMessageBuffer, pMessageSize, MaxSize);
    if (*pMessageSize > MaxSize)
    {
        // not enough room to copy the message
        NvOsMutexUnlock(s_TransportInfo.mutex);
        NV_ASSERT(!" RM Transport: Illegal message size. ");
    }


    // if there was backpressure asserted, try to handle the currently posted message, and re-enable messages
    if (s_TransportInfo.ReceiveBackPressureOn != s_TransportInfo.ReceiveBackPressureOff)
    {
        NV_ASSERT( ((NvU8)s_TransportInfo.ReceiveBackPressureOn) == ((NvU8)(s_TransportInfo.ReceiveBackPressureOff+1)) );
        ++s_TransportInfo.ReceiveBackPressureOff;

        if (s_TransportInfo.pReceiveMem == NULL)
        {
            /* QT/EMUTRANS takes this path. */
            NvRmMemRead(s_TransportInfo.hMessageMem, 
                        MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE,
                        TmpMessage,
                        MAX_MESSAGE_LENGTH);
            HandlePortMessage(hPort->hRmDevice, (volatile void *)TmpMessage);
            NvRmMemWrite(s_TransportInfo.hMessageMem,
                         MAX_MESSAGE_LENGTH + MAX_COMMAND_SIZE,
                         TmpMessage,
                         2*sizeof(NvU32) );
        }
        else
        {
            HandlePortMessage(hPort->hRmDevice, (NvU32*)s_TransportInfo.pReceiveMem);
        }
    }

#if LOOPBACK_PROFILE
    if (hPort->bLoopTest)
    {
# if NV_IS_AVP
        ((NvU32*)pMessageBuffer)[LOOP_AVP_RECV_INDEX] = *s_TransportInfo.pTimer;
# else
        ((NvU32*)pMessageBuffer)[LOOP_CPU_RECV_INDEX] = *s_TransportInfo.pTimer;
# endif
    }
#endif

    NvOsMutexUnlock(s_TransportInfo.mutex);

    return NvSuccess;
}

void 
NvRmTransportGetPortName( 
    NvRmTransportHandle hPort,
    NvU8 *PortName,
    NvU32 PortNameSize )
{
    NvU32 len;

    NV_ASSERT(hPort);
    NV_ASSERT(PortName);

    len = NvOsStrlen(hPort->PortName);
    if (len >= PortNameSize)
    {
        NV_ASSERT(!" RM Transport: Port Name too long. ");
    }

    NvOsStrncpy((char *)PortName, hPort->PortName, PortNameSize);
}