summaryrefslogtreecommitdiff
path: root/arch/arm/mach-tegra/nvrm/core/common/nvrm_power.c
blob: e1936360e7ac8b651f6575ed4361372397c1ce06 (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
/*
 * Copyright (c) 2007-2009 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:
 *           Power Resource manager </b>
 *
 * @b Description: Implements the interface of the NvRM Power.
 *
 */

#include "nvrm_power_private.h"
#include "nvrm_pmu_private.h"
#include "ap15/ap15rm_private.h"
#include "ap15/project_relocation_table.h"
#include "nvassert.h"
#include "nvrm_hwintf.h"
#include "ap15/arapbpm.h"
#include "nvrm_clocks.h"
#include "nvodm_query.h"

// TODO: Always Disable before check-in
// Module debug: 0=disable, 1=enable
#define NVRM_POWER_ENABLE_PRINTF (0)

// TODO: Always Disable before check-in
// Report every change in RM clients power state: 0=disable, 1=enable
#define NVRM_POWER_VERBOSE_PRINTF (0)

#if NVRM_POWER_ENABLE_PRINTF || NVRM_POWER_VERBOSE_PRINTF
#define NVRM_POWER_PRINTF(x)   NvOsDebugPrintf x
#else
#define NVRM_POWER_PRINTF(x)
#endif

// Active modules report on suspend entry : 0=disable, 1=enable
#define NVRM_POWER_DEBUG_SUSPEND_ENTRY (1)

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

// Specifies initial registry size as well as delta for dynamic size change
#define NVRM_POWER_REGISTRY_DELTA (NvRmPrivModuleID_Num)

/*
 * Convert registry index to client ID and vice versa: just use
 * provided mask as high bits combined with index in low bits
 * (index is expected to not exceed 16 bits ever)
 */
#define NVRM_POWER_INDEX2ID(index, mask) (((mask) << 16) | (index))
#define NVRM_POWER_ID2INDEX(id) ((id) & 0xFFFF)


/*
 * Holds power client voltage request information for a
 * particular module
 */
typedef struct ModuleVoltageReqRec
{
    // Target module (combined ID and instance)
    NvRmModuleID ModuleId;

    // Power group number module belongs to
    NvU32 PowerGroup;

    // Module power cycle indicator
    NvBool PowerCycled;

    // Requested voltage range
    NvRmMilliVolts MinVolts;
    NvRmMilliVolts MaxVolts;

    // Pointer to the next module info node
    struct ModuleVoltageReqRec* pNext;
} ModuleVoltageReq;

/*
 * Holds power client clock request information for a
 * particular module
 */
typedef struct ModuleClockReqRec
{
    // TODO: Define clock request information members

    // Pointer to the next module info node
    struct ModuleClockReqRec* pNext;
} ModuleClockReq;

/*
 * Holds power client busy hint information for a
 * particular clock domain
 */
typedef struct BusyHintReqRec
{
    // Requested busy pulse mode
    NvBool BusyPulseMode;

    // Requested frequency boost in KHz
    NvRmFreqKHz BoostKHz;

    // Requested boost interval in ms
    NvU32 IntervalMs;

    // Boost start time in ms
    NvU32 StartTimeMs;

    // Id of the requester
    NvU32 ClientId;

    // Pointer to the next busy hint node
    struct BusyHintReqRec* pNext;
} BusyHintReq;

/*
 * Combines voltage and clock requets, starvation and busy hints,
 * as well as recorded power events for a particular client
 */
typedef struct NvRmPowerClientRec
{
    // Client registration ID
    NvU32 id;

    // Client semaphore for power management event signaling
    NvOsSemaphoreHandle hEventSemaphore;

    // Last detected power management event
    NvRmPowerEvent Event;

    // Pointer to the array of starvation hints
    NvBool* pStarvationHints;

    // Head pointer to client volatge request list
    ModuleVoltageReq* pVoltageReqHead;

    // Head pointer to client clock request list
    ModuleClockReq* pClockReqHead;

    // Client 4-character tag
    NvU32 tag;
} NvRmPowerClient;

/*
 * Combines information on power clients registred
 * with RM
 */
typedef struct NvRmPowerRegistryRec
{
    // Array of pointers to power client records
    NvRmPowerClient** pPowerClients;

    // Used index range (max used entry index + 1)
    NvU32 UsedIndexRange;

    // Total number of available entries (array size)
    NvU32 AvailableEntries;
} NvRmPowerRegistry;

// RM power clients registry
static NvRmPowerRegistry s_PowerRegistry;

// Mutex for thread-safe access to RM power clients records
static NvOsMutexHandle s_hPowerClientMutex = NULL;

// "Power On" request reference count for each SoC Power Group. Appended
// at the end is a duplicate entry for NPG group that represents power
// requirements for autonomous h/w operations with no s/w activity
static NvU32 s_PowerOnRefCounts[NV_POWERGROUP_MAX + 1];
#define NVRM_POWERGROUP_NPG_AUTO (NV_POWERGROUP_MAX)

// Active starvation hints reference count for each DFS clock domain
static NvU32 s_StarveOnRefCounts[NvRmDfsClockId_Num];

// Heads of busy hint lists for DFS clock domain
static BusyHintReq s_BusyReqHeads[NvRmDfsClockId_Num];

// Busy requests pool
#define NVRM_BUSYREQ_POOL_SIZE (24)
static BusyHintReq s_BusyReqPool[NVRM_BUSYREQ_POOL_SIZE];
static BusyHintReq* s_pFreeBusyReqPool[NVRM_BUSYREQ_POOL_SIZE];
static NvU32 s_FreeBusyReqPoolSize = 0;

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

/*
 * Release memory and system resources allocated for the specified power client
 */
static void FreePowerClient(NvRmPowerClient* pPowerClient);

/*
 * Cancel all requests issued by the specified power client
 */
static void CancelPowerRequests(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmPowerClient* pPowerClient);

/*
 * Notifies RM Clients about power management event
 */
static void
PowerEventNotify(NvRmDeviceHandle hRmDeviceHandle, NvRmPowerEvent Event);

/*
 * Records power cycle for all RM clients in the specified group
 */
static void
RecordPowerCycle(NvRmDeviceHandle hRmDeviceHandle, NvU32 PowerGroup);

/*
 * Reports combined RM clients power state to OS adaptation layer
 * (chip-aware implementation)
 */
static void
ReportRmPowerState(NvRmDeviceHandle hRmDeviceHandle);

/*
 * Manages busy request pool
 */
static BusyHintReq* BusyReqAlloc(void);
static void BusyReqFree(BusyHintReq* pBusyHintReq);

/*
 * Cancels busy hints reported by the specified client for
 * specified domain
 */
static void
CancelBusyHints(NvRmDfsClockId ClockId, NvU32 ClientId);

/*
 * Records starvation hints reported against DFS domains by
 * the specified client
 */
static NvError
RecordStarvationHints(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmPowerClient* pPowerClient,
    const NvRmDfsStarvationHint* pMultiHint,
    NvU32 NumHints);

/*
 * Records busy hints reported against DFS domains by
 * the specified client
 */
static NvError
RecordBusyHints(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32 ClientId,
    const NvRmDfsBusyHint* pMultiHint,
    NvU32 NumHints,
    NvBool* pSignalDfs);

/* Send a simple message to the AVP indicating that it needs
 * to save state in preparation for LP0 (explicit case)
 */
NvError
NvRmPrivSendAVPIdleMessage( NvRmDeviceHandle hRmDeviceHandle );

/*****************************************************************************/
static void FreePowerClient(NvRmPowerClient* pPowerClient)
{
    ModuleVoltageReq* pVoltageReq = NULL;
    ModuleClockReq* pClockReq = NULL;

    // Just return if null-pointer
    if (pPowerClient == NULL)
        return;

    // Free memory occupied by voltage requests
    while (pPowerClient->pVoltageReqHead != NULL)
    {
        pVoltageReq = pPowerClient->pVoltageReqHead;
        pPowerClient->pVoltageReqHead = pVoltageReq->pNext;
        NvOsFree(pVoltageReq);
    }

    // Free memory occupied by clock requests
    while (pPowerClient->pClockReqHead != NULL)
    {
        pClockReq = pPowerClient->pClockReqHead;
        pPowerClient->pClockReqHead = pClockReq->pNext;
        NvOsFree(pClockReq);
    }

    // Free memory occupied by starvation hints array
    NvOsFree(pPowerClient->pStarvationHints);

    // Free power management event semaphore handle
    NvOsSemaphoreDestroy(pPowerClient->hEventSemaphore);

    // Free memory occupied by the client record
    NvOsFree(pPowerClient);
}

static void CancelPowerRequests(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmPowerClient* pPowerClient)
{
    NvU32 i;
    ModuleVoltageReq* pVoltageReq = NULL;

    // Cancel power On requests and update power planes as well as
    // combined RM clients power state accordingly
    pVoltageReq = pPowerClient->pVoltageReqHead;
    while (pVoltageReq != NULL)
    {
        if (pVoltageReq->MaxVolts != NvRmVoltsOff)
        {
            NvU32 PowerGroup = pVoltageReq->PowerGroup;
            pVoltageReq->MaxVolts = NvRmVoltsOff;

            NV_ASSERT(s_PowerOnRefCounts[PowerGroup] != 0);
            s_PowerOnRefCounts[PowerGroup]--;
            if (s_PowerOnRefCounts[PowerGroup] == 0)
            {
                NvRmPrivPowerGroupControl(hRmDeviceHandle, PowerGroup,
                    NV_FALSE);
                ReportRmPowerState(hRmDeviceHandle);
            }
        }
        pVoltageReq = pVoltageReq->pNext;
    }
    // Cancel starvation hints
    if (pPowerClient->pStarvationHints != NULL)
    {
        for (i = 0; i < NvRmDfsClockId_Num; i++)
        {
            if (pPowerClient->pStarvationHints[i])
            {
                pPowerClient->pStarvationHints[i] = NV_FALSE;
                if ((i == NvRmDfsClockId_Cpu) ||
                    (i == NvRmDfsClockId_Avp) ||
                    (i == NvRmDfsClockId_Vpipe))
                {
                    NV_ASSERT(s_StarveOnRefCounts[NvRmDfsClockId_Emc] != 0);
                    s_StarveOnRefCounts[NvRmDfsClockId_Emc]--;
                }
                NV_ASSERT(s_StarveOnRefCounts[i] != 0);
                s_StarveOnRefCounts[i]--;
            }
        }
    }

    // Cancle busy hints
    for (i = 0; i < NvRmDfsClockId_Num; i++)
    {
        CancelBusyHints(i, pPowerClient->id);
    }

    // TODO: Cancel clock requests issued by the client
}

/*****************************************************************************/
NvError NvRmPrivPowerInit(NvRmDeviceHandle hRmDeviceHandle)
{
    NvU32 i;
    NvError e;

    NV_ASSERT(hRmDeviceHandle);

    // Initialize registry
    s_PowerRegistry.pPowerClients = NULL;
    s_PowerRegistry.AvailableEntries = 0;
    s_PowerRegistry.UsedIndexRange = 0;

    // Clear busy head pointers as well as starvation and power plane
    // reference counts. Aalthough power plane references are cleared
    // here, the combined power state is not updated - it will kept as
    // set by the boot code, until the 1st client requests power.
    NvOsMemset(s_BusyReqHeads, 0, sizeof(s_BusyReqHeads));
    NvOsMemset(s_StarveOnRefCounts, 0, sizeof(s_StarveOnRefCounts));
    NvOsMemset(s_PowerOnRefCounts, 0, sizeof(s_PowerOnRefCounts));

    // Initialize busy requests pool
    NvOsMemset(s_BusyReqPool, 0, sizeof(s_BusyReqPool));
    for (i = 0; i < NVRM_BUSYREQ_POOL_SIZE; i++)
        s_pFreeBusyReqPool[i] = &s_BusyReqPool[i];
    s_FreeBusyReqPoolSize = NVRM_BUSYREQ_POOL_SIZE;

    // Create the RM registry mutex and initialize RM/OAL interface
    s_hPowerClientMutex = NULL;
    NV_CHECK_ERROR_CLEANUP(NvOsMutexCreate(&s_hPowerClientMutex));
    NV_CHECK_ERROR_CLEANUP(NvRmPrivOalIntfInit(hRmDeviceHandle));

    // Initialize power group control, and power gate SoC partitions
    NvRmPrivPowerGroupControlInit(hRmDeviceHandle);
    return NvSuccess;

fail:
    NvRmPrivOalIntfDeinit(hRmDeviceHandle);
    NvOsMutexDestroy(s_hPowerClientMutex);
    s_hPowerClientMutex = NULL;
    return e;
}


void NvRmPrivPowerDeinit(NvRmDeviceHandle hRmDeviceHandle)
{
    NvU32 i;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;

    NV_ASSERT(hRmDeviceHandle);

    // TODO: expand after clock API is completed

    // Free busy hint lists for DFS clock domains
    for (i = 0; i < NvRmDfsClockId_Num; i++)
    {
        while (s_BusyReqHeads[i].pNext != NULL)
        {
            BusyHintReq* pBusyHintReq = s_BusyReqHeads[i].pNext;
            s_BusyReqHeads[i].pNext = pBusyHintReq->pNext;
            BusyReqFree(pBusyHintReq);
        }
    }
    // Free RM power registry memory
    for (i = 0; i < pRegistry->UsedIndexRange; i++)
    {
        FreePowerClient(pRegistry->pPowerClients[i]);
    }
    NvOsFree(pRegistry->pPowerClients);
    pRegistry->pPowerClients = NULL;
    pRegistry->AvailableEntries = 0;
    pRegistry->UsedIndexRange = 0;

    // Destroy RM registry mutex and free RM/OAL interface resources
    NvRmPrivOalIntfDeinit(hRmDeviceHandle);
    NvOsMutexDestroy(s_hPowerClientMutex);
    s_hPowerClientMutex = NULL;
}

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

NvError
NvRmPowerRegister(
    NvRmDeviceHandle hRmDeviceHandle,
    NvOsSemaphoreHandle hEventSemaphore,
    NvU32* pClientId)
{
    NvU32 FreeIndex;
    NvError error;
    NvOsSemaphoreHandle hSema = NULL;
    NvRmPowerClient* pNewClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;

    NV_ASSERT(hRmDeviceHandle);
    NV_ASSERT(pClientId);

    // If non-zero semaphore handle is passed, duplicate it to be avialable
    // after the call. Abort registration if non-zero handle is invalid
    if (hEventSemaphore != NULL)
    {
        error = NvOsSemaphoreClone(hEventSemaphore, &hSema);
        if (error != NvSuccess)
        {
            NV_ASSERT(!" Power Register Semaphore Clone error. ");
        }
    }

    NvOsMutexLock(s_hPowerClientMutex);

    // Find free registry entry for the new client
    for (FreeIndex = 0; FreeIndex < pRegistry->UsedIndexRange; FreeIndex++)
    {
        if (pRegistry->pPowerClients[FreeIndex] == NULL)
            break;
    }
    if (FreeIndex == pRegistry->AvailableEntries)
    {
        // If all avilable entries are used, re-size registry array
        NvU32 entries = pRegistry->AvailableEntries +
            NVRM_POWER_REGISTRY_DELTA;
        size_t s = sizeof(*pRegistry->pPowerClients) * (size_t)entries;
        NvRmPowerClient** p = NvOsRealloc(pRegistry->pPowerClients, s);
        if (p == NULL)
        {
            NvU32 old_size;

            /* fall back to NvOsAlloc */
            p = NvOsAlloc( s );
            if( p == NULL )
            {
                goto failed;
            }

            /* copy the old data, free, etc, */
            old_size = sizeof(*pRegistry->pPowerClients) *
                pRegistry->AvailableEntries;

            NvOsMemcpy( p, pRegistry->pPowerClients, old_size );
            NvOsFree( pRegistry->pPowerClients );
        }
        pRegistry->pPowerClients = p;
        pRegistry->AvailableEntries = entries;
    }
    if (FreeIndex == pRegistry->UsedIndexRange)
    {
        // If reached used index range boundary, advance it
        pRegistry->UsedIndexRange++;
    }

    // Allocate and store new client record pointer in registry (null-pointer
    // marks registry entry as free, so it's OK to store it before error check)
    pNewClient = NvOsAlloc(sizeof(*pNewClient));
    pRegistry->pPowerClients[FreeIndex] = pNewClient;
    if (pNewClient == NULL)
    {
        goto failed;
    }

    // Fill in new client entry
    pNewClient->hEventSemaphore = hSema;
    pNewClient->Event = NvRmPowerEvent_NoEvent;
    pNewClient->pVoltageReqHead = NULL;
    pNewClient->pClockReqHead = NULL;
    pNewClient->pStarvationHints = NULL;
    pNewClient->tag = *pClientId;

    /*
     * Combine index with client pointer into registration ID returned to the
     * client. This will make it a little bit more difficult for not-registered
     * clients to guess/re-use IDs
     */
    pNewClient->id = NVRM_POWER_INDEX2ID(FreeIndex, (NvU32)pClientId);
    *pClientId = pNewClient->id;

    NvOsMutexUnlock(s_hPowerClientMutex);
    return NvSuccess;

failed:
    NvOsFree(pNewClient);
    NvOsSemaphoreDestroy(hSema);
    NvOsMutexUnlock(s_hPowerClientMutex);
    return NvError_InsufficientMemory;
}

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

void NvRmPowerUnRegister(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32 ClientId)
{
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;
    NvU32 ClientIndex = NVRM_POWER_ID2INDEX(ClientId);

    NV_ASSERT(hRmDeviceHandle);

    NvOsMutexLock(s_hPowerClientMutex);

    // Check if this ID was registered
    if (ClientIndex < pRegistry->UsedIndexRange)
    {
        pPowerClient = pRegistry->pPowerClients[ClientIndex];
    }
    if ((pPowerClient == NULL) || (pPowerClient->id != ClientId))
    {
        NvOsMutexUnlock(s_hPowerClientMutex);
        return;
    }

    // Cancel power requets issued by the power client to be unregistered
    CancelPowerRequests(hRmDeviceHandle, pPowerClient);

    // Free power client memory and mark the respectve registry entry as free
    FreePowerClient(pPowerClient);
    pRegistry->pPowerClients[ClientIndex] = NULL;

    // Decrement used index range as much as possible
    while ((pRegistry->UsedIndexRange > 0) &&
           (pRegistry->pPowerClients[pRegistry->UsedIndexRange - 1] == NULL))
    {
        pRegistry->UsedIndexRange--;
    }

    // Shrink registry if too much free space (keep one delta margin)
    if ((pRegistry->UsedIndexRange + 2 * NVRM_POWER_REGISTRY_DELTA) <=
         pRegistry->AvailableEntries)
    {
        NvU32 entries = pRegistry->UsedIndexRange + NVRM_POWER_REGISTRY_DELTA;
        size_t s = sizeof(*pRegistry->pPowerClients) * (size_t)entries;
        NvRmPowerClient** p = NvOsRealloc(pRegistry->pPowerClients, s);
        if (p != NULL)
        {
            pRegistry->pPowerClients = p;
            pRegistry->AvailableEntries = entries;
        }

        // FIXME: handle NvOsRealloc failure -- try NvOsAlloc instead
    }
    NvOsMutexUnlock(s_hPowerClientMutex);
}

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

NvError NvRmPowerGetEvent(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32 ClientId,
    NvRmPowerEvent* pEvent)
{
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;
    NvU32 ClientIndex = NVRM_POWER_ID2INDEX(ClientId);

    NV_ASSERT(hRmDeviceHandle);
    NV_ASSERT(pEvent);

    NvOsMutexLock(s_hPowerClientMutex);

    // Check if this ID was registered; return error otherwise
    if (ClientIndex < pRegistry->UsedIndexRange)
    {
        pPowerClient = pRegistry->pPowerClients[ClientIndex];
    }
    if ((pPowerClient == NULL) || (pPowerClient->id != ClientId))
    {
        NvOsMutexUnlock(s_hPowerClientMutex);
        return NvError_BadValue;
    }

    // Return last recorded power event and set no outstanding events
    *pEvent = pPowerClient->Event;
    pPowerClient->Event = NvRmPowerEvent_NoEvent;

    NvOsMutexUnlock(s_hPowerClientMutex);
    return NvSuccess;
}

void NvRmPowerEventNotify(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmPowerEvent Event)
{
    NV_ASSERT(hRmDeviceHandle);

    // Just in case
    if (Event == NvRmPowerEvent_NoEvent)
         return;

    NvOsMutexLock(s_hPowerClientMutex);
    PowerEventNotify(hRmDeviceHandle, Event);
    NvOsMutexUnlock(s_hPowerClientMutex);
}

static void
PowerEventNotify(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmPowerEvent Event)
{
    NvU32 i;
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;

    NVRM_POWER_PRINTF(("%s is reported to RM clients\n",
        (Event == NvRmPowerEvent_WakeLP0)? "Wake from LP0" : "Wake from LP1"));

    // Restore clocks after LP0
    if (Event == NvRmPowerEvent_WakeLP0)
        NvRmPrivClocksResume(hRmDeviceHandle);

    // Store event for all registered clients, and signal only those, that
    // have provided valid semaphore handle; on wake from low power states
    // set power cycled indicators
    for (i = 0; i < pRegistry->UsedIndexRange; i++)
    {
        pPowerClient = pRegistry->pPowerClients[i];
        if (pPowerClient != NULL)
        {
            ModuleVoltageReq* pVoltageReq = pPowerClient->pVoltageReqHead;
            while (pVoltageReq != NULL)
            {
                if (Event == NvRmPowerEvent_WakeLP0)
                {
                    //LP0: all power groups, except AO group, are powered down
                    // when core power is down
                    if (pVoltageReq->PowerGroup != NV_POWERGROUP_AO)
                        pVoltageReq->PowerCycled = NV_TRUE;
                }
                else if (Event == NvRmPowerEvent_WakeLP1)
                {
                    // LP1: core power is preserved; but all  power groups
                    // except AO and NPG group are power gated
                    if ((pVoltageReq->PowerGroup != NV_POWERGROUP_AO) &&
                        (pVoltageReq->PowerGroup != NV_POWERGROUP_NPG))
                        pVoltageReq->PowerCycled = NV_TRUE;
                }
                pVoltageReq = pVoltageReq->pNext;
            }
            pPowerClient->Event = Event;
            if (pPowerClient->hEventSemaphore != NULL)
            {
                NvOsSemaphoreSignal(pPowerClient->hEventSemaphore);
            }
        }
    }
}

static void
RecordPowerCycle(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32 PowerGroup)
{
    NvU32 i;
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;

    NVRM_POWER_PRINTF(("Power Cycled partition: %d\n", PowerGroup));

    // Traverse registered clients, and mark all modules in the specified
    // power group as power cycled
    for (i = 0; i < pRegistry->UsedIndexRange; i++)
    {
        pPowerClient = pRegistry->pPowerClients[i];
        if (pPowerClient != NULL)
        {
            ModuleVoltageReq* pVoltageReq = pPowerClient->pVoltageReqHead;
            while (pVoltageReq != NULL)
            {
                if (pVoltageReq->PowerGroup == PowerGroup)
                {
                    pVoltageReq->PowerCycled = NV_TRUE;
                }
                pVoltageReq = pVoltageReq->pNext;
            }
        }
    }
}

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

static void
ReportRmPowerState(NvRmDeviceHandle hRmDeviceHandle)
{
    NvU32 i;
    NvRmPowerState OldRmState = NvRmPrivPowerGetState(hRmDeviceHandle);
    NvRmPowerState NewRmState = NvRmPowerState_Idle;

    // RM clients are in h/w autonomous (bypass) state if there are Power On
    // references for NPG_AUTO group only; RM clients are in active state if
    // there are Power On references for any other group
    if (s_PowerOnRefCounts[NVRM_POWERGROUP_NPG_AUTO] != 0)
        NewRmState = NvRmPowerState_AutoHw;

    for (i = 0; i < NV_POWERGROUP_MAX; i++)
    {
        if (s_PowerOnRefCounts[i] != 0)
        {
            NewRmState = NvRmPowerState_Active;
            break;
        }
    }
    if (NewRmState == OldRmState)
        return;

#if NVRM_POWER_VERBOSE_PRINTF
    NVRM_POWER_PRINTF(("RM Clients Power State: %s\n",
        ((NewRmState == NvRmPowerState_Active) ? "Active" :
         ((NewRmState == NvRmPowerState_AutoHw) ? "AutoHw" : "Idle"))));
#endif
    /*
     * Set new combined RM clients power state in the storage shared with the
     * OS adaptation layer. Check the previous state; if it was any of the low
     * power states (i.e., this is the 1st RM power state report after suspend)
     * notify all clients about wake up event.
     */
    NvRmPrivPowerSetState(hRmDeviceHandle, NewRmState);
    switch (OldRmState)
    {
        case NvRmPowerState_LP0:
            NvOsDebugPrintf("*** Wakeup from LP0 *** wake-source: 0x%x\n",
                    NV_REGR(hRmDeviceHandle, NvRmModuleID_Pmif, 0, 0x14));
            PowerEventNotify(hRmDeviceHandle, NvRmPowerEvent_WakeLP0);
            break;
        case NvRmPowerState_LP1:
            NvOsDebugPrintf("*** Wakeup from LP1 ***\n");
            PowerEventNotify(hRmDeviceHandle, NvRmPowerEvent_WakeLP1);
            break;
        case NvRmPowerState_SkippedLP0:
            NvOsDebugPrintf("*** Wakeup after Skipped LP0 ***\n");
            // resume procedure after Skipped LP0 is the same as after LP1
            PowerEventNotify(hRmDeviceHandle, NvRmPowerEvent_WakeLP1);
            break;
        default:
            break;
    }
}

NvError
NvRmPowerGetState(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmPowerState* pState)
{
    NV_ASSERT(hRmDeviceHandle);
    NV_ASSERT(pState);

    NvOsMutexLock(s_hPowerClientMutex);
    *pState = NvRmPrivPowerGetState(hRmDeviceHandle);
    NvOsMutexUnlock(s_hPowerClientMutex);
    return NvSuccess;
}

NvError
NvRmPowerVoltageControl(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmModuleID ModuleId,
    NvU32 ClientId,
    NvRmMilliVolts MinVolts,
    NvRmMilliVolts MaxVolts,
    const NvRmMilliVolts* PrefVoltageList,
    NvU32 PrefVoltageListCount,
    NvRmMilliVolts* pCurrentVolts)
{
    NvError error;
    NvU32 PowerGroup = 0;
    NvBool PowerChanged = NV_FALSE;
    NvRmModuleInstance *pInstance = NULL;
    ModuleVoltageReq* pVoltageReq = NULL;
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;
    NvU32 ClientIndex = NVRM_POWER_ID2INDEX(ClientId);

    /* validate the Rm Handle */
    NV_ASSERT(hRmDeviceHandle);

    // Validate module ID and get associated Power Group
    if (ModuleId == NvRmPrivModuleID_System)
    {
        PowerGroup = NVRM_POWERGROUP_NPG_AUTO;
    }
    else
    {
        error = NvRmPrivGetModuleInstance(hRmDeviceHandle, ModuleId, &pInstance);
        if (error != NvSuccess)
        {
            NV_ASSERT(!" Voltage control: Invalid module ID. ");
            return NvError_ModuleNotPresent;
        }
        PowerGroup = pInstance->DevPowerGroup;
        NV_ASSERT(PowerGroup < NV_POWERGROUP_MAX);
    }

    NvOsMutexLock(s_hPowerClientMutex);

    // Check if this ID was registered; return error otherwise
    if (ClientIndex < pRegistry->UsedIndexRange)
    {
        pPowerClient = pRegistry->pPowerClients[ClientIndex];
    }
    if ((pPowerClient == NULL) || (pPowerClient->id != ClientId))
    {
        NvOsMutexUnlock(s_hPowerClientMutex);
        return NvError_BadValue;
    }

    // Search for the previously recorded voltage request for this module
    pVoltageReq = pPowerClient->pVoltageReqHead;
    while ((pVoltageReq != NULL) && (pVoltageReq->ModuleId != ModuleId))
    {
        pVoltageReq = pVoltageReq->pNext;
    }

    // If it is a new voltage request record, allocate and fill it in,
    // otherwise just update power status. In both cases determine if
    // power requirements for the module have changed.
    if (pVoltageReq == NULL)
    {
        pVoltageReq = NvOsAlloc(sizeof(*pVoltageReq));
        if (pVoltageReq == NULL)
        {
            NvOsMutexUnlock(s_hPowerClientMutex);
            return NvError_InsufficientMemory;
        }
        // Link at head
        pVoltageReq->pNext = pPowerClient->pVoltageReqHead;
        pPowerClient->pVoltageReqHead = pVoltageReq;
        pVoltageReq->ModuleId = ModuleId;
        pVoltageReq->PowerGroup = PowerGroup;
        pVoltageReq->PowerCycled = NV_FALSE;

        // Only new power On request counts as change
        PowerChanged = (MaxVolts != NvRmVoltsOff);
    }
    else
    {
        // Only changes from On to Off or vice versa counts
        PowerChanged = (pVoltageReq->MaxVolts != MaxVolts) &&
                       ((pVoltageReq->MaxVolts == NvRmVoltsOff) ||
                        (MaxVolts == NvRmVoltsOff));
    }
    // Record new power request voltages
    pVoltageReq->MinVolts = MinVolts;
    pVoltageReq->MaxVolts = MaxVolts;

    // If module power requirements have changed, update power group reference
    // count, and execute the respective h/w power control procedure
    if (PowerChanged)
    {
        if (MaxVolts != NvRmVoltsOff)
        {
            s_PowerOnRefCounts[PowerGroup]++;
            if (s_PowerOnRefCounts[PowerGroup] == 1)
            {
                NvRmMilliVolts v =
                    NvRmPrivPowerGroupGetVoltage(hRmDeviceHandle, PowerGroup);
                if (v == NvRmVoltsOff)
                {
                    RecordPowerCycle(hRmDeviceHandle, PowerGroup);
                    NvRmPrivPowerGroupControl(hRmDeviceHandle, PowerGroup, NV_TRUE);
                }
            }
        }
        else
        {
            NV_ASSERT(s_PowerOnRefCounts[PowerGroup] != 0);
            if (s_PowerOnRefCounts[PowerGroup] == 0)
            {
                NVRM_POWER_PRINTF(("Power balance failed: module %d\n", ModuleId));
            }
            s_PowerOnRefCounts[PowerGroup]--;
            if (s_PowerOnRefCounts[PowerGroup] == 0)
            {
                NvRmPrivPowerGroupControl(hRmDeviceHandle, PowerGroup, NV_FALSE);
            }
        }
    }
    ReportRmPowerState(hRmDeviceHandle);

    // Return current voltage, unless this is the first request after module
    // was power cycled by RM; in the latter case return NvRmVoltsCycled value
    if (pCurrentVolts != NULL)
    {
        *pCurrentVolts = NvRmPrivPowerGroupGetVoltage(hRmDeviceHandle, PowerGroup);
        if (pVoltageReq->PowerCycled && (*pCurrentVolts != NvRmVoltsOff))
        {
            *pCurrentVolts = NvRmVoltsCycled;
        }
    }
    // In any case clear power cycled indicator
    pVoltageReq->PowerCycled = NV_FALSE;

    NvOsMutexUnlock(s_hPowerClientMutex);
    return NvSuccess;
}

void
NvRmListPowerAwareModules(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32* pListSize,
    NvRmModuleID* pIdList,
    NvBool* pActiveList)
{
    NvBool active;
    NvU32 i, ModulesNum, ActiveNum;
    ModuleVoltageReq* pVoltageReq = NULL;
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;


    /* validate the Rm Handle */
    NV_ASSERT(hRmDeviceHandle);
    NV_ASSERT(pListSize);
    NV_ASSERT(((*pListSize) == 0) || (pIdList && pActiveList));

    NvOsMutexLock(s_hPowerClientMutex);

    // Count power aware modules, fill in the list
    for (i = ModulesNum = ActiveNum = 0; i < pRegistry->UsedIndexRange; i++)
    {
        pPowerClient = pRegistry->pPowerClients[i];
        if (pPowerClient)
        {
            pVoltageReq = pPowerClient->pVoltageReqHead;
            while (pVoltageReq != NULL)
            {
                ModulesNum++;
                active = (pVoltageReq->MaxVolts != NvRmVoltsOff);
                ActiveNum += active ? 1 : 0;
                if (*pListSize >= ModulesNum)
                {
                    *(pIdList++) = pVoltageReq->ModuleId;
                    *(pActiveList++) = active;
                }
                pVoltageReq = pVoltageReq->pNext;
            }
        }
    }
    // Report number of found modules
    if ((*pListSize == 0) || (*pListSize > ModulesNum))
    {
        *pListSize = ModulesNum;
    }
    // Total refcounts must be = number of active modules
    for (i = 0; i <= NV_POWERGROUP_MAX; i++)
        ActiveNum -= s_PowerOnRefCounts[i];
    NV_ASSERT(ActiveNum == 0);

    NvOsMutexUnlock(s_hPowerClientMutex);
}

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

static NvError
RecordStarvationHints(
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmPowerClient* pPowerClient,
    const NvRmDfsStarvationHint* pMultiHint,
    NvU32 NumHints)
{
    NvU32 i;
    NvBool HintChanged = NV_FALSE;

    for (i = 0; i < NumHints; i++)
    {
        NvRmDfsClockId ClockId = pMultiHint[i].ClockId;
        NvBool Starving = pMultiHint[i].Starving;
        NV_ASSERT((0 < ClockId) && (ClockId < NvRmDfsClockId_Num));

        /*
         * If this is the first starvation hint, allocate hints array and fill
         * it in. Otherwise, just update starvation hint status. In both cases
         * determine if starvation hint for clock domain has changed.
         */
        if (pPowerClient->pStarvationHints == NULL)
        {
            size_t s = sizeof(NvBool) * (size_t)NvRmDfsClockId_Num;
            NvBool* p = NvOsAlloc(s);
            if (p == NULL)
            {
                return NvError_InsufficientMemory;
            }
            NvOsMemset(p, 0, s);
            pPowerClient->pStarvationHints = p;

            // Only new Satrvation On hint counts as change
            HintChanged = Starving;
        }
        else
        {
            // Only changes from On to Off or vice versa counts
            HintChanged = (pPowerClient->pStarvationHints[ClockId] != Starving);
        }
        pPowerClient->pStarvationHints[ClockId] = Starving;

        // If hint has changed, update clock domain starvation reference count
        // (hint against CPU, or AVP, or VDE is automatically applied to EMC)
        if (HintChanged)
        {
            if (Starving)
            {
                if ((ClockId == NvRmDfsClockId_Cpu) ||
                    (ClockId == NvRmDfsClockId_Avp) ||
                    (ClockId == NvRmDfsClockId_Vpipe))
                {
                    s_StarveOnRefCounts[NvRmDfsClockId_Emc]++;
                }
                s_StarveOnRefCounts[ClockId]++;
            }
            else
            {
                if ((ClockId == NvRmDfsClockId_Cpu) ||
                    (ClockId == NvRmDfsClockId_Avp) ||
                    (ClockId == NvRmDfsClockId_Vpipe))
                {
                    NV_ASSERT(s_StarveOnRefCounts[NvRmDfsClockId_Emc] != 0);
                    s_StarveOnRefCounts[NvRmDfsClockId_Emc]--;
                }
                NV_ASSERT(s_StarveOnRefCounts[ClockId] != 0);
                s_StarveOnRefCounts[ClockId]--;
            }
        }
    }
    return NvSuccess;
}

NvBool NvRmPrivDfsIsStarving(NvRmDfsClockId ClockId)
{
    NV_ASSERT((0 < ClockId) && (ClockId < NvRmDfsClockId_Num));
    // Boolean read - no need for lock
    return (s_StarveOnRefCounts[ClockId] != 0);
}

NvError
NvRmPowerStarvationHintMulti(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32 ClientId,
    const NvRmDfsStarvationHint* pMultiHint,
    NvU32 NumHints)
{
    NvError error;
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;
    NvU32 ClientIndex = NVRM_POWER_ID2INDEX(ClientId);

    NV_ASSERT(hRmDeviceHandle);
    NV_ASSERT(pMultiHint && NumHints);

    /* Do nothing on platforms where there is no freq scaling like QT and FPGA */
    if (NvRmPrivGetExecPlatform(hRmDeviceHandle) != ExecPlatform_Soc)
    {
        return NvSuccess;
    }
    // Do nothing if DFS is disabled, and therefore all clocks are maxed anyway
    if (NvRmDfsGetState(hRmDeviceHandle) <= NvRmDfsRunState_Disabled)
    {
        return NvSuccess;
    }

    NvOsMutexLock(s_hPowerClientMutex);

    // Check if this client ID was registered; return error otherwise
    if (ClientIndex < pRegistry->UsedIndexRange)
    {
        pPowerClient = pRegistry->pPowerClients[ClientIndex];
    }
    if ((pPowerClient == NULL) || (pPowerClient->id != ClientId))
    {
        NvOsMutexUnlock(s_hPowerClientMutex);
        return NvError_BadValue;
    }
    // Add new stravtion hint
    error = RecordStarvationHints(
        hRmDeviceHandle, pPowerClient, pMultiHint, NumHints);

    NvOsMutexUnlock(s_hPowerClientMutex);

    if (error == NvSuccess)
        NvRmPrivStarvationHintPrintf(
            ClientIndex, pPowerClient->tag, pMultiHint, NumHints);
    return error;
}

NvError
NvRmPowerStarvationHint (
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmDfsClockId ClockId,
    NvU32 ClientId,
    NvBool Starving)
{
    NvRmDfsStarvationHint StarvationHint;

    // Pack hit record
    StarvationHint.ClockId = ClockId;
    StarvationHint.Starving = Starving;

    return NvRmPowerStarvationHintMulti(
        hRmDeviceHandle, ClientId, &StarvationHint, 1);
}

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

static BusyHintReq* BusyReqAlloc(void)
{
    if (s_FreeBusyReqPoolSize != 0)
        return s_pFreeBusyReqPool[--s_FreeBusyReqPoolSize];
    else
    {
        NV_ASSERT(!"Busy pool size is too small");
        return NvOsAlloc(sizeof(BusyHintReq));
    }
}

static void BusyReqFree(BusyHintReq* pBusyHintReq)
{
    if ((pBusyHintReq >= &s_BusyReqPool[0]) &&
        (pBusyHintReq < &s_BusyReqPool[NVRM_BUSYREQ_POOL_SIZE]))
    {
        NV_ASSERT(s_FreeBusyReqPoolSize < NVRM_BUSYREQ_POOL_SIZE);
        s_pFreeBusyReqPool[s_FreeBusyReqPoolSize++] = pBusyHintReq;
        return;
    }
    NvOsFree(pBusyHintReq);
}

static void CancelBusyHints(NvRmDfsClockId ClockId, NvU32 ClientId)
{
    BusyHintReq* pBusyHintReq = NULL;
    BusyHintReq* pBusyHintNext = NULL;

    /*
     * Traverse busy hints list, starting from the head and looking for hints
     * reported by the specified client. Remove found hint nodes on the way.
     */
    pBusyHintReq = &s_BusyReqHeads[ClockId];
    if (pBusyHintReq->ClientId == ClientId)
    {
        pBusyHintReq->IntervalMs = 0;   // Keep head for just one more sample
    }
    while (pBusyHintReq != NULL)
    {
        pBusyHintNext = pBusyHintReq->pNext;
        if ((pBusyHintNext != NULL) && (pBusyHintNext->ClientId == ClientId))
        {
            pBusyHintReq->pNext = pBusyHintNext->pNext;
            BusyReqFree(pBusyHintNext);
            continue;
        }
        pBusyHintReq = pBusyHintNext;
    }
}

static void PurgeBusyHints(NvRmDfsClockId ClockId, NvU32 msec)
{
    static NvU32 s_LastPurgeMs = 0;
    BusyHintReq* pBusyHintReq = NULL;
    BusyHintReq* pBusyHintNext = NULL;

    if ((msec - s_LastPurgeMs) <= NVRM_DFS_BUSY_PURGE_MS)
        return;

    /*
     * If time to purge the busy hints list, traverse it starting from the
     * head and looking for the expired hints. Remove found nodes on the way.
     */
    pBusyHintReq = &s_BusyReqHeads[ClockId];
    while (pBusyHintReq != NULL)
    {
        pBusyHintNext = pBusyHintReq->pNext;
        if ( (pBusyHintNext != NULL) &&
             (pBusyHintNext->IntervalMs < (msec - pBusyHintNext->StartTimeMs)) )
        {
            pBusyHintReq->pNext = pBusyHintNext->pNext;
            BusyReqFree(pBusyHintNext);
            continue;
        }
        pBusyHintReq = pBusyHintNext;
    }
    s_LastPurgeMs = msec;
}

static NvError
RecordBusyHints(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32 ClientId,
    const NvRmDfsBusyHint* pMultiHint,
    NvU32 NumHints,
    NvBool* pSignalDfs)
{
    NvU32 i;
    NvRmFreqKHz MaxKHz;
    BusyHintReq* pInsert = NULL;
    BusyHintReq* pBusyHintReq = NULL;
    NvU32 msec = NvOsGetTimeMS();

    *pSignalDfs = NV_FALSE;

    for (i = 0; i < NumHints; i++)
    {
        NvRmDfsClockId ClockId = pMultiHint[i].ClockId;
        NvRmFreqKHz BoostKHz = pMultiHint[i].BoostKHz;
        NvU32 BoostDurationMs = pMultiHint[i].BoostDurationMs;
        NvBool BusyPulseMode = pMultiHint[i].BusyAttribute;
        NV_ASSERT((0 < ClockId) && (ClockId < NvRmDfsClockId_Num));

        // Clip requested boost frequency to domain maximum
        MaxKHz = NvRmPrivDfsGetMaxKHz(ClockId);
        if (BoostKHz > MaxKHz)
        {
            BoostKHz = MaxKHz;
        }

        // Cancel all hints sent by this client if it is no longer busy;
        // signal DFS boost removed
        if (BoostKHz == 0)
        {
            CancelBusyHints(ClockId, ClientId);
            *pSignalDfs = NV_TRUE;
            continue;
        }

        // Update maximum boost frequency stored in the head entry; signal DFS
        // boost increase
        if (s_BusyReqHeads[ClockId].BoostKHz < BoostKHz)
        {
            s_BusyReqHeads[ClockId].BoostKHz = BoostKHz;
            s_BusyReqHeads[ClockId].IntervalMs = BoostDurationMs;
            s_BusyReqHeads[ClockId].BusyPulseMode = BusyPulseMode;
            s_BusyReqHeads[ClockId].StartTimeMs = msec;
            s_BusyReqHeads[ClockId].ClientId = ClientId;
            *pSignalDfs = NV_TRUE;
        }

        /*
         * If it is a short spike no need to store the record, as maximum boost
         * has been already updated. Otherwise, insert new busy record into the
         * busy hints list in descending order of requested boost frequencies
         */
        if (BoostDurationMs > NVRM_DFS_BUSY_MIN_MS)
        {
            for (pInsert = &s_BusyReqHeads[ClockId] ;;)
            {
                if ((pInsert->pNext == NULL) ||
                    (pInsert->pNext->BoostKHz < BoostKHz))
                {
                    // Allocate and initialize new boost hint record
                    pBusyHintReq = BusyReqAlloc();
                    if (pBusyHintReq == NULL)
                    {
                        return NvError_InsufficientMemory;
                    }
                    pBusyHintReq->BoostKHz = BoostKHz;
                    pBusyHintReq->IntervalMs = BoostDurationMs;
                    pBusyHintReq->BusyPulseMode = BusyPulseMode;
                    pBusyHintReq->StartTimeMs = msec;
                    pBusyHintReq->ClientId = ClientId;
                    pBusyHintReq->pNext = pInsert->pNext;
                    pInsert->pNext = pBusyHintReq;
                    break;
                }
                else if (pInsert->pNext->BoostKHz == BoostKHz)
                {
                    // Combine hints from the same client with the same
                    // boost level and pulse mode
                    if ((pInsert->pNext->ClientId == ClientId) &&
                        (pInsert->pNext->BusyPulseMode == BusyPulseMode))
                    {
                        NvU32 t = msec - pInsert->pNext->StartTimeMs;
                        if ((BoostDurationMs > pInsert->pNext->IntervalMs) ||
                            (t > (pInsert->pNext->IntervalMs - BoostDurationMs)))
                        {
                            pInsert->pNext->StartTimeMs = msec;
                            pInsert->pNext->IntervalMs = BoostDurationMs;
                        }
                        break;
                    }
                }
                pInsert = pInsert->pNext;
            }
            PurgeBusyHints(ClockId, msec);  // Purge the list once in a while
        }
    }
    return NvSuccess;
}

void NvRmPrivDfsGetBusyHint(
    NvRmDfsClockId ClockId,
    NvRmFreqKHz* pBusyKHz,
    NvBool* pBusyPulseMode,
    NvU32* pBusyExpireMs)
{
    NvU32 msec;
    BusyHintReq* pBusyHintReq;

    NV_ASSERT((0 < ClockId) && (ClockId < NvRmDfsClockId_Num));

    // Boolean read - no need for lock - fast path for most common case
    // when no busy hints are recoeded
    if (s_BusyReqHeads[ClockId].BoostKHz == 0)
    {
        *pBusyKHz = 0;
        *pBusyPulseMode = NV_FALSE;
        *pBusyExpireMs = 0;
        return;
    }
    msec = NvOsGetTimeMS();

    NvOsMutexLock(s_hPowerClientMutex);
    /*
     * Get boost frequency from the head. Then, traverse busy hints list,
     * starting from the head looking for max non-expired frequency boost.
     * Remove expired nodes on the way. Update head boost frequency.
     */
    pBusyHintReq = &s_BusyReqHeads[ClockId];
    *pBusyKHz = pBusyHintReq->BoostKHz;
    *pBusyPulseMode = pBusyHintReq->BusyPulseMode;
    *pBusyExpireMs = 0;     // assume head hint has already expired
    if (pBusyHintReq->IntervalMs == NV_WAIT_INFINITE)
        *pBusyExpireMs = NV_WAIT_INFINITE;  // head hint until canceled
    else if (pBusyHintReq->IntervalMs >= (msec - pBusyHintReq->StartTimeMs))
        *pBusyExpireMs =                    // non-expired head hint
        pBusyHintReq->IntervalMs - (msec - pBusyHintReq->StartTimeMs);

    pBusyHintReq = pBusyHintReq->pNext;
    while (pBusyHintReq != NULL)
    {
        BusyHintReq* p;
        if (pBusyHintReq->IntervalMs >= (msec - pBusyHintReq->StartTimeMs))
        {
            break;
        }
        p = pBusyHintReq;
        pBusyHintReq = pBusyHintReq->pNext;
        BusyReqFree(p);
    }
    if (pBusyHintReq)
    {
        s_BusyReqHeads[ClockId] = *pBusyHintReq;
        s_BusyReqHeads[ClockId].pNext = pBusyHintReq;
    }
    else
        NvOsMemset(&s_BusyReqHeads[ClockId], 0, sizeof(s_BusyReqHeads[ClockId]));
    NvOsMutexUnlock(s_hPowerClientMutex);
}

NvError
NvRmPowerBusyHintMulti(
    NvRmDeviceHandle hRmDeviceHandle,
    NvU32 ClientId,
    const NvRmDfsBusyHint* pMultiHint,
    NvU32 NumHints,
    NvRmDfsBusyHintSyncMode Mode)
{
    NvError error;
    NvRmDfsRunState DfsState;
    NvBool SignalDfs = NV_FALSE;
    NvRmPowerClient* pPowerClient = NULL;
    NvRmPowerRegistry* pRegistry = &s_PowerRegistry;
    NvU32 ClientIndex = NVRM_POWER_ID2INDEX(ClientId);

    NV_ASSERT(hRmDeviceHandle);
    NV_ASSERT(pMultiHint && NumHints);
    DfsState = NvRmDfsGetState(hRmDeviceHandle);

    /* Do nothing on platforms where there is no freq scaling like QT and FPGA */
    if (NvRmPrivGetExecPlatform(hRmDeviceHandle) != ExecPlatform_Soc)
    {
        return NvSuccess;
    }
    // Do nothing if DFS is disabled, and therefore all clocks are maxed anyway
    if (DfsState <= NvRmDfsRunState_Disabled)
    {
        return NvSuccess;    // error if disabled
    }

    NvOsMutexLock(s_hPowerClientMutex);

    // Check if this client ID was registered; return error otherwise
    if (ClientIndex < pRegistry->UsedIndexRange)
    {
        pPowerClient = pRegistry->pPowerClients[ClientIndex];
    }
    if ((pPowerClient == NULL) || (pPowerClient->id != ClientId))
    {
        NvOsMutexUnlock(s_hPowerClientMutex);
        return NvError_BadValue;
    }
    // Add new busy hint record to the list
    error = RecordBusyHints(
        hRmDeviceHandle, ClientId, pMultiHint, NumHints, &SignalDfs);

    NvOsMutexUnlock(s_hPowerClientMutex);

    if (error == NvSuccess)
    {
        NvRmPrivBusyHintPrintf(
            ClientIndex, pPowerClient->tag, pMultiHint, NumHints);
        if (SignalDfs && (DfsState > NvRmDfsRunState_Stopped))
        {
            // Signal DFS clock control provided DFS is running
            NvRmPrivDfsSignal(Mode);
        }
    }
    return error;
}

NvError
NvRmPowerBusyHint (
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmDfsClockId ClockId,
    NvU32 ClientId,
    NvU32 BoostDurationMs,
    NvRmFreqKHz BoostKHz)
{
    NvRmDfsBusyHint BusyHint;

    // Pack hint record
    BusyHint.ClockId = ClockId;
    BusyHint.BoostKHz = BoostKHz;
    BusyHint.BoostDurationMs = BoostDurationMs;
    BusyHint.BusyAttribute = NV_FALSE;

    return NvRmPowerBusyHintMulti(hRmDeviceHandle, ClientId, &BusyHint, 1,
                                  NvRmDfsBusyHintSyncMode_Async);
}

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

NvError
NvRmPowerActivityHint (
    NvRmDeviceHandle hRmDeviceHandle,
    NvRmModuleID ModuleId,
    NvU32 ClientId,
    NvU32 ActivityDurationMs)
{
    /* validate the Rm Handle */
    NV_ASSERT( hRmDeviceHandle );

    return NvError_NotImplemented;
}

NvError
NvRmKernelPowerSuspend( NvRmDeviceHandle hRmDeviceHandle )
{
    NvOdmSocPowerState state = NvRmPowerLowestStateGet();

    if (state ==  NvOdmSocPowerState_Suspend)
        NvRmPrivPowerGroupSuspend(hRmDeviceHandle);

#if NVRM_POWER_DEBUG_SUSPEND_ENTRY
    NvOsMutexLock(s_hPowerClientMutex);
    {
        NvU32 i;
        ModuleVoltageReq* pVoltageReq = NULL;
        NvRmPowerClient* pPowerClient = NULL;
        NvRmPowerRegistry* pRegistry = &s_PowerRegistry;
        NvRmPowerState s = NvRmPrivPowerGetState(hRmDeviceHandle);

        // Report combined RM power stste and active modules
        NvOsDebugPrintf("RM power state before suspend: %s (%d)\n",
           ((s == NvRmPowerState_Active) ? "Active" :
            ((s == NvRmPowerState_AutoHw) ? "AutoHw" : "Idle")), s);
        if (s == NvRmPowerState_Active)
        {
            for (i = 0; i < pRegistry->UsedIndexRange; i++)
            {
                pPowerClient = pRegistry->pPowerClients[i];
                if (pPowerClient)
                {
                    pVoltageReq = pPowerClient->pVoltageReqHead;
                    while (pVoltageReq != NULL)
                    {
                        if (pVoltageReq->MaxVolts != NvRmVoltsOff)
                        {
                            // could also set some bad e = NvError_Bad???
                            NvOsDebugPrintf("Active Module: 0x%x\n",
                                                pVoltageReq->ModuleId);
                        }
                        pVoltageReq = pVoltageReq->pNext;
                    }
                }
            }
        }
    }
    NvOsMutexUnlock(s_hPowerClientMutex);
#endif

    return NvSuccess;
}

NvError
NvRmKernelPowerResume( NvRmDeviceHandle hRmDeviceHandle )
{
    NvOdmSocPowerState state = NvRmPowerLowestStateGet();

    NvOsMutexLock(s_hPowerClientMutex);
    ReportRmPowerState(hRmDeviceHandle);
    NvOsMutexUnlock(s_hPowerClientMutex);

    if (state ==  NvOdmSocPowerState_Suspend)
        NvRmPrivPowerGroupResume(hRmDeviceHandle);
    return NvSuccess;
}