summaryrefslogtreecommitdiffstats
path: root/userspace/sdks/nv570/nvalloc/unix/src/os.c
blob: b441a66fe735e834f830bae9344333c31b16c1f2 (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
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
/*
 * SPDX-FileCopyrightText: Copyright (c) 1999-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include <nv.h>                     // NV device driver interface
#include <nv-priv.h>
#include <nv-caps.h>
#include <os/os.h>
#include <nvos.h>
#include <osapi.h>
#include <ctrl/ctrl0000/ctrl0000gpu.h>
#include <ctrl/ctrl0000/ctrl0000unix.h>
#include <class/cl90cd.h> // NV_EVENT_BUFFER_BIND
#include <nvdevid.h>

#include <nverror.h>
#include <gpu/device/device.h>

#include "gpu/gpu.h"
#include <gpu_mgr/gpu_mgr.h>
#include <platform/chipset/chipset.h>

#include "nverror.h"
#include "kernel/gpu/bif/kernel_bif.h"

#include "gpu/mig_mgr/kernel_mig_manager.h"

#include "gpu/mem_sys/kern_mem_sys.h"

#include "mem_mgr/io_vaspace.h"
#include <diagnostics/journal.h>
#include "kernel/diagnostics/xid_context.h"
#include "gpu/mem_mgr/mem_desc.h"
#include "gpu/mem_mgr/mem_mgr.h"
#include "core/thread_state.h"
#include <nvacpitypes.h>
#include <platform/acpi_common.h>
#include <core/locks.h>
#include <ctrl/ctrl2080/ctrl2080gpu.h>
#include "virtualization/hypervisor/hypervisor.h"
#include "rmobjexportimport.h"
#include <nvi2c.h>
#include "rmapi/rs_utils.h"
#include "rmapi/client_resource.h"
#include "os/dce_rm_client_ipc.h"
#include "mem_mgr/mem.h"
#include "gpu/mem_mgr/virt_mem_allocator_common.h"
#include "nvrm_registry.h"

#include "vgpu/vgpu_util.h"

#include "platform/chipset/chipset.h"

#include <acpidsmguids.h>
#include <pex.h>
#include "gps.h"
#include "jt.h"




extern const char *ppOsBugCheckBugcodeStr[];


ct_assert(NV_RM_PAGE_SIZE == RM_PAGE_SIZE);
ct_assert(NV_RM_PAGE_MASK == RM_PAGE_MASK);
ct_assert(NV_RM_PAGE_SHIFT == RM_PAGE_SHIFT);

typedef struct
{
    NvU32 euid;
    NvU32 pid;
} TOKEN_USER, *PTOKEN_USER;

struct OS_RM_CAPS
{
    NvU32 count;

    // This should be the last element
    nv_cap_t **caps;
};

NvBool osIsRaisedIRQL(void)
{
    return (!os_semaphore_may_sleep());
}

NvBool osIsISR(void)
{
    return os_is_isr();
}

NV_STATUS osGetDriverBlock
(
    OS_GPU_INFO     *pOsGpuInfo,
    OS_DRIVER_BLOCK *pBlock
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NvU64 osGetMonotonicTimeNs(void)
{
    return os_get_monotonic_time_ns();
}

NV_STATUS osGetPerformanceCounter(NvU64 *pTimeInNs)
{
    *pTimeInNs = os_get_monotonic_time_ns_hr();
    return NV_OK;
}

NV_STATUS osGetSystemTime(
    NvU32 *pSeconds,
    NvU32 *pMicroSeconds
)
{
    return os_get_system_time(pSeconds, pMicroSeconds);
}

/*!
 * @brief Get timestamp for logging.
 *
 * Everything that logs a time stamp should use this routine for consistency.
 *
 * The returned value is OS dependent.  We want the time stamp to use
 * KeQueryPerformanceCounter on Windows so it matches the DirectX timestamps.
 * Linux uses microseconds since 1970 (osGetSystemTime), since matching DirectX
 * is not a priority.
 *
 * osGetTimestampFreq returns the frequency required to decode the time stamps.
 *
 * @returns   system dependent timestamp.
 */
NvU64 osGetTimestamp(void)
{
    NvU32 sec  = 0;
    NvU32 usec = 0;
    osGetSystemTime(&sec, &usec);
    return (NvU64)sec * 1000000 + usec;
}

/*!
 * @brief Get timestamp frequency.
 *
 * Timestamps are OS dependent.  This call returns the frequency
 * required to decode them.
 *
 * @returns   Timestamp frequency.  For example, 1000000 for MHz.
 */
NvU64 osGetTimestampFreq(void)
{
    return 1000000;
}

NV_STATUS osDelay(NvU32 milliseconds)
{
    return os_delay(milliseconds);
}

NV_STATUS osDelayUs(NvU32 microseconds)
{
    return os_delay_us(microseconds);
}

NV_STATUS osDelayNs(NvU32 nanoseconds)
{
    NvU32 microseconds = NV_MAX(1, (nanoseconds / 1000));
    return os_delay_us(microseconds);
}

NvU32 osGetCpuFrequency(void)
{
    /* convert os_get_cpu_frequency()'s return value from Hz to MHz */
    return ((NvU32)(os_get_cpu_frequency() / 1000000ULL));
}

void* osPciInitHandle(
    NvU32  Domain,
    NvU8   Bus,
    NvU8   Slot,
    NvU8   Function,
    NvU16 *pVendor,
    NvU16 *pDevice
)
{
    //
    // Check if the BDF is for a GPU that's already been attached, for which
    // we should already have a handle cached. This won't catch devices that
    // have been probed but not yet attached, but that shouldn't be a common
    // occurrence.
    //
    // More importantly, having this check here means we don't need to check
    // a global list of devices in the kernel interface layer, which could
    // have the implication of taking another lock, causing hairy lock
    // ordering issues.
    //
    if (Function == 0)
    {
        OBJGPU *pGpu = gpumgrGetGpuFromBusInfo(Domain, Bus, Slot);
        if (pGpu != NULL)
        {
            nv_state_t *nv = NV_GET_NV_STATE(pGpu);
            if (pVendor) *pVendor = nv->pci_info.vendor_id;
            if (pDevice) *pDevice = nv->pci_info.device_id;
            return nv->handle;
        }
    }

    return os_pci_init_handle(Domain, Bus, Slot, Function, pVendor, pDevice);
}

NvU8 osPciReadByte(
    void *pHandle,
    NvU32 Offset
)
{
    NvU8 val;
    os_pci_read_byte(pHandle, Offset, &val);
    return val;
}

NvU16 osPciReadWord(
    void *pHandle,
    NvU32 Offset
)
{
    NvU16 val;
    os_pci_read_word(pHandle, Offset, &val);
    return val;
}

NvU32 osPciReadDword(
    void *pHandle,
    NvU32 Offset
)
{
    NvU32 val;
    os_pci_read_dword(pHandle, Offset, &val);
    return val;
}

void osPciWriteByte(
    void *pHandle,
    NvU32 Offset,
    NvU8  Value
)
{
    os_pci_write_byte(pHandle, Offset, Value);
}

void osPciWriteWord(
    void  *pHandle,
    NvU32 Offset,
    NvU16 Value
)
{
    os_pci_write_word(pHandle, Offset, Value);
}

void osPciWriteDword(
    void  *pHandle,
    NvU32 Offset,
    NvU32 Value
)
{
    os_pci_write_dword(pHandle, Offset, Value);
}

void* osMapKernelSpace(
    RmPhysAddr Start,
    NvU64      Size,
    NvU32      Mode,
    NvU32      Protect
)
{
    NvU64 offset;
    NvU8 *ptr;

    if (0 == Size)
    {
        NV_ASSERT(Size != 0);
        return NULL;
    }

    offset = (Start & ~os_page_mask);
    Start &= os_page_mask;

    if (!portSafeAddU64(Size, offset, &Size) ||
        !portSafeAddU64(Size, ~os_page_mask, &Size))
    {
        return NULL;
    }
    Size &= os_page_mask;

    ptr = os_map_kernel_space(Start, Size, Mode);
    if (ptr != NULL)
        return (ptr + offset);

    return NULL;
}

void osUnmapKernelSpace(
    void *pAddress,
    NvU64 Size
)
{
    NvU64 offset;
    NvUPtr ptr = (NvUPtr)pAddress;

    if (0 == Size)
    {
        NV_ASSERT(Size != 0);
        return;
    }

    offset = (ptr & ~os_page_mask);
    ptr &= os_page_mask;
    Size = ((Size + offset + ~os_page_mask) & os_page_mask);
    os_unmap_kernel_space((void *)ptr, Size);
}

static NV_STATUS setNumaPrivData
(
    KernelMemorySystem      *pKernelMemorySystem,
    nv_state_t              *nv,
    MEMORY_DESCRIPTOR       *pMemDesc
)
{
    NV_STATUS   rmStatus      = NV_OK;
    void       *pAllocPrivate = NULL;
    NvU64      *addrArray     = NULL;
    NvU64       numPages      = pMemDesc->PageCount;
    NvU64       numOsPages    = numPages;
    RmPhysAddr *pteArray      = memdescGetPteArray(pMemDesc, AT_CPU);
    NvU64       i;

    //
    // Since this function will also deal with the memory allocated from PMA,
    // we have to perform page size inflate/deflate here.
    //
    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc))
    {
        NvU64 size = pMemDesc->ActualSize;
        numOsPages = size / NV_MIN(os_page_size, pMemDesc->pageArrayGranularity);
    }

    addrArray = portMemAllocNonPaged(numOsPages * sizeof(NvU64));
    if (addrArray == NULL)
    {
        return NV_ERR_NO_MEMORY;
    }

    if (!IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc) && NV_RM_PAGE_SIZE < os_page_size)
    {
        numOsPages = NV_RM_PAGES_TO_OS_PAGES(numPages);
    }

    if (!memdescGetContiguity(pMemDesc, AT_CPU))
    {
        NvU64 copyByteSize = 0;
        if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc))
        {
            // pMemDesc->pageArraySize is calculated by 4KB, it should NOT smaller than `numOSPages`.
            NV_ASSERT_OR_ELSE(pMemDesc->pageArraySize >= numOsPages, rmStatus = NV_ERR_INVALID_STATE; goto errors);
            copyByteSize = numOsPages * sizeof(NvU64);
        }
        else
        {
            copyByteSize = numPages * sizeof(NvU64);
        }

        portMemCopy((void*)addrArray,
            copyByteSize,
            (void*)pteArray,
            copyByteSize);

        if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc))
        {
            NvU64 size = pMemDesc->ActualSize;
            //
            // Because of PMA case, we need to convert page array 
            // from RM native granularity to OS granularity.
            //
            convertPageArrayBetweenOsAndRm(
                addrArray, 
                size / pMemDesc->pageArrayGranularity, 
                pMemDesc->pageArrayGranularity,
                size / os_page_size, 
                os_page_size,
                &numOsPages
            );
        }
        else if (NV_RM_PAGE_SIZE < os_page_size)
        {
            RmDeflateRmToOsPageArray(addrArray, numPages);
        }

        for (i = 0; i < numOsPages; i++)
        {
            // Update GPA to system physical address
            addrArray[i] += pKernelMemorySystem->coherentCpuFbBase;
        }
    }
    else
    {
        //
        // Original PTE array in contiguous memdesc only holds start address.
        // We need to fill the OS page array with adjacent page addresses to
        // map contiguously.
        //
        NvU64 offset = pteArray[0] + pKernelMemorySystem->coherentCpuFbBase;

        for (i = 0; i < numOsPages; i++, offset += os_page_size)
        {
            addrArray[i] = offset;
        }
    }

    rmStatus = nv_register_phys_pages(nv, addrArray, numOsPages, NV_MEMORY_CACHED, &pAllocPrivate);
    if (rmStatus != NV_OK)
    {
        goto errors;
    }

    memdescSetMemData(pMemDesc, pAllocPrivate, NULL);

errors:
    portMemFree(addrArray);

    return rmStatus;
}

NV_STATUS osGetNumMemoryPages
(
    MEMORY_DESCRIPTOR *pMemDesc,
    NvU32 *pNumPages
)
{
    void *pAllocPrivate = NULL;

    pAllocPrivate = memdescGetMemData(pMemDesc);
    if (pAllocPrivate == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "pAllocPrivate is NULL!\n");
        return NV_ERR_INVALID_STATE;
    }

    return nv_get_num_phys_pages(pAllocPrivate, pNumPages);
}

NV_STATUS osGetMemoryPages
(
    MEMORY_DESCRIPTOR *pMemDesc,
    void *pPages,
    NvU32 *pNumPages
)
{
    void *pAllocPrivate = NULL;

    pAllocPrivate = memdescGetMemData(pMemDesc);
    if (pAllocPrivate == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "pAllocPrivate is NULL!\n");
        return NV_ERR_INVALID_STATE;
    }

    return nv_get_phys_pages(pAllocPrivate, pPages, pNumPages);
}

NV_STATUS osMapSystemMemory
(
    MEMORY_DESCRIPTOR *pMemDesc,
    NvU64 Offset,
    NvU64 Length,
    NvBool Kernel,
    NvU32 Protect,
    NvP64 *ppAddress,
    NvP64 *ppPrivate
)
{
    OBJGPU *pGpu = pMemDesc->pGpu;

    NvU64     rootOffset = 0;
    pMemDesc = memdescGetRootMemDesc(pMemDesc, &rootOffset);
    Offset  += rootOffset;

    RmPhysAddr userAddress;
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    NV_STATUS rmStatus = NV_OK;
    void *pAllocPrivate = NULL;
    void *pAddress;
    void *pPrivate = NULL;
    NvU64 pageIndex;
    NvU32 pageOffset = (Offset & ~os_page_mask);

    if (pGpu != NULL &&
        pGpu->getProperty(pGpu, PDB_PROP_GPU_COHERENT_CPU_MAPPING) &&
        memdescGetAddressSpace(pMemDesc) == ADDR_FBMEM)
    {
        KernelMemorySystem *pKernelMemorySystem = GPU_GET_KERNEL_MEMORY_SYSTEM(pGpu);

        rmStatus = setNumaPrivData(pKernelMemorySystem, nv, pMemDesc);
        if (rmStatus != NV_OK)
            return rmStatus;

        pageOffset = memdescGetPhysAddr(pMemDesc, FORCE_VMMU_TRANSLATION(pMemDesc, AT_GPU), Offset) & ~os_page_mask;
    }

    *ppAddress = NvP64_NULL;
    *ppPrivate = NvP64_NULL;

    if ((Offset + Length) < Length)
        return NV_ERR_INVALID_ARGUMENT;
    if ((Offset + Length) > pMemDesc->Size)
        return NV_ERR_INVALID_ARGUMENT;

    pageIndex = (Offset >> os_page_shift);

    pAllocPrivate = memdescGetMemData(pMemDesc);
    if (!pAllocPrivate)
    {
        NV_PRINTF(LEVEL_ERROR, "pAllocPrivate is NULL!\n");
        return NV_ERR_INVALID_STATE;
    }

    if (Kernel)
    {
        pAddress = nv_alloc_kernel_mapping(nv, pAllocPrivate,
                pageIndex, pageOffset, Length, &pPrivate);
        if (pAddress == NULL)
        {
            NV_PRINTF(LEVEL_ERROR,
                      "failed to create system memory kernel mapping!\n");
            rmStatus = NV_ERR_GENERIC;
        }
        else
        {
            *ppAddress = NV_PTR_TO_NvP64(pAddress);
            *ppPrivate = NV_PTR_TO_NvP64(pPrivate);
        }
    }
    else
    {
        rmStatus = nv_alloc_user_mapping(nv, pAllocPrivate,
                pageIndex, pageOffset, Length, Protect, &userAddress,
                &pPrivate);
        if (rmStatus != NV_OK)
        {
            NV_PRINTF(LEVEL_ERROR,
                      "failed to create system memory user mapping!\n");
        }
        else
        {
            *ppAddress = (NvP64)(userAddress);
            *ppPrivate = NV_PTR_TO_NvP64(pPrivate);
        }
    }

    return rmStatus;
}

void osUnmapSystemMemory
(
    MEMORY_DESCRIPTOR *pMemDesc,
    NvBool Kernel,
    NvP64  pAddress,
    NvP64  pPrivate
)
{
    void *pAllocPrivate;
    OBJGPU *pGpu = pMemDesc->pGpu;
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    pMemDesc = memdescGetRootMemDesc(pMemDesc, NULL);
    pAllocPrivate = memdescGetMemData(pMemDesc);

    if (Kernel)
    {
        nv_free_kernel_mapping(nv, pAllocPrivate, NvP64_VALUE(pAddress),
                NvP64_VALUE(pPrivate));
    }
    else
    {
        nv_free_user_mapping(nv, pAllocPrivate, (NvU64)pAddress,
                NvP64_VALUE(pPrivate));
    }

    if (pGpu != NULL &&
        pGpu->getProperty(pGpu, PDB_PROP_GPU_COHERENT_CPU_MAPPING) &&
        memdescGetAddressSpace(pMemDesc) == ADDR_FBMEM &&
        pAllocPrivate != NULL)
    {
        nv_unregister_phys_pages(nv, pAllocPrivate);
        memdescSetMemData(pMemDesc, NULL, NULL);
    }
}

void osIoWriteByte(
    NvU32   Address,
    NvU8    Value
)
{
    os_io_write_byte(Address, Value);
}

NvU16 osIoReadWord(
    NvU32   Address
)
{
    return os_io_read_word(Address);
}

void osIoWriteWord(
    NvU32 Address,
    NvU16 Value
)
{
    os_io_write_word(Address, Value);
}

NvU8 osIoReadByte(
    NvU32   Address
)
{
    return os_io_read_byte(Address);
}

NvBool osIsAdministrator(void)
{
    return os_is_administrator();
}

NvBool osCheckAccess(RsAccessRight accessRight)
{
    return os_check_access(accessRight);
}

NvU32 osGetCurrentProcess(void)
{
    return os_get_current_process();
}

void osGetCurrentProcessName(char *ProcName, NvU32 Length)
{
    return os_get_current_process_name(ProcName, Length);
}

NV_STATUS osGetCurrentThread(OS_THREAD_HANDLE *pThreadId)
{
    NV_STATUS rmStatus;
    NvU64 threadId = 0;

    if (pThreadId == NULL)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    rmStatus = os_get_current_thread(&threadId);
    if (rmStatus == NV_OK)
    {
        *pThreadId = threadId;
    }
    else
    {
        *pThreadId = 0;
    }

    return rmStatus;
}

void* osGetPidInfo(void)
{
    return os_get_pid_info();
}

void osPutPidInfo(void *pOsPidInfo)
{
    os_put_pid_info(pOsPidInfo);
}

NV_STATUS osFindNsPid(void *pOsPidInfo, NvU32 *pNsPid)
{
    return os_find_ns_pid(pOsPidInfo, pNsPid);
}

NvBool osIsInitNs(void)
{
    return os_is_init_ns();
}

NV_STATUS osAttachToProcess(void** ppProcessInfo, NvU32 ProcessId)
{
    //
    // This function is used by RmUnmapMemory() to attach to the
    // process for which a given device memory mapping was
    // created, in order to be able to unmap it. On Linux/UNIX
    // platforms, we can't "attach" to a random process, but
    // since we don't create/destroy user mappings in the RM, we
    // don't need to, either.
    //
    // Report success to the caller to keep RmUnmapMemory() from
    // failing, and memory from being leaked as a result.
    //
    *ppProcessInfo = NULL;
    return NV_OK;
}

void osDetachFromProcess(void* pProcessInfo)
{
    // stub
    return;
}

NV_STATUS osAcquireRmSema(void *pSema)
{
    return NV_OK;
}

NV_STATUS osCondAcquireRmSema(void *pSema)
{
    return NV_OK;
}

NvU32 osReleaseRmSema(void *pSema, OBJGPU *pDpcGpu)
{
    return NV_SEMA_RELEASE_SUCCEED;
}

void osSpinLoop(void)
{
    
}

NvU64 osGetMaxUserVa(void)
{
    return os_get_max_user_va();
}

NV_STATUS osSchedule(void)
{
    return os_schedule();
}

NV_STATUS osQueueWorkItem(
    OBJGPU *pGpu,
    OSWorkItemFunction pFunction,
    void *pParams,
    OsQueueWorkItemFlags flags
)
{
    nv_work_item_t *pWi;
    nv_state_t *nv;
    NV_STATUS status;

    pWi = portMemAllocNonPaged(sizeof(nv_work_item_t));

    if (NULL == pWi)
    {
        return NV_ERR_NO_MEMORY;
    }

    pWi->flags = (OsQueueWorkItemFlags){0};
    pWi->flags.bDontFreeParams         = flags.bDontFreeParams;
    pWi->flags.bLockSema               = flags.bLockSema;
    pWi->flags.apiLock                 = flags.apiLock;
    pWi->flags.bLockGpus               = flags.bLockGpus;
    pWi->flags.bLockGpuGroupDevice     = flags.bLockGpuGroupDevice;
    pWi->flags.bLockGpuGroupSubdevice  = flags.bLockGpuGroupSubdevice;
    pWi->flags.bFullGpuSanity          = flags.bFullGpuSanity;
    pWi->flags.bDropOnUnloadQueueFlush = flags.bDropOnUnloadQueueFlush;
    pWi->flags.bSetExpandedGpuVisibility = flags.bSetExpandedGpuVisibility;

    pWi->flags.bRequiresGpu = NV_TRUE;
    pWi->gpuInstance = gpuGetInstance(pGpu);

    pWi->func.pGpuFunction = pFunction;
    pWi->pData = pParams;
    nv = NV_GET_NV_STATE(pGpu);

    status = os_queue_work_item(nv ? nv->queue : NULL, pWi);

    if (NV_OK != status)
    {
        portMemFree((void *)pWi);
    }

    return status;
}

NV_STATUS osQueueSystemWorkItem(
    OSSystemWorkItemFunction pFunction,
    void *pParams
)
{
    nv_work_item_t *pWi;
    NV_STATUS status;

    pWi = portMemAllocNonPaged(sizeof(nv_work_item_t));

    if (NULL == pWi)
    {
        return NV_ERR_NO_MEMORY;
    }

    pWi->flags = (OsQueueWorkItemFlags){0};
    pWi->func.pSystemFunction = pFunction;
    pWi->pData = pParams;

    status = os_queue_work_item(NULL, pWi);

    if (NV_OK != status)
    {
        portMemFree((void *)pWi);
    }

    return status;
}

NV_STATUS osQueueSystemWorkItemWithFlags(
    OSSystemWorkItemFunction pFunction,
    void *pParams,
    OsQueueWorkItemFlags flags
)
{
    nv_work_item_t *pWi;
    NV_STATUS status;

    pWi = portMemAllocNonPaged(sizeof(nv_work_item_t));

    if (NULL == pWi)
    {
        return NV_ERR_NO_MEMORY;
    }

    pWi->flags = (OsQueueWorkItemFlags){0};
    pWi->flags.bDontFreeParams         = flags.bDontFreeParams;
    pWi->flags.bLockSema               = flags.bLockSema;
    pWi->flags.apiLock                 = flags.apiLock;
    pWi->flags.bLockGpus               = flags.bLockGpus;
    pWi->flags.bLockGpuGroupDevice     = flags.bLockGpuGroupDevice;
    pWi->flags.bLockGpuGroupSubdevice  = flags.bLockGpuGroupSubdevice;
    pWi->flags.bFullGpuSanity          = flags.bFullGpuSanity;
    pWi->flags.bDropOnUnloadQueueFlush = flags.bDropOnUnloadQueueFlush;
    pWi->func.pSystemFunction = pFunction;
    pWi->pData = pParams;

    status = os_queue_work_item(NULL, pWi);

    if (NV_OK != status)
    {
        portMemFree((void *)pWi);
    }

    return status;
}

void osQueueMMUFaultHandler(OBJGPU *pGpu)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    nv_schedule_uvm_isr(nv);
}

NvBool osGpuSupportsAts(OBJGPU *pGpu)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    // Checks ATS support from both OS side and RM side.
    return nv->ats_support && 
        pGpu->getProperty(pGpu, PDB_PROP_GPU_ATS_SUPPORTED);
}

NV_STATUS osQueueDrainP2PHandler(NvU8 *pUuid)
{
    return nv_schedule_uvm_drain_p2p(pUuid);
}

void osQueueResumeP2PHandler(NvU8 *pUuid)
{
    nv_schedule_uvm_resume_p2p(pUuid);
}

static inline nv_dma_device_t* osGetDmaDeviceForMemDesc(
    OS_GPU_INFO *pOsGpuInfo,
    MEMORY_DESCRIPTOR *pMemDesc
)
{
    return (pOsGpuInfo->niso_dma_dev != NULL) &&
           memdescGetFlag(pMemDesc, MEMDESC_FLAGS_MEMORY_TYPE_DISPLAY_NISO) ?
           pOsGpuInfo->niso_dma_dev : pOsGpuInfo->dma_dev;
}

//
// Set the DMA address size for the given GPU
//
// This is a global device setting and care would need to be taken if it was to
// be modified outside of GPU initialization. At least on Linux other drivers,
// like UVM, might be requesting its own DMA mappings for the same GPU after
// the GPU has been initialized.
//
void osDmaSetAddressSize(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32        bits
)
{
    nv_set_dma_address_size(pOsGpuInfo, bits);
}

static NV_STATUS osGetPagesInfo(
    MEMORY_DESCRIPTOR *pMemDesc,
    NvU64 *pageSize,
    NvU64 *osPageCount,
    NvU64 *rmPageCount
)
{
    NvU64 osPageSize  = osGetPageSize();
    NvU64 maxPageSize = NV_MAX(osPageSize, RM_PAGE_SIZE);
    NvU64 alignedSize = NV_ALIGN_UP(pMemDesc->Size, maxPageSize);

    *osPageCount = alignedSize >> BIT_IDX_32(osPageSize);
    *rmPageCount = alignedSize >> RM_PAGE_SHIFT;
    *pageSize = memdescGetAdjustedPageSize(pMemDesc);

    // In the non-contig case need to protect against page array overflows.
    if (!memdescGetContiguity(pMemDesc, AT_CPU))
        NV_ASSERT_OR_RETURN(*rmPageCount <= pMemDesc->pageArraySize, NV_ERR_INVALID_ARGUMENT);

    if (*osPageCount > NV_U32_MAX || *rmPageCount > NV_U32_MAX)
        return NV_ERR_INVALID_LIMIT;

    return NV_OK;
}

NV_STATUS osAllocPagesInternal(
    MEMORY_DESCRIPTOR *pMemDesc
)
{
    OBJSYS           *pSys      = SYS_GET_INSTANCE();
    OBJGPU           *pGpu      = pMemDesc->pGpu;
    nv_state_t       *nv        = NV_GET_NV_STATE(pGpu);
    void             *pMemData  = NULL;
    NV_STATUS         status;
    NvS32             nodeId    = memdescGetNumaNode(pMemDesc);
    NV_ADDRESS_SPACE  addrSpace = memdescGetAddressSpace(pMemDesc);
    NvU64             pageSize;
    NvU64             osPageCount;
    NvU64             rmPageCount;
    NvU32             cpuCacheAttrib = memdescGetCpuCacheAttrib(pMemDesc);

    memdescSetMemData(pMemDesc, NULL, NULL);

#if (defined(NVCPU_AARCH64) && RMCFG_MODULE_CL)
    {
        OBJCL   *pCl       = SYS_GET_CL(pSys);

        if ((pCl != NULL) &&
             pCl->getProperty(pCl, PDB_PROP_CL_IS_CHIPSET_IO_COHERENT) &&
             !memdescGetFlag(pMemDesc, MEMDESC_FLAGS_NON_IO_COHERENT))
        {
            cpuCacheAttrib = NV_MEMORY_CACHED;
        }
    }
#endif

    //
    // For carveout, the memory is already reserved so we don't have
    // to allocate memory.
    //
    if (memdescIsCarveoutMemory(pMemDesc) ||
        memdescGetFlag(pMemDesc, MEMDESC_FLAGS_GUEST_ALLOCATED))
    {
        // We only support carveout with contiguous memory.
        if (memdescIsCarveoutMemory(pMemDesc) &&
            !memdescGetContiguity(pMemDesc, AT_CPU))
        {
            status = NV_ERR_NOT_SUPPORTED;
            goto done;
        }

        status = osGetPagesInfo(pMemDesc, &pageSize, &osPageCount, &rmPageCount);
        if (status != NV_OK)
            goto done;

        if (!IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc) && 
            NV_RM_PAGE_SIZE < os_page_size &&
            !memdescGetContiguity(pMemDesc, AT_CPU))
        {
            RmDeflateRmToOsPageArray(memdescGetPteArray(pMemDesc, AT_CPU),
                                    rmPageCount);
        }

        status = nv_alias_pages(
            NV_GET_NV_STATE(pGpu),
            osPageCount,
            pageSize,
            memdescGetContiguity(pMemDesc, AT_CPU),
            cpuCacheAttrib,
            memdescGetGuestId(pMemDesc),
            memdescGetPteArray(pMemDesc, AT_CPU),
            memdescIsCarveoutMemory(pMemDesc),
            &pMemData);
    }
    else
    {
        NvBool unencrypted = 0;

        if (nv && (memdescGetFlag(pMemDesc, MEMDESC_FLAGS_ALLOC_32BIT_ADDRESSABLE)))
            nv->force_dma32_alloc = NV_TRUE;

        //
        // If AMD SEV is enabled but APM(Ampere protected) or CC(Confidential
        // Compute) mode is not enabled on the GPU, all RM and client
        // allocations must be an unprotected sysmem.  If APM is enabled and RM
        // is allocating sysmem for its internal use, then it has to be
        // unprotected as protected sysmem is not accessible to GPU.
        //
        unencrypted = memdescGetFlag(pMemDesc, MEMDESC_FLAGS_ALLOC_IN_UNPROTECTED_MEMORY);

        //
        // OBJGPU/nv may be NULL if constructing NV01_MEMORY_DEVICELESS. Assume that
        // NV01_MEMORY_DEVICELESS won't be used for display.
        //
        if (pGpu != NULL &&
            pGpu->getProperty(pGpu, PDB_PROP_GPU_TEGRA_SOC_NVDISPLAY) &&
            addrSpace == ADDR_SYSMEM)
        {
            if (!memdescGetFlag(pMemDesc, MEMDESC_FLAGS_MEMORY_TYPE_DISPLAY_NISO) &&
                !NV_SOC_IS_ISO_IOMMU_PRESENT(nv))
            {
                NV_PRINTF(LEVEL_INFO, "Forcing physically contiguous flags for ISO\n");
                memdescSetContiguity(pMemDesc, AT_CPU, NV_TRUE);
            }

            if (memdescGetFlag(pMemDesc, MEMDESC_FLAGS_MEMORY_TYPE_DISPLAY_NISO) &&
                !NV_SOC_IS_NISO_IOMMU_PRESENT(nv))
            {
                NV_PRINTF(LEVEL_INFO, "Forcing physically contiguous flags for NISO\n");
                memdescSetContiguity(pMemDesc, AT_CPU, NV_TRUE);
            }
        }

        status = osGetPagesInfo(pMemDesc, &pageSize, &osPageCount, &rmPageCount);
        if (status != NV_OK)
            goto done;

        status = nv_alloc_pages(
            NV_GET_NV_STATE(pGpu),
            osPageCount,  // TODO: This call needs to receive the page count param at the requested page size.
            pageSize,
            memdescGetContiguity(pMemDesc, AT_CPU),
            cpuCacheAttrib,
            pSys->getProperty(pSys,
                PDB_PROP_SYS_INITIALIZE_SYSTEM_MEMORY_ALLOCATIONS),
            unencrypted,
            nodeId,
            memdescGetPteArray(pMemDesc, AT_CPU),
            &pMemData);

        if (nv && nv->force_dma32_alloc)
            nv->force_dma32_alloc = NV_FALSE;
    }

    if (status != NV_OK)
    {
        goto done;
    }

    // Guest allocated memory is already initialized
    if (!memdescGetFlag(pMemDesc, MEMDESC_FLAGS_GUEST_ALLOCATED))
    {
        if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc))
        {
            NV_ASSERT_OK_OR_RETURN(memdescSetAllocSizeFields(pMemDesc, osPageCount * os_page_size, os_page_size));
        }
        else
        {
            NV_ASSERT_OK_OR_RETURN(memdescSetAllocSizeFields(pMemDesc, rmPageCount * RM_PAGE_SIZE, RM_PAGE_SIZE));
        }
    }

    //
    // If the OS layer doesn't think in RM page size, we need to inflate the
    // PTE array into RM pages.
    //
    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc))
    {
        NV_ASSERT_OR_RETURN(pMemDesc->pageArrayGranularity == os_page_size, NV_ERR_INVALID_ARGUMENT);
    }
    else if (NV_RM_PAGE_SIZE < os_page_size &&
            !memdescGetContiguity(pMemDesc, AT_CPU))
    {
        RmInflateOsToRmPageArray(memdescGetPteArray(pMemDesc, AT_CPU),
                                pMemDesc->PageCount);
    }

    memdescSetMemData(pMemDesc, pMemData, NULL);

    if ((pGpu != NULL) && IS_VIRTUAL(pGpu))
        NV_ASSERT_OK_OR_RETURN(vgpuUpdateGuestSysmemPfnBitMap(pGpu, pMemDesc, NV_TRUE));
done:
    return status;
}

void osFreePagesInternal(
    MEMORY_DESCRIPTOR *pMemDesc
)
{
    OBJGPU *pGpu = pMemDesc->pGpu;
    NV_STATUS rmStatus;
    NvU64 osPageCount;

    if ((pGpu != NULL) && IS_VIRTUAL(pGpu))
        NV_ASSERT_OR_RETURN_VOID(vgpuUpdateGuestSysmemPfnBitMap(pGpu, pMemDesc, NV_FALSE) == NV_OK);

    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pMemDesc))
    {
        NV_ASSERT(pMemDesc->pageArrayGranularity == os_page_size);
        osPageCount = pMemDesc->PageCount;
    }
    else if (NV_RM_PAGE_SIZE < os_page_size &&
            !memdescGetContiguity(pMemDesc, AT_CPU))
    {
        osPageCount = NV_RM_PAGES_TO_OS_PAGES(pMemDesc->PageCount);
        RmDeflateRmToOsPageArray(memdescGetPteArray(pMemDesc, AT_CPU),
                                pMemDesc->PageCount);
    }
    else
    {
        osPageCount = NV_RM_PAGES_TO_OS_PAGES(pMemDesc->PageCount);
    }

    rmStatus = nv_free_pages(NV_GET_NV_STATE(pGpu),
        osPageCount,
        memdescGetContiguity(pMemDesc, AT_CPU),
        memdescGetCpuCacheAttrib(pMemDesc),
        memdescGetMemData(pMemDesc));
    NV_ASSERT(rmStatus == NV_OK);
}

NV_STATUS osLockMem(
    MEMORY_DESCRIPTOR *pMemDesc
)
{
    // Not supported on this OS.
    DBG_BREAKPOINT();
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS osUnlockMem(
    MEMORY_DESCRIPTOR *pMemDesc
)
{
    // Not supported on this OS.
    DBG_BREAKPOINT();
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS osMapPciMemoryAreaUser
(
    OS_GPU_INFO *pOsGpuInfo,
    MemoryArea memArea,
    NvU32 protect,
    NvU32 mode,
    NvP64 *pVirtualAddress,
    NvP64 *pPriv
)
{
    NV_STATUS status = NV_OK;
    NvU64 origStart;
    NvU64 origSize;
    NvU64 diffStart;

    if (memArea.numRanges == 0)
    {
        *pVirtualAddress = (NvP64) NULL;
        *pPriv = NULL;
        return NV_OK;
    }

    // Fix alignment insofar as we can (middle blocks can't be force-aligned this way)
    origStart = memArea.pRanges[0].start;
    memArea.pRanges[0].start = NV_ALIGN_DOWN64(origStart, os_page_size);
    diffStart = origStart - memArea.pRanges[0].start;
    memArea.pRanges[0].size += diffStart;
    origSize = memArea.pRanges[memArea.numRanges - 1llu].size;
    memArea.pRanges[memArea.numRanges - 1llu].size = NV_ALIGN_UP64(origSize, os_page_size);

    {
        nv_usermap_access_params_t **ppNvuap, tNvuap;
        NvU64 totalRangeSize = sizeof(MemoryRange) * memArea.numRanges;

        portMemSet(&tNvuap, 0, sizeof(nv_usermap_access_params_t));

        tNvuap.memArea = memArea;
        // access_size is only for caching, we can use os_page_size for now until linux has been properly plumbed
        tNvuap.access_start = memArea.pRanges[0].start;
        tNvuap.access_size = os_page_size;

        tNvuap.caching = mode;
        tNvuap.contig = NV_TRUE;

        ppNvuap = (nv_usermap_access_params_t **) tlsEntryAcquire(TLS_ENTRY_ID_MAPPING_CONTEXT);
        NV_ASSERT_OR_RETURN(ppNvuap != NULL, NV_ERR_INVALID_STATE);

        NV_ASSERT_OK_OR_GOTO(status,
            os_alloc_mem((void**) ppNvuap, sizeof(nv_alloc_mapping_context_t)),
            free_tls);

        portMemCopy(*ppNvuap, sizeof(nv_usermap_access_params_t),
            &tNvuap, sizeof(nv_usermap_access_params_t));

        NV_ASSERT_OK_OR_GOTO(status, 
            os_alloc_mem((void**) &((*ppNvuap)->memArea.pRanges), totalRangeSize),
            free_nvuap);

        portMemCopy((*ppNvuap)->memArea.pRanges, totalRangeSize, memArea.pRanges, totalRangeSize);

        *pVirtualAddress = (NvP64) (memArea.pRanges[0].start + diffStart);
        goto unalign_and_return;

free_nvuap:
        os_free_mem(*ppNvuap);
free_tls:
        tlsEntryRelease(TLS_ENTRY_ID_MAPPING_CONTEXT);
    }
unalign_and_return:
    memArea.pRanges[memArea.numRanges - 1llu].size =  origSize;
    memArea.pRanges[0].size -= diffStart;
    memArea.pRanges[0].start = origStart;
    return status;
}

NV_STATUS osMapPciMemoryUser(
    OS_GPU_INFO *pOsGpuInfo,
    RmPhysAddr   busAddress,
    NvU64        length,
    NvU32        Protect,
    NvP64       *pVirtualAddress,
    NvP64       *pPriv,
    NvU32        modeFlag
)
{
    MemoryArea memArea;
    MemoryRange memRange;

    memArea.numRanges = 1;
    memArea.pRanges = &memRange;

    memRange.start = busAddress;
    memRange.size = length;

    return osMapPciMemoryAreaUser(pOsGpuInfo, memArea, Protect, modeFlag, pVirtualAddress, pPriv);
}

void osUnmapPciMemoryUser(
    OS_GPU_INFO *pOsGpuInfo,
    NvP64        virtualAddress,
    NvU64        length,
    NvP64        pPriv
)
{
}

NV_STATUS osMapPciMemoryKernelOld
(
    OBJGPU    *pGpu,
    RmPhysAddr busAddress,
    NvU64      length,
    NvU32      Protect,
    void     **pVirtualAddress,
    NvU32      modeFlag
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    nv_kern_mapping_t *mapping;

    if (pVirtualAddress == NULL)
        return NV_ERR_GENERIC;

    *pVirtualAddress = os_map_kernel_space(busAddress, length, modeFlag);
    if (*pVirtualAddress == NULL)
        return NV_ERR_GENERIC;

    mapping = portMemAllocNonPaged(sizeof(nv_kern_mapping_t));
    if (NULL == mapping)
    {
        os_unmap_kernel_space(*pVirtualAddress, length);
        *pVirtualAddress = 0;
        return NV_ERR_GENERIC;
    }

    mapping->addr = *pVirtualAddress;
    mapping->size = length;
    mapping->modeFlag = modeFlag;

    mapping->next = nv->kern_mappings;
    nv->kern_mappings = mapping;

    return NV_OK;
}

NV_STATUS osMapPciMemoryKernel64
(
    OBJGPU    *pGpu,
    RmPhysAddr busAddress,
    NvU64      length,
    NvU32      Protect,
    NvP64     *pVirtualAddress,
    NvU32      modeFlag
)
{
    void *tmppVirtualAddress = NvP64_VALUE(pVirtualAddress);
    NV_STATUS rc;

    rc = osMapPciMemoryKernelOld(pGpu,
                                 busAddress,
                                 length,
                                 Protect,
                                 &tmppVirtualAddress,
                                 modeFlag);

    *pVirtualAddress = NV_PTR_TO_NvP64(tmppVirtualAddress);

    return rc;
}

void osUnmapPciMemoryKernelOld
(
    OBJGPU *pGpu,
    void*   virtualAddress
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    nv_kern_mapping_t *mapping, *tmp;

    // this can happen, for example, during a call to RmShutdownAdapter()
    // from a failed RmInitAdapter()
    if (virtualAddress == NULL)
    {
        return;
    }

    tmp = mapping = nv->kern_mappings;
    while (mapping)
    {
        if (mapping->addr == virtualAddress)
        {
            if (mapping == nv->kern_mappings)
            {
                nv->kern_mappings = mapping->next;
            }
            else
            {
                tmp->next = mapping->next;
            }

            os_unmap_kernel_space(mapping->addr, mapping->size);

            portMemFree(mapping);
            return;
        }
        tmp = mapping;
        mapping = mapping->next;
    }

    DBG_BREAKPOINT();
}

void osUnmapPciMemoryKernel64
(
    OBJGPU *pGpu,
    NvP64   virtualAddress
)
{
    osUnmapPciMemoryKernelOld(pGpu, NvP64_VALUE(virtualAddress));
}

NV_STATUS osMapGPU(
    OBJGPU        *pGpu,
    RS_PRIV_LEVEL  privLevel,
    NvU64          offset,
    NvU64          length,
    NvU32          Protect,
    NvP64         *pAddress,
    NvP64         *pPriv
)
{
    NV_STATUS rmStatus = NV_OK;

    if (privLevel >= RS_PRIV_LEVEL_KERNEL)
    {
        if (!portSafeAddU64((NvUPtr)pGpu->deviceMappings[0].gpuNvAddr, offset, (NvU64*)pAddress))
        {
            rmStatus = NV_ERR_INVALID_LIMIT;
        }
    }
    else
    {
        RmPhysAddr busAddress;
        if (!portSafeAddU64(pGpu->busInfo.gpuPhysAddr, offset, &busAddress))
        {
            rmStatus = NV_ERR_INVALID_LIMIT;
        }
        else
        {
            rmStatus = osMapPciMemoryUser(pGpu->pOsGpuInfo,
                                          busAddress,
                                          length,
                                          Protect,
                                          pAddress,
                                          pPriv,
                                          NV_MEMORY_UNCACHED);
        }
    }

    return rmStatus;
}

void osUnmapGPU(
    OS_GPU_INFO   *pOsGpuInfo,
    RS_PRIV_LEVEL  privLevel,
    NvP64          address,
    NvU64          length,
    NvP64          priv
)
{
    if (privLevel < RS_PRIV_LEVEL_KERNEL)
    {
        osUnmapPciMemoryUser(pOsGpuInfo, address, length, priv);
    }
}

static NV_STATUS referenceEventForPost(
    nv_event_t *event,
    NvBool bDoRefCount,
    nv_event_t *eventSnapshot,
    nv_file_private_t **ppNvfp
)
{
    nv_state_t *nv = nv_get_ctl_state();

    portSyncSpinlockAcquire(nv->event_spinlock);

    if (event->active == 0)
    {
        portSyncSpinlockRelease(nv->event_spinlock);
        return NV_ERR_INVALID_EVENT;
    }

    if (bDoRefCount)
        ++event->refcount;

    // Snapshot while event_spinlock still protects the event lifetime.
    *eventSnapshot = *event;
    *ppNvfp = eventSnapshot->nvfp;
    portAtomicIncrementS32(&(*ppNvfp)->event_posting_refcount);

    portSyncSpinlockRelease(nv->event_spinlock);
    return NV_OK;
}

static void dereferenceEventForPost(
    nv_event_t *event,
    NvBool bDoRefCount,
    nv_file_private_t *nvfp
)
{
    if (bDoRefCount)
    {
        nv_state_t *nv = nv_get_ctl_state();

        portSyncSpinlockAcquire(nv->event_spinlock);

        NV_ASSERT(event->refcount > 0);
        if (--event->refcount == 0 && !event->active)
            portMemFree(event);

        portSyncSpinlockRelease(nv->event_spinlock);
    }

    portAtomicDecrementS32(&nvfp->event_posting_refcount);
}

static void postEvent(
    nv_event_t *event,
    NvU32 hEvent,
    NvU32 notifyIndex,
    NvU32 info32,
    NvU16 info16,
    NvBool dataValid,
    NvBool bDoRefCount
)
{
    nv_event_t *eventToPost = event;

    nv_file_private_t *nvfp = NULL;
    nv_event_t eventSnapshot;

    if (referenceEventForPost(event, bDoRefCount, &eventSnapshot, &nvfp) != NV_OK)
        return;

    eventToPost = &eventSnapshot;

    nv_post_event(eventToPost, hEvent, notifyIndex,
                  info32, info16, dataValid);

    dereferenceEventForPost(bDoRefCount ? event : NULL, bDoRefCount, nvfp);
}

NvU32 osSetEvent
(
    OBJGPU   *pGpu,
    NvP64     eventID
)
{
    nv_event_t *event = NvP64_VALUE(eventID);
    postEvent(event, 0, 0, 0, 0, NV_FALSE, NV_TRUE);
    return 1;
}

NV_STATUS osNotifyEvent(
    OBJGPU             *pGpu,
    PEVENTNOTIFICATION  NotifyEvent,
    NvU32               Method,
    NvU32               Data,
    NV_STATUS           Status,
    NvBool              bDoRefCount
)
{
    NV_STATUS rmStatus = NV_OK;

    // notify the event
    switch (NotifyEvent->NotifyType)
    {
        case NV01_EVENT_OS_EVENT:
        {
            nv_event_t *event = NvP64_VALUE(NotifyEvent->Data);
            postEvent(event,
                      NotifyEvent->hEvent,
                      NotifyEvent->NotifyIndex,
                      0, 0,
                      NotifyEvent->bEventDataRequired,
                      bDoRefCount);
            break;
        }

        // NOTE: NV01_EVENT_KERNEL_CALLBACK is deprecated. please use NV01_EVENT_KERNEL_CALLBACK_EX.
        case NV01_EVENT_KERNEL_CALLBACK:
        {
            MINIPORT_CALLBACK callBackToMiniport =
                (MINIPORT_CALLBACK)NvP64_VALUE(NotifyEvent->Data);

            // perform a direct callback to the miniport
            if (callBackToMiniport)
                callBackToMiniport(NV_GET_NV_STATE(pGpu));
            break;
        }

        case NV01_EVENT_KERNEL_CALLBACK_EX:
        {
            NVOS10_EVENT_KERNEL_CALLBACK_EX *kc = (NVOS10_EVENT_KERNEL_CALLBACK_EX *)NvP64_VALUE(NotifyEvent->Data);

            // passes two arguments (arg, params) to the kernel callback instead of one (arg).
            if (kc && kc->func)
            {
                kc->func(kc->arg, NULL, NotifyEvent->hEvent, Data, Status);
            }
            break;
        }


        default:
        {
            rmStatus = NV_ERR_GENERIC;
            break;
        }
    }

    return rmStatus;

} // end of osNotifyEvent()

// Allow CPL Events to be callback or events
NV_STATUS osEventNotification
(
    OBJGPU   *pGpu,
    PEVENTNOTIFICATION pNotifyEvent,
    NvU32 notifyIndex,
    void * pEventData,
    NvU32 eventDataSize
)
{
    return osEventNotificationWithInfo(pGpu, pNotifyEvent, notifyIndex, 0, 0,
                                       pEventData, eventDataSize);
}

NV_STATUS osEventNotificationWithInfo
(
    OBJGPU   *pGpu,
    PEVENTNOTIFICATION pNotifyEvent,
    NvU32 notifyIndex,
    NvU32 info32,
    NvU16 info16,
    void * pEventData,
    NvU32 eventDataSize
)
{
    NV_STATUS rmStatus = NV_OK;
    NvBool bMatchSubdev = NV_FALSE;

    if ((notifyIndex != OS_EVENT_NOTIFICATION_INDEX_ALL) &&
        (OS_EVENT_NOTIFICATION_INDEX_MATCH_SUBDEV & notifyIndex))
    {
        bMatchSubdev = NV_TRUE;
        notifyIndex &= ~OS_EVENT_NOTIFICATION_INDEX_MATCH_SUBDEV;
    }

    // walk this object's event list and find any matches for this specific notify
    for (; pNotifyEvent; pNotifyEvent = pNotifyEvent->Next)
    {
        // notifyIndex must match if request isn't for all
        if ((notifyIndex != OS_EVENT_NOTIFICATION_INDEX_ALL) &&
            (pNotifyEvent->NotifyIndex != notifyIndex))
        {
            continue;
        }

        if (bMatchSubdev && (pGpu->subdeviceInstance != pNotifyEvent->subdeviceInst))
            continue;

        switch (pNotifyEvent->NotifyType)
        {
            case NV_EVENT_BUFFER_BIND:
            case NV01_EVENT_WIN32_EVENT:
            {
                nv_event_t *event = NvP64_VALUE(pNotifyEvent->Data);
                postEvent(event,
                          pNotifyEvent->hEvent,
                          pNotifyEvent->NotifyIndex,
                          info32, info16,
                          pNotifyEvent->bEventDataRequired,
                          NV_TRUE);
                break;
            }

            // NOTE: NV01_EVENT_KERNEL_CALLBACK is deprecated. please use NV01_EVENT_KERNEL_CALLBACK_EX.
            case NV01_EVENT_KERNEL_CALLBACK:
            {
                MINIPORT_CALLBACK callBackToMiniport =
                    (MINIPORT_CALLBACK)NvP64_VALUE(pNotifyEvent->Data);

                // perform a direct callback to the miniport
                if (callBackToMiniport)
                    callBackToMiniport(NV_GET_NV_STATE(pGpu));
                break;
            }

            case NV01_EVENT_KERNEL_CALLBACK_EX:
            {
                NVOS10_EVENT_KERNEL_CALLBACK_EX *kc = (NVOS10_EVENT_KERNEL_CALLBACK_EX *)NvP64_VALUE(pNotifyEvent->Data);

                if (kc && kc->func)
                {
                    kc->func(kc->arg, pEventData, pNotifyEvent->hEvent, 0, NV_OK);
                }
                break;
            }

            default:
                break;
        }
    }

    return rmStatus;
}

// Allow CPL Events to be callback or events
NV_STATUS osObjectEventNotification
(
    NvHandle            hClient,
    NvHandle            hObject,
    NvU32               hClass,
    PEVENTNOTIFICATION  pNotifyEvent,
    NvU32               notifyIndex,
    void                *pEventData,
    NvU32               eventDataSize
)
{
    NV_STATUS rmStatus = NV_OK;

    NV_PRINTF(LEVEL_INFO, "%s()\n", __FUNCTION__);
    // walk this object's event list and find any matches for this specific notify
    for (; pNotifyEvent; pNotifyEvent = pNotifyEvent->Next)
    {
        // notifyIndex must match if request isn't for all
        if ((notifyIndex != OS_EVENT_NOTIFICATION_INDEX_ALL) &&
            (pNotifyEvent->NotifyIndex != notifyIndex))
        {
            continue;
        }

        switch (pNotifyEvent->NotifyType)
        {
            case NV01_EVENT_OS_EVENT:
            {
                nv_event_t *event = NvP64_VALUE(pNotifyEvent->Data);
                postEvent(event,
                          pNotifyEvent->hEvent,
                          pNotifyEvent->NotifyIndex,
                          0, 0,
                          pNotifyEvent->bEventDataRequired,
                          NV_TRUE);
                break;
            }

            case NV01_EVENT_KERNEL_CALLBACK_EX:
            {
                NVOS10_EVENT_KERNEL_CALLBACK_EX *kc = (NVOS10_EVENT_KERNEL_CALLBACK_EX *)NvP64_VALUE(pNotifyEvent->Data);

                if (kc && kc->func)
                {
                    kc->func(kc->arg, pEventData, pNotifyEvent->hEvent, 0, NV_OK);
                }
                break;
            }

            default:
                break;
        }
    }

    return rmStatus;
}

NV_STATUS osReferenceObjectCount(void *pEvent)
{
    nv_state_t *nv = nv_get_ctl_state();
    nv_event_t *event = pEvent;

    portSyncSpinlockAcquire(nv->event_spinlock);
    // If event->active is false, don't allow any more reference
    if (event->active == 0)
    {
        portSyncSpinlockRelease(nv->event_spinlock);
        return NV_ERR_INVALID_EVENT;
    }
    ++event->refcount;
    portSyncSpinlockRelease(nv->event_spinlock);
    return NV_OK;
}

NV_STATUS osDereferenceObjectCount(void *pOSEvent)
{
    nv_state_t *nv = nv_get_ctl_state();
    nv_event_t *event = pOSEvent;

    portSyncSpinlockAcquire(nv->event_spinlock);
    NV_ASSERT(event->refcount > 0);
    // If event->refcount == 0 but event->active is true, the client
    // has not yet freed the OS event.  free_os_event will free its
    // memory when they do, or else when the client itself is freed.
    if (--event->refcount == 0 && !event->active)
        portMemFree(event);
    portSyncSpinlockRelease(nv->event_spinlock);

    return NV_OK;
}

NV_STATUS osUserHandleToKernelPtr(NvHandle hClient, NvP64 hEvent, NvP64 *pEvent)
{
    nv_state_t *nv = nv_get_ctl_state();
    NvU32 fd = (NvU64)hEvent;
    NV_STATUS result;

    portSyncSpinlockAcquire(nv->event_spinlock);
    nv_event_t *e = nv->event_list;
    while (e != NULL)
    {
        if (e->fd == fd && e->hParent == hClient)
            break;
        e = e->next;
    }

    if (e != NULL)
    {
        ++e->refcount;
        *pEvent = NV_PTR_TO_NvP64(e);
        result = NV_OK;
    }
    else
        result = NV_ERR_OBJECT_NOT_FOUND;
    portSyncSpinlockRelease(nv->event_spinlock);

    return result;
}

NV_STATUS osFlushCpuCache(void)
{
    return os_flush_cpu_cache_all();
}

void osFlushCpuWriteCombineBuffer(void)
{
    os_flush_cpu_write_combine_buffer();
}


//
// Evict GPU memory range from the CPU caches.
//
// On some platforms (e.g. P9+V100), the CPU can coherently cache GPU memory
// and RM takes advantage of that. Most everything is handled transparently,
// but there are two exceptions that require explicitly flushing any CPU cache
// lines of GPU memory. These are:
//
// 1) Flushing memory backing ACR regions before they get locked.
//
// Otherwise the cache could get flushed while the regions are locked causing a
// region violation physical fault. See more details in
// acrFlushRegionsFromGpuCoherentCpuCache_IMPL().
//
// 2) Flushing all of FB before GPU reset (NVLink going down)
//
// Leaving cache entries on the CPU causes fatal errors when the CPU tries
// flushing them later while the link is down. See more details in
// nvlinkStatePostUnload_IMPL().
//
void osFlushGpuCoherentCpuCacheRange
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU64        cpuVirtual,
    NvU64        size
)
{
    nv_flush_coherent_cpu_cache_range(pOsGpuInfo, cpuVirtual, size);
}

void osErrorLogV(OBJGPU *pGpu, XidContext context, const char * pFormat, va_list arglist)
{
    NV_STATUS        rmStatus;
    nv_state_t      *nv             = NV_GET_NV_STATE(pGpu);

    if ((pFormat == NULL) || (*pFormat == '\0'))
    {
        return;
    }

    rmStatus = nv_log_error(nv, context.xid, pFormat, arglist);
    NV_ASSERT(rmStatus == NV_OK);
}

void osErrorLog(OBJGPU *pGpu, NvU32 num, const char* pFormat, ...)
{
    va_list arglist;
    va_start(arglist, pFormat);
    osErrorLogV(pGpu, (XidContext){.xid = num}, pFormat, arglist);
    va_end(arglist);
}

NvU32
osPollHotkeyState
(
    OBJGPU  *pGpu
)
{
    return 0;
}

void osDevWriteReg008(
     OBJGPU            *pGpu,
     DEVICE_MAPPING    *pMapping,
     NvU32              thisAddress,
     NvV8               thisValue
)
{
    if (thisAddress >= pMapping->gpuNvLength)
    {
        NV_ASSERT(thisAddress < pMapping->gpuNvLength);
        return;
    }

    NV_PRIV_REG_WR08(pMapping->gpuNvAddr, thisAddress, thisValue);
}

void osDevWriteReg016(
     OBJGPU            *pGpu,
     DEVICE_MAPPING    *pMapping,
     NvU32              thisAddress,
     NvV16              thisValue
)
{
    if (thisAddress >= pMapping->gpuNvLength)
    {
        NV_ASSERT(thisAddress < pMapping->gpuNvLength);
        return;
    }

    NV_PRIV_REG_WR16(pMapping->gpuNvAddr, thisAddress, thisValue);
}

void osDevWriteReg032(
     OBJGPU            *pGpu,
     DEVICE_MAPPING    *pMapping,
     NvU32              thisAddress,
     NvV32              thisValue
)
{
    NvBool vgpuHandled = NV_FALSE;

    vgpuDevWriteReg032(pGpu, thisAddress, thisValue, &vgpuHandled);
    if (vgpuHandled)
    {
        return;
    }

    if (thisAddress >= pMapping->gpuNvLength)
    {
        NV_ASSERT(thisAddress < pMapping->gpuNvLength);
        return;
    }

    NV_PRIV_REG_WR32(pMapping->gpuNvAddr, thisAddress, thisValue);
}

NvU8 osDevReadReg008(
    OBJGPU             *pGpu,
    DEVICE_MAPPING     *pMapping,
    NvU32               thisAddress
)
{
    NvU8 retval = 0;

    if (thisAddress >= pMapping->gpuNvLength)
    {
        NV_ASSERT(thisAddress < pMapping->gpuNvLength);
    }
    else
        retval = NV_PRIV_REG_RD08(pMapping->gpuNvAddr, thisAddress);

    return retval;
}

NvU16 osDevReadReg016(
    OBJGPU             *pGpu,
    DEVICE_MAPPING     *pMapping,
    NvU32               thisAddress
)
{
    NvU16 retval = 0;

    if (thisAddress >= pMapping->gpuNvLength)
    {
        NV_ASSERT(thisAddress < pMapping->gpuNvLength);
    }
    else
        retval = NV_PRIV_REG_RD16(pMapping->gpuNvAddr, thisAddress);

    return retval;
}

NvU32 osDevReadReg032(
    OBJGPU             *pGpu,
    DEVICE_MAPPING     *pMapping,
    NvU32               thisAddress
)
{
    NvU32 retval = 0;
    NvBool vgpuHandled = NV_FALSE;

    retval = vgpuDevReadReg032(pGpu, thisAddress, &vgpuHandled);
    if (vgpuHandled)
    {
        return retval;
    }

    if (thisAddress >= pMapping->gpuNvLength)
    {
        NV_ASSERT(thisAddress < pMapping->gpuNvLength);
    }
    else
        retval = NV_PRIV_REG_RD32(pMapping->gpuNvAddr, thisAddress);

    return retval;
}

NV_STATUS osReadRegistryDwordBase(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU32      *Data
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    return RmReadRegistryDword(nv, regParmStr, Data);
}

NV_STATUS osWriteRegistryDword(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU32       Data
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    return RmWriteRegistryDword(nv, regParmStr, Data);
}

NV_STATUS osReadRegistryBinary(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU8       *Data,
    NvU32      *cbLen
)
{
#if defined(DEBUG) || defined(DEVELOP)
    NV_ASSERT_OK_OR_RETURN(osValidateRegistryKeyPrefix(regParmStr));
#endif

    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    return RmReadRegistryBinary(nv, regParmStr, Data, cbLen);
}

NV_STATUS osWriteRegistryBinary(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU8       *Data,
    NvU32       cbLen
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    return RmWriteRegistryBinary(nv, regParmStr, Data, cbLen);
}

NV_STATUS osWriteRegistryVolatile(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU8       *Data,
    NvU32       cbLen
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS osReadRegistryVolatile
(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU8       *Data,
    NvU32       cbLen
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS osReadRegistryVolatileSize
(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU32      *pSize
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS osReadRegistryStringBase(
    OBJGPU     *pGpu,
    const char *regParmStr,
    NvU8       *buffer,
    NvU32      *pBufferLength
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    return RmReadRegistryString(nv, regParmStr, buffer, pBufferLength);
}

NV_STATUS osPackageRegistry(
    OBJGPU                 *pGpu,
    PACKED_REGISTRY_TABLE  *pRegTable,
    NvU32                  *pSize
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    return RmPackageRegistry(nv, pRegTable, pSize);
}

NvU32 osGetCpuCount(void)
{
    return os_get_cpu_count();   // Total number of logical CPUs.
}

NvU32 osGetCurrentProcessorNumber(void)
{
    return os_get_cpu_number();
}

ClientGroupID osClientGroupID(NvU64 process, void *pidInfo)
{
    return os_cgroup_for_pid(process, pidInfo);
}

NvCgroupImpl osCgroupImplementation(void)
{
    switch (os_cgroup_implementation())
    {
    case OS_CGROUP_IMPL_DMEM: return CGROUP_IMPL_OS;
    case OS_CGROUP_IMPL_MISC: return CGROUP_IMPL_FALLBACK;
    default:                  return CGROUP_IMPL_NONE;
    }
}

void *osCgroupRegisterRegion(OBJGPU *pGpu, NvU64 size)
{
    char name[32];
    nvDbgSnprintf(name, sizeof name, "nvidia/%04x:%02x:%02x/vidmem",
        gpuGetDomain(pGpu),
        gpuGetBus(pGpu),
        gpuGetDevice(pGpu));
    return os_dmem_cgroup_register_region(size, name);
}

void osCgroupUnregisterRegion(void *region)
{
    os_dmem_cgroup_unregister_region(region);
}

NV_STATUS osMemacctTryCharge(void *pRegion, NvLength size, void **ppPool)
{
    return os_dmem_cgroup_try_charge(pRegion, size, ppPool, NULL);
}

void osMemacctReleaseCharge(void *pool, NvLength size)
{
    os_dmem_cgroup_uncharge(pool, size);
}

void *osCgroupGetFromFd(NvS32 fd)
{
    return os_cgroup_get_from_fd(fd);
}

void osCgroupPut(void *cgroup)
{
    os_cgroup_put(cgroup);
}

void osGetTimeoutParams(OBJGPU *pGpu, NvU32 *pTimeoutUs, NvU32 *pScale, NvU32 *pFlags)
{
    NvU32 gpuMode   = gpuGetMode(pGpu);

    NV_ASSERT((NV_GPU_MODE_GRAPHICS_MODE == gpuMode) ||
              (NV_GPU_MODE_COMPUTE_MODE  == gpuMode));

    if (hypervisorIsVgxHyper())
    {
        //
        // 1.8 seconds is chosen because it is 90% of the overall hard limit of 2.0
        // seconds, imposed by WDDM driver rules.
        // Currently primary use case of VGX is Windows, so setting 1.8 as default
        //
        *pTimeoutUs = 1.8 * 1000000;
    }
    else
    {
        switch (gpuMode)
        {
        default:
        case NV_GPU_MODE_GRAPHICS_MODE:
            *pTimeoutUs = 4 * 1000000;
            break;

        case NV_GPU_MODE_COMPUTE_MODE:
            *pTimeoutUs = 30 * 1000000;
            break;
        }
    }

    *pFlags = GPU_TIMEOUT_FLAGS_OSTIMER;

    *pScale = 1;
    if (IS_EMULATION(pGpu) || IS_SIMULATION(pGpu))
    {
        *pScale = 60;       // 1s -> 1m
    }

    return;
}

void osFlushLog(void)
{
    // Not implemented
}

static NvU32 _osGetTegraPlatform(void)
{
    NV_STATUS status;
    NvU32 mode;

    status = os_get_tegra_platform(&mode);
    if (status != NV_ERR_NOT_SUPPORTED)
    {
        return mode;
    }

    return NV_OS_TEGRA_PLATFORM_SILICON;
}

NvU32 osGetSimulationMode(void)
{
    NvU32 mode;

    switch (_osGetTegraPlatform())
    {
        case NV_OS_TEGRA_PLATFORM_SIM:
            mode = NV_SIM_MODE_CMODEL;
            break;
        case NV_OS_TEGRA_PLATFORM_FPGA:
            mode = NV_SIM_MODE_TEGRA_FPGA;
            break;
        case NV_OS_TEGRA_PLATFORM_SILICON:
        default:
            mode = NV_SIM_MODE_HARDWARE;
            break;
    }

    return mode;
}

NV_STATUS
cliresCtrlCmdOsUnixFlushUserCache_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_FLUSH_USER_CACHE_PARAMS *pAddressSpaceParams
)
{
    Memory *pMemory;
    MEMORY_DESCRIPTOR *pMemDesc;
    NvU64 start, end;
    NvBool bInvalidateOnly;

    NV_CHECK_OK_OR_RETURN(LEVEL_SILENT,
        memGetByHandle(RES_GET_CLIENT(pRmCliRes),
                       pAddressSpaceParams->hObject,
                       &pMemory));

    pMemDesc = pMemory->pMemDesc;

    if (memdescGetAddressSpace(pMemDesc) != ADDR_SYSMEM)
    {
        NV_PRINTF(LEVEL_ERROR, "%s: wrong address space %d\n",
                  __FUNCTION__, memdescGetAddressSpace(pMemDesc));
        return NV_ERR_INVALID_COMMAND;
    }

    if (memdescGetCpuCacheAttrib(pMemDesc) != NV_MEMORY_CACHED)
    {
        NV_PRINTF(LEVEL_ERROR, "%s: wrong caching type %d\n",
                  __FUNCTION__, memdescGetCpuCacheAttrib(pMemDesc));
        return NV_ERR_INVALID_COMMAND;
    }

    start = pAddressSpaceParams->offset;
    end = start + pAddressSpaceParams->length;

    switch(pAddressSpaceParams->cacheOps)
    {
        case NV0000_CTRL_OS_UNIX_FLAGS_USER_CACHE_FLUSH_INVALIDATE:
        case NV0000_CTRL_OS_UNIX_FLAGS_USER_CACHE_FLUSH:
            bInvalidateOnly = NV_FALSE;
            break;

        case NV0000_CTRL_OS_UNIX_FLAGS_USER_CACHE_INVALIDATE:
            bInvalidateOnly = NV_TRUE;
            break;

        default:
            NV_PRINTF(LEVEL_ERROR, "%s: cacheOps not specified\n", __FUNCTION__);
            return NV_ERR_INVALID_COMMAND;
    }

    if ((end - start) > pMemory->Length)
    {
        NV_PRINTF(LEVEL_ERROR,
                  "%s: end address 0x%llx exceeded buffer length: 0x%llx\n",
                  __FUNCTION__, end, pMemory->Length);
        return NV_ERR_INVALID_LIMIT;
    }

    if (bInvalidateOnly)
    {
        //
        // XXX: this seems fishy - I'm not sure if invalidating by the kernel
        // VA only as nv_dma_cache_invalidate() does here is sufficient for
        // this control call.
        // pAddressSpaceParams->internalOnly is expected to be the RM client
        // VA for this control call; if we wanted to invalidate the user VA we
        // could do so using that.
        //
        // For I/O coherent platforms this won't actually do anything.
        // On non-I/O-coherent platforms, there's no need to do a second
        // invalidation after the full flush.
        //
        nv_state_t *nv = NV_GET_NV_STATE(pMemDesc->pGpu);
        if (nv->iovaspace_id != NV_IOVA_DOMAIN_NONE)
        {
            PIOVAMAPPING pIovaMapping = memdescGetIommuMap(pMemDesc, nv->iovaspace_id);
            //
            // This should only be called for devices that map memory descriptors
            // through the nv-dma library, where the memory descriptor data
            // contains all the kernel-specific context we need for the
            // invalidation.
            //
            // (These checks match those in osIovaUnmap() leading up to
            // nv_dma_unmap_alloc()).
            //
            if (pIovaMapping == NULL ||
                pIovaMapping->pOsData == NULL ||
                memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_GUEST_ALLOCATED) ||
                memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_PEER_IO_MEM))
            {
                return NV_ERR_INVALID_ARGUMENT;
            }

            nv_dma_cache_invalidate(nv->dma_dev, pIovaMapping->pOsData);
        }
        else
        {
            return NV_ERR_INVALID_ARGUMENT;
        }
    }
    else
    {
        return os_flush_user_cache();
    }

    return NV_OK;
}

static NV_STATUS
_initializeExportObjectFd
(
    nv_file_private_t *nvfp,
    NvHandle           hClient,
    NvHandle           hDevice,
    NvU16              maxObjects,
    NvU8              *metadata
)
{
    NV_STATUS      status;
    RsResourceRef *pResourceRef;
    Device        *pDevice;
    NvU32          deviceInstance = NV_MAX_DEVICES;
    NvU32          gpuInstanceId = NV_U32_MAX;

    if (nvfp->handles != NULL)
    {
        return NV_ERR_STATE_IN_USE;
    }

    if (hDevice != 0)
    {
        OBJGPU *pGpu;
        MIG_INSTANCE_REF ref;

        status = serverutilGetResourceRef(hClient, hDevice, &pResourceRef);
        if (status != NV_OK)
        {
            return status;
        }

        pDevice = dynamicCast(pResourceRef->pResource, Device);
        if (pDevice == NULL)
        {
            return NV_ERR_INVALID_PARAMETER;
        }

        deviceInstance = pDevice->deviceInst;
        pGpu = GPU_RES_GET_GPU(pDevice);

        if (IS_MIG_IN_USE(pGpu))
        {
            KernelMIGManager *pKernelMIGManager = GPU_GET_KERNEL_MIG_MANAGER(pGpu);
            status = kmigmgrGetInstanceRefFromDevice(pGpu, pKernelMIGManager,
                                                     pDevice, &ref);
            if (status == NV_OK)
            {
                gpuInstanceId = ref.pKernelMIGGpuInstance->swizzId;
            }
        }
    }

    NV_ASSERT_OK_OR_RETURN(os_alloc_mem((void **)&nvfp->handles,
                           sizeof(nvfp->handles[0]) * maxObjects));

    os_mem_set(nvfp->handles, 0,
               sizeof(nvfp->handles[0]) * maxObjects);

    nvfp->maxHandles        = maxObjects;
    nvfp->deviceInstance    = deviceInstance;
    nvfp->gpuInstanceId     = gpuInstanceId;

    if (metadata != NULL)
    {
        os_mem_copy(nvfp->metadata, metadata, sizeof(nvfp->metadata));
    }

    return NV_OK;
}

NV_STATUS
cliresCtrlCmdOsUnixExportObjectToFd_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_EXPORT_OBJECT_TO_FD_PARAMS *pParams
)
{
    NvHandle           hClient = RES_GET_CLIENT_HANDLE(pRmCliRes);
    RmObjExportHandle  hExportHandle = 0;
    nv_file_private_t *nvfp = NULL;
    void              *priv = NULL;
    NV_STATUS          status = NV_OK;

    /*
     * This flag is intended to be implemented entirely in the rmapi library in
     * userspace, we should never encounter it here.
     */
    if (FLD_TEST_DRF(0000_CTRL, _OS_UNIX_EXPORT_OBJECT_TO_FD_FLAGS,
                     _EMPTY_FD, _TRUE, pParams->flags))
    {
        return NV_ERR_INVALID_PARAMETER;
    }

    if (pParams->object.type != NV0000_CTRL_OS_UNIX_EXPORT_OBJECT_TYPE_RM ||
        pParams->fd == -1)
    {
        return NV_ERR_INVALID_PARAMETER;
    }

    status = RmExportObject(hClient,
                            pParams->object.data.rmObject.hObject,
                            &hExportHandle, NULL);
    if (status != NV_OK)
    {
        goto done;
    }
    NV_ASSERT(hExportHandle != 0);

    nvfp = nv_get_file_private(pParams->fd, NV_TRUE, &priv);
    if (nvfp == NULL)
    {
        NV_ASSERT(priv == NULL);
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    status = _initializeExportObjectFd(nvfp, hClient,
                                       pParams->object.data.rmObject.hDevice,
                                       1, NULL);
    if (status != NV_OK)
    {
        goto done;
    }

    nvfp->handles[0] = hExportHandle;

done:

    if (status != NV_OK && hExportHandle != 0)
    {
        RmFreeObjExportHandle(hExportHandle);
    }

    if (priv != NULL)
    {
        nv_put_file_private(priv);
    }

    return status;
}

// This control call has been deprecated. It will be deleted soon.
NV_STATUS
cliresCtrlCmdOsUnixCreateExportObjectFd_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_CREATE_EXPORT_OBJECT_FD_PARAMS *pParams
)
{
    NV_STATUS          status;
    NvHandle           hClient = RES_GET_CLIENT_HANDLE(pRmCliRes);
    nv_file_private_t *nvfp = NULL;
    void              *priv = NULL;

    ct_assert(sizeof(nvfp->metadata) == sizeof(pParams->metadata));

    if (pParams->maxObjects == 0)
    {
        return NV_ERR_INVALID_PARAMETER;
    }

    nvfp = nv_get_file_private(pParams->fd, NV_TRUE, &priv);
    if (nvfp == NULL)
    {
        NV_ASSERT(priv == NULL);
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    status = _initializeExportObjectFd(nvfp, hClient, pParams->hDevice,
                                       pParams->maxObjects, pParams->metadata);

done:
    if (priv != NULL)
    {
        nv_put_file_private(priv);
    }

    return status;
}

NV_STATUS
cliresCtrlCmdOsUnixExportObjectsToFd_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_EXPORT_OBJECTS_TO_FD_PARAMS *pParams
)
{
    NvHandle           hClient = RES_GET_CLIENT_HANDLE(pRmCliRes);
    RmObjExportHandle *pExportHandle;
    nv_file_private_t *nvfp = NULL;
    void              *priv = NULL;
    NV_STATUS          status = NV_OK;
    NvU32              i;
    NvU32              deviceInstance;
    NvU32              result;
    NvHandle          *exportHandles = NULL;
    NvBool             bFdSetup = NV_FALSE;

    nvfp = nv_get_file_private(pParams->fd, NV_TRUE, &priv);
    if (nvfp == NULL)
    {
        NV_ASSERT(priv == NULL);
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    ct_assert(sizeof(nvfp->metadata) == sizeof(pParams->metadata));

    /* Setup export FD if not done */
    if (nvfp->handles == NULL)
    {
        if (pParams->maxObjects == 0)
        {
            status = NV_ERR_INVALID_PARAMETER;
            goto done;
        }

        status = _initializeExportObjectFd(nvfp, hClient, pParams->hDevice,
                                           pParams->maxObjects,
                                           pParams->metadata);
        if (status != NV_OK)
        {
            goto done;
        }

        bFdSetup = NV_TRUE;
    }

    if ((nvfp->handles == NULL) ||
        (pParams->numObjects >
            NV0000_CTRL_OS_UNIX_EXPORT_OBJECTS_TO_FD_MAX_OBJECTS))
    {
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    if (!portSafeAddU32(pParams->numObjects, pParams->index, &result) ||
        (result > nvfp->maxHandles))
    {
        status = NV_ERR_OUT_OF_RANGE;
        goto done;
    }

    status = os_alloc_mem((void **)&exportHandles,
                          sizeof(exportHandles[0]) *
                            pParams->numObjects);
    if (status != NV_OK)
    {
        goto done;
    }

    for (i = 0; i < pParams->numObjects; i++)
    {
        exportHandles[i] = 0;

        if (pParams->objects[i] == 0)
        {
            continue;
        }

        status = RmExportObject(hClient,
                                pParams->objects[i],
                                &exportHandles[i],
                                &deviceInstance);
        if (status != NV_OK)
        {
            goto done;
        }

        NV_ASSERT(exportHandles[i] != 0);

        if (deviceInstance != nvfp->deviceInstance)
        {
            status = NV_ERR_INVALID_PARAMETER;
            goto done;
        }
    }

    for (i = 0; i < pParams->numObjects; i++)
    {
        pExportHandle = &nvfp->handles[i + pParams->index];

        // If the handle already exists in this position, free it
        if (*pExportHandle != 0)
        {
            RmFreeObjExportHandle(*pExportHandle);
            *pExportHandle = 0;
        }

        *pExportHandle = exportHandles[i];
    }

done:

    if ((status != NV_OK) && (exportHandles != NULL))
    {
        for (i = 0; i < pParams->numObjects; i++)
        {
            if (exportHandles[i] != 0)
            {
                RmFreeObjExportHandle(exportHandles[i]);
            }
        }
    }

    if (exportHandles != NULL)
    {
        os_free_mem(exportHandles);
    }

    if ((status != NV_OK) && bFdSetup)
    {
        os_free_mem(nvfp->handles);
        nvfp->handles = NULL;
        nvfp->maxHandles = 0;
    }

    if (priv != NULL)
    {
        nv_put_file_private(priv);
    }

    return status;
}

NV_STATUS
cliresCtrlCmdOsUnixImportObjectFromFd_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_IMPORT_OBJECT_FROM_FD_PARAMS *pParams
)
{
    NvHandle           hClient = RES_GET_CLIENT_HANDLE(pRmCliRes);
    nv_file_private_t *nvfp = NULL;
    void              *priv = NULL;
    NV_STATUS          status = NV_OK;

    if (pParams->object.type != NV0000_CTRL_OS_UNIX_EXPORT_OBJECT_TYPE_RM ||
        pParams->fd == -1)
    {
        return NV_ERR_INVALID_PARAMETER;
    }

    nvfp = nv_get_file_private(pParams->fd, NV_TRUE, &priv);
    if (nvfp == NULL)
    {
        NV_ASSERT(priv == NULL);
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    if ((nvfp->handles == NULL) || (nvfp->handles[0] == 0) ||
        (nvfp->maxHandles < 1))
    {
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    status = RmImportObject(hClient,
                            pParams->object.data.rmObject.hParent,
                            &pParams->object.data.rmObject.hObject,
                            nvfp->handles[0], NULL);

done:
    if (priv != NULL)
    {
        nv_put_file_private(priv);
    }

    return status;
}

NV_STATUS
cliresCtrlCmdOsUnixImportObjectsFromFd_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_IMPORT_OBJECTS_FROM_FD_PARAMS *pParams
)
{
    NvHandle           hClient = RES_GET_CLIENT_HANDLE(pRmCliRes);
    nv_file_private_t *nvfp = NULL;
    void              *priv = NULL;
    NV_STATUS          status = NV_OK;
    NvU32              i = 0;
    RmObjExportHandle  hImportHandle;
    NvU32              result;
    RM_API            *pRmApi;

    nvfp = nv_get_file_private(pParams->fd, NV_TRUE, &priv);
    if (nvfp == NULL)
    {
        NV_ASSERT(priv == NULL);
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    if ((nvfp->handles == NULL) ||
        (pParams->numObjects >
           NV0000_CTRL_OS_UNIX_IMPORT_OBJECTS_TO_FD_MAX_OBJECTS))
    {
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    if (!portSafeAddU32(pParams->numObjects, pParams->index, &result) ||
        (result > nvfp->maxHandles))
    {
        status = NV_ERR_OUT_OF_RANGE;
        goto done;
    }

    for (i = 0; i < pParams->numObjects; i++)
    {
        hImportHandle = nvfp->handles[i + pParams->index];

        /* Nothing to import, just continue */
        if (hImportHandle == 0)
        {
            pParams->objectTypes[i] = \
                NV0000_CTRL_CMD_OS_UNIX_IMPORT_OBJECT_TYPE_NONE;
            continue;
        }

        status = RmImportObject(hClient,
                                pParams->hParent,
                                &pParams->objects[i],
                                hImportHandle,
                                &pParams->objectTypes[i]);
        if (status != NV_OK)
        {
            NV_PRINTF(LEVEL_ERROR, "%s: Unable to import handle (%x, %x, %x)\n",
                __FUNCTION__, pParams->hParent, pParams->objects[i], hImportHandle);
            goto done;
        }
    }

done:

    if (status != NV_OK)
    {
        pRmApi = rmapiGetInterface(RMAPI_API_LOCK_INTERNAL);
        while (i > 0)
        {
            i--;

            if (pParams->objects[i] != 0)
            {
                pRmApi->Free(pRmApi, hClient, pParams->objects[i]);
            }
        }
    }

    if (priv != NULL)
    {
        nv_put_file_private(priv);
    }

    return status;
}

NV_STATUS
cliresCtrlCmdOsUnixGetExportObjectInfo_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_GET_EXPORT_OBJECT_INFO_PARAMS *pParams
)
{
    nv_file_private_t *nvfp = NULL;
    void              *priv = NULL;
    NV_STATUS         status = NV_OK;

    if (pParams->fd < 0)
    {
        return NV_ERR_INVALID_PARAMETER;
    }

    nvfp = nv_get_file_private(pParams->fd, NV_TRUE, &priv);
    if (nvfp == NULL)
    {
        NV_ASSERT(priv == NULL);
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    if (nvfp->handles == NULL)
    {
        status = NV_ERR_INVALID_PARAMETER;
        goto done;
    }

    pParams->maxObjects = nvfp->maxHandles;
    pParams->deviceInstance = nvfp->deviceInstance;
    pParams->gpuInstanceId = nvfp->gpuInstanceId;

    os_mem_copy(pParams->metadata, nvfp->metadata, sizeof(nvfp->metadata));

done:
    if (priv != NULL)
    {
        nv_put_file_private(priv);
    }

    return status;
}

NV_STATUS
cliresCtrlCmdOsUnixMemacctSetLimits_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_MEMACCT_SET_LIMITS_PARAMS *pParams
)
{
    void *cgroup = osCgroupGetFromFd(pParams->cgroupFd);
    if (cgroup == NULL)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    NV_STATUS status = memacctSetLimits((ClientGroupID)cgroup, pParams->gpuId, pParams->softLimit, pParams->hardLimit);
    osCgroupPut(cgroup);
    return status;
}

NV_STATUS
cliresCtrlCmdOsUnixMemacctGetLimits_IMPL
(
    RmClientResource *pRmCliRes,
    NV0000_CTRL_OS_UNIX_MEMACCT_GET_LIMITS_PARAMS *pParams
)
{
    NvU32     gpuMask        = 0;
    NvU32     gpuIdx         = 0;
    OBJGPU   *pGpu           = NULL;
    NV_STATUS status         = NV_OK;

    pParams->count = 0;
    NV_ASSERT_OK_OR_RETURN(gpumgrGetGpuAttachInfo(NULL, &gpuMask));

    void *cgroup = osCgroupGetFromFd(pParams->cgroupFd);
    if (cgroup == NULL)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    NvU32 i = 0;
    while ((i < NV0000_CTRL_GPU_MAX_ATTACHED_GPUS) &&
        ((pGpu = gpumgrGetNextGpu(gpuMask, &gpuIdx)) != NULL))
    {
        NV_CHECK_OK_OR_GOTO(status, LEVEL_ERROR,
            memacctGetLimits((ClientGroupID)cgroup, pGpu->gpuId,
                &pParams->limits[i].soft,
                &pParams->limits[i].hard,
                &pParams->limits[i].current),
            out);
        pParams->limits[i].gpuId = pGpu->gpuId;
        i++;
    }
    pParams->count = i;
out:
    osCgroupPut(cgroup);
    return status;
}

/*!
 * osAcpiDsm
 *
 * @brief Handles os specific _DSM method function calls.
 *
 * Input parameters:
 * @param[in]     pGpu   : OBJGPU pointer
 * @param[in]     acpiDsmFunction    : ACPI DSM function
 * @param[in]     acpiDsmSubFunction : ACPI DSM subfunction
 * @param[in/out] pInOut : in/out buffer, caller should make sure the buffer is large enough.
 * @param[in]     pSize  : when input, size of data that the caller wants to read, in bytes.
 *                         when output, size of valid data in pInOuta in bytes.
 */
NV_STATUS osCallACPI_DSM
(
    OBJGPU            *pGpu,
    ACPI_DSM_FUNCTION  acpiDsmFunction,
    NvU32              acpiDsmSubFunction,
    NvU32             *pInOut,
    NvU16             *pSize
)
{
    NV_STATUS   status;
    NvU8       *pAcpiDsmGuid = NULL;
    NvU32       acpiDsmRev;
    nv_state_t *nv  = NV_GET_NV_STATE(pGpu);
    nv_priv_t  *nvp = NV_GET_NV_PRIV(nv);
    NvU16       acpiDsmInArgSize = 4;
    NvBool      acpiNvpcfDsmFunction = NV_FALSE;

    // do any handling/remapping of guid needed.
    status = checkDsmCall(pGpu,
                          (ACPI_DSM_FUNCTION *) &acpiDsmFunction,
                          &acpiDsmSubFunction,
                          pInOut,
                          pSize);

    // return if subfunction is not supported or we're returning cache data
    if (status != NV_WARN_MORE_PROCESSING_REQUIRED)
    {
        return status;
    }

    switch ((NvU32) acpiDsmFunction)
    {
        case ACPI_DSM_FUNCTION_NBSI:
            pAcpiDsmGuid = (NvU8 *) &NBSI_DSM_GUID;
            acpiDsmRev  = NBSI_REVISION_ID;
            break;
        case ACPI_DSM_FUNCTION_NVHG:
            pAcpiDsmGuid = (NvU8 *) &NVHG_DSM_GUID;
            acpiDsmRev  = NVHG_REVISION_ID;
            break;
        case ACPI_DSM_FUNCTION_MXM:
            pAcpiDsmGuid = (NvU8 *) &DSM_MXM_GUID;
            acpiDsmRev  = ACPI_MXM_REVISION_ID;
            break;
        case ACPI_DSM_FUNCTION_NBCI:
            pAcpiDsmGuid = (NvU8 *) &NBCI_DSM_GUID;
            acpiDsmRev  = NBCI_REVISION_ID;
            break;
        case ACPI_DSM_FUNCTION_NVOP:
            pAcpiDsmGuid = (NvU8 *) &NVOP_DSM_GUID;
            acpiDsmRev  = NVOP_REVISION_ID;
            break;
        case ACPI_DSM_FUNCTION_PCFG:
            pAcpiDsmGuid = (NvU8 *) &PCFG_DSM_GUID;
            acpiDsmRev  = PCFG_REVISION_ID;
            break;
        case ACPI_DSM_FUNCTION_GPS_2X:
            pAcpiDsmGuid = (NvU8 *) &GPS_DSM_GUID;
            acpiDsmRev = GPS_2X_REVISION_ID;
            acpiDsmInArgSize = (*pSize);
            break;
        case ACPI_DSM_FUNCTION_GPS:
            if (IsTU10X(pGpu))
            {
                pAcpiDsmGuid = (NvU8 *) &GPS_DSM_GUID;
                acpiDsmRev = GPS_REVISION_ID;
                acpiDsmInArgSize = (*pSize);
            }
            else
            {
                return NV_ERR_NOT_SUPPORTED;
            }
            break;
        case ACPI_DSM_FUNCTION_PEX:
            pAcpiDsmGuid = (NvU8 *) &PEX_DSM_GUID;
            acpiDsmRev   = PEX_REVISION_ID;
            if (acpiDsmSubFunction == PEX_FUNC_SETLTRLATENCY)
            {
                acpiDsmInArgSize = (3 + *pSize);
            }
            break;
        case (ACPI_DSM_FUNCTION_JT):
            pAcpiDsmGuid = (NvU8 *) &JT_DSM_GUID;
            acpiDsmRev = JT_REVISION_ID;
            break;
        case ACPI_DSM_FUNCTION_NVPCF:
            {
                pAcpiDsmGuid = (NvU8 *)&NVPCF_ACPI_DSM_GUID;
                acpiDsmRev = NVPCF_ACPI_DSM_REVISION_ID;
                acpiDsmInArgSize = (*pSize);
                acpiNvpcfDsmFunction = NV_TRUE;
                break;
            }
        case ACPI_DSM_FUNCTION_NVPCF_2X:
            pAcpiDsmGuid = (NvU8 *)&NVPCF_ACPI_DSM_GUID;
            acpiDsmRev = NVPCF_2X_ACPI_DSM_REVISION_ID;
            acpiDsmInArgSize = (*pSize);
            acpiNvpcfDsmFunction = NV_TRUE;
            break;

        default:
            return NV_ERR_NOT_SUPPORTED;
            break;
    }

    status = nv_acpi_dsm_method(nv,
                                pAcpiDsmGuid,
                                acpiDsmRev,
                                acpiNvpcfDsmFunction,
                                acpiDsmSubFunction,
                                pInOut,
                                acpiDsmInArgSize,
                                NULL,
                                pInOut,
                                pSize);

    if (status == NV_OK)
    {
        if (acpiDsmSubFunction == NV_ACPI_ALL_FUNC_SUPPORT)
        {
            // if handling get supported functions list... cache it for later calls
            cacheDsmSupportedFunction(pGpu, acpiDsmFunction, acpiDsmSubFunction, pInOut, *pSize);
        }
    }
    else if (nvp->b_mobile_config_enabled)
    {
        NV_PRINTF(LEVEL_ERROR,
                  "osCallACPI_DSM: Error during 0x%x DSM subfunction 0x%x! status=0x%x\n",
                  acpiDsmFunction, acpiDsmSubFunction, status);
    }

    return status;
}

NV_STATUS osCallACPI_DOD
(
    OBJGPU  *pGpu,
    NvU32   *pOut,
    NvU32   *pSize
)
{
    NV_STATUS rmStatus;
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    if ((pOut == NULL) || (pSize == NULL))
    {
        return NV_ERR_INVALID_POINTER;
    }

    rmStatus = nv_acpi_dod_method(nv, pOut, pSize);

    return rmStatus;
}

//
// osAcpiDdc
//
// Handles os specific _DDC method function calls. _DDC is to get EDID from SBIOS.
//
NV_STATUS osCallACPI_DDC
(
    OBJGPU *pGpu,
    NvU32   ulAcpiId,
    NvU8   *pOutData,
    NvU32  *pOutSize,
    NvBool  bReadMultiBlock
)
{
    NV_STATUS rmStatus;

    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    if ((pOutData == NULL) || (pOutSize == NULL))
    {
        return NV_ERR_INVALID_POINTER;
    }

    portMemSet(pOutData, 0, *pOutSize);

    rmStatus = nv_acpi_ddc_method(nv, pOutData, pOutSize, bReadMultiBlock);

    return rmStatus;
}

// osCallACPI_NVHG_ROM
// Making ACPI Call into SBIOS with ROM method to get display device's ROM data.
//
NV_STATUS  osCallACPI_NVHG_ROM
(
    OBJGPU *pGpu,
    NvU32 *pInData,
    NvU32 *pOutData
)
{
    NV_STATUS rmStatus;
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    if ((pOutData == NULL) || (pInData == NULL))
    {
        return NV_ERR_INVALID_POINTER;
    }

    if (pInData[1] > ROM_METHOD_MAX_RETURN_BUFFER_SIZE)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    rmStatus = nv_acpi_rom_method(nv, pInData, pOutData);

    return rmStatus;
}

void osInitSystemStaticConfig(SYS_STATIC_CONFIG *pConfig)
{
    pConfig->bIsNotebook = rm_is_system_notebook();
    pConfig->bOsCCEnabled = os_cc_enabled;
    pConfig->bOsCCSevSnpEnabled = os_cc_sev_snp_enabled;
    pConfig->bOsCCSmeEnabled = os_cc_sme_enabled;
    pConfig->bOsCCSnpVtomEnabled = os_cc_snp_vtom_enabled;
    pConfig->bOsCCTdxEnabled = os_cc_tdx_enabled;
}

NvU32 osApiLockAcquireConfigureFlags(NvU32 flags)
{
    return flags;
}

NV_STATUS osGpuLocksQueueRelease(OBJGPU *pGpu, NvU32 dpcGpuLocksRelease)
{
    return NV_SEMA_RELEASE_FAILED;
}

void osSyncWithRmDestroy(void)
{
}

void osSyncWithGpuDestroy(NvBool bEntry)
{
}

void osModifyGpuSwStatePersistence
(
    OS_GPU_INFO *pOsGpuInfo,
    NvBool       bEnable
)
{
    if (!osIsLegacyPersistenceModeSupported(pOsGpuInfo))
        return;

    if (bEnable)
    {
        pOsGpuInfo->flags |= NV_FLAG_PERSISTENT_SW_STATE;
    }
    else
    {
        pOsGpuInfo->flags &= ~NV_FLAG_PERSISTENT_SW_STATE;
    }
}

//
//osCallACPI_MXDS
//
//Handles OS specific MXDS function call.
//
NV_STATUS osCallACPI_MXDS
(
    OBJGPU *pGpu,
    NvU32 acpiId,
    NvU32 *pInOut
)
{
    NV_STATUS rmStatus;

    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    if (pInOut == NULL)
    {
        return NV_ERR_INVALID_POINTER;
    }

    rmStatus = nv_acpi_mux_method(nv, pInOut, acpiId, "MXDS");

    return rmStatus;
}

//
//osCallACPI_MXDM
//
//Handles OS specific MXDM function call.
//
NV_STATUS osCallACPI_MXDM
(
    OBJGPU *pGpu,
    NvU32 acpiId,
    NvU32 *pInOut
)
{
    NV_STATUS rmStatus;

    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    if (pInOut == NULL)
    {
        return NV_ERR_INVALID_POINTER;
    }

    rmStatus = nv_acpi_mux_method(nv, pInOut, acpiId, "MXDM");

    return rmStatus;
}

#include "lib/protobuf/prb.h"
#include "lib/protobuf/prb_util.h"
#include "g_nvdebug_pb.h"

NV_STATUS osGetVersionDump(void * pVoid)
{
    PRB_ENCODER * pPrbEnc = (PRB_ENCODER *)pVoid;
    NV_STATUS rmStatus;
    os_version_info * pOsVersionInfo = NULL;
    const char NV_UNKNOWN_BUILD_VERSION[] = "Unknown build version";
    const char NV_UNKNOWN_BUILD_DATE[]    = "Unknown build date";

    NV_ASSERT_OK_OR_RETURN(os_alloc_mem((void**)&pOsVersionInfo,
                                        sizeof(os_version_info)));
    portMemSet(pOsVersionInfo, 0, sizeof(os_version_info));

    prbEncAddUInt32(pPrbEnc,
                    NVDEBUG_SYSTEMINFO_OSINFO_FAMILY,
                    NVDEBUG_OS_UNIX);

    rmStatus = os_get_version_info(pOsVersionInfo);
    if (rmStatus != NV_OK)
    {
        goto cleanup;
    }

    prbEncAddUInt32(pPrbEnc,
                    NVDEBUG_SYSTEMINFO_OSINFO_OSMAJORVERSION,
                    pOsVersionInfo->os_major_version);

    prbEncAddUInt32(pPrbEnc,
                    NVDEBUG_SYSTEMINFO_OSINFO_OSMINORVERSION,
                    pOsVersionInfo->os_minor_version);

    prbEncAddUInt32(pPrbEnc,
                    NVDEBUG_SYSTEMINFO_OSINFO_OSBLDNUM,
                    pOsVersionInfo->os_build_number);

    if (NULL == pOsVersionInfo->os_build_version_str)
    {
        pOsVersionInfo->os_build_version_str = NV_UNKNOWN_BUILD_VERSION;
    }

    prbEncAddString(pPrbEnc,
                    NVDEBUG_SYSTEMINFO_OSINFO_BUILDVERSION,
                    pOsVersionInfo->os_build_version_str);

    if (NULL == pOsVersionInfo->os_build_date_plus_str)
    {
        pOsVersionInfo->os_build_date_plus_str = NV_UNKNOWN_BUILD_DATE;
    }

    prbEncAddString(pPrbEnc,
                    NVDEBUG_SYSTEMINFO_OSINFO_BUILDDATEPLUS,
                    pOsVersionInfo->os_build_date_plus_str);

cleanup:
    os_free_mem(pOsVersionInfo);
    return rmStatus;
}

NV_STATUS osTegraiGpuPerfBoost(OBJGPU *pGpu, NvBool enable, NvU32 duration)
{
    return os_tegra_igpu_perf_boost(pGpu->pOsGpuInfo, enable, duration);
}

NV_STATUS osGetVersion(NvU32 *majorVer, NvU32 *minorVer, NvU32 *buildNum, NvU16 *unusedPatchVersion, NvU16 *unusedProductType)
{
    os_version_info osVersionInfo;
    NV_STATUS rmStatus;

    portMemSet(&osVersionInfo, 0, sizeof(osVersionInfo));

    rmStatus = os_get_version_info(&osVersionInfo);
    if (rmStatus == NV_OK)
    {
        if (majorVer)
            *majorVer = osVersionInfo.os_major_version;
        if (minorVer)
            *minorVer = osVersionInfo.os_minor_version;
        if (buildNum)
            *buildNum = osVersionInfo.os_build_number;
    }

    return rmStatus;
}

NV_STATUS osGetIsOpenRM(NvBool *bOpenRm)
{
    return os_get_is_openrm(bOpenRm);
}

NvBool osIsBifResetSupported(OS_GPU_INFO *pOsGpuInfo)
{
    return os_is_bif_reset_supported((void *)pOsGpuInfo);
}

NV_STATUS
osGetCarveoutInfo
(
    NvU64 *pAddr,
    NvU64 *pSize
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS
osGetVPRInfo
(
    NvU64 *pAddr,
    NvU64 *pSize
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS
osAllocInVPR
(
    MEMORY_DESCRIPTOR *pMemDesc
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS
osGetGenCarveout
(
    NvU64  *pAddr,
    NvU64  *pSize,
    NvU32   id,
    NvU64   align
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS
osI2CClosePorts
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32        numPorts
)
{
    nv_i2c_unregister_clients(pOsGpuInfo);
    return NV_OK;
}

static NvU32
i2cSwPortMapping(
    nv_state_t *nv,
    NvU32 physicalI2CPort
)
{
    NvU32 linuxI2CSwPort = NV_U32_MAX;

    /**
     *  For T23X, Linux Tegra I2C controller driver uses logical port(controller) number
     *  where logical port number of I2C1(Gen1) controller is 0, logical port number for
     *  I2C2(Gen2) controller is 1 and so on. But RM passes I2C physical port(controller)
     *  number i.e RM passes "1" for I2C1(Gen1), 2 for I2C2(Gen2), etc. So convert
     *  physical port number to logical port number(linuxI2CSwPort).
     *
     *  For other chips, the above mentioned logic does not apply and we do not need
     *  conversion as the physical controller number was updated to 0 and RM passes the
     *  same.
     */
    if ((nv->disp_sw_soc_chip_id == NV_CHIP_ID_T234)
        || (nv->disp_sw_soc_chip_id == NV_CHIP_ID_T239)
        )
    {
        linuxI2CSwPort = physicalI2CPort - 1;
    }
    else
    {
        linuxI2CSwPort = physicalI2CPort;
    }

    return linuxI2CSwPort;
}

NV_STATUS
osI2CTransfer
(
    OBJGPU *pGpu,
    NvU32 Port,
    NvU8 Address,
    nv_i2c_msg_t *nv_i2c_msgs,
    NvU32 count
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    if (NV_IS_SOC_DISPLAY_DEVICE(nv))
    {
        Port = i2cSwPortMapping(nv, Port);
        return nv_i2c_transfer(nv, Port, Address,
                               nv_i2c_msgs, count);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

NV_STATUS
osTegraI2CGetBusState
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32 port,
    NvS32 *scl,
    NvS32 *sda
)
{
    if (NV_IS_SOC_DISPLAY_DEVICE(pOsGpuInfo))
    {
        port = i2cSwPortMapping(pOsGpuInfo, port);
        return nv_i2c_bus_status(pOsGpuInfo, port, scl, sda);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

NV_STATUS
osReadI2CBufferDirect
(
    OBJGPU *pGpu,
    NvU32   Port,
    NvU8    Address,
    void   *pOutputBuffer,
    NvU32   OutputSize,
    void   *pInputBuffer,
    NvU32   InputSize
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS
osWriteI2CBufferDirect
(
    OBJGPU  *pGpu,
    NvU32    Port,
    NvU8     Address,
    void    *pOutputBuffer0,
    NvU32    OutputSize0,
    void    *pOutputBuffer1,
    NvU32    OutputSize1
)
{
    return NV_ERR_NOT_SUPPORTED;
}

NV_STATUS
osGC6PowerControl
(
    OBJGPU *pGpu,
    NvU32   cmd,
    NvU32  *pOut
)
{
    NV_STATUS status;
    NvU32 inOut   = cmd;
    NvU16 rtnSize = sizeof(inOut);

    if (FLD_TEST_DRF(_JT_FUNC, _POWERCONTROL, _GPU_POWER_CONTROL, _GSS, inOut))
    {
        if (!pOut)
        {
            return NV_ERR_INVALID_ARGUMENT;
        }
    }

    status = osCallACPI_DSM(pGpu,
                            ACPI_DSM_FUNCTION_JT,
                            JT_FUNC_POWERCONTROL,
                            &inOut,
                            &rtnSize);

    if ((status != NV_OK) || !pOut)
    {
        return status;
    }

    *pOut = inOut;

    return NV_OK;
}

NvBool osTestPcieExtendedConfigAccess(void *handle, NvU32 offset)
{
    OBJGPU    *pGpu;
    KernelBif *pKernelBif;
    NvU32      nvXveId       = 0;
    NvU32      nvXveVccapHdr = 0;
    NvU32      pciStart      = 0;
    NvU32      pcieStart     = 0;

    static NvBool retryAllowed = NV_TRUE;
    static NvBool configAccess = NV_FALSE;

    //
    // Return early for offset within PCI space
    // and does not requires extended config space access
    //
    if (offset < 0x100)
    {
        return NV_TRUE;
    }

    if (!retryAllowed)
    {
        return configAccess;
    }

    pGpu = gpumgrGetSomeGpu();
    if (pGpu == NULL)
    {
        return configAccess;
    }

    retryAllowed = NV_FALSE;

    pKernelBif = GPU_GET_KERNEL_BIF(pGpu);
    if (pKernelBif == NULL || gpuGetBusIntfType_HAL(pGpu) !=
                                  NV2080_CTRL_BUS_INFO_TYPE_PCI_EXPRESS)
    {
        return configAccess;
    }

    // Now verify PCI and PCIe config start registers.
    kbifGetPcieConfigAccessTestRegisters_HAL(pGpu, pKernelBif, &pciStart, &pcieStart);
    os_pci_read_dword(handle, pciStart,  &nvXveId);
    os_pci_read_dword(handle, pcieStart, &nvXveVccapHdr);

    if (NV_OK == kbifVerifyPcieConfigAccessTestRegisters_HAL(pGpu,
                                                             pKernelBif,
                                                             nvXveId,
                                                             nvXveVccapHdr))
    {
        configAccess = NV_TRUE;
    }

    return configAccess;
}

static NvBool skipIovaMappingForTegra
(
    PIOVAMAPPING pIovaMapping,
    nv_state_t *nv
)
{
    //
    // TODO: When ISO SMMU is not present, dma mapping of imported ISO memory
    //       causes crash during __clean_dcache_area_poc. dma mapping of ISO
    //       memory allocated by RM (via __get_free_pages) still works.
    //       Skip dma mapping of imported ISO memory to unblock Tegra Display in
    //       AV+L. Bug 200765629
    //

    NV_ASSERT(nv != NULL);

    if (NV_IS_SOC_DISPLAY_DEVICE(nv) &&
        !NV_SOC_IS_ISO_IOMMU_PRESENT(nv) &&
        !memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_MEMORY_TYPE_DISPLAY_NISO) &&
        memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_EXT_PAGE_ARRAY_MEM))
    {
        NV_PRINTF(LEVEL_INFO, "%s: Skip memdescMapIommu mapping\n", __FUNCTION__);
        return NV_TRUE;
    }

    return NV_FALSE;
}

static NvBool osMemDescRequiresReadOnlyDeviceDmaMap
(
    MEMORY_DESCRIPTOR *pMemDesc
)
{
    //
    // MEMDESC_FLAGS_USER_READ_ONLY is also used by RM-owned buffers that the
    // kernel writes and user/GSP reads. Restrict RO DMA direction to external
    // OS descriptor mappings.
    //
    return memdescGetFlag(pMemDesc, MEMDESC_FLAGS_EXT_PAGE_ARRAY_MEM) &&
           !memdescGetFlag(pMemDesc, MEMDESC_FLAGS_KERNEL_MODE) &&
           (memdescGetFlag(pMemDesc, MEMDESC_FLAGS_USER_READ_ONLY) ||
            memdescGetFlag(pMemDesc, MEMDESC_FLAGS_DEVICE_READ_ONLY));
}

/*!
 * @brief Map memory into an IOVA space according to the given mapping info.
 *
 * @param[in]   pIovaMapping    IOVA mapping info
 *
 * @return      NV_ERR_NOT_SUPPORTED
 */
NV_STATUS
osIovaMap
(
    PIOVAMAPPING pIovaMapping
)
{
    OBJGPU *pGpu;
    nv_state_t *nv, *peer;
    NV_STATUS status;
    RmPhysAddr base;
    NvBool bIsBar0;
    PMEMORY_DESCRIPTOR pRootMemDesc;
    NvBool bIsFbOffset = NV_FALSE;
    NvBool bIsIndirectPeerMapping = NV_FALSE;
    NvBool bIsContig;
    NV_ADDRESS_SPACE addressSpace;
    NvU32 osPageCount;

    if (pIovaMapping == NULL)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    pGpu = gpumgrGetGpuFromId(pIovaMapping->iovaspaceId);
    if (pGpu == NULL)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    pRootMemDesc = memdescGetRootMemDesc(pIovaMapping->pPhysMemDesc, NULL);
    addressSpace = memdescGetAddressSpace(pIovaMapping->pPhysMemDesc);
    if (gpumgrCheckIndirectPeer(pGpu, pRootMemDesc->pGpu) &&
        (addressSpace == ADDR_FBMEM))
    {
        bIsIndirectPeerMapping = NV_TRUE;
    }

    if ((addressSpace != ADDR_SYSMEM) && !bIsIndirectPeerMapping)
    {
        NV_PRINTF(LEVEL_INFO,
                  "%s passed memory descriptor in an unsupported address space (%s)\n",
                  __FUNCTION__,
                  memdescGetApertureString(memdescGetAddressSpace(pIovaMapping->pPhysMemDesc)));
        return NV_ERR_NOT_SUPPORTED;
    }

    //
    // For guest-allocated memory, we don't actually want to do any remapping,
    // since the physical address is already the DMA address to be used by the
    // GPU.
    //
    // For carveout memory, we setup identity mapping, so physical
    // address is same as the DMA address.
    //
    //
    if (memdescIsCarveoutMemory(pIovaMapping->pPhysMemDesc) ||
        memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_GUEST_ALLOCATED))
    {
        return NV_OK;
    }

    nv = NV_GET_NV_STATE(pGpu);
    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pIovaMapping->pPhysMemDesc))
    {
        osPageCount = pIovaMapping->pPhysMemDesc->PageCount;
        NV_ASSERT_OR_RETURN(os_page_size == pIovaMapping->pPhysMemDesc->pageArrayGranularity, NV_ERR_INVALID_PARAMETER);
    }
    else
    {
        osPageCount = NV_RM_PAGES_TO_OS_PAGES(pIovaMapping->pPhysMemDesc->PageCount);
    }

    //
    // Intercept peer IO type memory. These are contiguous allocations, so no
    // need to adjust pages.
    //
    if (memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_PEER_IO_MEM))
    {
        NV_ASSERT(memdescGetContiguity(pIovaMapping->pPhysMemDesc, AT_CPU));

        status = nv_dma_map_mmio(nv->dma_dev,
            osPageCount,
            &pIovaMapping->iovaArray[0]);

        if (status != NV_OK)
        {
            NV_PRINTF(LEVEL_ERROR,
                      "%s: failed to map peer IO mem (status = 0x%x)\n",
                      __FUNCTION__, status);
        }

        return status;
    }

    //
    // We need to check against the "root" GPU, e.g., the GPU that owns this
    // allocation. If we're trying to map one of its BARs for a peer, we need
    // to handle it differently because it wouldn't have gone through our system
    // memory page allocation paths, obviously, and wouldn't have alloc private
    // data associated with it.
    //
    peer = NV_GET_NV_STATE(pRootMemDesc->pGpu);
    bIsContig = memdescGetContiguity(pIovaMapping->pPhysMemDesc, AT_CPU);
    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pIovaMapping->pPhysMemDesc))
    {
        NV_ASSERT_OR_RETURN(pIovaMapping->pPhysMemDesc->pageArrayGranularity == os_page_size, NV_ERR_INVALID_ARGUMENT);
    }
    else if (NV_RM_PAGE_SIZE < os_page_size && !bIsContig)
    {
        RmDeflateRmToOsPageArray(&pIovaMapping->iovaArray[0],
                                pIovaMapping->pPhysMemDesc->PageCount);
    }

    base = memdescGetPhysAddr(pIovaMapping->pPhysMemDesc, AT_CPU, 0);
    bIsBar0 = IS_REG_OFFSET(peer, base, pIovaMapping->pPhysMemDesc->Size);

    bIsFbOffset = IS_FB_OFFSET(peer, base, pIovaMapping->pPhysMemDesc->Size);

    void *pPriv = memdescGetMemData(pIovaMapping->pPhysMemDesc);

    if (!bIsBar0 && !bIsFbOffset)
    {
        if (pPriv == NULL)
        {
            return NV_ERR_INVALID_STATE;
        }
    }
    else if(bIsIndirectPeerMapping)
    {
        NV_ASSERT(!bIsBar0 && bIsFbOffset);
        //
        // TODO: Align onlined GPU memory allocation paths with system memory allocation
        //       That way pMemDesc->pMemData is setup correctly when we try to create mapping
        //       to onlined memory of indirect peer. After that we can also get rid of some
        //       extra code in nv_dma_map_alloc. See bug 190324 for details
        //

        status = memdescGetNvLinkGpa(pRootMemDesc->pGpu, (bIsContig ? 1 : osPageCount),
                                    &pIovaMapping->iovaArray[0]);
        if (status != NV_OK)
        {
            NV_PRINTF(LEVEL_ERROR, "%s Failed to get SPA\n", __FUNCTION__);
            return status;
        }
    }

    if (skipIovaMappingForTegra(pIovaMapping, nv))
    {
        return NV_OK;
    }

    if (!bIsBar0 && (!bIsFbOffset || bIsIndirectPeerMapping))
    {
        NvBool bReadOnlyDeviceMap =
            osMemDescRequiresReadOnlyDeviceDmaMap(pIovaMapping->pPhysMemDesc);

        status = nv_dma_map_alloc(
                    osGetDmaDeviceForMemDesc(nv, pIovaMapping->pPhysMemDesc),
                    osPageCount,
                    &pIovaMapping->iovaArray[0],
                    bIsContig, bReadOnlyDeviceMap, &pPriv);
        if (status != NV_OK)
        {
            NV_PRINTF(LEVEL_ERROR,
                      "%s: failed to map allocation (status = 0x%x)\n",
                      __FUNCTION__, status);
            return status;
        }

        pIovaMapping->pOsData = pPriv;
    }
    else if (peer != nv)
    {
        status = nv_dma_map_peer(nv->dma_dev, peer->dma_dev, bIsBar0 ? 0 : 1,
                                 osPageCount, &pIovaMapping->iovaArray[0]);
        if (status != NV_OK)
        {
            NV_PRINTF(LEVEL_INFO,
                      "%s: failed to map peer (base = 0x%llx, status = 0x%x)\n",
                      __FUNCTION__, base, status);
            return status;
        }

        //
        // pOsData must be NULL to distinguish a peer DMA mapping from a
        // system memory mapping in osIovaUnmap(), so make sure to set it
        // accordingly here.
        //
        pIovaMapping->pOsData = NULL;
    }
    else
    {
        NV_PRINTF(LEVEL_INFO, "cannot map a GPU's BAR to itself\n");
        return NV_ERR_NOT_SUPPORTED;
    }

    //
    // If the OS layer doesn't think in RM page size, we need to inflate the
    // PTE array into RM pages.
    //
    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pIovaMapping->pPhysMemDesc))
    {
        NV_ASSERT_OR_RETURN(pIovaMapping->pPhysMemDesc->pageArrayGranularity == os_page_size, NV_ERR_INVALID_ARGUMENT);
    }
    else if (NV_RM_PAGE_SIZE < os_page_size && !bIsContig)
    {
        RmInflateOsToRmPageArray(&pIovaMapping->iovaArray[0],
                                pIovaMapping->pPhysMemDesc->PageCount);
    }

    return NV_OK;
}

/*!
 * @brief Unmap memory from an IOVA space according to the given mapping info.
 *
 * This mapping info must have been previously mapped by osIovaMap().
 *
 * @param[in]   pIovaMapping    IOVA mapping info
 *
 */
void
osIovaUnmap
(
    PIOVAMAPPING pIovaMapping
)
{
    OBJGPU *pGpu;
    nv_state_t *nv;
    void *pPriv;
    NV_STATUS status;
    NvU64 osPageCount;

    if (pIovaMapping == NULL)
    {
        return;
    }

    pGpu = gpumgrGetGpuFromId(pIovaMapping->iovaspaceId);
    if (pGpu == NULL)
    {
        return;
    }

    //
    // For guest-allocated or carveout memory, we never actually remapped the
    // memory, so we shouldn't try to unmap it here.
    //
    if (memdescIsCarveoutMemory(pIovaMapping->pPhysMemDesc) ||
        memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_GUEST_ALLOCATED))
    {
        return;
    }

    nv = NV_GET_NV_STATE(pGpu);

    if (skipIovaMappingForTegra(pIovaMapping, nv))
    {
        return;
    }
    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pIovaMapping->pPhysMemDesc))
    {
        osPageCount = pIovaMapping->pPhysMemDesc->PageCount;
        NV_ASSERT(os_page_size == pIovaMapping->pPhysMemDesc->pageArrayGranularity);
    }
    else
    {
        osPageCount = NV_RM_PAGES_TO_OS_PAGES(pIovaMapping->pPhysMemDesc->PageCount);
    }

    if (memdescGetFlag(pIovaMapping->pPhysMemDesc, MEMDESC_FLAGS_PEER_IO_MEM))
    {
        nv_dma_unmap_mmio(nv->dma_dev,
            osPageCount,
            pIovaMapping->iovaArray[0]);

        return;
    }

    //
    // TODO: Formalize the interface with the OS layers so we can use a common
    // definition of OS_IOVA_MAPPING_DATA.
    //
    pPriv = (void *)pIovaMapping->pOsData;

    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pIovaMapping->pPhysMemDesc))
    {
        NV_ASSERT(pIovaMapping->pPhysMemDesc->pageArrayGranularity == os_page_size);
    }
    else if (NV_RM_PAGE_SIZE < os_page_size &&
            !memdescGetContiguity(pIovaMapping->pPhysMemDesc, AT_CPU))
    {
        RmDeflateRmToOsPageArray(&pIovaMapping->iovaArray[0],
                                pIovaMapping->pPhysMemDesc->PageCount);
    }

    if (pPriv != NULL)
    {
        status = nv_dma_unmap_alloc(nv->dma_dev,
            osPageCount,
            &pIovaMapping->iovaArray[0], &pPriv);
        if (status != NV_OK)
        {
            NV_PRINTF(LEVEL_ERROR,
                      "%s: failed to unmap allocation (status = 0x%x)\n",
                      __FUNCTION__, status);
        }
    }
    else
    {
        nv_dma_unmap_peer(nv->dma_dev,
            osPageCount,
            pIovaMapping->iovaArray[0]);
    }

    //
    // If the OS layer doesn't think in RM page size, we need to fluff out the
    // PTE array into RM pages.
    //
    if (IS_DISCONTIG_AND_DYNGRAN_ENABLED(pIovaMapping->pPhysMemDesc))
    {
        NV_ASSERT(pIovaMapping->pPhysMemDesc->pageArrayGranularity == os_page_size);
    }
    else if (NV_RM_PAGE_SIZE < os_page_size &&
            !memdescGetContiguity(pIovaMapping->pPhysMemDesc, AT_CPU))
    {
        RmInflateOsToRmPageArray(&pIovaMapping->iovaArray[0],
                                pIovaMapping->pPhysMemDesc->PageCount);
    }

    pIovaMapping->pOsData = NULL;
}

/*!
 * @brief Set the GPU Rail Voltage in Tegra SoC. Currently not supported
 *
 * @param[in]  pGpu            GPU object pointer
 * @param[in]  reqVoltageuV    Rail Voltage requested in uV
 * @param[out] pSetVoltageuV   Rail Voltage set in uV
 *
 * @return    NV_ERR_NOT_SUPPORTED
 */
NV_STATUS
osSetGpuRailVoltage
(
   OBJGPU   *pGpu,
   NvU32     reqVoltageuV,
   NvU32    *pSetVoltageuV
)
{
    return NV_ERR_NOT_SUPPORTED;
}

/*!
 * @brief Get the GPU Rail Voltage in Tegra SoC. Currently not supported
 *
 * @param[in]  pGpu        GPU object pointer
 * @param[out] voltageuV   Rail Voltage in uV
 *
 * @return    NV_ERR_NOT_SUPPORTED
 */
NV_STATUS
osGetGpuRailVoltage
(
    OBJGPU   *pGpu,
    NvU32    *pVoltageuV
)
{
    return NV_ERR_NOT_SUPPORTED;
}

/*!
 * @brief Bring down system in a controlled manner on known error conditions.
 *
 * @bugCode[in] Error code / reason.
 */
void osBugCheck(NvU32 bugCode)
{
    if (bugCode > OS_BUG_CHECK_BUGCODE_LAST)
    {
        bugCode = OS_BUG_CHECK_BUGCODE_UNKNOWN;
    }

    os_bug_check(bugCode, ppOsBugCheckBugcodeStr[bugCode]);
}

/*!
 * @brief Perform an action at assertion failure.
 */
void osAssertFailed(void)
{
    os_dump_stack();
}

/*!
 * @brief Get the GPU Chip Info - Speedo and IDDQ values
 *
 *
 * @param[in]   pGpu           GPU object pointer
 * @param[out]  pGpuSpeedoHv   Pointer to GPU Speedo value at high voltage corner.
 * @param[out]  pGpuSpeedoLv   Pointer to GPU Speedo value at low voltage corner.
 * @param[out]  pGpuIddq       Pointer to GPU Iddq Value
 * @param[out]  pChipSkuId     SKU ID for the chip
 *
 * @return     NV_ERR_NOT_SUPPORTED
 */
NV_STATUS
osGetChipInfo
(
    OBJGPU   *pGpu,
    NvU32    *pGpuSpeedoHv,
    NvU32    *pGpuSpeedoLv,
    NvU32    *pGpuIddq,
    NvU32    *pChipSkuId
)
{
    return NV_ERR_NOT_SUPPORTED;
}

/*
 * @brief Get the GPU Rail Voltage Info (i.e. Min, Max and StepSize) in Tegra SoC.
 *
 * @param[in]  pGpu            GPU object pointer
 * @param[out] pMinVoltageuV   Minimum Voltage supported on the Rail in Micro Volts
 * @param[out] pMaxVoltageuV   Maximum Voltage supported on the Rail in Micro Volts
 * @param[out] pStepVoltageuV  Voltage Step-size supported on the Rail in Micro Volts
 *
 * @return    NV_ERR_NOT_SUPPORTED
 */
NV_STATUS
osGetGpuRailVoltageInfo
(
    OBJGPU    *pGpu,
    NvU32     *pMinVoltageuV,
    NvU32     *pMaxVoltageuV,
    NvU32     *pStepVoltageuV
)
{
    return NV_ERR_NOT_SUPPORTED;
}

/*!
 * @brief Get the current opaque security token.
 *
 * For Linux the security token is the effective UID of a process and process ID
 *
 * Note: This function allocates memory for the token. The onus is on the calling
 * function to free the memory associated with the token once its done with it.
 *
 * @return pointer to the security token.
 */
PSECURITY_TOKEN
osGetSecurityToken(void)
{
    NV_STATUS rmStatus;
    TOKEN_USER *pTokenUser;

    pTokenUser = portMemAllocNonPaged(sizeof(TOKEN_USER));
    if (pTokenUser == NULL)
    {
        return NULL;
    }
    rmStatus = os_get_euid(&pTokenUser->euid);
    if (rmStatus != NV_OK)
    {
        portMemFree(pTokenUser);
        return NULL;
    }

    pTokenUser->pid = os_get_current_process();

    return (PSECURITY_TOKEN)pTokenUser;
}

PUID_TOKEN
osGetCurrentUidToken(void)
{
    NV_STATUS rmStatus;
    NvU32 *pUidToken;

    pUidToken = portMemAllocNonPaged(sizeof(NvU32));
    if (pUidToken == NULL)
    {
        return NULL;
    }

    rmStatus = os_get_euid(pUidToken);
    if (rmStatus != NV_OK)
    {
        portMemFree(pUidToken);
        return NULL;
    }

    return (PUID_TOKEN)pUidToken;
}

/*!
 * @brief Interface function to validate the token for the current client
 *
 * This function takes two tokens as parameters, validates them and checks
 * if either the PID or EUID from client database matches the current PID or EUID.
 *
 * @param[in] pClientSecurityToken   security token cached in the client db
 * @param[in] pCurrentSecurityToken  security token of the current client
 * @return             NV_OK    if the validation is successful
 *                     NV_ERR_INVALID_CLIENT if the tokens do not match
 *                     NV_ERR_INVALID_POINTER if the tokens are invalid
 */
NV_STATUS
osValidateClientTokens
(
   PSECURITY_TOKEN pClientSecurityToken,
   PSECURITY_TOKEN pCurrentSecurityToken
)
{
    PTOKEN_USER  pClientTokenUser  = (PTOKEN_USER)pClientSecurityToken;
    PTOKEN_USER  pCurrentTokenUser = (PTOKEN_USER)pCurrentSecurityToken;

    if (pClientTokenUser == NULL || pCurrentTokenUser == NULL)
        return NV_ERR_INVALID_POINTER;

    if ((pClientTokenUser->euid != pCurrentTokenUser->euid) &&
        (pClientTokenUser->pid != pCurrentTokenUser->pid))
    {
        NV_PRINTF(LEVEL_INFO,
                  "NVRM: %s: Current security token doesn't match the one in the client database. "
                  "Current EUID: %d, PID: %d; Client DB EUID: %d, PID: %d\n",
                  __FUNCTION__, pCurrentTokenUser->euid, pCurrentTokenUser->pid,
                  pClientTokenUser->euid, pClientTokenUser->pid);
        return NV_ERR_INVALID_CLIENT;
    }

    return NV_OK;
}

/*!
 * @brief Interface function to compare the tokens for two client
 *
 * This function takes two tokens as parameters, validates them and checks
 * if the EUIDs of each token match.
 *
 * @param[in] pToken1  Token to compare
 * @param[in] pToken2  Token to compare
 * @return             NV_TRUE if the tokens match
 *                     NV_FALSE if the tokens do not match
 */
NvBool
osUidTokensEqual
(
   PUID_TOKEN pUidToken1,
   PUID_TOKEN pUidToken2
)
{
    NvU32 * pTokenUser1 = (NvU32*)pUidToken1;
    NvU32 * pTokenUser2 = (NvU32*)pUidToken2;

    NV_ASSERT_OR_RETURN((pTokenUser1 != NULL), NV_FALSE);
    NV_ASSERT_OR_RETURN((pTokenUser2 != NULL), NV_FALSE);

    if (*pTokenUser1 != *pTokenUser2)
    {
        return NV_FALSE;
    }

    return NV_TRUE;
}

NvBool
osRemoveGpuSupported
(
    void
)
{
    return os_pci_remove_supported();
}

/*
 * @brief Get the address ranges assigned to local or peer GPUs on a system that
 * supports hardware address translation services (ATS) over NVLink/C2C.
 *
 * @note
 * - All address values are in the System Physical Address (SPA) space
 * - Targets can either be "Local" (bIsPeer=False) or for a specified "Peer"
 *   (bIsPeer=True, peerIndex=#) GPU
 * - Target address and mask values have a specified bit width, and represent
 *   the higher order bits above the target address granularity
 *
 * @param[in]   pGpu                GPU object pointer
 * @param[out]  pAddrSysPhys        Pointer to hold SPA
 * @param[out]  pAddrWidth          Address range width value pointer
 * @param[out]  pMask               Mask value pointer
 * @param[out]  pMaskWidth          Mask width value pointer
 * @param[in]   bIsPeer             NV_TRUE if this is a peer, local GPU otherwise
 * @param[in]   peerIndex           Peer index
 *
 * @return      NV_OK or NV_ERR_NOT_SUPPORTED
 *
 *              A return value of NV_ERR_NOT_SUPPORTED for the local GPU would
 *              indicate that the system does not support ATS over NVLink/C2C
 */
NV_STATUS
osGetAtsTargetAddressRange
(
    OBJGPU *pGpu,
    NvU64   *pAddrSysPhys,
    NvU32   *pAddrWidth,
    NvU32   *pMask,
    NvU32   *pMaskWidth,
    NvBool  bIsPeer,
    NvU32   peerIndex
)
{
#if RMCFG_MODULE_KERNEL_BIF && RMCFG_MODULE_KERNEL_NVLINK && defined(NVCPU_AARCH64)
    KernelNvlink *pKernelNvlink = GPU_GET_KERNEL_NVLINK(pGpu);
    KernelBif    *pKernelBif    = GPU_GET_KERNEL_BIF(pGpu);
    nv_state_t   *nv;
    const int addrMaskWidth = 0x10;

    if (!pKernelNvlink && !pKernelBif->getProperty(pKernelBif, PDB_PROP_KBIF_IS_C2C_LINK_UP))
        return NV_ERR_INVALID_ARGUMENT;

    nv = NV_GET_NV_STATE(pGpu);

    //
    // TODO : Bug 1848958 restricts peer device tree parsing. Return early if
    // peer values are requested. This should be fixed by passing correct pGpu
    // pointer of the peer GPU retrieved using peerIds.
    //
    if (bIsPeer)
    {
        const int addrWidth = 0x10;

        *pAddrSysPhys = 0;
        *pAddrWidth = addrWidth;
        *pMask = 0;
        *pMaskWidth = addrMaskWidth;
        return NV_OK;
    }
    else
    {
        NV_STATUS status = nv_get_device_memory_config(nv, pAddrSysPhys, NULL, NULL, NULL,
                                                       pAddrWidth, NULL);
        if (status == NV_OK)
        {
            *pMask = NVBIT(*pAddrWidth) - 1U;
            *pMaskWidth = addrMaskWidth;
        }
        return status;
    }

    return NV_OK;
#endif
    return NV_ERR_NOT_SUPPORTED;
}

/*
 * @brief Get the physical address in CPU address map and NUMA node id
 * of the GPU memory.
 *
 * @note
 * - The physical address is System Physical Address (SPA) in baremetal/host
 *   and Intermediate Physical Address(IPA) or Guest Physical Address(GPA)
 *   inside a VM.
 *
 * @param[in]   pGpu             GPU object pointer
 * @param[out]  pAddrPhys        Pointer to hold the physical address of FB in
 *                               CPU address map
 * @param[out]  pSizePhys        Pointer to hold the size of FB mapped to CPU
 * @param[out]  pNodeId          NUMA nodeID of respective GPU memory
 *
 * @return      NV_OK or NV_ERR_NOT_SUPPORTED
 *
 */
NV_STATUS
osGetFbNumaInfo
(
    OBJGPU *pGpu,
    NvU64  *pAddrPhys,
    NvU64  *pSizePhys,
    NvU64  *pAddrRsvdPhys,
    NvS32  *pNodeId
)
{
#if RMCFG_MODULE_KERNEL_BIF && RMCFG_MODULE_KERNEL_NVLINK && defined(NVCPU_AARCH64)
    KernelNvlink *pKernelNvlink = GPU_GET_KERNEL_NVLINK(pGpu);
    KernelBif    *pKernelBif    = GPU_GET_KERNEL_BIF(pGpu);
    nv_state_t   *nv;

    *pNodeId = NV0000_CTRL_NO_NUMA_NODE;

    if (!pKernelNvlink && !pKernelBif->getProperty(pKernelBif, PDB_PROP_KBIF_IS_C2C_LINK_UP))
        return NV_ERR_INVALID_ARGUMENT;

    nv = NV_GET_NV_STATE(pGpu);

    NV_STATUS status = nv_get_device_memory_config(nv, NULL, pAddrPhys, pSizePhys,
                                                   pAddrRsvdPhys, NULL, pNodeId);

    return status;
#endif
    return NV_ERR_NOT_SUPPORTED;
}


/*
 * @brief Verif only function to get the chiplib overrides for link connection
 *        state for all C2C links.
 *
 * If chiplib overrides exist, each link can either be enabled (1) or disabled (0)
 *
 * @param[in]   pGpu                GPU object pointer
 * @param[in]   maxLinks            Size of pLinkConnection array
 * @param[out]  pLinkConnection     array of pLinkConnection values to be populated by MODS
 *
 * @return      NV_OK or NV_ERR_NOT_SUPPORTED (no overrides available)
 */
NV_STATUS
osGetForcedC2CConnection
(
    OBJGPU *pGpu,
    NvU32   maxLinks,
    NvU32   *pLinkConnection
)
{
    int i, ret;
    NV_STATUS status;
    char path[64];

    NV_ASSERT_OR_RETURN((pLinkConnection != NULL), NV_ERR_INVALID_POINTER);
    NV_ASSERT_OR_RETURN((maxLinks > 0), NV_ERR_NOT_SUPPORTED);
    NV_ASSERT_OR_RETURN((pGpu != NULL), NV_ERR_INVALID_ARGUMENT);

    for (i = 0; i < maxLinks; i++)
    {
        ret = os_snprintf(path, sizeof(path), "CPU_MODEL|CM_ATS_ADDRESS|C2C%u", i);
        NV_ASSERT((ret > 0) && (ret < (sizeof(path) - 1)));

        status = gpuSimEscapeRead(pGpu, path, 0, 4, &pLinkConnection[i]);
        if (status == NV_OK)
        {
            NV_PRINTF(LEVEL_INFO, "%s: %s=0x%X\n", __FUNCTION__,
                      path, pLinkConnection[i]);
        }
        else
        {
            NV_PRINTF(LEVEL_INFO, "%s: gpuSimEscapeRead for '%s' failed (%u)\n",
                      __FUNCTION__, path, status);
            return NV_ERR_NOT_SUPPORTED;
        }
    }
    return NV_OK;
}

static NV_STATUS
osGetSmbiosTableInfo
(
    const NvU8 *pMappedAddr,
    NvU64 *pBaseAddr,
    NvU64 *pLength,
    NvU64 *pNumSubTypes,
    NvU32 *pVersion
)
{
    *pBaseAddr = 0;
    *pLength = 0;
    *pNumSubTypes = 0;
    *pVersion = 0;

    if (portMemCmp(pMappedAddr, "_SM3_", 5) == 0)
    {
        *pVersion = (pMappedAddr[7] << 8) | pMappedAddr[8];
        portMemCopy(pLength, 4, pMappedAddr + 12, 4);
        portMemCopy(pBaseAddr, 8, pMappedAddr + 16, 8);

        *pNumSubTypes = *pLength / 4;

        return NV_OK;
    }

    if (portMemCmp(pMappedAddr, "_SM_", 4) == 0)
    {
        *pVersion = (pMappedAddr[6] << 8) | pMappedAddr[7];

        pMappedAddr += 16;

        if (portMemCmp(pMappedAddr, "_DMI_", 5) == 0)
        {
            portMemCopy(pLength, 2, pMappedAddr + 6, 2);
            portMemCopy(pBaseAddr, 4, pMappedAddr + 8, 4);
            portMemCopy(pNumSubTypes, 2, pMappedAddr + 12, 2);

            if (!*pVersion)
                *pVersion = (pMappedAddr[14] & 0xF0) << 4 |
                            (pMappedAddr[14] & 0x0F);

            return NV_OK;
        }
    }

    return NV_ERR_INVALID_ADDRESS;
}


/*
 * @brief Function to export SMBIOS table. Also, maps table in kernel-space.
 *
 * @param[out]   ppBaseVAddr         Base virtual address of SMBIOS table.
 * @param[out]   pLength             Size of SMBIOS table.
 * @param[out]   pNumSubTypes        Count of structures (types) embedded in
 *                                   the SMBIOS table.
 * @param[out]   pVersion            SMBIOS version
 *
 * @return NV_OK, NV_ERR_INSUFFICIENT_RESOURCES or NV_ERR_INVALID_ADDRESS
 *          or errors from OS layer
 */
NV_STATUS
osGetSmbiosTable
(
    void **ppBaseVAddr,
    NvU64 *pLength,
    NvU64 *pNumSubTypes,
    NvU32 *pVersion
)
{
    NV_STATUS status = NV_OK;
    NvU64 physSmbiosAddr = ~0ull;
    void *pMappedAddr = NULL;
    NvU64 basePAddr = 0;

    if (!NVCPU_IS_X86_64 && !NVCPU_IS_AARCH64)
    {
        return NV_ERR_NOT_SUPPORTED;
    }

    status = os_get_smbios_header(&physSmbiosAddr);
    if (status != NV_OK)
    {
        NV_PRINTF(LEVEL_INFO, "%s: Failed query SMBIOS table with error: %x \n",
                  __FUNCTION__, status);
        return status;
    }

    NV_ASSERT(physSmbiosAddr != ~0ull);

    pMappedAddr = osMapKernelSpace(physSmbiosAddr,
                                   os_page_size,
                                   NV_MEMORY_CACHED,
                                   NV_PROTECT_READ_WRITE);
    if (!pMappedAddr)
    {
        return NV_ERR_INSUFFICIENT_RESOURCES;
    }

    status = osGetSmbiosTableInfo(pMappedAddr,
                                  &basePAddr,
                                  pLength,
                                  pNumSubTypes,
                                  pVersion);

    osUnmapKernelSpace(pMappedAddr, os_page_size);

    if (status != NV_OK)
    {
        return status;
    }

    *ppBaseVAddr = osMapKernelSpace(basePAddr,
                                    *pLength,
                                    NV_MEMORY_CACHED,
                                    NV_PROTECT_READ_WRITE);
    if (!*ppBaseVAddr)
    {
        return NV_ERR_INSUFFICIENT_RESOURCES;
    }

    return NV_OK;
}

/*
 * @brief Function to free SMBIOS table mappings
 *
 * @param[in]   pBaseVAddr        Base virtual address of SMBIOS table.
 * @param[in]   length            Size of SMBIOS table.
 *
 */
void
osPutSmbiosTable
(
    void *pBaseVAddr,
    NvU64 length
)
{
    osUnmapKernelSpace(pBaseVAddr, length);
}

NV_STATUS
osGetAcpiRsdpFromUefi
(
    NvU32  *pRsdpAddr
)
{
    return os_get_acpi_rsdp_from_uefi(pRsdpAddr);
}

/*
 *  @brief Returns NV_TRUE if NvSwitch device is present in the system.
 */
NvBool
osIsNvswitchPresent
(
    void
)
{
    return os_is_nvswitch_present();
}

/*
 *  @brief Function to add crashlog buffer entry.
 *
 *  @param[in] pBuffer              virt_addr of nvlog buffer
 *  @param[in] length               size of nvlog buffer
 */
void
osAddRecordForCrashLog
(
    void *pBuffer,
    NvU32 length
)
{
    os_add_record_for_crashLog(pBuffer, length);
}

/*
 *  @brief Function to delete crashlog buffer entry.
 *
 *  @param[in] pBuffer              virt_addr of nvlog buffer
 */
void
osDeleteRecordForCrashLog
(
    void *pBuffer
)
{
    os_delete_record_for_crashLog(pBuffer);
}

/*
 *  @brief Queries the sysfs interface to get memblock size
 *  @param[out] memblock_size Pointer to the memblock_size
 */
NV_STATUS
osNumaMemblockSize
(
    NvU64 *memblock_size
)
{
    return os_numa_memblock_size(memblock_size);
}

NvBool
osNumaOnliningEnabled
(
    OS_GPU_INFO *pOsGpuInfo
)
{
    NvS32 numaNodeId = NV0000_CTRL_NO_NUMA_NODE;

    //
    // Note that this numaNodeId value fetched from Linux layer might not be
    // accurate since it is possible to overwrite it with regkey on some configs
    //
    if (nv_get_device_memory_config(pOsGpuInfo, NULL, NULL, NULL, NULL, NULL,
                                    &numaNodeId) != NV_OK)
    {
        return NV_FALSE;
    }

    return (numaNodeId != NV0000_CTRL_NO_NUMA_NODE);
}

/*
 *  @brief Function to call NUMA allocation entry.
 *
 *  @param[in]  nid       NUMA node id
 *  @param[in]  size      Allocation size
 *  @param[in]  flag      Allocation flags
 *  @param[out] pAddress  Ptr to the allocated physical address
 */
NV_STATUS
osAllocPagesNode
(
    NvS32       nid,
    NvLength    size,
    NvU32       flag,
    NvU64      *pAddress
)
{
    NV_STATUS  status    = NV_OK;
    NvU32      localFlag = NV_ALLOC_PAGES_NODE_NONE;

    if (pAddress == NULL || nid < 0 || size > NV_U32_MAX)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    // Translate the flags
    if (flag & OS_ALLOC_PAGES_NODE_SKIP_RECLAIM)
    {
        localFlag |= NV_ALLOC_PAGES_NODE_SKIP_RECLAIM;
    }

    status = os_alloc_pages_node(nid, (NvU32)size, localFlag, pAddress);
    return status;
}

void
osAllocAcquirePage
(
    NvU64 pAddress,
    NvU32 pageCount
)
{
    NvU32 i;

    for (i = 0; i < pageCount; i++)
    {
        os_get_page(pAddress + (i << os_page_shift));
    }
}

void
osAllocReleasePage
(
    NvU64 pAddress,
    NvU32 pageCount
)
{
    NvU32 i;

    for (i = 0; i < pageCount; i++)
    {
        os_put_page(pAddress + (i << os_page_shift));
    }
}

/*
 *  @brief Function to return refcount on a page
 *  @param[in] address  The physical address of the page
 */
NvU32
osGetPageRefcount
(
    NvU64       pAddress
)
{
    return os_get_page_refcount(pAddress);
}

/*
 *  @brief Function to return the number of tail pages if the address is
 *  referring to a compound page; For non-compound pages, 1 is returned.
 *  @param[in] address  The physical address of the page
 */
NvU32
osCountTailPages
(
    NvU64       pAddress
)
{
    return os_count_tail_pages(pAddress);
}

NvU64
osGetPageSize(void)
{
    return os_page_size;
}

NvU64
osGetSupportedSysmemPageSizeMask(void)
{
    //
    // We assume that the kernel can support all power-of-two pagesizes 
    // between os_page_size and os_max_page_size (inclusive).  Return a 
    // bitmask containing all of those.
    //
    return (((os_max_page_size << 1) - 1) & (~(os_page_size - 1)));
}

NvU8
osGetPageShift(void)
{
    return os_page_shift;
}



/*
 * @brief Opens a new temporary file for reading and writing
 *
 * @param[in]  ppFile      void double pointer
 *
 * @returns NV_STATUS, NV_OK if success,
                       NV_ERR_GENERIC, if error
                       NV_ERR_NOT_SUPPORTED, for unsupported platforms
 */
NV_STATUS
osOpenTemporaryFile
(
    void **ppFile
)
{
    return os_open_temporary_file(ppFile);
}

/*
 * @brief Closes the specified temporary file
 *
 * @param[in]  pFile      Pointer to file
 *
 * @returns void
 */
void
osCloseFile
(
    void *pFile
)
{
    os_close_file(pFile);
}

/*
 * @brief Writes the buffer to the specified file at the given offset
 *
 * @param[in]  pFile            Pointer to file (void)
 * @param[in]  pBuffer          Pointer to buffer from which to copy
 * @param[in]  size             Size of the copy
 * @parma[in]  offset           offset in the file
 *
 * @returns NV_STATUS, NV_OK if success,
                       NV_ERR_GENERIC, if error
                       NV_ERR_NOT_SUPPORTED, for unsupported platforms
 */
NV_STATUS
osWriteToFile
(
    void *pFile,
    NvU8 *pBuffer,
    NvU64 size,
    NvU64 offset
)
{
    return os_write_file(pFile, pBuffer, size, offset);
}

/*
 * @brief Reads from the specified file at the given offset
 *
 * @param[in]  pFile            Pointer to file (void *)
 * @param[in]  pBuffer          Pointer to buffer to which the data is copied
 * @param[in]  size             Size of the copy
 * @parma[in]  offset           offset in the file
 *
 * @returns NV_STATUS, NV_OK if success,
                       NV_ERR_GENERIC, if error
                       NV_ERR_NOT_SUPPORTED, for unsupported platforms
 */
NV_STATUS
osReadFromFile
(
    void *pFile,
    NvU8 *pBuffer,
    NvU64 size,
    NvU64 offset
)
{
    return os_read_file(pFile, pBuffer, size, offset);
}

/*
 * @brief Unregisters caps from the capability framework.
 *        The function assumes that the caps are allocated and stored in the
 *        hierarchical order. If they aren't, OS (Linux kernel) would warn and
 *        leak the caps.
 *
 * @param[in]  pOsRmCaps           caps of interest
 */
void
osRmCapUnregister
(
    OS_RM_CAPS **ppOsRmCaps
)
{
    OS_RM_CAPS *pOsRmCaps = *ppOsRmCaps;
    NvS32 i;

    if (pOsRmCaps == NULL)
    {
        return;
    }

    for (i = pOsRmCaps->count - 1; i >= 0; i--)
    {
        if (pOsRmCaps->caps[i] != NULL)
        {
            os_nv_cap_destroy_entry(pOsRmCaps->caps[i]);
        }
    }

    os_free_mem(pOsRmCaps->caps);
    os_free_mem(pOsRmCaps);

    *ppOsRmCaps = NULL;
}

static NV_STATUS
_allocOsRmCaps
(
    OS_RM_CAPS **ppOsRmCaps,
    NvU32        count
)
{
    NV_STATUS   status;
    OS_RM_CAPS *pOsRmCaps;

    *ppOsRmCaps = NULL;

    status = os_alloc_mem((void**)&pOsRmCaps, sizeof(OS_RM_CAPS));
    if (status != NV_OK)
        return status;

    pOsRmCaps->count = count;

    status = os_alloc_mem((void**)&pOsRmCaps->caps, sizeof(pOsRmCaps->caps[0]) * count);
    if (status != NV_OK)
    {
        os_free_mem(pOsRmCaps);
        return status;
    }

    os_mem_set(pOsRmCaps->caps, 0, sizeof(pOsRmCaps->caps[0]) * count);

    *ppOsRmCaps = pOsRmCaps;
    return NV_OK;
}

#define OS_RM_CAP_GPU_DIR 0
#define OS_RM_CAP_GPU_MIG_DIR 1
#define OS_RM_CAP_GPU_COUNT 2

/*
 * @brief Registers OBJGPU with the capability framework.
 *
 * @param[in]  pOsGpuInfo  OS specific GPU information pointer
 * @param[out] ppOsRmCaps  GPU OS specific capabilities pointer
 */
NV_STATUS
osRmCapRegisterGpu
(
    OS_GPU_INFO   *pOsGpuInfo,
    OS_RM_CAPS   **ppOsRmCaps
)
{
    NvU32 minor = nv_get_dev_minor(pOsGpuInfo);
    char name[16];
    NV_STATUS   status;
    OS_RM_CAPS *pOsRmCaps;
    nv_cap_t   *parent;
    nv_cap_t   *cap;

    // Return success on the unsupported platforms.
    if (nvidia_caps_root == NULL)
    {
        return NV_OK;
    }

    if (*ppOsRmCaps != NULL)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    status = _allocOsRmCaps(&pOsRmCaps, OS_RM_CAP_GPU_COUNT);
    if (status != NV_OK)
        return status;

    *ppOsRmCaps = pOsRmCaps;

    os_snprintf(name, sizeof(name), "gpu%u", minor);
    name[sizeof(name) - 1] = '\0';
    parent = nvidia_caps_root;

    cap = os_nv_cap_create_dir_entry(parent, name, (OS_RUGO | OS_XUGO));
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to setup gpu%u directory\n", minor);
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }

    pOsRmCaps->caps[OS_RM_CAP_GPU_DIR] = cap;
    parent = cap;

    // TODO: Bug 2679591: Add MIG directory only if SMC is enabled.
    // For now, always add "mig" directory.
    cap = os_nv_cap_create_dir_entry(parent, "mig", (OS_RUGO | OS_XUGO));
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to setup mig directory\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }

    pOsRmCaps->caps[OS_RM_CAP_GPU_MIG_DIR] = cap;

    return NV_OK;

failed:
    osRmCapUnregister(ppOsRmCaps);

    return status;
}

#define OS_RM_CAP_SMC_PART_DIR 0
#define OS_RM_CAP_SMC_PART_ACCESS_FILE 1
#define OS_RM_CAP_SMC_PART_COUNT 2

/*
 * @brief Registers SMC partition (a.k.a. GPU instance) with the capability
 *        framework
 *
 * @param[in]  pGpuOsRmCaps         GPU OS specific capabilities pointer
 * @param[out] ppPartitionOsRmCaps  OS specific capabilities pointer for SMC partition
 * @param[in]  swizzId              SMC partition swizz ID
 */
NV_STATUS
osRmCapRegisterSmcPartition
(
    OS_RM_CAPS  *pGpuOsRmCaps,
    OS_RM_CAPS **ppPartitionOsRmCaps,
    NvU32        swizzId
)
{
    char        name[16];
    NV_STATUS   status;
    nv_cap_t   *parent;
    nv_cap_t   *cap;
    OS_RM_CAPS *pOsRmCaps;

    // Return success as there is nothing to do.
    if (pGpuOsRmCaps == NULL)
    {
        return NV_OK;
    }

    if (*ppPartitionOsRmCaps != NULL || swizzId >= NV_U32_MAX)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    parent = pGpuOsRmCaps->caps[OS_RM_CAP_GPU_MIG_DIR];
    if (parent == NULL)
    {
        return NV_ERR_INVALID_STATE;
    }

    status = _allocOsRmCaps(&pOsRmCaps, OS_RM_CAP_SMC_PART_COUNT);
    if (status != NV_OK)
        return status;

    *ppPartitionOsRmCaps = pOsRmCaps;

    os_snprintf(name, sizeof(name), "gi%u", swizzId);
    name[sizeof(name) - 1] = '\0';

    cap = os_nv_cap_create_dir_entry(parent, name, OS_RUGO | OS_XUGO);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to setup gi%u directory\n",
                  swizzId);
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }

    pOsRmCaps->caps[OS_RM_CAP_SMC_PART_DIR] = cap;
    parent = cap;

    cap = os_nv_cap_create_file_entry(parent, "access", OS_RUGO);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to setup access file for ID:%u\n",
                  swizzId);
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }

    pOsRmCaps->caps[OS_RM_CAP_SMC_PART_ACCESS_FILE] = cap;

    return NV_OK;

failed:
    osRmCapUnregister(ppPartitionOsRmCaps);

    return status;
}

#define OS_RM_CAP_SMC_EXEC_PART_DIR 0
#define OS_RM_CAP_SMC_EXEC_PART_ACCESS_FILE 1
#define OS_RM_CAP_SMC_EXEC_PART_COUNT 2

/*
 * @brief Registers SMC execution partition (a.k.a. compute instance) with the
 *        capability framework
 *
 * @param[in]  pPartitionOsRmCaps       OS specific capabilities pointer for SMC partition
 * @param[out] ppExecPartitionOsRmCaps  OS specific capabilities pointer for SMC execution partition
 * @param[in]  execPartitionId          SMC execution partition ID
 */
NV_STATUS
osRmCapRegisterSmcExecutionPartition
(
    OS_RM_CAPS  *pPartitionOsRmCaps,
    OS_RM_CAPS **ppExecPartitionOsRmCaps,
    NvU32        execPartitionId
)
{
    char        name[16];
    NV_STATUS   status;
    nv_cap_t   *parent;
    nv_cap_t   *cap;
    OS_RM_CAPS *pOsRmCaps;

    // Return success as there is nothing to do.
    if (pPartitionOsRmCaps == NULL)
    {
        return NV_OK;
    }

    if ((*ppExecPartitionOsRmCaps != NULL) || (execPartitionId >= NV_U32_MAX))
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    parent = pPartitionOsRmCaps->caps[OS_RM_CAP_SMC_PART_DIR];
    if (parent == NULL)
    {
        return NV_ERR_INVALID_STATE;
    }

    status = _allocOsRmCaps(&pOsRmCaps, OS_RM_CAP_SMC_EXEC_PART_COUNT);
    if (status != NV_OK)
    {
        return status;
    }

    *ppExecPartitionOsRmCaps = pOsRmCaps;

    os_snprintf(name, sizeof(name), "ci%u", execPartitionId);
    name[sizeof(name) - 1] = '\0';

    cap = os_nv_cap_create_dir_entry(parent, name, OS_RUGO | OS_XUGO);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to setup ci%u directory\n",
                  execPartitionId);
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }

    pOsRmCaps->caps[OS_RM_CAP_SMC_EXEC_PART_DIR] = cap;
    parent = cap;

    cap = os_nv_cap_create_file_entry(parent, "access", OS_RUGO);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to setup access file for ID:%u\n",
                  execPartitionId);
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }

    pOsRmCaps->caps[OS_RM_CAP_SMC_EXEC_PART_ACCESS_FILE] = cap;

    return NV_OK;

failed:
    osRmCapUnregister(ppExecPartitionOsRmCaps);

    return status;
}

/*
 * @brief Release the acquired capability
 *
 * @param[in]  dupedCapDescriptor  descriptor to be released
 */
void
osRmCapRelease
(
    NvU64 dupedCapDescriptor
)
{
    if (dupedCapDescriptor == NV_U64_MAX)
    {
        return;
    }

    os_nv_cap_close_fd((int)dupedCapDescriptor);
}

#define OS_RM_CAP_SYS_MIG_DIR                   0
#define OS_RM_CAP_SYS_SMC_CONFIG_FILE           1
#define OS_RM_CAP_SYS_SMC_MONITOR_FILE          2
#define OS_RM_CAP_SYS_FABRIC_IMEX_MGMT_FILE     3
#define OS_RM_CAP_SYS_PROFILER_DEVICE_FILE      4
#define OS_RM_CAP_SYS_PROFILER_CONTEXT_FILE     5
#define OS_RM_CAP_SYS_TRACE_DEVICE_FILE         6
#define OS_RM_CAP_SYS_COUNT                     7

NV_STATUS
osRmCapRegisterSys
(
    OS_RM_CAPS **ppOsRmCaps
)
{
    nv_cap_t  **ppCaps;
    nv_cap_t   *parent;
    nv_cap_t   *cap;
    NV_STATUS   status;
    OS_RM_CAPS *pOsRmCaps;

    if (nvidia_caps_root == NULL)
        return NV_ERR_NOT_SUPPORTED;

    status = _allocOsRmCaps(&pOsRmCaps, OS_RM_CAP_SYS_COUNT);
    if (status != NV_OK)
        return status;

    *ppOsRmCaps = pOsRmCaps;

    ppCaps = pOsRmCaps->caps;

    parent = os_nv_cap_create_dir_entry(nvidia_caps_root, "mig", OS_RUGO | OS_XUGO);
    if (parent == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to create mig directory\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }
    ppCaps[OS_RM_CAP_SYS_MIG_DIR] = parent;

    cap = os_nv_cap_create_file_entry(parent, "config", OS_RUSR);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to create mig config file\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }
    ppCaps[OS_RM_CAP_SYS_SMC_CONFIG_FILE] = cap;

    cap = os_nv_cap_create_file_entry(parent, "monitor", OS_RUGO);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to create mig monitor file\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }
    ppCaps[OS_RM_CAP_SYS_SMC_MONITOR_FILE] = cap;

    cap = os_nv_cap_create_file_entry(nvidia_caps_root, "fabric-imex-mgmt", OS_RUSR);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to create imex file\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }
    ppCaps[OS_RM_CAP_SYS_FABRIC_IMEX_MGMT_FILE] = cap;

    cap = os_nv_cap_create_file_entry(nvidia_caps_root, "profiler-device", OS_RUSR);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to create profiler-device file\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }
    ppCaps[OS_RM_CAP_SYS_PROFILER_DEVICE_FILE] = cap;

    cap = os_nv_cap_create_file_entry(nvidia_caps_root, "profiler-context", OS_RUSR);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to create profiler-context file\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }
    ppCaps[OS_RM_CAP_SYS_PROFILER_CONTEXT_FILE] = cap;

    cap = os_nv_cap_create_file_entry(nvidia_caps_root, "trace-device", OS_RUSR);
    if (cap == NULL)
    {
        NV_PRINTF(LEVEL_ERROR, "Failed to create trace-device file\n");
        status = NV_ERR_OPERATING_SYSTEM;
        goto failed;
    }
    ppCaps[OS_RM_CAP_SYS_TRACE_DEVICE_FILE] = cap;

    return NV_OK;

failed:
    osRmCapUnregister(ppOsRmCaps);
    return status;
}

/*
 * @brief Acquire the requested capability
 *
 * @param[in]  pOsRmCaps           opaque pointer to the caps.
 * @param[in]  rmCap               the capability to be acquired.
 * @param[in]  capDescriptor       descriptor to be used for validation
 * @param[out] dupedCapDescriptor  returns duplicated descriptor if validation
 *                                 is successful
 *
 * Note: On Linux, duplicating fd is helpful to let administrators know about
 * the capability users. See https://linux.die.net/man/8/lsof usage.
 */
NV_STATUS
osRmCapAcquire
(
    OS_RM_CAPS *pOsRmCaps,
    NvU32       rmCap,
    NvU64       capDescriptor,
    NvU64      *dupedCapDescriptor
)
{
    nv_cap_t *cap;
    int fd = (int)capDescriptor;
    int duped_fd;
    NvU32 index;
    NV_STATUS status;

    *dupedCapDescriptor = NV_U64_MAX;

    switch (rmCap)
    {
        case NV_RM_CAP_SMC_PARTITION_ACCESS:
        {
            index = OS_RM_CAP_SMC_PART_ACCESS_FILE;
            break;
        }
        case NV_RM_CAP_EXT_FABRIC_MGMT:
        {
            status = nv_acquire_fabric_mgmt_cap(fd, &duped_fd);
            if (status != NV_OK)
            {
                return status;
            }

            goto done;
        }
        case NV_RM_CAP_SMC_EXEC_PARTITION_ACCESS:
        {
            index = OS_RM_CAP_SMC_EXEC_PART_ACCESS_FILE;
            break;
        }
        case NV_RM_CAP_SYS_SMC_CONFIG:
        {
            index = OS_RM_CAP_SYS_SMC_CONFIG_FILE;
            break;
        }
        case NV_RM_CAP_SYS_SMC_MONITOR:
        {
            index = OS_RM_CAP_SYS_SMC_MONITOR_FILE;
            break;
        }
        case NV_RM_CAP_SYS_FABRIC_IMEX_MGMT:
        {
            index = OS_RM_CAP_SYS_FABRIC_IMEX_MGMT_FILE;
            break;
        }
        case NV_RM_CAP_SYS_PROFILER_DEVICE:
        {
            index = OS_RM_CAP_SYS_PROFILER_DEVICE_FILE;
            break;
        }
        case NV_RM_CAP_SYS_PROFILER_CONTEXT:
        {
            index = OS_RM_CAP_SYS_PROFILER_CONTEXT_FILE;
            break;
        }
        case NV_RM_CAP_SYS_TRACE_DEVICE:
        {
            index = OS_RM_CAP_SYS_TRACE_DEVICE_FILE;
            break;
        }
        default:
        {
            return NV_ERR_INVALID_ARGUMENT;
        }
    }

    if (pOsRmCaps == NULL)
    {
        return NV_ERR_NOT_SUPPORTED;
    }

    if (index >= pOsRmCaps->count)
    {
        return NV_ERR_INVALID_ARGUMENT;
    }

    cap = pOsRmCaps->caps[index];

    duped_fd = os_nv_cap_validate_and_dup_fd(cap, fd);
    if (duped_fd < 0)
    {
        return NV_ERR_INSUFFICIENT_PERMISSIONS;
    }

done:
    *dupedCapDescriptor = duped_fd;

    return NV_OK;
}

/*
 * @brief Initializes capability descriptor
 *
 * @param[out] pCapDescriptor        descriptor to be used
 *
 */
void
osRmCapInitDescriptor
(
    NvU64 *pCapDescriptor
)
{
    *pCapDescriptor = NV_U64_MAX;
}

/*
 * @brief Checks if IMEX channel support is present.
 */
NvBool
osImexChannelIsSupported(void)
{
    return os_imex_channel_is_supported;
}

/*
 * @brief Returns IMEX channel count.
 */
NvS32
osImexChannelCount
(
    void
)
{
    return os_imex_channel_count();
}

/*
 * @brief Returns IMEX channel number.
 *
 * @param[in] descriptor   OS specific descriptor to query channel number.
 *
 */
NvS32
osImexChannelGet(NvU64 descriptor)
{
    return os_imex_channel_get(descriptor);
}

/*
 * @brief Generates random bytes which can be used as a universally unique
 *        identifier.
 *
 * This function may sleep (interruptible).
 *
 * @param[out] pBytes        Array of random bytes
 * @param[in]  numBytes      Size of the array
 */
NV_STATUS
osGetRandomBytes
(
    NvU8 *pBytes,
    NvU16 numBytes
)
{
    return os_get_random_bytes(pBytes, numBytes);
}

/*
 * @brief Get current process flags..
 */
NvU32
osGetCurrentProcessFlags
(
    void
)
{
    return os_get_current_process_flags();
}

/*
 * @brief Allocate wait queue
 *
 * @param[out] ppWq        Wait queue
 */
NV_STATUS
osAllocWaitQueue
(
    OS_WAIT_QUEUE **ppWq
)
{
    return os_alloc_wait_queue(ppWq);
}

/*
 * @brief Free wait queue
 *
 * @param[in] pWq        Wait queue
 */
void
osFreeWaitQueue
(
    OS_WAIT_QUEUE *pWq
)
{
    os_free_wait_queue(pWq);
}

/*
 * @brief Put thread to uninterruptible sleep
 *
 * @param[in] pWq        Wait queue
 */
void
osWaitUninterruptible
(
    OS_WAIT_QUEUE *pWq
)
{
    os_wait_uninterruptible(pWq);
}

/*
 * @brief Put thread to interruptible sleep
 *
 * @param[in] pWq        Wait queue
 */
void
osWaitInterruptible
(
    OS_WAIT_QUEUE *pWq
)
{
    os_wait_interruptible(pWq);
}

/*
 * @brief Wake up thread from uninterruptible sleep
 *
 * @param[in] pWq        Wait queue
 */
void
osWakeUp
(
    OS_WAIT_QUEUE *pWq
)
{
    os_wake_up(pWq);
}

NV_STATUS
osReadPFPciConfigInVF
(
    NvU32 addr,
    NvU32 *data
)
{
    return NV_ERR_NOT_SUPPORTED;
}

/*!
 * @brief Callback function to notify RM when unix layer receives an event
 *
 * This function is basically a wrapper to call the Core RM layer and is
 * being called from DCE KMD when an event is received from DCE RM.
 *
 * @param[in]  handle         handle allocated for corresponding IPC type with DCE
 * @param[in]  interfaceType  RM IPC interface type
 * @param[in]  length         length of the message passed from DCE
 * @param[in]  data           any specific data if present
 * @param[in]  usrCtx         any specific user context if present
 *
 * @returns void
 */
static void
osTegraDceClientIpcCallback
(
    NvU32 handle,
    NvU32 interfaceType,
    NvU32 length,
    void *data,
    void *usrCtx
)
{
    THREAD_STATE_NODE threadState;
    NvU32 rmInterfaceType = nv_tegra_get_rm_interface_type(interfaceType);

    threadStateInit(&threadState, THREAD_STATE_FLAGS_NONE);

    if (rmLocksAcquireAll(RM_LOCK_MODULES_KERNEL_RM_EVENTS) == NV_OK)
    {
        dceclientHandleAsyncRpcCallback(handle, rmInterfaceType, length, data, usrCtx);

        rmLocksReleaseAll();
    }

    threadStateFree(&threadState, THREAD_STATE_FLAGS_NONE);
}

/*!
 * @brief Performs IPC Client registration with DCE
 *
 * This function is basically a wrapper to call the unix/linux layer.
 *
 * @param[in]  interfaceType  RM IPC interface type
 * @param[in]  usrCtx         any specific user context if present
 * @param[out] clientId       unique ID registered with DCE for IPC
 *
 * @returns NV_OK if successful,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available, or
 *          other errors as may be returned by subfunctions.
 */
NV_STATUS
osTegraDceRegisterIpcClient
(
    NvU32 interfaceType,
    void *usrCtx,
    NvU32 *clientId
)
{
    if (interfaceType == DCE_CLIENT_RM_IPC_TYPE_SYNC)
        return nv_tegra_dce_register_ipc_client(interfaceType, usrCtx, NULL, clientId);
    else if (interfaceType == DCE_CLIENT_RM_IPC_TYPE_EVENT)
        return nv_tegra_dce_register_ipc_client(interfaceType, usrCtx, osTegraDceClientIpcCallback, clientId);
    else
        return NV_ERR_INVALID_ARGUMENT;
}

/*!
 * @brief Performs IPC Client destroy with DCE
 *
 * This function is basically a wrapper to call the unix/linux layer.
 *
 * @param[in] clientId  unique ID registered with DCE for IPC
 *
 * @returns NV_OK if successful,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available, or
 *          other errors as may be returned by subfunctions.
 */
NV_STATUS
osTegraDceUnregisterIpcClient
(
    NvU32 clientId
)
{
    return nv_tegra_dce_unregister_ipc_client(clientId);
}

/*!
 * @brief Performs IPC Send/Receive to/from DCE
 *
 * This function is basically a wrapper to call the unix/linux layer.
 *
 * @param[in]  clientId   unique ID registered with DCE KMD for corresponding IPC type
 * @param[in]  msg        structure to hold dce ipc message info
 * @param[in]  msgLength  length of the message
 *
 * @returns NV_OK if successful,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available, or
 *          other errors as may be returned by subfunctions.
 */
NV_STATUS
osTegraDceClientIpcSendRecv
(
    NvU32 clientId,
    void *msg,
    NvU32 msgLength
)
{
    return nv_tegra_dce_client_ipc_send_recv(clientId, msg, msgLength);
}

/*!
 * @brief Sends an MRQ (message-request) to BPMP
 *
 * The request, response, and ret parameters of this function correspond to the
 * components of the tegra_bpmp_message struct, which BPMP uses to receive
 * MRQs.
 *
 * @param[in]  pGpu               OBJGPU pointer
 * @param[in]  mrq                MRQ_xxx ID specifying what is requested
 * @param[in]  pRequestData       Pointer to request input data
 * @param[in]  requestDataSize    Size of structure pointed to by pRequestData
 * @param[out] pResponseData      Pointer to response output data
 * @param[in]  responseDataSize   Size of structure pointed to by pResponseData
 * @param[out] ret                MRQ return code (from "ret" element of
 *                                  tegra_bpmp_message struct)
 * @param[out] apiRet             Return code from tegra_bpmp_transfer call
 *
 * @returns NV_OK if successful,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available,
 *          NV_ERR_INVALID_POINTER if the tegra_bpmp struct pointer could not
 *            be obtained from nv, or
 *          NV_ERR_GENERIC if the tegra_bpmp_transfer call failed (see apiRet
 *            for Linux error code).
 */
NV_STATUS
osTegraSocBpmpSendMrq
(
    OBJGPU      *pGpu,
    NvU32        mrq,
    const void  *pRequestData,
    NvU32        requestDataSize,
    void        *pResponseData,
    NvU32        responseDataSize,
    NvS32       *pRet,
    NvS32       *pApiRet
)
{
    if (pGpu->getProperty(pGpu, PDB_PROP_GPU_IS_SOC_SDM))
    {
        return NV_ERR_NOT_SUPPORTED;
    }
    else if (pGpu->getProperty(pGpu, PDB_PROP_GPU_TEGRA_SOC_NVDISPLAY))
    {
        return nv_bpmp_send_mrq(pGpu->pOsGpuInfo,
                                mrq,
                                pRequestData,
                                requestDataSize,
                                pResponseData,
                                responseDataSize,
                                pRet,
                                pApiRet);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*!
 * @brief Returns IMP-relevant data collected from other modules
 *
 * This function is basically a wrapper to call the unix/linux layer.
 *
 * @param[out]  pTegraImpImportData  Structure to receive the data
 *
 * @returns NV_OK if successful,
 *          NV_ERR_BUFFER_TOO_SMALL if the array in TEGRA_IMP_IMPORT_DATA is
 *            too small,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available, or
 *          other errors as may be returned by subfunctions.
 */
NV_STATUS
osTegraSocGetImpImportData
(
    OBJGPU *pGpu,
    TEGRA_IMP_IMPORT_DATA *pTegraImpImportData
)
{
    if (pGpu->getProperty(pGpu, PDB_PROP_GPU_TEGRA_SOC_NVDISPLAY))
    {
        return nv_imp_get_import_data(pTegraImpImportData);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*!
 * @brief Returns IMP-relevant data collected from UEFI
 *
 * This function is basically a wrapper to call the unix/linux layer.
 *
 * @param[in]   pOsGpuInfo    Per GPU Linux state
 * @param[out]  pIsoBwKbps    ISO BW set by UEFI
 * @param[out]  pFloorBwKbps  DRAM Floor BW set by UEFI
 *
 * @returns NV_OK if successful,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available, or
 *          other errors as may be returned by subfunctions.
 */
NV_STATUS
osTegraSocGetImpUefiData
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32 *pIsoBwKbps,
    NvU32 *pFloorBwKbps
)
{
    return nv_imp_get_uefi_data(pOsGpuInfo, pIsoBwKbps, pFloorBwKbps);
}

/*!
 * @brief Tells BPMP whether or not RFL is valid
 *
 * Display HW generates an ok_to_switch signal which asserts when mempool
 * occupancy is high enough to be able to turn off memory long enough to
 * execute a dramclk frequency switch without underflowing display output.
 * ok_to_switch drives the RFL ("request for latency") signal in the memory
 * unit, and the switch sequencer waits for this signal to go active before
 * starting a dramclk switch.  However, if the signal is not valid (e.g., if
 * display HW or SW has not been initialized yet), the switch sequencer ignores
 * the signal.  This API tells BPMP whether or not the signal is valid.
 *
 * @param[in] pOsGpuInfo    Per GPU Linux state
 * @param[in] bEnable       True if RFL will be valid; false if invalid
 *
 * @returns NV_OK if successful,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available, or
 *          NV_ERR_GENERIC if some other kind of error occurred.
 */
NV_STATUS
osTegraSocEnableDisableRfl
(
    OS_GPU_INFO *pOsGpuInfo,
    NvBool       bEnable
)
{
    if (NV_IS_SOC_DISPLAY_DEVICE(pOsGpuInfo))
    {
        return nv_imp_enable_disable_rfl(pOsGpuInfo, bEnable);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*!
 * @brief Returns max rates for display clocks passed by UEFI
 *
 * @param[in]  pOsGpuInfo                   Per GPU Linux state
 * @param[out] pMaxDispClkRateDisppll       disp clock maxrate with disppll as parent
 * @param[out] pMaxDispClkRateSppllClkouta  disp clock maxrate with sppllclkouta as parent
 * @param[out] pMaxHubClkRateSppllClkoutb   hub clock maxrate with sppllclkoutb as parent
 *
 * @returns NV_OK if successful,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available
 */
NV_STATUS
osTegraSocGetDispClockRates
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32       *pMaxDispClkRateDisppll,
    NvU32       *pMaxDispClkRateSppllClkouta,
    NvU32       *pMaxHubClkRateSppllClkoutb
)
{
    nv_state_t *nv = pOsGpuInfo;

    if (NV_IS_SOC_DISPLAY_DEVICE(nv))
    {
        *pMaxDispClkRateDisppll = nv->clocks.max_dispclk_rate_using_disppllkhz;
        *pMaxDispClkRateSppllClkouta = nv->clocks.max_dispclk_rate_using_sppll0clkoutakhz;
        *pMaxHubClkRateSppllClkoutb = nv->clocks.max_hubclk_rate_using_sppll0clkoutbkhz;

        return NV_OK;
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*!
 * @brief Allocates a specified amount of ISO memory bandwidth for display
 *
 * floorBandwidthKBPS is the minimum required (i.e., floor) dramclk frequency
 * multiplied by the width of the pipe over which the display data will travel.
 * (It is understood that the bandwidth calculated by multiplying the clock
 * frequency by the pipe width will not be realistically achievable, due to
 * overhead in the memory subsystem.  The infrastructure will not actually use
 * the bandwidth value, except to reverse the calculation to get the required
 * dramclk frequency.)
 *
 * This function is basically a wrapper to call the unix/linux layer.
 *
 * @param[in]   pOsGpuInfo            OS specific GPU information pointer
 * @param[in]   averageBandwidthKBPS  Amount of ISO memory bandwidth requested
 * @param[in]   floorBandwidhtKBPS    Min required dramclk freq * pipe width
 *
 * @returns NV_OK if successful,
 *          NV_ERR_INSUFFICIENT_RESOURCES if one of the bandwidth values is too
 *            high, and bandwidth cannot be allocated,
 *          NV_ERR_NOT_SUPPORTED if the functionality is not available, or
 *          NV_ERR_GENERIC if some other kind of error occurred.
 */
NV_STATUS
osTegraAllocateDisplayBandwidth
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32        averageBandwidthKBPS,
    NvU32        floorBandwidthKBPS
)
{
    if (NV_IS_SOC_DISPLAY_DEVICE(pOsGpuInfo))
    {
        return nv_imp_icc_set_bw(pOsGpuInfo,
                                 averageBandwidthKBPS,
                                 floorBandwidthKBPS);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*!
 * @brief Creates or sets up platform specific nano second resolution timer
 *
 * @param[in]     pOsGpuInfo     OS specific GPU information pointer
 * @param[in]     pTmrEvent      Pointer to timer event information
 * @param[in/out] pTimer         pointer to hold high resolution timer object
 */
NV_STATUS
osCreateNanoTimer
(
    OS_GPU_INFO *pOsGpuInfo,
    void *pTmrEvent,
    void **pTimer
)
{
    nv_create_nano_timer(pOsGpuInfo, pTmrEvent, (nv_nano_timer_t **)pTimer);
    return NV_OK;
}

/*!
 * @brief Starts platform specific nano second resolution timer
 *
 * @param[in] pOsGpuInfo     OS specific GPU information pointer
 * @param[in] pTimer         pointer to high resolution timer object
 * @param[in] timeNs         Relative time in nano seconds
 */
NV_STATUS
osStartNanoTimer
(
    OS_GPU_INFO *pOsGpuInfo,
    void *pTimer,
    NvU64 timeNs
)
{
    nv_start_nano_timer(pOsGpuInfo, (nv_nano_timer_t *)pTimer, timeNs);
    return NV_OK;
}

/*!
 * @brief Cancels platform specific nano second resolution timer
 *
 * @param[in] pOsGpuInfo     OS specific GPU information pointer
 * @param[in] pTimer       pointer to timer object
 */
NV_STATUS
osCancelNanoTimer
(
    OS_GPU_INFO *pOsGpuInfo,
    void *pTimer
)
{
    nv_cancel_nano_timer(pOsGpuInfo, (nv_nano_timer_t *)pTimer);
    return NV_OK;
}

/*!
 * @brief Destroys & cancels platform specific nano second resolution timer
 *
 *
 * @param[in] pGpu         Device of interest
 * @param[in] pTimer       pointer to timer object
 */
NV_STATUS
osDestroyNanoTimer
(
    OS_GPU_INFO *pOsGpuInfo,
    void *pTimer
)
{
    nv_destroy_nano_timer(pOsGpuInfo, (nv_nano_timer_t *)pTimer);
    return NV_OK;
}


NvBool osIsNonPreemptableDebuggerSessionActive(OBJGPU *pGpu)
{
    NvU32 data = 0;
    if ((osReadRegistryDword(pGpu, NV_REG_STR_RM_NON_PREEMTABLE_DEBUGGER_SESSION_ACTIVE, &data) == NV_OK) && (data == NV_REG_STR_RM_NON_PREEMTABLE_DEBUGGER_SESSION_ACTIVE_ENABLE)) 
    {
        return NV_TRUE;
    }

    return NV_FALSE;
}

/*!
 * @brief Get number of dpAux instances.
 * It is wrapper function to call unix/linux layer.
 *
 * @param[in]  pGpu           GPU object pointer
 * @param[out]  pNumIntances  Number of dpAux instances.
 *
 * @returns NV_STATUS, NV_OK if success,
 *                     NV_ERR_GENERIC, if error
 *                     NV_ERR_NOT_SUPPORTED, for unsupported platforms
 */

NV_STATUS
osGetTegraNumDpAuxInstances
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32  *pNumIntances
)
{
    if (NV_IS_SOC_DISPLAY_DEVICE(pOsGpuInfo))
    {
        return nv_get_num_dpaux_instances(pOsGpuInfo, pNumIntances);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*
 * @brief Return the priv Data of current IRQ.
 * It is wrapper function to call unix/linux layer.
 *
 * @param[in]  pGpu           Device of interest
 * @param[out] pPrivData      privData of current IRQ
 *
 * @returns NV_STATUS, NV_OK if success,
 *                     NV_ERR_GENERIC, if error
 *                     NV_ERR_NOT_SUPPORTED, for unsupported platforms
 */
NV_STATUS
osGetCurrentIrqPrivData
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32  *pPrivData
)
{
    if (NV_IS_SOC_DISPLAY_DEVICE(pOsGpuInfo))
    {
        return nv_get_current_irq_priv_data(pOsGpuInfo, pPrivData);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*!
 * @brief Get the brightness level
 * It is wrapper function to call unix/linux layer.
 *
 * @param[in]  pGpu           GPU object pointer
 * @param[out] brightness     Pointer to brightness level
 *
 * @returns NV_STATUS, NV_OK if success,
 *                     NV_ERR_GENERIC, if error
 *                     NV_ERR_NOT_SUPPORTED, for unsupported platforms
 */
NV_STATUS
osGetTegraBrightnessLevel
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32 *brightness
)
{
    if (NV_IS_SOC_DISPLAY_DEVICE(pOsGpuInfo))
    {
        return nv_get_tegra_brightness_level(pOsGpuInfo, brightness);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/*!
 * @brief Set the brightness level
 * It is wrapper function to call unix/linux layer.
 *
 * @param[in]  pGpu           GPU object pointer
 * @param[out] brightness     brightness level
 *
 * @returns NV_STATUS, NV_OK if success,
 *                     NV_ERR_GENERIC, if error
 *                     NV_ERR_NOT_SUPPORTED, for unsupported platforms
 */
NV_STATUS
osSetTegraBrightnessLevel
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32 brightness
)
{
    if (NV_IS_SOC_DISPLAY_DEVICE(pOsGpuInfo))
    {
        return nv_set_tegra_brightness_level(pOsGpuInfo, brightness);
    }
    else
    {
        return NV_ERR_NOT_SUPPORTED;
    }
}

/* @brief Gets syncpoint aperture information
 *
 * @param[in] OS_GPU_INFO OS specific GPU information pointer
 * @param[in]  syncpointId
 * @param[out] *physAddr
 * @param[out] *limit
 * @param[out] *offset
 */
NV_STATUS
osGetSyncpointAperture
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32 syncpointId,
    NvU64 *physAddr,
    NvU64 *limit,
    NvU32 *offset
)
{
    return nv_get_syncpoint_aperture(syncpointId, physAddr, limit, offset);
}

/*!
 * @brief Enable PCIe AtomicOp Requester Enable and return
 * the completer side capabilities that the requester can send.
 *
 * @param[in]    pOsGpuInfo   OS_GPU_INFO OS specific GPU information pointer
 * @param[out]   pMask        mask of supported atomic size, including one or more of:
 *                            OS_PCIE_CAP_MASK_REQ_ATOMICS_32
 *                            OS_PCIE_CAP_MASK_REQ_ATOMICS_64
 *                            OS_PCIE_CAP_MASK_REQ_ATOMICS_128
 *
 * @returns NV_STATUS, NV_OK if success
 *                     NV_ERR_NOT_SUPPORTED if platform doesn't support this
 *                     feature.
 *                     NV_ERR_GENERIC for any other error
 */

NV_STATUS
osConfigurePcieReqAtomics
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU32       *pMask
)
{
    if (pMask)
    {
        *pMask = 0U;
        if (pOsGpuInfo)
        {
            if (os_enable_pci_req_atomics(pOsGpuInfo->handle,
                                          OS_INTF_PCIE_REQ_ATOMICS_32BIT) == NV_OK)
                *pMask |= OS_PCIE_CAP_MASK_REQ_ATOMICS_32;
            if (os_enable_pci_req_atomics(pOsGpuInfo->handle,
                                          OS_INTF_PCIE_REQ_ATOMICS_64BIT) == NV_OK)
                *pMask |= OS_PCIE_CAP_MASK_REQ_ATOMICS_64;
            if (os_enable_pci_req_atomics(pOsGpuInfo->handle,
                                          OS_INTF_PCIE_REQ_ATOMICS_128BIT) == NV_OK)
                *pMask |= OS_PCIE_CAP_MASK_REQ_ATOMICS_128;

            if (*pMask != 0)
                return NV_OK;
        }
    }
    return NV_ERR_NOT_SUPPORTED;
}

/*!
 * @brief Check GPU is accessible or not
 *
 * @param[in]  pGpu           GPU object pointer
 *
 * @returns NVBool, Returns TRUE if the GPU is accessible,
 *                  FALSE, if error
 */
NvBool
osIsGpuAccessible
(
    OBJGPU *pGpu
)
{
    return nv_is_gpu_accessible(NV_GET_NV_STATE(pGpu));
}

/*!
 * @brief Check whether GPU has received a shutdown notification from the OS
 */
NvBool
osIsGpuShutdown
(
    OBJGPU *pGpu
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);
    return nv ? nv->is_shutdown : NV_TRUE;
}

/*!
 * @brief Check GPU OS info matches
 *
 * @param[in]  pGpu           GPU object pointer
 *
 * @returns NVBool, Returns TRUE if matched.
 */
NvBool
osMatchGpuOsInfo
(
    OBJGPU *pGpu,
    void   *pOsInfo
)
{
    return nv_match_gpu_os_info(NV_GET_NV_STATE(pGpu), pOsInfo);
}

/*!
 * @brief Release GPU OS info.
 *
 * @param[in]  pOsInfo        GPU OS info pointer
 *
 * @returns void
 */
void
osReleaseGpuOsInfo
(
    void   *pOsInfo
)
{
    nv_put_file_private(pOsInfo);
}

/*!
 * @brief Get free, total memory of a NUMA node by NUMA node ID from kernel.
 *
 * @param[in]      numaId              NUMA node ID.
 * @param[out]     free_memory_bytes   free memory in bytes.
 * @param[out]     total_memory_bytes  total memory in bytes.
 *
 */
void
osGetNumaMemoryUsage
(
    NvS32 numaId,
    NvU64 *free_memory_bytes,
    NvU64 *total_memory_bytes
)
{
    NV_STATUS status = os_get_numa_node_memory_usage(numaId,
                                                     free_memory_bytes,
                                                     total_memory_bytes);
    NV_ASSERT(status == NV_OK);
}

/*!
 * @brief Add GPU memory as a NUMA node.
 *
 * @param[in/out]  pOsGpuInfo   OS specific GPU information pointer
 * @param[in]      offset       start offset of the partition within FB
 * @param[in]      size         size of the partition
 * @param[out]     pNumaNodeId  OS NUMA node id for the added memory.
 *
 * @returns NV_OK if all is okay.  Otherwise an error-specific value.
 *
 */
NV_STATUS
osNumaAddGpuMemory
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU64       offset,
    NvU64       size,
    NvU32       *pNumaNodeId
)
{
    nv_state_t *nv = pOsGpuInfo;

    return os_numa_add_gpu_memory(nv->handle, offset, size, pNumaNodeId);
}

/*!
 * @brief Remove a particular SMC partition's GPU memory from OS kernel.
 *
 * Remove GPU memory from the OS kernel that is earlier added as a NUMA node
 * to the kernel in platforms where GPU is coherently connected to the CPU.
 *
 * @param[in/out]  pOsGpuInfo   OS_GPU_INFO OS specific GPU information pointer
 * @param[in]      offset       start offset of the partition within FB
 * @param[in]      size         size of the partition
 * @param[in]      numaNodeId   OS NUMA node id of the memory to be removed.
 *
 */
void
osNumaRemoveGpuMemory
(
    OS_GPU_INFO *pOsGpuInfo,
    NvU64       offset,
    NvU64       size,
    NvU32       numaNodeId
)
{
    nv_state_t *nv = pOsGpuInfo;

    NV_STATUS status = os_numa_remove_gpu_memory(nv->handle, offset, size, numaNodeId);
    NV_ASSERT(status == NV_OK);

    return;
}

NvBool
osDmabufIsSupported(void)
{
    return os_dma_buf_enabled;
}

NV_STATUS
osGetEgmInfo
(
    OBJGPU *pGpu,
    NvU64  *pPhysAddr,
    NvU64  *pSize,
    NvS32  *pNodeId
)
{
    return nv_get_egm_info(NV_GET_NV_STATE(pGpu), pPhysAddr, pSize, pNodeId);
}

/*!
 * @brief Offline (i.e., blacklist) the page containing a given address from OS kernel.
 *
 * @param[in]      address   Address (SPA) of the page to be offlined
 *
 */
NV_STATUS
osOfflinePageAtAddress
(
    NvU64       address
)
{
    return os_offline_page_at_address(address);
}

void osAllocatedRmClient(void *pOsInfo)
{
    nv_file_private_t* nvfp = (nv_file_private_t*)pOsInfo;

    if (nvfp != NULL)
        nvfp->bCleanupRmapi = NV_TRUE;
}

/*!
 * @brief Update variable to indicate console managed by drm driver.
 *
 * @param[in]  OBJGPU  GPU object pointer
 *
 * @returns void
 */
void
osDisableConsoleManagement
(
    OBJGPU *pGpu
)
{
    nv_state_t *nv  = NV_GET_NV_STATE(pGpu);

    nv->client_managed_console = NV_TRUE;
}

/*
 * @brief Return NV_TRUE if GPU is configured as CXL device.
 *
 * @param[in]   pGpu             GPU object pointer
 */
NvBool
osGpuIsCxlDevice
(
    OBJGPU *pGpu
)
{
    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    return nv->is_cxl_dev;
}

/*
 * @brief Disabel CXL cache and perform writeback and invalidate for CXL device.
 *
 * @param[in]   pGpu             GPU object pointer
 * @param[in]   bEnableCache     Enable/Disable flag
 */
void
osCxlSetCaching
(
    OBJGPU *pGpu,
    NvBool  bEnableCache
)
{

    nv_state_t *nv = NV_GET_NV_STATE(pGpu);

    nv_pci_cxl_set_caching(nv, bEnableCache);
}