singe-nvml 0.1.0-alpha.7

Safe Rust wrappers for NVIDIA Management Library (NVML), monitoring, MIG, and vGPU APIs.
Documentation
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
#![allow(deprecated)]

use std::{
    mem::{self, MaybeUninit},
    ptr,
};

use singe_core::string_from_c_chars;
use singe_nvml_sys as sys;

use crate::{
    error::{Error, Result, Status},
    gpu_instance::{GpuInstance, OwnedGpuInstance},
    library::GpmSample,
    try_ffi,
    types::{
        AccountingStats, AdaptiveClockInfoStatus, AffinityScope, Architecture, AutoBoostClocks,
        Bar1MemoryInfo, BbxFlushTime, Brand, BridgeChipHierarchy, BusType, C2cModeInfo,
        ClkMonStatus, ClockId, ClockOffset, ClockRange, ClockRangeI32, ClockType,
        ComputeCapability, ComputeMode, ConfComputeGpuAttestationReport, ConfComputeGpuCertificate,
        ConfComputeMemSizeInfo, CoolerInfo, CurrentClockFreqs, CurrentPending,
        DeviceAddressingMode, DeviceAttributes, DeviceCapabilities, DeviceVgpuCapability,
        DramEncryptionInfo, DriverModel, DriverModelFlags, DynamicPstatesInfo, EccCounterType,
        EccErrorCounts, EccSramErrorStatus, EccSramUniqueUncorrectedErrorCounts, EnableState,
        EncoderSessionInfo, EncoderStats, EncoderType, EventTypes, FanPolicy, FanSpeedInfo,
        FbcSessionInfo, FbcStats, FieldId, FieldQuery, FieldSample, FieldValue, GpmSupport,
        GpuFabricInfo, GpuInstancePlacement, GpuInstanceProfileInfo, GpuOperationMode,
        GspFirmwareMode, HostVgpuMode, InforomObject, MarginTemperature, MemoryErrorType,
        MemoryInfo, MemoryLocation, MigMode, MigModeActivation, MinMaxFanSpeed, NvLinkBwMode,
        NvLinkCapability, NvLinkErrorCounter, NvLinkInfo, NvLinkRemoteDeviceType,
        NvLinkSupportedBwModes, NvLinkVersion, P2pCapabilityIndex, P2pStatus, PageRetirementCause,
        PciInfo, PciInfoExt, PcieUtilCounter, Pdi, PerfPolicyType, PerformanceModes,
        PerformanceState, PgpuMetadata, PlatformInfo, PowerLimits, PowerMizerMode, PowerMizerModes,
        PowerSource, ProcessDetail, ProcessInfo, ProcessMode, ProcessUtilizationInfo,
        ProcessUtilizationSample, RemappedRows, RepairStatus, RestrictedApi, RetiredPage,
        RowRemapperHistogram, Sample, Samples, SamplingType, TemperatureInfo, TemperatureSensor,
        TemperatureThreshold, ThermalSettings, TopologyLevel, Utilization, UtilizationCounter,
        VgpuInstanceId, VgpuPlacementId, VgpuPlacementMode, VgpuTypeId, ViolationTime,
        VirtualizationMode, WorkloadPowerCurrentProfiles, WorkloadPowerProfilesInfo,
        try_from_nvml_enum,
    },
    utility::{
        device_clock_offset_range, device_string_query, device_ulong_bitmask_list,
        device_utilization_counter, query_process_info_list, query_sized_raw, query_u32_list,
        struct_version,
    },
    vgpu_instance::VgpuInstance,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Device(sys::nvmlDevice_t);

impl Device {
    pub const unsafe fn from_raw(handle: sys::nvmlDevice_t) -> Self {
        Self(handle)
    }

    pub const fn as_raw(self) -> sys::nvmlDevice_t {
        self.0
    }

    pub const fn is_null(self) -> bool {
        self.0.is_null()
    }

    /// Returns the NVML index of this device.
    ///
    /// For all products.
    ///
    /// Valid indices are derived from the accessible device count returned by [`Library::device_count`](crate::library::Library::device_count).
    /// For example, if the count is 2 the valid indices are 0 and 1, corresponding to GPU 0 and GPU 1.
    ///
    /// The order in which NVML enumerates devices has no guarantees of consistency between reboots.
    /// Prefer PCI bus IDs or GPU UUIDs for stable device lookup.
    /// See [`Library::device_by_pci_bus_id`](crate::library::Library::device_by_pci_bus_id) and [`Library::device_by_uuid`](crate::library::Library::device_by_uuid).
    ///
    /// With MIG device handles, this returns indices that can be passed to [`Device::mig_device`] to retrieve an identical handle.
    /// MIG device indices are unique within a device.
    ///
    /// The NVML index may not correlate with other APIs, such as the CUDA device index.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or index output, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn index(self) -> Result<u32> {
        let mut index = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetIndex(self.0, &raw mut index))?;
        }
        Ok(index)
    }

    /// Returns the name of this device.
    ///
    /// For all products.
    ///
    /// The name is an alphanumeric product identifier such as `Tesla C2070`.
    /// It does not exceed 96 bytes including the terminating NUL byte.
    /// This wrapper allocates the required NVML buffer internally.
    ///
    /// With MIG device handles, this returns MIG device names that can identify devices based on their attributes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the internal name
    /// buffer is too small, if NVML rejects the handle or output buffer, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn name(self) -> Result<String> {
        let mut buffer = [0i8; sys::NVML_DEVICE_NAME_BUFFER_SIZE as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetName(
                self.0,
                buffer.as_mut_ptr(),
                buffer.len() as u32,
            ))?;
        }
        Ok(string_from_c_chars(&buffer))
    }

    /// Returns the hostname for the device.
    ///
    /// For Blackwell or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// Returns the hostname string for the GPU device that was set using [`sys::nvmlDeviceSetHostname_v1`].
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or hostname output, if the device does not support hostnames, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn hostname(self) -> Result<String> {
        let mut hostname = sys::nvmlHostname_v1_t::default();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetHostname_v1(self.0, &raw mut hostname))?;
        }
        Ok(string_from_c_chars(&hostname.value))
    }

    /// Returns the brand of this device.
    ///
    /// For all products.
    ///
    /// The type is a member of [`Brand`] defined above.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or brand output, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn brand(self) -> Result<Brand> {
        let mut brand = sys::nvmlBrandType_t::NVML_BRAND_UNKNOWN as u32;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetBrand(
                self.0,
                (&raw mut brand).cast::<sys::nvmlBrandType_t>(),
            ))?;
        }
        Ok(Brand::from_raw(brand))
    }

    /// Returns architecture for the device.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or architecture output, or if
    /// NVML has not been initialized.
    pub fn architecture(self) -> Result<Architecture> {
        let mut architecture = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetArchitecture(
                self.0,
                &raw mut architecture
            ))?;
        }
        Ok(Architecture::from_raw(architecture))
    }

    pub fn serial(self) -> Result<String> {
        device_string_query(
            self,
            sys::NVML_DEVICE_SERIAL_BUFFER_SIZE as usize,
            sys::nvmlDeviceGetSerial,
        )
    }

    pub fn uuid(self) -> Result<String> {
        device_string_query(
            self,
            sys::NVML_DEVICE_UUID_V2_BUFFER_SIZE as usize,
            sys::nvmlDeviceGetUUID,
        )
    }

    pub fn vbios_version(self) -> Result<String> {
        // From docs: "It will not exceed 32 characters in length (including the terminating NUL byte)"
        // https://docs.nvidia.com/deploy/nvml-api/group__nvmlDeviceQueries.html#group__nvmlDeviceQueries_1g4a02015969489ad8a28d8c56b34c825e
        device_string_query(self, 32, sys::nvmlDeviceGetVbiosVersion)
    }

    pub fn board_part_number(self) -> Result<String> {
        device_string_query(
            self,
            sys::NVML_DEVICE_PART_NUMBER_BUFFER_SIZE as usize,
            sys::nvmlDeviceGetBoardPartNumber,
        )
    }

    /// Returns a unique identifier for the device module on the baseboard.
    ///
    /// Returns a unique identifier for each GPU module on a given baseboard.
    /// For non-baseboard products, this ID would always be 0.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or module ID output, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn module_id(self) -> Result<u32> {
        let mut module_id = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetModuleId(self.0, &raw mut module_id))?;
        }
        Ok(module_id)
    }

    /// Returns whether the device is on a multi-GPU board.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support this query, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn is_multi_gpu_board(self) -> Result<bool> {
        let mut multi_gpu = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMultiGpuBoard(self.0, &raw mut multi_gpu))?;
        }
        Ok(multi_gpu != 0)
    }

    /// Returns attributes (engine counts etc.) for the given NVML device handle.
    ///
    /// This currently supports only MIG device handles.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the device handle, if the device does
    /// not support this query, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn attributes(self) -> Result<DeviceAttributes> {
        unsafe {
            let mut attributes = MaybeUninit::<sys::nvmlDeviceAttributes_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetAttributes_v2(
                self.0,
                attributes.as_mut_ptr()
            ))?;
            Ok(attributes.assume_init().into())
        }
    }

    /// Returns the root/admin permissions for the target NVML operation.
    /// See [`RestrictedApi`] for the list of supported operations.
    /// If an operation is restricted, only callers with root privileges can call it.
    /// See [`sys::nvmlDeviceSetAPIRestriction`] to change current permissions.
    ///
    /// For all fully supported products.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, API restriction, or output, if the device or queried feature does
    /// not support API restriction reporting, if NVML has not been initialized,
    /// or if NVML reports an unexpected failure.
    pub fn is_api_restricted(self, api: RestrictedApi) -> Result<EnableState> {
        let mut state = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetAPIRestriction(
                self.0,
                api.into(),
                &raw mut state,
            ))?;
        }
        Ok(state.into())
    }

    /// Returns platform information of this device.
    ///
    /// For Blackwell or newer fully supported devices.
    ///
    /// Returns the platform information reported by NVML for this device.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the request, if system memory is
    /// insufficient, if the device does not support this query, or if NVML
    /// reports an unexpected failure.
    pub fn platform_info(self) -> Result<PlatformInfo> {
        let mut info = sys::nvmlPlatformInfo_t {
            version: struct_version::<sys::nvmlPlatformInfo_t>(2),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPlatformInfo(self.0, &raw mut info))?;
        }
        Ok(info.into())
    }

    /// Returns the Per Device Identifier (PDI) associated with this device.
    ///
    /// For Pascal or newer fully supported devices.
    ///
    /// Returns the per-device identifier reported by NVML.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML rejects the handle
    /// or output, if the device does not support PDI reporting, if NVML has not
    /// been initialized, or if NVML reports an unexpected failure.
    pub fn pdi(self) -> Result<Pdi> {
        let mut pdi = sys::nvmlPdi_t {
            version: struct_version::<sys::nvmlPdi_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPdi(self.0, &raw mut pdi))?;
        }
        Ok(pdi.into())
    }

    /// Returns the Device's C2C Mode information.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support C2C mode reporting, or
    /// if NVML reports an unexpected failure.
    pub fn c2c_mode_info(self) -> Result<C2cModeInfo> {
        unsafe {
            let mut info = MaybeUninit::<sys::nvmlC2cModeInfo_v1_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetC2cModeInfoV(self.0, info.as_mut_ptr()))?;
            Ok(info.assume_init().into())
        }
    }

    /// Returns the current Auto Boosted clocks state for this device.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// Auto Boosted clocks are enabled by default on some hardware, allowing the GPU to run at higher clock rates to maximize performance as thermal limits allow.
    ///
    /// On Pascal and newer hardware, Auto Boosted clocks are controlled through application clocks.
    /// Use [`sys::nvmlDeviceSetApplicationsClocks`] and [`sys::nvmlDeviceResetApplicationsClocks`] to control Auto Boost behavior.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support Auto Boosted clocks, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn auto_boosted_clocks(self) -> Result<AutoBoostClocks> {
        let mut enabled = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        let mut default_enabled = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetAutoBoostedClocksEnabled(
                self.0,
                &raw mut enabled,
                &raw mut default_enabled,
            ))?;
        }
        Ok(AutoBoostClocks {
            enabled: enabled.into(),
            default_enabled: default_enabled.into(),
        })
    }

    /// Tries to set the default state of Auto Boosted clocks on a device.
    /// Auto Boosted clocks return to this default state when no compute
    /// processes, such as CUDA applications with active contexts, are running.
    ///
    /// For Kepler or newer non-GeForce fully supported devices and Maxwell or newer GeForce devices.
    /// Requires root/admin permissions.
    ///
    /// Auto Boosted clocks are enabled by default on some hardware, allowing the GPU to run at higher clock rates to maximize performance as thermal limits allow.
    /// Disable Auto Boosted clocks when fixed clock rates are required.
    ///
    /// On Pascal and newer hardware, Auto Boosted clocks are controlled through application clocks.
    /// Use [`sys::nvmlDeviceSetApplicationsClocks`] and [`sys::nvmlDeviceResetApplicationsClocks`] to control Auto Boost behavior.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, if the device does not support Auto Boosted clocks, if the
    /// current process lacks permission to change the default state, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn set_default_auto_boosted_clocks_enabled(
        self,
        enabled: EnableState,
        flags: DriverModelFlags,
    ) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetDefaultAutoBoostedClocksEnabled(
                self.0,
                enabled.into(),
                flags.bits(),
            ))?;
        }
        Ok(())
    }

    /// Returns the PCI attributes of this device.
    ///
    /// For all products.
    ///
    /// Returns the PCI information reported by NVML.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or PCI info output, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn pci_info(self) -> Result<PciInfo> {
        unsafe {
            let mut pci = MaybeUninit::<sys::nvmlPciInfo_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetPciInfo_v3(self.0, pci.as_mut_ptr()))?;
            Ok(pci.assume_init().into())
        }
    }

    /// Returns PCI attributes of this device.
    ///
    /// For all products.
    ///
    /// Returns the extended PCI information reported by NVML.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or PCI info output, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn pci_info_ext(self) -> Result<PciInfoExt> {
        let mut pci = sys::nvmlPciInfoExt_t {
            version: struct_version::<sys::nvmlPciInfoExt_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPciInfoExt(self.0, &raw mut pci))?;
        }
        Ok(pci.into())
    }

    /// Returns bridge chip information for all the bridge chips on the board.
    ///
    /// For all fully supported products.
    /// Only applicable to multi-GPU products.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if bridge-chip reporting is not supported for the
    /// device, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn bridge_chip_hierarchy(self) -> Result<BridgeChipHierarchy> {
        unsafe {
            let mut hierarchy = MaybeUninit::<sys::nvmlBridgeChipHierarchy_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetBridgeChipInfo(
                self.0,
                hierarchy.as_mut_ptr()
            ))?;
            Ok(hierarchy.assume_init().into())
        }
    }

    /// Returns the current PCIe link generation.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if PCIe link information is unavailable, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn current_pcie_link_generation(self) -> Result<u32> {
        let mut generation = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetCurrPcieLinkGeneration(
                self.0,
                &raw mut generation,
            ))?;
        }
        Ok(generation)
    }

    /// Returns the current PCIe link width.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if PCIe link information is unavailable, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn current_pcie_link_width(self) -> Result<u32> {
        let mut width = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetCurrPcieLinkWidth(self.0, &raw mut width))?;
        }
        Ok(width)
    }

    /// Returns the maximum PCIe link generation possible with this device and system.
    ///
    /// For example, a generation 2 PCIe device attached to a generation 1 PCIe bus reports generation 1.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if PCIe link information is unavailable, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn max_pcie_link_generation(self) -> Result<u32> {
        let mut generation = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMaxPcieLinkGeneration(
                self.0,
                &raw mut generation,
            ))?;
        }
        Ok(generation)
    }

    /// Returns the maximum PCIe link generation supported by this device.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if PCIe link information is unavailable, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn gpu_max_pcie_link_generation(self) -> Result<u32> {
        let mut generation = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuMaxPcieLinkGeneration(
                self.0,
                &raw mut generation,
            ))?;
        }
        Ok(generation)
    }

    /// Returns the maximum PCIe link width possible with this device and system.
    ///
    /// For example, a device with a 16x PCIe bus width attached to an 8x PCIe
    /// system bus reports a maximum link width of 8.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if PCIe link information is unavailable, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn max_pcie_link_width(self) -> Result<u32> {
        let mut width = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMaxPcieLinkWidth(self.0, &raw mut width))?;
        }
        Ok(width)
    }

    /// Returns PCIe utilization information.
    /// Queries a byte counter over a 20 ms interval to report PCIe throughput.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// Not supported in virtual machines running virtual GPU (vGPU).
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, counter, or output, if the device does not support PCIe
    /// utilization queries, if NVML has not been initialized, or if NVML reports
    /// an unexpected failure.
    pub fn pcie_throughput(self, counter: PcieUtilCounter) -> Result<u32> {
        let mut throughput = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPcieThroughput(
                self.0,
                counter.into(),
                &raw mut throughput,
            ))?;
        }
        Ok(throughput)
    }

    /// Returns the PCIe replay counter.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support replay-counter queries,
    /// if NVML has not been initialized, or if NVML reports an unexpected
    /// failure.
    pub fn pcie_replay_counter(self) -> Result<u32> {
        let mut counter = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPcieReplayCounter(
                self.0,
                &raw mut counter
            ))?;
        }
        Ok(counter)
    }

    /// Returns the device's PCIe Max Link speed in MB/s.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support this query, or if NVML
    /// has not been initialized.
    pub fn pcie_link_max_speed(self) -> Result<u32> {
        let mut speed = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPcieLinkMaxSpeed(self.0, &raw mut speed))?;
        }
        Ok(speed)
    }

    /// Returns the device's PCIe Link speed in Mbps.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support PCIe speed queries, if NVML has not been initialized, or if
    /// NVML reports an unexpected failure.
    pub fn pcie_speed(self) -> Result<u32> {
        let mut speed = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPcieSpeed(self.0, &raw mut speed))?;
        }
        Ok(speed)
    }

    /// Indicates whether the supplied device supports GPM.
    ///
    /// For Hopper or newer fully supported devices.
    ///
    /// This supports device handles and MIG device handles.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or cannot query GPM support.
    pub fn gpm_support(self) -> Result<GpmSupport> {
        let mut support = sys::nvmlGpmSupport_t {
            version: sys::NVML_GPM_SUPPORT_VERSION,
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlGpmQueryDeviceSupport(self.0, &raw mut support))?;
        }
        Ok(support.into())
    }

    /// Returns GPM stream state.
    ///
    /// For Hopper or newer fully supported devices.
    /// Supported on Linux, Windows TCC.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support GPM streaming-state queries, or if NVML has not been
    /// initialized.
    pub fn gpm_streaming_enabled(self) -> Result<EnableState> {
        let mut state = 0;
        unsafe {
            try_ffi!(sys::nvmlGpmQueryIfStreamingEnabled(self.0, &raw mut state))?;
        }
        try_from_nvml_enum("enable state", state)
    }

    /// Read a sample of GPM metrics into the provided `sample` buffer.
    /// After two samples are gathered, you can call [`Library::gpm_metrics`](crate::library::Library::gpm_metrics) on those samples to retrieve metrics.
    ///
    /// For Hopper or newer fully supported devices.
    ///
    /// * The interval between two [`Device::gpm_sample`] calls must be greater than 100 ms due to the internal sample refresh rate.
    /// * Supports device handles and MIG device handles.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or sample buffer, if the
    /// device does not support GPM sampling, or if samples are requested too
    /// quickly.
    pub fn gpm_sample(self, sample: &GpmSample) -> Result<()> {
        unsafe { try_ffi!(sys::nvmlGpmSampleGet(self.0, sample.as_raw())) }
    }

    /// Read a sample of GPM metrics into the provided `sample` buffer for a MIG GPU instance.
    ///
    /// After two samples are gathered, you can call [`Library::gpm_metrics`](crate::library::Library::gpm_metrics) on those samples to retrieve metrics.
    ///
    /// For Hopper or newer fully supported devices.
    ///
    /// The interval between two [`Device::gpm_mig_sample`] calls must be greater than 100 ms due to the internal sample refresh rate.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, GPU instance id, or sample
    /// buffer, if the device does not support GPM MIG sampling, or if samples
    /// are requested too quickly.
    pub fn gpm_mig_sample(self, gpu_instance_id: u32, sample: &GpmSample) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlGpmMigSampleGet(
                self.0,
                gpu_instance_id,
                sample.as_raw(),
            ))
        }
    }

    pub fn memory_info(self) -> Result<MemoryInfo> {
        let mut memory = sys::nvmlMemory_v2_t {
            version: struct_version::<sys::nvmlMemory_v2_t>(2),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMemoryInfoV(self.0, &raw mut memory))?;
        }
        Ok(memory.into())
    }

    /// Returns the current utilization rates for the device's major subsystems.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// * During driver initialization when ECC is enabled, GPU and memory utilization readings can be high.
    ///   ECC memory scrubbing during driver initialization causes this.
    /// * On MIG-enabled GPUs, querying device utilization rates is not currently supported.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support utilization queries, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn utilization(self) -> Result<Utilization> {
        unsafe {
            let mut utilization = MaybeUninit::<sys::nvmlUtilization_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetUtilizationRates(
                self.0,
                utilization.as_mut_ptr(),
            ))?;
            Ok(utilization.assume_init().into())
        }
    }

    pub fn encoder_utilization(self) -> Result<UtilizationCounter> {
        device_utilization_counter(self, sys::nvmlDeviceGetEncoderUtilization)
    }

    pub fn decoder_utilization(self) -> Result<UtilizationCounter> {
        device_utilization_counter(self, sys::nvmlDeviceGetDecoderUtilization)
    }

    pub fn jpg_utilization(self) -> Result<UtilizationCounter> {
        device_utilization_counter(self, sys::nvmlDeviceGetJpgUtilization)
    }

    pub fn ofa_utilization(self) -> Result<UtilizationCounter> {
        device_utilization_counter(self, sys::nvmlDeviceGetOfaUtilization)
    }

    /// Returns the current capacity of the device's encoder, as a percentage of maximum encoder capacity with valid values in the range 0-100.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if the device does not support the requested encoder, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn encoder_capacity(self, encoder: EncoderType) -> Result<u32> {
        let mut capacity = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetEncoderCapacity(
                self.0,
                encoder.into(),
                &raw mut capacity,
            ))?;
        }
        Ok(capacity)
    }

    /// Returns the current encoder statistics for the given device.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn encoder_stats(self) -> Result<EncoderStats> {
        let mut session_count = 0;
        let mut average_fps = 0;
        let mut average_latency_us = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetEncoderStats(
                self.0,
                &raw mut session_count,
                &raw mut average_fps,
                &raw mut average_latency_us,
            ))?;
        }
        Ok(EncoderStats {
            session_count,
            average_fps,
            average_latency_us,
        })
    }

    /// Returns information about active encoder sessions on a target device.
    ///
    /// This wrapper queries the required session count first, then returns the active encoder sessions as a [`Vec`].
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the active-session
    /// count changes while the wrapper is fetching sessions, if NVML reports an
    /// invalid session count, if the device does not support this query, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn encoder_sessions(self) -> Result<Vec<EncoderSessionInfo>> {
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetEncoderSessions(self.as_raw(), &raw mut count, ptr::null_mut())
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut sessions = vec![sys::nvmlEncoderSessionInfo_t::default(); count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetEncoderSessions(
                self.as_raw(),
                &raw mut count,
                sessions.as_mut_ptr(),
            ))?;
        }
        sessions.truncate(count as usize);
        Ok(sessions.into_iter().map(Into::into).collect())
    }

    /// Returns total, available, and used size of BAR1 memory.
    ///
    /// BAR1 maps framebuffer memory so the CPU or third-party PCIe peer devices can access it directly.
    ///
    /// In MIG mode, a device handle returns aggregate information only if the caller has appropriate privileges.
    /// Per-instance information can be queried by using specific MIG device handles.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if the device does not support BAR1 memory reporting, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn bar1_memory_info(self) -> Result<Bar1MemoryInfo> {
        unsafe {
            let mut memory = MaybeUninit::<sys::nvmlBAR1Memory_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetBAR1MemoryInfo(
                self.0,
                memory.as_mut_ptr()
            ))?;
            Ok(memory.assume_init().into())
        }
    }

    /// Returns the current clock speeds for the device.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// See [`ClockType`] for details on available clock information.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, clock type, or output, if the device cannot report the requested
    /// clock, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn clock(self, kind: ClockType) -> Result<u32> {
        let mut clock = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetClockInfo(
                self.0,
                kind.into(),
                &raw mut clock
            ))?;
        }
        Ok(clock)
    }

    /// Returns the clock speed for the clock specified by the clock type and clock ID.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, clock type, clock ID, or output, if the device does not support
    /// this clock query, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn clock_with_id(self, kind: ClockType, clock_id: ClockId) -> Result<u32> {
        let mut clock = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetClock(
                self.0,
                kind.into(),
                clock_id.into(),
                &raw mut clock,
            ))?;
        }
        Ok(clock)
    }

    /// Returns the maximum clock speeds for the device.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// See [`ClockType`] for details on available clock information.
    ///
    /// Current P0 clocks (reported by [`Device::clock`]) can differ from max clocks by a few MHz.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, clock type, or output, if the device cannot report the requested
    /// maximum clock, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn max_clock(self, kind: ClockType) -> Result<u32> {
        let mut clock = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMaxClockInfo(
                self.0,
                kind.into(),
                &raw mut clock,
            ))?;
        }
        Ok(clock)
    }

    /// Returns a string with the associated current GPU Clock and Memory Clock values.
    ///
    /// Not all tokens are reported on all GPUs, and additional tokens may be added in the future.
    ///
    /// These clock values include the offset set by clients through [`Device::set_clock_offsets`].
    ///
    /// Clock values are returned as a comma-separated list of "token=value" pairs.
    /// Valid tokens:
    ///
    /// - `perf`: performance level.
    /// - `nvclock`: GPU clock in MHz for the performance level.
    /// - `nvclockmin`: minimum GPU clock in MHz for the performance level.
    /// - `nvclockmax`: maximum GPU clock in MHz for the performance level.
    /// - `nvclockeditable`: whether the GPU clock domain is editable for the performance level.
    /// - `memclock`: memory clock in MHz for the performance level.
    /// - `memclockmin`: minimum memory clock in MHz for the performance level.
    /// - `memclockmax`: maximum memory clock in MHz for the performance level.
    /// - `memclockeditable`: whether the memory clock domain is editable for the performance level.
    /// - `memtransferrate`: memory transfer rate in MHz for the performance level.
    /// - `memtransferratemin`: minimum memory transfer rate in MHz for the performance level.
    /// - `memtransferratemax`: maximum memory transfer rate in MHz for the performance level.
    /// - `memtransferrateeditable`: whether the memory transfer rate is editable for the performance level.
    ///
    /// Example:
    ///
    /// `nvclock=324, nvclockmin=324, nvclockmax=324, nvclockeditable=0, memclock=324, memclockmin=324, memclockmax=324, memclockeditable=0, memtransferrate=648, memtransferratemin=648, memtransferratemax=648, memtransferrateeditable=0;`
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the internal
    /// clock-frequency buffer is too small, if NVML rejects the handle or
    /// output, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn current_clock_freqs(self) -> Result<CurrentClockFreqs> {
        let mut current = sys::nvmlDeviceCurrentClockFreqs_t {
            version: struct_version::<sys::nvmlDeviceCurrentClockFreqs_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetCurrentClockFreqs(
                self.0,
                &raw mut current
            ))?;
        }
        Ok(current.into())
    }

    /// Returns a performance mode string with all the performance modes defined for this device along with their associated GPU Clock and Memory Clock values.
    /// Not all tokens are reported on all GPUs, and additional tokens may be added in the future.
    /// For backward compatibility, NVML still provides `nvclock` and `memclock`; those are the same as `nvclockmin` and `memclockmin`.
    ///
    /// These clock values include the offset set by clients through [`Device::set_clock_offsets`].
    ///
    /// Maximum available Pstate (P15) shows the minimum performance level (0) and vice versa.
    ///
    /// Each performance mode is returned as a comma-separated list of "token=value" pairs.
    /// Performance-mode token sets are separated by semicolons.
    /// Valid tokens:
    ///
    /// - `perf`: performance level.
    /// - `nvclock`: GPU clock in MHz for the performance level.
    /// - `nvclockmin`: minimum GPU clock in MHz for the performance level.
    /// - `nvclockmax`: maximum GPU clock in MHz for the performance level.
    /// - `nvclockeditable`: whether the GPU clock domain is editable for the performance level.
    /// - `memclock`: memory clock in MHz for the performance level.
    /// - `memclockmin`: minimum memory clock in MHz for the performance level.
    /// - `memclockmax`: maximum memory clock in MHz for the performance level.
    /// - `memclockeditable`: whether the memory clock domain is editable for the performance level.
    /// - `memtransferrate`: memory transfer rate in MHz for the performance level.
    /// - `memtransferratemin`: minimum memory transfer rate in MHz for the performance level.
    /// - `memtransferratemax`: maximum memory transfer rate in MHz for the performance level.
    /// - `memtransferrateeditable`: whether the memory transfer rate is editable for the performance level.
    ///
    /// Example:
    ///
    /// `perf=0, nvclock=324, nvclockmin=324, nvclockmax=324, nvclockeditable=0, memclock=324, memclockmin=324, memclockmax=324, memclockeditable=0, memtransferrate=648, memtransferratemin=648, memtransferratemax=648, memtransferrateeditable=0; perf=1, nvclock=324, nvclockmin=324, nvclockmax=640, nvclockeditable=0, memclock=810, memclockmin=810, memclockmax=810, memclockeditable=0, memtransferrate=1620, memtransferrate=1620, memtransferrate=1620, memtransferrateeditable=0;`
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the internal
    /// performance-mode buffer is too small, if NVML rejects the handle or
    /// output, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn performance_modes(self) -> Result<PerformanceModes> {
        let mut modes = sys::nvmlDevicePerfModes_t {
            version: struct_version::<sys::nvmlDevicePerfModes_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPerformanceModes(self.0, &raw mut modes))?;
        }
        Ok(modes.into())
    }

    pub fn applications_clock(self, kind: ClockType) -> Result<u32> {
        self.clock_with_id(kind, ClockId::AppClockTarget)
    }

    pub fn default_applications_clock(self, kind: ClockType) -> Result<u32> {
        self.clock_with_id(kind, ClockId::AppClockDefault)
    }

    /// Returns the customer-defined maximum boost clock speed specified by `kind`.
    ///
    /// For Pascal or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, clock type, or output, if the device or requested clock type does
    /// not support customer boost clocks, if NVML has not been initialized, or
    /// if NVML reports an unexpected failure.
    pub fn max_customer_boost_clock(self, kind: ClockType) -> Result<u32> {
        let mut clock = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMaxCustomerBoostClock(
                self.0,
                kind.into(),
                &raw mut clock,
            ))?;
        }
        Ok(clock)
    }

    /// Returns the minimum and maximum clocks of a clock domain for a P-state.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, clock type, P-state, or
    /// outputs, if the device does not support this query, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn min_max_clock_of_pstate(
        self,
        kind: ClockType,
        pstate: PerformanceState,
    ) -> Result<ClockRange> {
        let mut min = 0;
        let mut max = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMinMaxClockOfPState(
                self.0,
                kind.into(),
                pstate.into(),
                &raw mut min,
                &raw mut max,
            ))?;
        }
        Ok(ClockRange { min, max })
    }

    /// Returns the minimum, maximum, and current clock offset for a clock domain and P-state.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// [`Device::gpc_clock_vf_offset`], [`Device::memory_clock_vf_offset`],
    /// [`sys::nvmlDeviceGetGpcClkMinMaxVfOffset`], and
    /// [`sys::nvmlDeviceGetMemClkMinMaxVfOffset`] are deprecated and are planned
    /// for removal in a future release.
    /// Use [`Device::clock_offsets`] instead.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the device, clock type, P-state, or
    /// outputs, if the device does not support clock-offset queries, or if NVML
    /// has not been initialized.
    pub fn clock_offsets(self, kind: ClockType, pstate: PerformanceState) -> Result<ClockOffset> {
        let mut info = sys::nvmlClockOffset_t {
            version: struct_version::<sys::nvmlClockOffset_t>(1),
            type_: kind.into(),
            pstate: pstate.into(),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetClockOffsets(self.0, &raw mut info))?;
        }
        Ok(info.into())
    }

    /// Controls current clock offset of some clock domain for the given PState
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// Requires privileged access.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the handle, clock type, P-state, or
    /// offset, if the device does not support clock-offset control, if the
    /// current process lacks permission, or if NVML has not been initialized.
    pub fn set_clock_offsets(self, offset: ClockOffset) -> Result<()> {
        let mut info = sys::nvmlClockOffset_t {
            version: struct_version::<sys::nvmlClockOffset_t>(1),
            type_: offset.kind.into(),
            pstate: offset.pstate.into(),
            clockOffsetMHz: offset.clock_offset_mhz,
            minClockOffsetMHz: offset.min_clock_offset_mhz,
            maxClockOffsetMHz: offset.max_clock_offset_mhz,
        };
        unsafe { try_ffi!(sys::nvmlDeviceSetClockOffsets(self.0, &raw mut info)) }
    }

    /// Returns the GPCCLK VF offset value.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support this deprecated offset query, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn gpc_clock_vf_offset(self) -> Result<i32> {
        let mut offset = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpcClkVfOffset(self.0, &raw mut offset))?;
        }
        Ok(offset)
    }

    /// Returns the MemClk (Memory Clock) VF offset value.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support this deprecated offset query, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn memory_clock_vf_offset(self) -> Result<i32> {
        let mut offset = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMemClkVfOffset(self.0, &raw mut offset))?;
        }
        Ok(offset)
    }

    pub fn gpc_clock_vf_offset_range(self) -> Result<ClockRangeI32> {
        device_clock_offset_range(self, sys::nvmlDeviceGetGpcClkMinMaxVfOffset)
    }

    pub fn memory_clock_vf_offset_range(self) -> Result<ClockRangeI32> {
        device_clock_offset_range(self, sys::nvmlDeviceGetMemClkMinMaxVfOffset)
    }

    /// Returns the list of possible memory clocks that can be used as an argument for [`sys::nvmlDeviceSetMemoryLockedClocks`].
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the clock list changes
    /// while the wrapper is fetching it, if NVML rejects the handle or count
    /// output, if the device does not support this query, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn supported_memory_clocks(self) -> Result<Vec<u32>> {
        query_u32_list(|count, values| unsafe {
            sys::nvmlDeviceGetSupportedMemoryClocks(self.0, count, values)
        })
    }

    /// Returns the list of possible graphics clocks that can be used as an argument for [`sys::nvmlDeviceSetGpuLockedClocks`].
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the clock list changes
    /// while the wrapper is fetching it, if NVML rejects the handle, memory
    /// clock, or output, if `memory_clock_mhz` is unsupported, if the device does
    /// not support this query, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn supported_graphics_clocks(self, memory_clock_mhz: u32) -> Result<Vec<u32>> {
        query_u32_list(|count, values| unsafe {
            sys::nvmlDeviceGetSupportedGraphicsClocks(self.0, memory_clock_mhz, count, values)
        })
    }

    pub fn temperature_reading(self, sensor: TemperatureSensor) -> Result<u32> {
        let value = self.temperature(sensor)?.temperature;
        u32::try_from(value).map_err(|_| Error::NegativeValue {
            name: "temperature".into(),
            value: i64::from(value),
        })
    }

    /// Returns the temperature threshold for the GPU with the specified threshold type in degrees C.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// See [`TemperatureThreshold`] for details on available temperature thresholds.
    ///
    /// This is no longer the preferred interface for retrieving the following temperature thresholds on Ada and later architectures: [`TemperatureThreshold::Shutdown`], [`TemperatureThreshold::Slowdown`], [`TemperatureThreshold::MemoryMax`] and [`TemperatureThreshold::GpuMax`].
    ///
    /// Support for reading these temperature thresholds for Ada and later architectures may be removed in future releases.
    /// Use [`Device::field_values`] with `NVML_FI_DEV_TEMPERATURE_*` fields to retrieve temperature thresholds on these architectures.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, threshold type, or output, if the device does not support the
    /// requested temperature threshold, if NVML has not been initialized, or if
    /// NVML reports an unexpected failure.
    pub fn temperature_threshold(self, threshold: TemperatureThreshold) -> Result<u32> {
        let mut temperature = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetTemperatureThreshold(
                self.0,
                threshold.into(),
                &raw mut temperature,
            ))?;
        }
        Ok(temperature)
    }

    /// Sets the temperature threshold for the GPU with the specified threshold type in degrees C.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// See [`TemperatureThreshold`] for details on available temperature thresholds.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, threshold type, or temperature value, if the device does not
    /// support setting this threshold, if NVML has not been initialized, or if
    /// NVML reports an unexpected failure.
    pub fn set_temperature_threshold(
        self,
        threshold: TemperatureThreshold,
        temperature: i32,
    ) -> Result<i32> {
        let mut temperature = temperature;
        unsafe {
            try_ffi!(sys::nvmlDeviceSetTemperatureThreshold(
                self.0,
                threshold.into(),
                &raw mut temperature,
            ))?;
        }
        Ok(temperature)
    }

    /// Returns the thermal margin temperature (distance to nearest slowdown threshold).
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML rejects the handle
    /// or output, if the platform does not support this query, or if NVML
    /// reports an unexpected failure.
    pub fn margin_temperature(self) -> Result<MarginTemperature> {
        let mut margin = sys::nvmlMarginTemperature_t {
            version: struct_version::<sys::nvmlMarginTemperature_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMarginTemperature(self.0, &raw mut margin))?;
        }
        Ok(margin.into())
    }

    /// Used to execute a list of thermal system instructions.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, sensor index, or output, if the device does not support thermal
    /// settings, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn thermal_settings(self, sensor_index: u32) -> Result<ThermalSettings> {
        unsafe {
            let mut settings = MaybeUninit::<sys::nvmlGpuThermalSettings_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetThermalSettings(
                self.0,
                sensor_index,
                settings.as_mut_ptr(),
            ))?;
            Ok(settings.assume_init().into())
        }
    }

    /// Returns power usage for this GPU and its associated circuitry, such as memory, in milliwatts.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// On Fermi and Kepler GPUs the reading is accurate to within +/- 5% of current power draw.
    /// On Ampere (except GA100) or newer GPUs, this returns power averaged over a one-second interval.
    /// On GA100 and older architectures, instantaneous power is returned.
    ///
    /// See `NVML_FI_DEV_POWER_AVERAGE` on newer architectures and `NVML_FI_DEV_POWER_INSTANT` to query specific power values.
    ///
    /// It is only available if power management mode is supported.
    /// See [`sys::nvmlDeviceGetPowerManagementMode`].
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support power readings, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn power_usage(self) -> Result<u32> {
        let mut power = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPowerUsage(self.0, &raw mut power))?;
        }
        Ok(power)
    }

    pub fn power_management_mode(self) -> Result<EnableState> {
        let sample = self.single_field_value(FieldId::POWER_CURRENT_LIMIT, 0)?;
        match sample.result {
            Ok(_) => Ok(EnableState::Enabled),
            Err(Error::Nvml {
                code: Status::NotSupported,
                ..
            }) => Ok(EnableState::Disabled),
            Err(err) => Err(err),
        }
    }

    /// Returns the power management limit associated with this device.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// The power limit defines the upper boundary for the card's power draw.
    /// If the card's total power draw reaches this limit the power management algorithm kicks in.
    ///
    /// This reading is only available if power management mode is supported.
    /// See [`sys::nvmlDeviceGetPowerManagementMode`].
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support power limits, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn power_management_limit(self) -> Result<u32> {
        let mut limit = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPowerManagementLimit(
                self.0,
                &raw mut limit
            ))?;
        }
        Ok(limit)
    }

    /// Sets a new power limit for this device.
    ///
    /// For Kepler or newer fully supported devices.
    /// Requires root/admin permissions.
    ///
    /// See [`Device::power_management_limit_constraints`] to check the allowed ranges of values.
    ///
    /// Limit is not persistent across reboots or driver unloads.
    /// Enable persistent mode to prevent driver from unloading when no application is using the device.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or power limit, if the device does not support power-limit
    /// control, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn set_power_management_limit(self, limit: u32) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetPowerManagementLimit(self.0, limit))?;
        }
        Ok(())
    }

    /// Returns default power management limit on this device, in milliwatts.
    /// Default power management limit is a power management limit that the device boots with.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support power limits, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn power_management_default_limit(self) -> Result<u32> {
        let mut limit = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPowerManagementDefaultLimit(
                self.0,
                &raw mut limit,
            ))?;
        }
        Ok(limit)
    }

    /// Returns the effective power limit that the driver enforces after taking into account all limiters.
    ///
    /// This can differ from [`Device::power_management_limit`] if other limits are set elsewhere.
    /// This includes the out-of-band power-limit interface.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support power limits, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn enforced_power_limit(self) -> Result<u32> {
        let mut limit = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetEnforcedPowerLimit(self.0, &raw mut limit))?;
        }
        Ok(limit)
    }

    /// Returns information about possible values of power management limits on this device.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or outputs, if the device does not support power-limit ranges, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn power_management_limit_constraints(self) -> Result<PowerLimits> {
        let mut min = 0;
        let mut max = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPowerManagementLimitConstraints(
                self.0,
                &raw mut min,
                &raw mut max,
            ))?;
        }
        Ok(PowerLimits { min, max })
    }

    /// Returns current power mizer mode on this device.
    ///
    /// PowerMizerMode provides a hint to the driver as to how to manage the performance of the GPU.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support PowerMizer mode
    /// readings, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn power_mizer_mode(self) -> Result<PowerMizerModes> {
        unsafe {
            let mut modes = MaybeUninit::<sys::nvmlDevicePowerMizerModes_v1_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetPowerMizerMode_v1(
                self.0,
                modes.as_mut_ptr()
            ))?;
            Ok(modes.assume_init().into())
        }
    }

    /// Sets the new power mizer mode.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or mode, if the device does not support PowerMizer mode changes,
    /// if NVML has not been initialized, or if NVML reports an unexpected
    /// failure.
    pub fn set_power_mizer_mode(self, mode: PowerMizerMode) -> Result<()> {
        let mut power_mizer = sys::nvmlDevicePowerMizerModes_v1_t {
            mode: mode.into(),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceSetPowerMizerMode_v1(
                self.0,
                &raw mut power_mizer
            ))
        }
    }

    /// Returns total energy consumption for this GPU in millijoules (mJ) since the driver was last reloaded.
    ///
    /// For Volta or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support energy readings, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn total_energy_consumption(self) -> Result<u64> {
        let mut energy = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetTotalEnergyConsumption(
                self.0,
                &raw mut energy
            ))?;
        }
        Ok(energy)
    }

    /// Returns the CUDA compute capability of the device.
    ///
    /// For all products.
    ///
    /// Returns the major and minor compute capability version numbers of the device.
    /// The major and minor versions are equivalent to the `CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR` and `CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR` attributes returned by `cuDeviceGetAttribute`.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or outputs, if NVML has not been initialized, or if NVML reports
    /// an unexpected failure.
    pub fn compute_capability(self) -> Result<ComputeCapability> {
        let mut major = 0;
        let mut minor = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetCudaComputeCapability(
                self.0,
                &raw mut major,
                &raw mut minor,
            ))?;
        }
        Ok(ComputeCapability { major, minor })
    }

    /// Returns the current performance state for the device.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// See [`PerformanceState`] for details on allowed performance states.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support performance-state
    /// queries, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn performance_state(self) -> Result<PerformanceState> {
        let mut state = sys::nvmlPstates_t::NVML_PSTATE_UNKNOWN;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPerformanceState(self.0, &raw mut state))?;
        }
        Ok(state.into())
    }

    pub fn power_state(self) -> Result<PerformanceState> {
        self.performance_state()
    }

    /// Returns all supported performance states (P-states) for the device.
    ///
    /// The returned array contains a contiguous list of valid P-states supported
    /// by the device.
    /// If the number of supported P-states is smaller than the supplied array,
    /// missing elements contain [`PerformanceState::Unknown`].
    ///
    /// The number of returned elements never exceeds `NVML_MAX_GPU_PERF_PSTATES`.
    ///
    /// # Errors
    ///
    /// Returns an error if the fixed internal P-state buffer is too small, if
    /// NVML rejects the query, if the device does not support performance-state
    /// readings, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn supported_performance_states(self) -> Result<Vec<PerformanceState>> {
        let mut states =
            [sys::nvmlPstates_t::NVML_PSTATE_UNKNOWN; sys::NVML_MAX_GPU_PERF_PSTATES as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetSupportedPerformanceStates(
                self.0,
                states.as_mut_ptr(),
                states.len() as u32,
            ))?;
        }
        Ok(states
            .into_iter()
            .filter(|state| *state != sys::nvmlPstates_t::NVML_PSTATE_UNKNOWN)
            .map(Into::into)
            .collect())
    }

    /// Returns current clocks event reasons.
    ///
    /// For all fully supported products.
    ///
    /// More than one bit can be enabled at the same time.
    /// Multiple reasons can be affecting clocks at once.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support clocks-event reasons, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn current_clocks_event_reasons(self) -> Result<u64> {
        let mut reasons = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetCurrentClocksEventReasons(
                self.0,
                &raw mut reasons,
            ))?;
        }
        Ok(reasons)
    }

    pub fn current_clocks_throttle_reasons(self) -> Result<u64> {
        self.current_clocks_event_reasons()
    }

    /// Returns bitmask of supported clocks event reasons that can be returned by [`Device::current_clocks_event_reasons`].
    ///
    /// For all fully supported products.
    ///
    /// Not supported in virtual machines running virtual GPU (vGPU).
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn supported_clocks_event_reasons(self) -> Result<u64> {
        let mut reasons = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetSupportedClocksEventReasons(
                self.0,
                &raw mut reasons,
            ))?;
        }
        Ok(reasons)
    }

    pub fn supported_clocks_throttle_reasons(self) -> Result<u64> {
        self.supported_clocks_event_reasons()
    }

    /// Returns the event types supported by this device.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// Events are not supported on Windows.
    /// Therefore, this call returns an empty event mask on Windows.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the event
    /// mask output, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn supported_event_types(self) -> Result<EventTypes> {
        let mut event_types = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetSupportedEventTypes(
                self.0,
                &raw mut event_types,
            ))?;
        }
        Ok(EventTypes::from_bits_retain(event_types))
    }

    /// Returns the device board ID in the range `0..N`.
    /// Devices with the same board ID indicate GPUs connected to the same PLX.
    /// Use in conjunction with [`Device::is_multi_gpu_board`] to decide if they are on the same board as well.
    /// The returned board ID is unique for the current configuration.
    /// Uniqueness and ordering across reboots and system configurations are not
    /// guaranteed, but IDs remain distinct within one configuration.
    ///
    /// For Fermi or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support board IDs, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn board_id(self) -> Result<u32> {
        let mut board_id = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetBoardId(self.0, &raw mut board_id))?;
        }
        Ok(board_id)
    }

    /// Returns the display mode for the device.
    ///
    /// For all products.
    ///
    /// Indicates whether a physical display, such as a monitor, is currently connected to any of the device's connectors.
    ///
    /// See [`EnableState`] for details on allowed modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support display-mode reporting,
    /// if NVML has not been initialized, or if NVML reports an unexpected
    /// failure.
    pub fn display_mode(self) -> Result<EnableState> {
        let mut mode = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetDisplayMode(self.0, &raw mut mode))?;
        }
        try_from_nvml_enum("enable state", mode as u32)
    }

    /// Returns the display active state for the device.
    ///
    /// For all products.
    ///
    /// Indicates whether a display is initialized on the device.
    /// For example whether X Server is attached to this device and has allocated memory for the screen.
    ///
    /// Display can be active even when no monitor is physically attached.
    ///
    /// See [`EnableState`] for details on allowed modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if the device does not support display-active reporting, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn display_active(self) -> Result<EnableState> {
        let mut active = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetDisplayActive(self.0, &raw mut active))?;
        }
        Ok(active.into())
    }

    /// Returns the current and pending ECC modes for the device.
    ///
    /// For Fermi or newer fully supported devices.
    /// Only applicable to devices with ECC.
    /// Requires [`InforomObject::Ecc`] version 1.0 or higher.
    ///
    /// Changing ECC modes requires a reboot.
    /// The "pending" ECC mode refers to the target mode following the next reboot.
    ///
    /// See [`EnableState`] for details on allowed modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or outputs, if the device does not support ECC mode reporting, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn ecc_mode(self) -> Result<CurrentPending<EnableState>> {
        let mut current = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        let mut pending = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetEccMode(
                self.0,
                &raw mut current,
                &raw mut pending,
            ))?;
        }
        Ok(CurrentPending {
            current: current.into(),
            pending: pending.into(),
        })
    }

    /// Returns the default ECC modes for the device.
    ///
    /// For Fermi or newer fully supported devices.
    /// Only applicable to devices with ECC.
    /// Requires [`InforomObject::Ecc`] version 1.0 or higher.
    ///
    /// See [`EnableState`] for details on allowed modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support ECC mode reporting, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn default_ecc_mode(self) -> Result<EnableState> {
        let mut default_mode = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetDefaultEccMode(
                self.0,
                &raw mut default_mode
            ))?;
        }
        Ok(default_mode.into())
    }

    /// Returns the current GPU operation mode and the pending mode that will
    /// take effect after reboot.
    ///
    /// For GK110 M-class and X-class Tesla products from the Kepler family.
    /// Modes [`GpuOperationMode::LowDp`] and [`GpuOperationMode::AllOn`] are supported on fully supported GeForce products.
    /// Not supported on Quadro and Tesla C-class products.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or outputs, if the device does not support GPU operation modes, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn gpu_operation_mode(self) -> Result<CurrentPending<GpuOperationMode>> {
        let mut current = sys::nvmlGpuOperationMode_t::NVML_GOM_ALL_ON;
        let mut pending = sys::nvmlGpuOperationMode_t::NVML_GOM_ALL_ON;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuOperationMode(
                self.0,
                &raw mut current,
                &raw mut pending,
            ))?;
        }
        Ok(CurrentPending {
            current: current.into(),
            pending: pending.into(),
        })
    }

    /// Returns the current and pending driver model for the device.
    ///
    /// For Kepler or newer fully supported devices.
    /// For windows only.
    ///
    /// On Windows platforms the device driver can run in either WDDM, MCDM or WDM (TCC) modes.
    /// If a display is attached to the device it must run in WDDM mode.
    /// MCDM mode is preferred if a display is not attached.
    /// TCC mode is deprecated.
    ///
    /// See [`DriverModel`] for details on available driver models.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or outputs, if the platform is not Windows, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn driver_model(self) -> Result<CurrentPending<DriverModel>> {
        let mut current = sys::nvmlDriverModel_t::NVML_DRIVER_WDDM;
        let mut pending = sys::nvmlDriverModel_t::NVML_DRIVER_WDDM;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetDriverModel_v2(
                self.0,
                &raw mut current,
                &raw mut pending,
            ))?;
        }
        Ok(CurrentPending {
            current: current.into(),
            pending: pending.into(),
        })
    }

    /// Sets the driver model for the device.
    ///
    /// For Fermi or newer fully supported devices.
    /// For windows only.
    /// Requires root/admin permissions.
    ///
    /// On Windows platforms the device driver can run in either WDDM or WDM (TCC) mode.
    /// If a display is attached to the device it must run in WDDM mode.
    ///
    /// It is possible to force the change to WDM (TCC) while the display is still attached with a force flag (nvmlFlagForce).
    /// Use the force flag only if the host is powered down afterward and the display is detached from the device before the next reboot.
    ///
    /// This operation takes effect after the next reboot.
    ///
    /// Windows driver model may only be set to WDDM when running in DEFAULT compute mode.
    ///
    /// Changing the driver model to WDDM is not supported when the GPU does not
    /// support graphics acceleration, or would not support it after reboot.
    /// See [`Device::set_gpu_operation_mode`].
    ///
    /// See [`DriverModel`] for details on available driver models.
    /// See [`DriverModelFlags`] for the available flag values.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, driver model, or flags, if the platform is not Windows or the
    /// device does not support driver-model changes, if the current process
    /// lacks permission, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn set_driver_model(self, model: DriverModel, flags: DriverModelFlags) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetDriverModel(
                self.0,
                model.into(),
                flags.bits(),
            ))?;
        }
        Ok(())
    }

    /// Sets the GPU operation mode.
    /// See [`GpuOperationMode`] for details.
    ///
    /// For GK110 M-class and X-class Tesla products from the Kepler family.
    /// Modes [`GpuOperationMode::LowDp`] and [`GpuOperationMode::AllOn`] are supported on fully supported GeForce products.
    /// Not supported on Quadro and Tesla C-class products.
    /// Requires root/admin permissions.
    ///
    /// Changing GOMs requires a reboot.
    /// The reboot requirement might be removed in the future.
    ///
    /// Compute-only GOMs do not support graphics acceleration.
    /// On Windows, switching to these GOMs is not supported when the pending driver model is WDDM.
    /// See [`Device::set_driver_model`].
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or mode, if the device does not support GPU operation mode changes
    /// or the requested mode, if the current process lacks permission, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn set_gpu_operation_mode(self, mode: GpuOperationMode) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetGpuOperationMode(self.0, mode.into()))?;
        }
        Ok(())
    }

    pub fn inforom_image_version(self) -> Result<String> {
        device_string_query(self, 16, sys::nvmlDeviceGetInforomImageVersion)
    }

    /// Returns the version information for the device's infoROM object.
    ///
    /// For all products with an inforom.
    ///
    /// Fermi and higher parts have non-volatile on-board memory for persisting device info, such as aggregate ECC counts.
    /// The version of the data structures in this memory may change from time to time.
    /// It does not exceed 16 bytes including the terminating NUL byte.
    /// This wrapper allocates the required NVML buffer internally.
    ///
    /// See [`InforomObject`] for details on the available infoROM objects.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the internal infoROM
    /// version buffer is too small, if NVML rejects the output, if the device
    /// does not have an infoROM, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn inforom_version(self, object: InforomObject) -> Result<String> {
        let mut buffer = vec![0i8; sys::NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetInforomVersion(
                self.as_raw(),
                object.into(),
                buffer.as_mut_ptr(),
                buffer.len() as u32,
            ))?;
        }
        Ok(string_from_c_chars(&buffer))
    }

    /// Returns the checksum of the configuration stored in the device's infoROM.
    ///
    /// For all products with an inforom.
    ///
    /// Can be used to make sure that two GPUs have the exact same configuration.
    /// Current checksum takes into account configuration stored in PWR and ECC infoROM objects.
    /// The checksum can change between driver releases or when configuration changes, such as disabling or enabling ECC.
    ///
    /// # Errors
    ///
    /// Returns an error if the infoROM checksum cannot be read because the
    /// infoROM is corrupted, if the device is inaccessible, if NVML rejects the
    /// output, if the device does not support checksums, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn inforom_configuration_checksum(self) -> Result<u32> {
        let mut checksum = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetInforomConfigurationChecksum(
                self.0,
                &raw mut checksum,
            ))?;
        }
        Ok(checksum)
    }

    /// Reads the infoROM from the flash and verifies the checksums.
    ///
    /// For all products with an inforom.
    ///
    /// # Errors
    ///
    /// Returns an error if the infoROM is corrupted, if the device is
    /// inaccessible, if the device does not support infoROM validation, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn validate_inforom(self) -> Result<()> {
        unsafe { try_ffi!(sys::nvmlDeviceValidateInforom(self.0)) }
    }

    /// Returns the timestamp and the duration of the last flush of the BBX (blackbox) infoROM object during the current run.
    ///
    /// For all products with an inforom.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the BBX object has not
    /// been flushed yet, if the device does not have an infoROM, or if NVML
    /// reports an unexpected failure.
    pub fn last_bbx_flush_time(self) -> Result<BbxFlushTime> {
        let mut timestamp = 0;
        let mut duration_us = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetLastBBXFlushTime(
                self.0,
                &raw mut timestamp,
                &raw mut duration_us,
            ))?;
        }
        Ok(BbxFlushTime {
            timestamp,
            duration_us,
        })
    }

    /// Returns the device's Adaptive Clock status.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support adaptive-clock status,
    /// or if NVML has not been initialized.
    pub fn adaptive_clock_info_status(self) -> Result<AdaptiveClockInfoStatus> {
        let mut status = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetAdaptiveClockInfoStatus(
                self.0,
                &raw mut status
            ))?;
        }
        try_from_nvml_enum("adaptive clock info status", status)
    }

    /// Returns the frequency monitor fault status for the device.
    ///
    /// For Ampere or newer fully supported devices.
    /// Requires root privileges.
    ///
    /// Returns the decoded frequency-monitor fault status reported by NVML.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support frequency-monitor
    /// status, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn clk_mon_status(self) -> Result<ClkMonStatus> {
        unsafe {
            let mut status = MaybeUninit::<sys::nvmlClkMonStatus_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetClkMonStatus(self.0, status.as_mut_ptr()))?;
            Ok(status.assume_init().into())
        }
    }

    /// Returns SRAM ECC error status of this device.
    ///
    /// For Ampere or newer fully supported devices.
    /// Requires root/admin permissions.
    ///
    /// Returns the SRAM ECC error status reported by NVML.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML rejects the handle
    /// or output, if the device does not support SRAM ECC status, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn sram_ecc_error_status(self) -> Result<EccSramErrorStatus> {
        let mut status = sys::nvmlEccSramErrorStatus_t {
            version: struct_version::<sys::nvmlEccSramErrorStatus_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetSramEccErrorStatus(
                self.0,
                &raw mut status,
            ))?;
        }
        Ok(status.into())
    }

    pub fn sram_unique_uncorrected_ecc_error_counts(
        self,
    ) -> Result<EccSramUniqueUncorrectedErrorCounts> {
        let mut counts = sys::nvmlEccSramUniqueUncorrectedErrorCounts_t {
            version: struct_version::<sys::nvmlEccSramUniqueUncorrectedErrorCounts_t>(1),
            ..Default::default()
        };

        unsafe {
            try_ffi!(sys::nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts(
                self.0,
                &raw mut counts,
            ))?;

            let entries = if counts.entryCount == 0 || counts.entries.is_null() {
                Vec::new()
            } else {
                std::slice::from_raw_parts(counts.entries, counts.entryCount as usize)
                    .iter()
                    .copied()
                    .map(Into::into)
                    .collect()
            };

            Ok(EccSramUniqueUncorrectedErrorCounts { entries })
        }
    }

    /// Returns the device's interrupt number.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support IRQ-number reporting, or
    /// if NVML has not been initialized.
    pub fn irq_number(self) -> Result<u32> {
        let mut irq = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetIrqNum(self.0, &raw mut irq))?;
        }
        Ok(irq)
    }

    /// Returns the device's core count.
    ///
    /// On MIG-enabled GPUs, querying the device's core count is currently not supported by this operation.
    /// Use [`sys::nvmlDeviceGetGpuInstanceProfileInfo`] to fetch the MIG device's core count.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device or MIG device does not support core-count
    /// reporting, or if NVML has not been initialized.
    pub fn num_gpu_cores(self) -> Result<u32> {
        let mut cores = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNumGpuCores(self.0, &raw mut cores))?;
        }
        Ok(cores)
    }

    /// Returns the device's memory bus width.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support memory-bus-width
    /// reporting, or if NVML has not been initialized.
    pub fn memory_bus_width(self) -> Result<u32> {
        let mut width = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMemoryBusWidth(self.0, &raw mut width))?;
        }
        Ok(width)
    }

    /// Returns the GPU bus type, such as PCIe or PCI.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML has not been initialized, if NVML rejects the
    /// handle or output, or if NVML reports an unexpected failure.
    pub fn bus_type(self) -> Result<BusType> {
        let mut bus_type = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetBusType(self.0, &raw mut bus_type))?;
        }
        Ok(BusType::from_raw(bus_type))
    }

    /// Returns the device power source.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support power-source reporting,
    /// or if NVML has not been initialized.
    pub fn power_source(self) -> Result<PowerSource> {
        let mut power_source = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPowerSource(self.0, &raw mut power_source))?;
        }
        Ok(PowerSource::from_raw(power_source))
    }

    /// Returns the total ECC error counts for the device.
    ///
    /// For Fermi or newer fully supported devices.
    /// Only applicable to devices with ECC.
    /// Requires [`InforomObject::Ecc`] version 1.0 or higher.
    /// Requires ECC Mode to be enabled.
    ///
    /// The total error count is the sum of errors across each separate memory system, that is, the total set of errors across the entire device.
    ///
    /// See [`MemoryErrorType`] for a description of available error types.
    /// See [`EccCounterType`] for a description of available counter types.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, error type, counter type, or output, if the device does not
    /// support ECC error reporting, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn total_ecc_errors(
        self,
        error_type: MemoryErrorType,
        counter_type: EccCounterType,
    ) -> Result<u64> {
        let mut count = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetTotalEccErrors(
                self.0,
                error_type.into(),
                counter_type.into(),
                &raw mut count,
            ))?;
        }
        Ok(count)
    }

    pub fn detailed_ecc_errors(
        self,
        error_type: MemoryErrorType,
        counter_type: EccCounterType,
    ) -> Result<EccErrorCounts> {
        Ok(EccErrorCounts {
            l1_cache: self.memory_error_counter(
                error_type,
                counter_type,
                MemoryLocation::L1Cache,
            )?,
            l2_cache: self.memory_error_counter(
                error_type,
                counter_type,
                MemoryLocation::L2Cache,
            )?,
            device_memory: self.memory_error_counter(
                error_type,
                counter_type,
                MemoryLocation::Dram,
            )?,
            register_file: self.memory_error_counter(
                error_type,
                counter_type,
                MemoryLocation::RegisterFile,
            )?,
        })
    }

    /// Returns the requested memory error counter for the device.
    ///
    /// For Fermi or newer fully supported devices.
    /// Requires [`InforomObject::Ecc`] version 2.0 or higher to report aggregate location-based memory error counts.
    /// Requires [`InforomObject::Ecc`] version 1.0 or higher to report all other memory error counts.
    ///
    /// Only applicable to devices with ECC.
    ///
    /// Requires ECC Mode to be enabled.
    ///
    /// On MIG-enabled GPUs, per instance information can be queried using specific MIG device handles.
    /// Per instance information is currently only supported for non-DRAM uncorrectable volatile errors.
    /// Querying volatile errors using device handles is currently not supported.
    ///
    /// See [`MemoryErrorType`] for a description of available memory error types.
    /// See [`EccCounterType`] for a description of available counter types.
    /// See [`MemoryLocation`] for a description of available counter locations.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, error type, counter type, memory location, or output, if the
    /// device does not support ECC error reporting for the requested memory
    /// location, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn memory_error_counter(
        self,
        error_type: MemoryErrorType,
        counter_type: EccCounterType,
        location: MemoryLocation,
    ) -> Result<u64> {
        let mut count = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMemoryErrorCounter(
                self.0,
                error_type.into(),
                counter_type.into(),
                location.into(),
                &raw mut count,
            ))?;
        }
        Ok(count)
    }

    pub fn violation_status(self, perf_policy: PerfPolicyType) -> Result<ViolationTime> {
        let sample = self.single_field_value(field_id_for_perf_policy(perf_policy), 0)?;
        Ok(ViolationTime {
            reference_time: u64::try_from(sample.timestamp).unwrap_or_default(),
            violation_time: field_sample_as_u64(sample)?,
        })
    }

    /// Returns the list of retired pages by source, including pages that are pending retirement.
    /// The returned address information is the hardware address of the retired page.
    /// This does not match the virtual address used in CUDA, but it matches the
    /// address information in Xid 63.
    ///
    /// [`Device::retired_pages`] adds an additional timestamps parameter to return the time of each page's retirement.
    /// This is supported for Pascal and newer architecture.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the retired-page list
    /// changes while the wrapper is fetching it, if NVML rejects the handle,
    /// cause, count, or outputs, if the device does not support page retirement,
    /// if NVML has not been initialized, or if NVML reports an unexpected
    /// failure.
    pub fn retired_pages(self, cause: PageRetirementCause) -> Result<Vec<RetiredPage>> {
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetRetiredPages_v2(
                self.0,
                cause.into(),
                &raw mut count,
                ptr::null_mut(),
                ptr::null_mut(),
            )
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut addresses = vec![0u64; count as usize];
        let mut timestamps = vec![0u64; count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetRetiredPages_v2(
                self.0,
                cause.into(),
                &raw mut count,
                addresses.as_mut_ptr(),
                timestamps.as_mut_ptr(),
            ))?;
        }
        addresses.truncate(count as usize);
        timestamps.truncate(count as usize);
        Ok(addresses
            .into_iter()
            .zip(timestamps)
            .map(|(address, timestamp)| RetiredPage {
                address,
                timestamp: Some(timestamp),
            })
            .collect())
    }

    /// Check if any pages are pending retirement and need a reboot to fully retire.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support page-retirement status,
    /// if NVML has not been initialized, or if NVML reports an unexpected
    /// failure.
    pub fn retired_pages_pending_status(self) -> Result<EnableState> {
        let mut pending = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetRetiredPagesPendingStatus(
                self.0,
                &raw mut pending,
            ))?;
        }
        Ok(pending.into())
    }

    /// Returns the number of remapped rows.
    /// The number of rows reported is based on the remapping cause.
    /// `is_pending` indicates whether there are pending remappings.
    /// A reset is required to actually remap the row.
    /// `failure_occurred` is set if a row remapping ever failed in the past.
    /// A pending remapping does not affect future GPU work because error
    /// containment and dynamic page blacklisting handle it.
    ///
    /// On MIG-enabled GPUs with active instances, querying the number of remapped rows is not supported.
    ///
    /// For Ampere or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or outputs, if MIG is enabled
    /// or the device does not support remapped-row reporting, or if NVML reports
    /// an unexpected failure.
    pub fn remapped_rows(self) -> Result<RemappedRows> {
        let mut corrected = 0;
        let mut uncorrected = 0;
        let mut pending = 0;
        let mut failure_occurred = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetRemappedRows(
                self.0,
                &raw mut corrected,
                &raw mut uncorrected,
                &raw mut pending,
                &raw mut failure_occurred,
            ))?;
        }
        Ok(RemappedRows {
            corrected,
            uncorrected,
            pending: pending != 0,
            failure_occurred: failure_occurred != 0,
        })
    }

    /// Returns the row remapper histogram.
    /// Returns the remap availability for each bank on the GPU.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML reports an unexpected row-remapper query
    /// failure.
    pub fn row_remapper_histogram(self) -> Result<RowRemapperHistogram> {
        unsafe {
            let mut histogram = MaybeUninit::<sys::nvmlRowRemapperHistogramValues_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetRowRemapperHistogram(
                self.0,
                histogram.as_mut_ptr(),
            ))?;
            Ok(histogram.assume_init().into())
        }
    }

    /// Requests values for a list of device fields.
    /// Allows multiple fields to be queried at once.
    /// If multiple field IDs are populated by the same driver call, NVML
    /// populates those results from one call rather than one call per field ID.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the device handle or field-value buffer.
    pub fn field_values(self, queries: &[FieldQuery]) -> Result<Vec<FieldSample>> {
        let mut values = queries
            .iter()
            .map(|query| sys::nvmlFieldValue_t {
                fieldId: query.field.0,
                scopeId: query.scope_id,
                ..Default::default()
            })
            .collect::<Vec<_>>();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetFieldValues(
                self.0,
                values.len() as i32,
                values.as_mut_ptr(),
            ))?;
        }
        Ok(values.into_iter().map(FieldSample::from_raw).collect())
    }

    fn single_field_value(self, field: FieldId, scope_id: u32) -> Result<FieldSample> {
        self.field_values(&[FieldQuery { field, scope_id }])?
            .into_iter()
            .next()
            .ok_or(Error::EmptyOutput {
                name: "nvmlDeviceGetFieldValues".into(),
            })
    }

    /// Clear values for a list of fields for a device.
    /// Allows multiple fields to be cleared at once.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the device handle or field-value buffer.
    pub fn clear_field_values(self, queries: &[FieldQuery]) -> Result<Vec<FieldSample>> {
        let mut values = queries
            .iter()
            .map(|query| sys::nvmlFieldValue_t {
                fieldId: query.field.0,
                scopeId: query.scope_id,
                ..Default::default()
            })
            .collect::<Vec<_>>();
        unsafe {
            try_ffi!(sys::nvmlDeviceClearFieldValues(
                self.0,
                values.len() as i32,
                values.as_mut_ptr(),
            ))?;
        }
        Ok(values.into_iter().map(FieldSample::from_raw).collect())
    }

    /// Returns recent samples for the GPU.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// Fetches power, utilization, or clock samples maintained in the driver's buffer, depending on the requested sample type.
    ///
    /// Power, utilization, and clock samples are returned as unsigned integer values.
    ///
    /// This wrapper performs the size query internally and returns the samples as an owned collection.
    ///
    /// `last_seen_timestamp` represents a CPU timestamp in microseconds.
    /// Use `0` to fetch all samples maintained by the buffer.
    /// Use a timestamp returned by a previous query to get more recent samples.
    ///
    /// This wrapper performs the NVML size query internally and returns the samples that were actually retrieved.
    /// Compared with polling the current-value methods, samples provide higher-frequency data at lower polling cost.
    ///
    /// On MIG-enabled GPUs, querying the following sample types, [`SamplingType::GpuUtilization`], [`SamplingType::MemoryUtilization`], [`SamplingType::EncoderUtilization`], and [`SamplingType::DecoderUtilization`], is not currently supported.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if the device does not support the requested sample type, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    /// Missing sample entries are returned as an empty sample list.
    pub fn samples(self, kind: SamplingType, last_seen_timestamp: u64) -> Result<Samples> {
        let mut value_type = sys::nvmlValueType_t::NVML_VALUE_TYPE_UNSIGNED_INT;
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetSamples(
                self.0,
                kind.into(),
                last_seen_timestamp,
                &raw mut value_type,
                &raw mut count,
                ptr::null_mut(),
            )
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Samples {
                value_type: try_from_nvml_enum("field value type", u32::from(value_type))?,
                samples: Vec::new(),
            });
        }
        if status == sys::nvmlReturn_t::NVML_ERROR_NOT_FOUND {
            return Ok(Samples {
                value_type: try_from_nvml_enum("field value type", u32::from(value_type))?,
                samples: Vec::new(),
            });
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut samples = vec![sys::nvmlSample_t::default(); count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetSamples(
                self.0,
                kind.into(),
                last_seen_timestamp,
                &raw mut value_type,
                &raw mut count,
                samples.as_mut_ptr(),
            ))?;
        }
        samples.truncate(count as usize);
        Ok(Samples {
            value_type: try_from_nvml_enum("field value type", u32::from(value_type))?,
            samples: samples
                .into_iter()
                .map(|sample| Sample::from_raw(value_type, sample))
                .collect::<Result<Vec<_>>>()?,
        })
    }

    /// Returns GSP firmware version.
    ///
    /// This wrapper allocates the firmware-version buffer internally and returns it as a [`String`].
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the device or output buffer, if GSP
    /// firmware is not enabled for the GPU, or if NVML reports an unexpected
    /// failure.
    pub fn gsp_firmware_version(self) -> Result<String> {
        let mut buffer = vec![0i8; sys::NVML_GSP_FIRMWARE_VERSION_BUF_SIZE as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGspFirmwareVersion(
                self.0,
                buffer.as_mut_ptr()
            ))?;
        }
        Ok(string_from_c_chars(&buffer))
    }

    /// Returns GSP firmware mode.
    ///
    /// Returns GSP firmware enablement and default mode information.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if GSP firmware is not
    /// enabled for the GPU, or if NVML reports an unexpected failure.
    pub fn gsp_firmware_mode(self) -> Result<GspFirmwareMode> {
        let mut enabled = 0;
        let mut default_mode = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGspFirmwareMode(
                self.0,
                &raw mut enabled,
                &raw mut default_mode,
            ))?;
        }
        Ok(GspFirmwareMode {
            enabled: enabled != 0,
            default_mode: default_mode != 0,
        })
    }

    /// Returns the number of fans on the device.
    ///
    /// For all discrete products with dedicated fans.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not have a fan, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn num_fans(self) -> Result<u32> {
        let mut fans = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNumFans(self.0, &raw mut fans))?;
        }
        Ok(fans)
    }

    /// Returns the intended operating speed of the device's fan.
    ///
    /// The reported speed is the intended fan speed.
    /// If the fan is physically blocked and unable to spin, the output does not
    /// match the actual fan speed.
    ///
    /// For all discrete products with dedicated fans.
    ///
    /// The fan speed is expressed as a percentage of the product's maximum noise tolerance fan speed.
    /// This value may exceed 100% in certain cases.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not have a fan, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn default_fan_speed(self) -> Result<u32> {
        let mut speed = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetFanSpeed(self.0, &raw mut speed))?;
        }
        Ok(speed)
    }

    /// Returns the intended operating speed of the device's specified fan.
    ///
    /// The reported speed is the intended fan speed.
    /// If the fan is physically blocked and unable to spin, the output does not
    /// match the actual fan speed.
    ///
    /// For all discrete products with dedicated fans.
    ///
    /// The fan speed is expressed as a percentage of the product's maximum noise tolerance fan speed.
    /// This value may exceed 100% in certain cases.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, fan index, or output, if the device does not have a supported fan
    /// interface, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn fan_speed(self, fan: u32) -> Result<u32> {
        let mut speed = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetFanSpeed_v2(self.0, fan, &raw mut speed))?;
        }
        Ok(speed)
    }

    /// Returns the intended operating speed in rotations per minute (RPM) of the device's specified fan.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// For all discrete products with dedicated fans.
    ///
    /// The reported speed is the intended fan speed.
    /// If the fan is physically blocked and unable to spin, the output does not
    /// match the actual fan speed.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the handle, fan index, or output, if the
    /// device does not support fan RPM reporting, or if NVML has not been
    /// initialized.
    pub fn fan_speed_rpm(self, fan: u32) -> Result<FanSpeedInfo> {
        let mut info = sys::nvmlFanSpeedInfo_t {
            version: struct_version::<sys::nvmlFanSpeedInfo_t>(1),
            fan,
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetFanSpeedRPM(self.0, &raw mut info))?;
        }
        Ok(FanSpeedInfo {
            fan: info.fan,
            speed: info.speed,
        })
    }

    /// Returns current fan control policy.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// For all cuda-capable discrete products with fans.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, fan index, or output, if
    /// the device does not support fan policies, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn fan_control_policy(self, fan: u32) -> Result<FanPolicy> {
        let mut policy = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetFanControlPolicy_v2(
                self.0,
                fan,
                &raw mut policy
            ))?;
        }
        try_from_nvml_enum("fan policy", policy)
    }

    /// Sets the speed of the fan control policy to default.
    ///
    /// For all cuda-capable discrete products with fans.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or fan index, if the device
    /// does not support fan-speed control, if NVML has not been initialized, or
    /// if NVML reports an unexpected failure.
    pub fn set_default_fan_speed(self, fan: u32) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetDefaultFanSpeed_v2(self.0, fan))?;
        }
        Ok(())
    }

    /// Sets current fan control policy.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// Requires privileged access.
    ///
    /// For all cuda-capable discrete products with fans.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, fan index, or policy, if the
    /// device does not support fan policies, if NVML has not been initialized,
    /// or if NVML reports an unexpected failure.
    pub fn set_fan_control_policy(self, fan: u32, policy: FanPolicy) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetFanControlPolicy(
                self.0,
                fan,
                policy.into()
            ))?;
        }
        Ok(())
    }

    /// Sets the speed of a specified fan.
    ///
    /// Warning: this changes the fan control policy to manual.
    /// You must monitor the temperature and adjust the fan speed accordingly.
    /// Setting the fan speed too low can damage the GPU.
    /// Use [`Device::set_default_fan_speed`] to restore default control policy.
    ///
    /// For all cuda-capable discrete products with fans that are Maxwell or Newer.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML has not been initialized, if NVML rejects the
    /// handle, fan index, or speed, if the device does not support manual fan
    /// speed control, or if NVML reports an unexpected failure.
    pub fn set_fan_speed(self, fan: u32, speed: u32) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetFanSpeed_v2(self.0, fan, speed))?;
        }
        Ok(())
    }

    /// Returns the intended target speed of the device's specified fan.
    ///
    /// Normally, the driver dynamically adjusts the fan based on the needs of the GPU.
    /// When the caller sets fan speed with [`Device::set_fan_speed`], the driver attempts to make the fan achieve that setting.
    /// The actual current speed of the fan is reported in [`Device::fan_speed`].
    ///
    /// For all discrete products with dedicated fans.
    ///
    /// The fan speed is expressed as a percentage of the product's maximum noise tolerance fan speed.
    /// This value may exceed 100% in certain cases.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, fan index, or output, if the device does not have a supported fan
    /// interface, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn target_fan_speed(self, fan: u32) -> Result<u32> {
        let mut speed = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetTargetFanSpeed(
                self.0,
                fan,
                &raw mut speed
            ))?;
        }
        Ok(speed)
    }

    /// Returns the min and max fan speed that can be set for the GPU fan.
    ///
    /// For all cuda-capable discrete products with fans.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support fan-speed range reporting, if NVML has not been initialized,
    /// or if NVML reports an unexpected failure.
    pub fn min_max_fan_speed(self) -> Result<MinMaxFanSpeed> {
        let mut min = 0;
        let mut max = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMinMaxFanSpeed(
                self.0,
                &raw mut min,
                &raw mut max,
            ))?;
        }
        Ok(MinMaxFanSpeed { min, max })
    }

    /// Returns the cooler's information.
    /// Returns a cooler's control signal characteristics.
    /// The possible types are restricted, Variable and Toggle.
    /// See [`CoolerControl`](crate::types::CoolerControl) for details on available signal types.
    /// Returns objects that cooler cools.
    /// Targets may be GPU, Memory, Power Supply or All of these.
    /// See [`CoolerTarget`](crate::types::CoolerTarget) for details on available targets.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// For all discrete products with dedicated fans.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the handle or cooler index, if the device
    /// does not support cooler reporting, or if NVML has not been initialized.
    pub fn cooler_info(self, index: u32) -> Result<CoolerInfo> {
        let mut info = sys::nvmlCoolerInfo_t {
            version: struct_version::<sys::nvmlCoolerInfo_t>(1),
            index,
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetCoolerInfo(self.0, &raw mut info))?;
        }
        Ok(CoolerInfo {
            index: info.index,
            signal_type: info.signalType.into(),
            target: info.target.into(),
        })
    }

    /// Returns the current temperature readings (in degrees C) for the given device.
    ///
    /// For all products.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, sensor type, or output, if the device does not have the requested
    /// sensor, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn temperature(self, sensor: TemperatureSensor) -> Result<TemperatureInfo> {
        let mut temperature = sys::nvmlTemperature_t {
            version: struct_version::<sys::nvmlTemperature_t>(1),
            sensorType: sensor.into(),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetTemperatureV(self.0, &raw mut temperature))?;
        }
        Ok(TemperatureInfo {
            sensor: temperature.sensorType.into(),
            temperature: temperature.temperature,
        })
    }

    /// Returns minor number for the device.
    /// The minor number is the suffix in the Linux device node path
    /// `/dev/nvidia[minor_number]`.
    ///
    /// For all products.
    /// Supported only for Linux.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support Linux minor-number
    /// reporting, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn minor_number(self) -> Result<u32> {
        let mut minor_number = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMinorNumber(self.0, &raw mut minor_number))?;
        }
        Ok(minor_number)
    }

    /// Returns the current compute mode for the device.
    ///
    /// For all products.
    ///
    /// See [`ComputeMode`] for details on allowed compute modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support compute-mode reporting,
    /// if NVML has not been initialized, or if NVML reports an unexpected
    /// failure.
    pub fn compute_mode(self) -> Result<ComputeMode> {
        let mut compute_mode = sys::nvmlComputeMode_t::NVML_COMPUTEMODE_DEFAULT;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetComputeMode(self.0, &raw mut compute_mode))?;
        }
        Ok(compute_mode.into())
    }

    /// Returns the persistence mode associated with this device.
    ///
    /// For all products.
    /// For Linux only.
    ///
    /// When driver persistence mode is enabled the driver software state is not torn down when the last client disconnects.
    /// By default this feature is disabled.
    ///
    /// See [`EnableState`] for details on allowed modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output, if the device does not support persistence mode, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn persistence_mode(self) -> Result<EnableState> {
        let mut mode = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetPersistenceMode(self.0, &raw mut mode))?;
        }
        Ok(mode.into())
    }

    /// Sets the compute mode for the device.
    ///
    /// For all products.
    /// Requires root/admin permissions.
    ///
    /// The compute mode determines whether a GPU can be used for compute operations and whether it can be shared across contexts.
    ///
    /// This operation takes effect immediately.
    /// Under Linux it is not persistent across reboots and always resets to "Default".
    /// Under Windows it is persistent.
    ///
    /// Under Windows, compute mode may only be set to default when running in
    /// WDDM.
    ///
    /// On MIG-enabled GPUs, compute mode is set to default and changing it is
    /// not supported.
    ///
    /// See [`ComputeMode`] for details on available compute modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or mode, if the device does not support compute-mode changes, if
    /// the current process lacks permission, if NVML has not been initialized,
    /// or if NVML reports an unexpected failure.
    pub fn set_compute_mode(self, mode: ComputeMode) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetComputeMode(self.0, mode.into()))?;
        }
        Ok(())
    }

    /// Sets the persistence mode for the device.
    ///
    /// For all products.
    /// For Linux only.
    /// Requires root/admin permissions.
    ///
    /// The persistence mode determines whether the GPU driver software is torn down after the last client exits.
    ///
    /// This operation takes effect immediately.
    /// It is not persistent across reboots.
    /// After each reboot the persistence mode is reset to "Disabled".
    ///
    /// See [`EnableState`] for available modes.
    ///
    /// After disabling persistence mode on a device that has its own NUMA memory,
    /// the current device handle is no longer valid. Acquire a fresh handle from
    /// the library before continuing to interact with the device.
    /// This limitation is currently only applicable to devices that have a coherent NVLink connection to system memory.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or mode, if the device does not support persistence mode, if the
    /// current process lacks permission, if NVML has not been initialized, or if
    /// NVML reports an unexpected failure.
    pub fn set_persistence_mode(self, mode: EnableState) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetPersistenceMode(self.0, mode.into()))?;
        }
        Ok(())
    }

    /// Sets the ECC mode for the device.
    ///
    /// For Kepler or newer fully supported devices.
    /// Only applicable to devices with ECC.
    /// Requires [`InforomObject::Ecc`] version 1.0 or higher.
    /// Requires root/admin permissions.
    ///
    /// The ECC mode determines whether the GPU enables its ECC support.
    ///
    /// This operation takes effect after the next reboot.
    ///
    /// See [`EnableState`] for details on available modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or mode, if the device does not support ECC mode changes, if the
    /// current process lacks permission, if NVML has not been initialized, or if
    /// NVML reports an unexpected failure.
    pub fn set_ecc_mode(self, mode: EnableState) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceSetEccMode(self.0, mode.into()))?;
        }
        Ok(())
    }

    /// Clear the ECC error and other memory error counts for the device.
    ///
    /// For Kepler or newer fully supported devices.
    /// Only applicable to devices with ECC.
    /// Requires [`InforomObject::Ecc`] version 2.0 or higher to clear aggregate location-based ECC counts.
    /// Requires [`InforomObject::Ecc`] version 1.0 or higher to clear all other ECC counts.
    /// Requires root/admin permissions.
    /// Requires ECC Mode to be enabled.
    ///
    /// Sets all of the specified ECC counters to 0, including both detailed and total counts.
    ///
    /// This operation takes effect immediately.
    ///
    /// See [`MemoryErrorType`] for details on available counter types.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or counter type, if the device does not support clearing ECC
    /// counters, if the current process lacks permission, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn clear_ecc_error_counts(self, counter_type: EccCounterType) -> Result<()> {
        unsafe {
            try_ffi!(sys::nvmlDeviceClearEccErrorCounts(
                self.0,
                counter_type.into()
            ))?;
        }
        Ok(())
    }

    /// Returns MIG mode for the device.
    ///
    /// For Ampere or newer fully supported devices.
    ///
    /// Changing MIG modes may require device unbind or reset.
    /// The "pending" MIG mode refers to the target mode following the next activation trigger.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or outputs, if the device
    /// does not support MIG mode, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn mig_mode(self) -> Result<CurrentPending<MigMode>> {
        let mut current = 0;
        let mut pending = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMigMode(
                self.0,
                &raw mut current,
                &raw mut pending,
            ))?;
        }
        Ok(CurrentPending {
            current: try_from_nvml_enum("mig mode", current)?,
            pending: try_from_nvml_enum("mig mode", pending)?,
        })
    }

    /// Sets MIG mode for the device.
    ///
    /// For Ampere or newer fully supported devices.
    /// Requires root privileges.
    ///
    /// This mode determines whether a GPU instance can be created.
    ///
    /// This may unbind or reset the device to activate the requested mode.
    /// Thus, the attributes associated with the device, such as minor number, might change.
    /// Query such attributes again after changing the mode.
    ///
    /// On certain platforms, such as pass-through virtualization, reset may not be exposed directly and a VM reboot is required.
    /// In those cases, the returned activation status is [`Status::ResetRequired`].
    ///
    /// The returned activation status contains the appropriate error code when activation is unsuccessful.
    /// For example, if device unbind fails because the device is not idle, the status is [`Status::InUse`].
    /// Idle the device and retry setting the mode in that case.
    ///
    /// On Windows, only disabling MIG mode is supported. `activation_status` returns [`Status::NotSupported`] because GPU reset is not supported on Windows through this operation.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, requested mode, or
    /// activation-status output, if the device does not support MIG mode, if the
    /// current process lacks permission, or if NVML has not been initialized.
    pub fn set_mig_mode(self, mode: MigMode) -> Result<MigModeActivation> {
        let mut activation_status = sys::nvmlReturn_t::NVML_SUCCESS;
        unsafe {
            try_ffi!(sys::nvmlDeviceSetMigMode(
                self.0,
                mode.into(),
                &raw mut activation_status,
            ))?;
        }
        Ok(MigModeActivation::from_raw(activation_status))
    }

    /// Returns the maximum number of MIG devices that can exist under a parent NVML device.
    ///
    /// Returns zero if MIG is not supported or enabled.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if NVML has not
    /// been initialized, or if NVML reports an unexpected failure.
    pub fn max_mig_device_count(self) -> Result<u32> {
        let mut count = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMaxMigDeviceCount(self.0, &raw mut count))?;
        }
        Ok(count)
    }

    /// Tests if this handle refers to a MIG device.
    ///
    /// A MIG device handle is an NVML abstraction which maps to a MIG compute instance.
    /// These overloaded references can be used (with some restrictions) interchangeably with a GPU device handle to execute queries at a per-compute instance granularity.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support this check, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn is_mig_device_handle(self) -> Result<bool> {
        let mut is_mig_device = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceIsMigDeviceHandle(
                self.0,
                &raw mut is_mig_device,
            ))?;
        }
        Ok(is_mig_device != 0)
    }

    /// Returns parent device handle from a MIG device handle.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the MIG device handle or parent output,
    /// if the device does not support this query, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn parent_device_from_mig_handle(self) -> Result<Self> {
        let mut device = ptr::null_mut();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetDeviceHandleFromMigDeviceHandle(
                self.0,
                &raw mut device,
            ))?;
            Ok(Self::from_raw(device))
        }
    }

    /// Returns MIG device handle for the given index under its parent NVML device.
    ///
    /// If the compute instance is destroyed, either explicitly or by destroying, resetting, or unbinding the parent GPU instance or GPU device, the MIG device handle remains invalid and must be requested again.
    /// Handles may be reused and their properties can change in the process.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, index, or output, if no MIG
    /// device exists at `index`, if the device does not support this query, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn mig_device(self, index: u32) -> Result<Self> {
        let mut device = ptr::null_mut();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetMigDeviceHandleByIndex(
                self.0,
                index,
                &raw mut device,
            ))?;
            Ok(Self::from_raw(device))
        }
    }

    pub fn mig_devices(self) -> Result<Vec<Self>> {
        let max_count = self.max_mig_device_count()?;
        let mut devices = Vec::with_capacity(max_count as usize);

        for index in 0..max_count {
            match self.mig_device(index) {
                Ok(device) => devices.push(device),
                Err(Error::Nvml {
                    code: Status::NotFound,
                    ..
                }) => {}
                Err(error) => return Err(error),
            }
        }

        Ok(devices)
    }

    /// Versioned wrapper that requests GPU-instance profile information using the latest supported NVML output layout.
    ///
    /// This wrapper sets the version field on the output structure before calling NVML.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, profile, or request layout,
    /// if MIG mode is disabled or the profile is unsupported, if the current
    /// process lacks permission, or if NVML has not been initialized.
    pub fn gpu_instance_profile_info(self, profile: u32) -> Result<GpuInstanceProfileInfo> {
        let mut info = sys::nvmlGpuInstanceProfileInfo_v3_t {
            version: struct_version::<sys::nvmlGpuInstanceProfileInfo_v3_t>(3),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuInstanceProfileInfoV(
                self.0,
                profile,
                (&raw mut info).cast(),
            ))?;
        }
        Ok(info.into())
    }

    /// GPU instance profile query function that accepts profile ID, instead of profile name.
    /// It requests the result using the latest supported NVML output layout.
    ///
    /// This wrapper sets the version field on the output structure before calling NVML.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, profile ID, or request
    /// layout, if MIG mode is disabled or the profile is unsupported, if the
    /// current process lacks permission, or if NVML has not been initialized.
    pub fn gpu_instance_profile_info_by_id(
        self,
        profile_id: u32,
    ) -> Result<GpuInstanceProfileInfo> {
        let mut info = sys::nvmlGpuInstanceProfileInfo_v3_t {
            version: struct_version::<sys::nvmlGpuInstanceProfileInfo_v3_t>(3),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuInstanceProfileInfoByIdV(
                self.0,
                profile_id,
                (&raw mut info).cast(),
            ))?;
        }
        Ok(info.into())
    }

    /// Returns GPU instance profile capacity.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    /// Requires privileged access.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if MIG mode is disabled or
    /// `profile_id` is unsupported, if the current process lacks permission, or
    /// if NVML has not been initialized.
    pub fn gpu_instance_remaining_capacity(self, profile_id: u32) -> Result<u32> {
        let mut count = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuInstanceRemainingCapacity(
                self.0,
                profile_id,
                &raw mut count,
            ))?;
        }
        Ok(count)
    }

    /// Returns GPU instance placements.
    ///
    /// A placement represents the location of a GPU instance within a device.
    /// Returns all possible placements for the given profile, regardless of whether MIG is enabled.
    /// A created GPU instance occupies memory slices described by its placement.
    /// Creating a GPU instance fails if its placement overlaps already occupied
    /// memory slices.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    /// Requires privileged access.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if the device does not
    /// support MIG or `profile_id` is unsupported, if the current process lacks
    /// permission, or if NVML has not been initialized.
    pub fn gpu_instance_possible_placements(
        self,
        profile_id: u32,
    ) -> Result<Vec<GpuInstancePlacement>> {
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetGpuInstancePossiblePlacements_v2(
                self.0,
                profile_id,
                ptr::null_mut(),
                &raw mut count,
            )
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut placements = vec![sys::nvmlGpuInstancePlacement_t::default(); count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuInstancePossiblePlacements_v2(
                self.0,
                profile_id,
                placements.as_mut_ptr(),
                &raw mut count,
            ))?;
        }
        placements.truncate(count as usize);
        Ok(placements.into_iter().map(Into::into).collect())
    }

    /// Returns GPU instances for the given instance ID.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    /// Requires privileged access.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if no GPU instance has the
    /// requested ID, if MIG mode is disabled, if the current process lacks
    /// permission, or if NVML has not been initialized.
    pub fn gpu_instance_by_id(self, id: u32) -> Result<GpuInstance> {
        let mut instance = ptr::null_mut();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuInstanceById(
                self.0,
                id,
                &raw mut instance,
            ))?;
            Ok(GpuInstance::from_raw(instance))
        }
    }

    /// Creates a GPU instance.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    /// Requires privileged access.
    ///
    /// If the parent device is unbound or reset, or if the GPU instance is destroyed, the GPU instance handle becomes invalid.
    /// The GPU instance must be recreated to acquire a valid handle.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML cannot allocate the requested GPU instance, if
    /// NVML rejects the query, if MIG mode is disabled or the device is a vGPU
    /// guest, if the current process lacks permission, or if NVML has not been
    /// initialized.
    pub fn create_gpu_instance(self, profile_id: u32) -> Result<OwnedGpuInstance> {
        let mut instance = ptr::null_mut();
        unsafe {
            try_ffi!(sys::nvmlDeviceCreateGpuInstance(
                self.0,
                profile_id,
                &raw mut instance,
            ))?;
            Ok(OwnedGpuInstance::from_raw(instance))
        }
    }

    /// Creates a GPU instance with the specified placement.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    /// Requires privileged access.
    ///
    /// If the parent device is unbound or reset, or if the GPU instance is destroyed, the GPU instance handle becomes invalid.
    /// The GPU instance must be recreated to acquire a valid handle.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML cannot allocate the requested GPU instance, if
    /// NVML rejects the query or placement, if MIG mode is disabled or the
    /// device is a vGPU guest, if the current process lacks permission, or if
    /// NVML has not been initialized.
    pub fn create_gpu_instance_with_placement(
        self,
        profile_id: u32,
        placement: GpuInstancePlacement,
    ) -> Result<OwnedGpuInstance> {
        let placement = sys::nvmlGpuInstancePlacement_t::from(placement);
        let mut instance = ptr::null_mut();
        unsafe {
            try_ffi!(sys::nvmlDeviceCreateGpuInstanceWithPlacement(
                self.0,
                profile_id,
                &raw const placement,
                &raw mut instance,
            ))?;
            Ok(OwnedGpuInstance::from_raw(instance))
        }
    }

    /// Returns GPU instances for the given profile ID.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    /// Requires privileged access.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if MIG mode is disabled, if
    /// the current process lacks permission, or if NVML has not been
    /// initialized.
    pub fn gpu_instances(self, profile_id: u32) -> Result<Vec<GpuInstance>> {
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetGpuInstances(self.0, profile_id, ptr::null_mut(), &raw mut count)
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut instances = vec![ptr::null_mut(); count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuInstances(
                self.0,
                profile_id,
                instances.as_mut_ptr(),
                &raw mut count,
            ))?;
        }
        instances.truncate(count as usize);
        Ok(instances
            .into_iter()
            .map(|instance| unsafe { GpuInstance::from_raw(instance) })
            .collect())
    }

    /// Returns the GPU instance ID for this MIG device handle.
    ///
    /// GPU instance IDs are unique per device and remain valid until the GPU instance is destroyed.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support this query, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn gpu_instance_id(self) -> Result<u32> {
        let mut id = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuInstanceId(self.0, &raw mut id))?;
        }
        Ok(id)
    }

    /// Returns the compute instance ID for this MIG device handle.
    ///
    /// Compute instance IDs are unique per GPU instance and remain valid until the compute instance is destroyed.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support this query, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn compute_instance_id(self) -> Result<u32> {
        let mut id = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetComputeInstanceId(self.0, &raw mut id))?;
        }
        Ok(id)
    }

    /// Returns the virtualization mode corresponding to the GPU.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn virtualization_mode(self) -> Result<VirtualizationMode> {
        let mut mode = sys::nvmlGpuVirtualizationMode_t::NVML_GPU_VIRTUALIZATION_MODE_NONE as u32;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetVirtualizationMode(
                self.0,
                (&raw mut mode).cast::<sys::nvmlGpuVirtualizationMode_t>(),
            ))?;
        }
        Ok(VirtualizationMode::from_raw(mode))
    }

    /// Queries if SR-IOV host operation is supported on a vGPU supported device.
    ///
    /// Checks whether SR-IOV host capability is supported by the device and the driver, and indicates device is in SR-IOV mode if both of these conditions are true.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if the device does not
    /// support host vGPU mode reporting, or if NVML reports an unexpected
    /// failure.
    pub fn host_vgpu_mode(self) -> Result<HostVgpuMode> {
        let mut mode = sys::nvmlHostVgpuMode_t::NVML_HOST_VGPU_MODE_NON_SRIOV;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetHostVgpuMode(self.0, &raw mut mode))?;
        }
        try_from_nvml_enum("host vgpu mode", mode as u32)
    }

    /// Returns the supported vGPU types on a physical GPU (device).
    ///
    /// This wrapper performs the NVML size query internally and returns the supported vGPU types as a [`Vec`].
    ///
    /// # Errors
    ///
    /// Returns an error if the vGPU type list changes while the wrapper is
    /// fetching it, if NVML rejects the query, if vGPU is unsupported by the
    /// device, or if NVML reports an unexpected failure.
    pub fn supported_vgpus(self) -> Result<Vec<VgpuTypeId>> {
        Ok(query_u32_list(|count, values| unsafe {
            sys::nvmlDeviceGetSupportedVgpus(self.0, count, values)
        })?
        .into_iter()
        .map(VgpuTypeId)
        .collect())
    }

    /// Returns the currently creatable vGPU types on a physical GPU.
    ///
    /// The creatable vGPU types for a device may differ over time because
    /// restrictions can limit which vGPU types may run concurrently.
    /// For example, if only one vGPU type is allowed at a time on a device, the
    /// creatable list is restricted to the currently running vGPU type.
    /// This wrapper performs the NVML size query internally and returns the creatable vGPU types as a [`Vec`].
    ///
    /// # Errors
    ///
    /// Returns an error if the vGPU type list changes while the wrapper is
    /// fetching it, if NVML rejects the query, if vGPU is unsupported by the
    /// device, or if NVML reports an unexpected failure.
    pub fn creatable_vgpus(self) -> Result<Vec<VgpuTypeId>> {
        Ok(query_u32_list(|count, values| unsafe {
            sys::nvmlDeviceGetCreatableVgpus(self.0, count, values)
        })?
        .into_iter()
        .map(VgpuTypeId)
        .collect())
    }

    pub fn vgpu_type_supported_placements(
        self,
        vgpu_type_id: VgpuTypeId,
        mode: VgpuPlacementMode,
    ) -> Result<Vec<VgpuPlacementId>> {
        self.query_vgpu_placements(
            vgpu_type_id,
            mode,
            sys::nvmlDeviceGetVgpuTypeSupportedPlacements,
        )
    }

    pub fn vgpu_type_creatable_placements(
        self,
        vgpu_type_id: VgpuTypeId,
        mode: VgpuPlacementMode,
    ) -> Result<Vec<VgpuPlacementId>> {
        self.query_vgpu_placements(
            vgpu_type_id,
            mode,
            sys::nvmlDeviceGetVgpuTypeCreatablePlacements,
        )
    }

    /// Returns the active vGPU instances on a device.
    ///
    /// This wrapper performs the NVML size query internally and returns the active vGPU instances as a [`Vec`].
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the active vGPU list changes while the wrapper is
    /// fetching it, if NVML rejects the query, if vGPU is unsupported by the
    /// device, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn active_vgpus(self) -> Result<Vec<VgpuInstance>> {
        Ok(query_u32_list(|count, values| unsafe {
            sys::nvmlDeviceGetActiveVgpus(self.0, count, values)
        })?
        .into_iter()
        .map(|instance| VgpuInstance::from_id(VgpuInstanceId(instance)))
        .collect())
    }

    /// Returns the vGPU heterogeneous mode for the device.
    ///
    /// When in heterogeneous mode, a vGPU can concurrently host timesliced vGPUs with differing framebuffer sizes.
    ///
    /// On success, returns the current vGPU heterogeneous mode as [`EnableState::Enabled`] or [`EnableState::Disabled`].
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the query, if MIG is enabled or the
    /// device does not support vGPU heterogeneous mode, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn vgpu_heterogeneous_mode(self) -> Result<EnableState> {
        let mut mode = sys::nvmlVgpuHeterogeneousMode_t {
            version: struct_version::<sys::nvmlVgpuHeterogeneousMode_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetVgpuHeterogeneousMode(
                self.0,
                &raw mut mode
            ))?;
        }
        try_from_nvml_enum("enable state", mode.mode)
    }

    /// Returns a vGPU metadata structure for this physical GPU.
    /// The structure contains information about the GPU and the currently installed NVIDIA host driver version that's controlling it, together with an opaque data section containing internal state.
    ///
    /// This wrapper allocates the metadata buffer internally and retries if NVML reports it is too small.
    ///
    /// # Errors
    ///
    /// Returns an error if the metadata buffer changes while the wrapper is
    /// fetching it, if NVML rejects the metadata request, if vGPU is unsupported
    /// by the system, or if NVML reports an unexpected failure.
    pub fn vgpu_metadata(self) -> Result<PgpuMetadata> {
        let raw = query_sized_raw(|size, buffer| unsafe {
            sys::nvmlDeviceGetVgpuMetadata(self.0, buffer.cast(), size)
        })?;

        let metadata = unsafe { &*raw.as_ptr().cast::<sys::nvmlVgpuPgpuMetadata_t>() };
        let opaque_offset = mem::offset_of!(sys::nvmlVgpuPgpuMetadata_t, opaqueData);
        let opaque_end = opaque_offset.saturating_add(metadata.opaqueDataSize as usize);
        let opaque_data = raw[opaque_offset..opaque_end].to_vec();

        Ok(PgpuMetadata::from_raw(metadata, opaque_data))
    }

    /// Returns this physical GPU's properties as an ASCII-encoded string.
    ///
    /// This wrapper allocates the metadata buffer internally and retries if NVML reports it is too small.
    ///
    /// # Errors
    ///
    /// Returns an error if the metadata buffer changes while the wrapper is
    /// fetching it, if NVML rejects the metadata request, if vGPU is unsupported
    /// by the system, or if NVML reports an unexpected failure.
    pub fn pgpu_metadata_string(self) -> Result<String> {
        let raw = query_sized_raw(|size, buffer| unsafe {
            sys::nvmlDeviceGetPgpuMetadataString(self.0, buffer.cast(), size)
        })?;
        let buffer = raw.into_iter().map(|byte| byte as i8).collect::<Vec<_>>();
        Ok(string_from_c_chars(&buffer))
    }

    /// Returns the requested vGPU capability for GPU.
    ///
    /// See [`DeviceVgpuCapability`] for the supported capabilities.
    /// Returns whether the capability is supported and any associated capability data.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the device, capability, or output, if
    /// the current state does not support this vGPU capability query, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn vgpu_capability(self, capability: DeviceVgpuCapability) -> Result<u32> {
        let mut result = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetVgpuCapabilities(
                self.0,
                capability.into(),
                &raw mut result,
            ))?;
        }
        Ok(result)
    }

    fn query_vgpu_placements(
        self,
        vgpu_type_id: VgpuTypeId,
        mode: VgpuPlacementMode,
        query: unsafe extern "C" fn(
            sys::nvmlDevice_t,
            sys::nvmlVgpuTypeId_t,
            *mut sys::nvmlVgpuPlacementList_t,
        ) -> sys::nvmlReturn_t,
    ) -> Result<Vec<VgpuPlacementId>> {
        let mut placement_list = sys::nvmlVgpuPlacementList_t {
            version: struct_version::<sys::nvmlVgpuPlacementList_t>(2),
            placementSize: size_of::<u32>() as u32,
            mode: mode as u32,
            ..Default::default()
        };

        let status = unsafe { query(self.0, vgpu_type_id.0, &raw mut placement_list) };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && placement_list.count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut placements = vec![0u32; placement_list.count as usize];
        placement_list.placementIds = placements.as_mut_ptr();
        unsafe {
            try_ffi!(query(self.0, vgpu_type_id.0, &raw mut placement_list))?;
        }
        placements.truncate(placement_list.count as usize);
        Ok(placements.into_iter().map(VgpuPlacementId).collect())
    }

    /// Returns bitmasks with the ideal CPU affinity for the device.
    /// For example, if processors 0, 1, 32, and 33 are ideal for the device and two mask words are requested, then `result[0] = 0x3` and `result[1] = 0x3`.
    /// This is equivalent to calling [`Device::cpu_affinity_within_scope`] with `NVML_AFFINITY_SCOPE_NODE`.
    ///
    /// For Kepler or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle or output buffer, if the device does not support CPU affinity
    /// reporting, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn cpu_affinity(self) -> Result<Vec<u64>> {
        device_ulong_bitmask_list(|set_size, set| unsafe {
            sys::nvmlDeviceGetCpuAffinity(self.0, set_size, set)
        })
    }

    /// Returns bitmasks with the ideal CPU affinity within a node or socket for the device.
    /// For example, if processors 0, 1, 32, and 33 are ideal for the device and two mask words are requested, then `result[0] = 0x3` and `result[1] = 0x3`.
    ///
    /// If the requested scope is not applicable to the target topology, NVML
    /// falls back to reporting CPU affinity for the device's immediate non-I/O
    /// ancestor.
    ///
    /// For Kepler or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, scope, or output buffer, if the device does not support scoped CPU
    /// affinity reporting, if NVML has not been initialized, or if NVML reports
    /// an unexpected failure.
    pub fn cpu_affinity_within_scope(self, scope: AffinityScope) -> Result<Vec<u64>> {
        device_ulong_bitmask_list(|set_size, set| unsafe {
            sys::nvmlDeviceGetCpuAffinityWithinScope(self.0, set_size, set, scope.into())
        })
    }

    /// Sets the ideal affinity for the calling thread and device using the guidelines given in [`Device::cpu_affinity`].
    /// Note, this is a change as of version 8.0.
    /// Older versions set the affinity for a calling process and all children.
    /// Currently supports up to 1024 processors.
    ///
    /// For Kepler or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, if the device does not support CPU affinity binding, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn set_cpu_affinity(self) -> Result<()> {
        unsafe { try_ffi!(sys::nvmlDeviceSetCpuAffinity(self.0)) }
    }

    /// Clear all affinity bindings for the calling thread.
    /// Note, this is a change as of version 8.0 as older versions cleared the affinity for a calling process and all children.
    ///
    /// For Kepler or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn clear_cpu_affinity(self) -> Result<()> {
        unsafe { try_ffi!(sys::nvmlDeviceClearCpuAffinity(self.0)) }
    }

    /// Returns bitmasks with the ideal memory affinity within a node or socket for this device.
    /// For example, if NUMA nodes 0 and 1 are ideal within the socket and one mask word is requested, `result[0] = 0x3`.
    ///
    /// If the requested scope is not applicable to the target topology, NVML
    /// falls back to reporting memory affinity for the device's immediate
    /// non-I/O ancestor.
    ///
    /// For Kepler or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, scope, or output buffer, if the device does not support memory
    /// affinity reporting, if NVML has not been initialized, or if NVML reports
    /// an unexpected failure.
    pub fn memory_affinity(self, scope: AffinityScope) -> Result<Vec<u64>> {
        device_ulong_bitmask_list(|set_size, set| unsafe {
            sys::nvmlDeviceGetMemoryAffinity(self.0, set_size, set, scope.into())
        })
    }

    /// Returns the addressing mode for the given GPU.
    ///
    /// [`DeviceAddressingMode::Hmm`] makes system-allocated memory (`malloc`,
    /// `mmap`) addressable from the GPU through software-based mirroring of the
    /// CPU page tables. [`DeviceAddressingMode::Ats`] makes system-allocated
    /// memory addressable from the GPU through Address Translation Services,
    /// which means there is effectively a single set of page tables used by
    /// both CPU and GPU. [`DeviceAddressingMode::None`] means neither HMM nor
    /// ATS is active.
    ///
    /// For Turing or newer fully supported devices.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the handle, or if the current platform
    /// does not support addressing-mode reporting.
    pub fn addressing_mode(self) -> Result<DeviceAddressingMode> {
        let mut mode = sys::nvmlDeviceAddressingMode_t {
            version: struct_version::<sys::nvmlDeviceAddressingMode_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetAddressingMode(self.0, &raw mut mode))?;
        }
        try_from_nvml_enum("device addressing mode", mode.value)
    }

    /// Returns the repair status for TPC/channel repair.
    ///
    /// For Ampere or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the handle or output, if the device does
    /// not support repair-status reporting, if NVML has not been initialized, or
    /// if NVML reports an unexpected failure.
    pub fn repair_status(self) -> Result<RepairStatus> {
        let mut status = sys::nvmlRepairStatus_t {
            version: struct_version::<sys::nvmlRepairStatus_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetRepairStatus(self.0, &raw mut status))?;
        }
        Ok(status.into())
    }

    /// Returns the NUMA node of the given GPU device.
    /// This only applies to platforms where the GPUs are NUMA nodes.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, or if the current
    /// platform does not support GPU NUMA-node reporting.
    pub fn numa_node_id(self) -> Result<u32> {
        let mut node = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNumaNodeId(self.0, &raw mut node))?;
        }
        Ok(node)
    }

    pub fn capabilities(self) -> Result<DeviceCapabilities> {
        let mut caps = sys::nvmlDeviceCapabilities_t {
            version: struct_version::<sys::nvmlDeviceCapabilities_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetCapabilities(self.0, &raw mut caps))?;
        }
        Ok(DeviceCapabilities::from_bits_retain(caps.capMask))
    }

    /// Returns performance monitor samples from the associated subdevice.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// query, if the device does not support dynamic P-state samples, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn dynamic_pstates_info(self) -> Result<DynamicPstatesInfo> {
        unsafe {
            let mut info = MaybeUninit::<sys::nvmlGpuDynamicPstatesInfo_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetDynamicPstatesInfo(
                self.0,
                info.as_mut_ptr()
            ))?;
            Ok(info.assume_init().into())
        }
    }

    /// Versioned wrapper that requests GPU fabric information using the latest supported NVML output layout.
    ///
    /// This wrapper sets the version field on the output structure before calling NVML.
    ///
    /// For Hopper or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device does not support GPU fabric reporting.
    pub fn gpu_fabric_info(self) -> Result<GpuFabricInfo> {
        let mut info = sys::nvmlGpuFabricInfoV_t {
            version: struct_version::<sys::nvmlGpuFabricInfoV_t>(3),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetGpuFabricInfoV(self.0, &raw mut info))?;
        }
        GpuFabricInfo::from_raw(info)
    }

    /// Returns performance profiles information.
    ///
    /// For Blackwell or newer fully supported devices.
    /// Returns the workload power profile information reported by NVML.
    /// The `perf_profiles_mask` field is a bitmask of all supported mode indices where the mode is supported if the index is 1.
    /// Each supported mode has a corresponding entry in the profile array containing the profile ID, the priority of this mode, and a conflicting mask.
    /// Lower priority values indicate higher priority, and each bit set in the conflicting mask corresponds to a different profile that cannot be used with the given profile.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML reports that the
    /// output layout is too small, if NVML rejects the query, if the device does
    /// not support workload power profiles, if NVML has not been initialized, or
    /// if NVML reports an unexpected failure.
    pub fn workload_power_profiles_info(self) -> Result<WorkloadPowerProfilesInfo> {
        let mut info = sys::nvmlWorkloadPowerProfileProfilesInfo_t {
            version: struct_version::<sys::nvmlWorkloadPowerProfileProfilesInfo_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceWorkloadPowerProfileGetProfilesInfo(
                self.0,
                &raw mut info,
            ))?;
        }
        Ok(info.into())
    }

    /// Returns current performance profiles.
    ///
    /// For Blackwell or newer fully supported devices.
    /// Returns the current workload power profile state reported by NVML.
    /// Returns the current, requested, and enforced performance profile masks.
    /// Each bit set in each bitmask indicates whether the profile is supported, currently requested, or currently engaged, respectively.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML rejects the query,
    /// if the device does not support workload power profiles, if NVML has not
    /// been initialized, or if NVML reports an unexpected failure.
    pub fn workload_power_current_profiles(self) -> Result<WorkloadPowerCurrentProfiles> {
        let mut profiles = sys::nvmlWorkloadPowerProfileCurrentProfiles_t {
            version: struct_version::<sys::nvmlWorkloadPowerProfileCurrentProfiles_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceWorkloadPowerProfileGetCurrentProfiles(
                self.0,
                &raw mut profiles,
            ))?;
        }
        Ok(profiles.into())
    }

    /// Returns the current and pending DRAM Encryption modes for the device.
    ///
    /// For Blackwell or newer fully supported devices.
    /// Only applicable to devices that support DRAM Encryption.
    /// Requires [`InforomObject::Den`] version 1.0 or higher.
    ///
    /// Changing DRAM Encryption modes requires a reboot.
    /// The "pending" DRAM Encryption mode refers to the target mode following the next reboot.
    ///
    /// See [`EnableState`] for details on allowed modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML rejects the handle
    /// or outputs, if the device does not support DRAM encryption, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn dram_encryption_mode(self) -> Result<CurrentPending<DramEncryptionInfo>> {
        let mut current = sys::nvmlDramEncryptionInfo_t {
            version: struct_version::<sys::nvmlDramEncryptionInfo_t>(1),
            ..Default::default()
        };
        let mut pending = sys::nvmlDramEncryptionInfo_t {
            version: struct_version::<sys::nvmlDramEncryptionInfo_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetDramEncryptionMode(
                self.0,
                &raw mut current,
                &raw mut pending,
            ))?;
        }
        Ok(CurrentPending {
            current: current.into(),
            pending: pending.into(),
        })
    }

    /// Sets the DRAM encryption mode for the device.
    ///
    /// For Kepler or newer fully supported devices.
    /// Only applicable to devices that support DRAM Encryption.
    /// Requires [`InforomObject::Den`] version 1.0 or higher.
    /// Requires root/admin permissions.
    ///
    /// The DRAM Encryption mode determines whether the GPU enables its DRAM Encryption support.
    ///
    /// This operation takes effect after the next reboot.
    ///
    /// See [`EnableState`] for details on available modes.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML rejects the handle
    /// or requested mode, if the device does not support DRAM encryption, if the
    /// current process lacks permission, if NVML has not been initialized, or if
    /// NVML reports an unexpected failure.
    pub fn set_dram_encryption_mode(self, dram_encryption: DramEncryptionInfo) -> Result<()> {
        let dram_encryption = sys::nvmlDramEncryptionInfo_t {
            version: struct_version::<sys::nvmlDramEncryptionInfo_t>(1),
            encryptionState: dram_encryption.encryption_state.into(),
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceSetDramEncryptionMode(
                self.0,
                &raw const dram_encryption,
            ))
        }
    }

    /// Returns Confidential Computing protected and unprotected memory sizes.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux, Windows TCC.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if the device does not
    /// support Confidential Computing memory-size reporting, or if NVML has not
    /// been initialized.
    pub fn conf_compute_mem_size_info(self) -> Result<ConfComputeMemSizeInfo> {
        let mut info = sys::nvmlConfComputeMemSizeInfo_t::default();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetConfComputeMemSizeInfo(
                self.0,
                &raw mut info
            ))?;
        }
        Ok(info.into())
    }

    /// Returns Confidential Computing protected memory usage.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux, Windows TCC.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if the device does not
    /// support Confidential Computing protected-memory reporting, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn conf_compute_protected_memory_usage(self) -> Result<MemoryInfo> {
        let mut memory = sys::nvmlMemory_v2_t {
            version: struct_version::<sys::nvmlMemory_v2_t>(2),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetConfComputeProtectedMemoryUsage(
                self.0,
                (&raw mut memory).cast(),
            ))?;
        }
        Ok(memory.into())
    }

    /// Returns Confidential Computing GPU certificate details.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux, Windows TCC.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if the device does not
    /// support Confidential Computing certificate reporting, if NVML has not
    /// been initialized, or if NVML reports an unexpected failure.
    pub fn conf_compute_gpu_certificate(self) -> Result<ConfComputeGpuCertificate> {
        unsafe {
            let mut certificate = MaybeUninit::<sys::nvmlConfComputeGpuCertificate_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetConfComputeGpuCertificate(
                self.0,
                certificate.as_mut_ptr(),
            ))?;
            Ok(certificate.assume_init().into())
        }
    }

    /// Returns Confidential Computing GPU attestation report.
    ///
    /// For Ampere or newer fully supported devices.
    /// Supported on Linux, Windows TCC.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the query, if the device does not
    /// support Confidential Computing attestation reports, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn conf_compute_gpu_attestation_report(self) -> Result<ConfComputeGpuAttestationReport> {
        unsafe {
            let mut report = MaybeUninit::<sys::nvmlConfComputeGpuAttestationReport_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetConfComputeGpuAttestationReport(
                self.0,
                report.as_mut_ptr(),
            ))?;
            Ok(report.assume_init().into())
        }
    }

    /// Returns the state of the device's NVLink for the specified link.
    ///
    /// For Pascal or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, link index, or output, if
    /// the device does not support NVLink state reporting, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn nvlink_state(self, link: u32) -> Result<EnableState> {
        let mut state = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvLinkState(self.0, link, &raw mut state))?;
        }
        Ok(state.into())
    }

    /// Returns the version of the device's NVLink for the specified link.
    ///
    /// For Pascal or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, link index, or output, if
    /// the device does not support NVLink version reporting, if NVML has not
    /// been initialized, or if NVML reports an unexpected failure.
    pub fn nvlink_version(self, link: u32) -> Result<NvLinkVersion> {
        let mut version = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvLinkVersion(
                self.0,
                link,
                &raw mut version
            ))?;
        }
        try_from_nvml_enum("nvlink version", version)
    }

    /// Returns the requested capability from the device's NVLink for the specified link.
    ///
    /// See [`NvLinkCapability`] for the supported capabilities.
    ///
    /// For Pascal or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, link index, capability, or
    /// output, if the device does not support NVLink capability reporting, if
    /// NVML has not been initialized, or if NVML reports an unexpected failure.
    pub fn nvlink_capability(self, link: u32, capability: NvLinkCapability) -> Result<bool> {
        let mut result = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvLinkCapability(
                self.0,
                link,
                capability.into(),
                &raw mut result,
            ))?;
        }
        Ok(result != 0)
    }

    /// Returns the PCI information for the remote node on an NVLink link.
    ///
    /// `pci_subsystem_id` is not filled by this query and is indeterminate.
    ///
    /// For Pascal or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, link index, or output, if
    /// the device does not support remote PCI reporting for NVLink, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn nvlink_remote_pci_info(self, link: u32) -> Result<PciInfo> {
        unsafe {
            let mut pci = MaybeUninit::<sys::nvmlPciInfo_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetNvLinkRemotePciInfo_v2(
                self.0,
                link,
                pci.as_mut_ptr(),
            ))?;
            Ok(pci.assume_init().into())
        }
    }

    /// Returns the NVLink device type of the remote device connected over the given link.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, link index, or output, if NVLink is unsupported, if NVML has not
    /// been initialized, or if NVML reports an unexpected failure.
    pub fn nvlink_remote_device_type(self, link: u32) -> Result<NvLinkRemoteDeviceType> {
        let mut device_type = sys::nvmlIntNvLinkDeviceType_t::NVML_NVLINK_DEVICE_TYPE_UNKNOWN;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvLinkRemoteDeviceType(
                self.0,
                link,
                &raw mut device_type,
            ))?;
        }
        Ok(device_type.into())
    }

    /// Returns the specified error counter value.
    ///
    /// See [`NvLinkErrorCounter`] for available counters.
    ///
    /// For Pascal or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, link index, counter, or
    /// output, if the device does not support NVLink error counters, if NVML has
    /// not been initialized, or if NVML reports an unexpected failure.
    pub fn nvlink_error_counter(self, link: u32, counter: NvLinkErrorCounter) -> Result<u64> {
        let mut value = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvLinkErrorCounter(
                self.0,
                link,
                counter.into(),
                &raw mut value,
            ))?;
        }
        Ok(value)
    }

    /// Returns the supported NVLink reduced bandwidth modes of the device.
    ///
    /// For Blackwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the handle or output, or if the device
    /// does not support NVLink bandwidth modes.
    pub fn nvlink_supported_bw_modes(self) -> Result<NvLinkSupportedBwModes> {
        let mut modes = sys::nvmlNvlinkSupportedBwModes_t {
            version: struct_version::<sys::nvmlNvlinkSupportedBwModes_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvlinkSupportedBwModes(
                self.0,
                &raw mut modes
            ))?;
        }
        Ok(modes.into())
    }

    /// Returns the NVLink reduced bandwidth mode for the device.
    ///
    /// For Blackwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if NVML rejects the handle or output, or if the device
    /// does not support NVLink bandwidth mode reporting.
    pub fn nvlink_bw_mode(self) -> Result<NvLinkBwMode> {
        let mut mode = sys::nvmlNvlinkGetBwMode_t {
            version: struct_version::<sys::nvmlNvlinkGetBwMode_t>(1),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvlinkBwMode(self.0, &raw mut mode))?;
        }
        Ok(mode.into())
    }

    /// Query NVLINK information associated with this device.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if NVML rejects the handle
    /// or output, if the device does not support NVLink info reporting, if NVML
    /// has not been initialized, or if NVML reports an unexpected failure.
    pub fn nvlink_info(self) -> Result<NvLinkInfo> {
        let mut info = sys::nvmlNvLinkInfo_t {
            version: struct_version::<sys::nvmlNvLinkInfo_t>(2),
            ..Default::default()
        };
        unsafe {
            try_ffi!(sys::nvmlDeviceGetNvLinkInfo(self.0, &raw mut info))?;
        }
        Ok(info.into())
    }

    /// Returns the active frame buffer capture sessions statistics for the given device.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the stats
    /// output, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn fbc_stats(self) -> Result<FbcStats> {
        unsafe {
            let mut stats = MaybeUninit::<sys::nvmlFBCStats_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetFBCStats(self.0, stats.as_mut_ptr()))?;
            Ok(stats.assume_init().into())
        }
    }

    /// Returns information about active frame buffer capture sessions on a target device.
    ///
    /// This wrapper queries the required session count first, then returns the active FBC sessions as a [`Vec`].
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// `h_resolution`, `v_resolution`, `average_fps`, and `average_latency` may be zero if no new frames were captured since the session started.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the FBC session list
    /// changes while the wrapper is fetching it, if NVML reports an invalid
    /// session count, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn fbc_sessions(self) -> Result<Vec<FbcSessionInfo>> {
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetFBCSessions(self.as_raw(), &raw mut count, ptr::null_mut() as _)
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut sessions = vec![sys::nvmlFBCSessionInfo_t::default(); count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetFBCSessions(
                self.as_raw(),
                &raw mut count,
                sessions.as_mut_ptr(),
            ))?;
        }
        sessions.truncate(count as usize);
        Ok(sessions.into_iter().map(Into::into).collect())
    }

    /// Returns the common ancestor for two devices.
    ///
    /// For all products.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects either handle or the output, if topology
    /// discovery is not supported on this device or OS, or if NVML fails during
    /// topology discovery.
    pub fn topology_common_ancestor(self, other: Self) -> Result<TopologyLevel> {
        let mut level = sys::nvmlGpuTopologyLevel_t::NVML_TOPOLOGY_SYSTEM;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetTopologyCommonAncestor(
                self.0,
                other.0,
                &raw mut level,
            ))?;
        }
        Ok(level.into())
    }

    /// Returns the set of GPUs nearest to this device at a specific interconnectivity level.
    /// Supported on Linux only.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, topology level, count, or
    /// output buffer, if topology discovery is not supported on this device or
    /// OS, or if NVML fails during topology discovery.
    pub fn topology_nearest_gpus(self, level: TopologyLevel) -> Result<Vec<Device>> {
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetTopologyNearestGpus(
                self.0,
                level.into(),
                &raw mut count,
                ptr::null_mut(),
            )
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut devices = vec![ptr::null_mut(); count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetTopologyNearestGpus(
                self.0,
                level.into(),
                &raw mut count,
                devices.as_mut_ptr(),
            ))?;
        }
        devices.truncate(count as usize);
        Ok(devices.into_iter().map(Self).collect())
    }

    /// Returns the status for a P2P capability between this device and `other`.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects either device handle, the capability, or
    /// output, or if NVML reports an unexpected failure.
    pub fn p2p_status(self, other: Self, capability: P2pCapabilityIndex) -> Result<P2pStatus> {
        let mut status = sys::nvmlGpuP2PStatus_t::NVML_P2P_STATUS_UNKNOWN;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetP2PStatus(
                self.0,
                other.0,
                capability.into(),
                &raw mut status,
            ))?;
        }
        Ok(status.into())
    }

    /// Check if the GPU devices are on the same physical board.
    ///
    /// For all fully supported products.
    ///
    /// # Errors
    ///
    /// Returns an error if either device is inaccessible, if NVML rejects either
    /// handle or output, if the check is unsupported, if NVML has not been
    /// initialized, or if NVML reports an unexpected failure.
    pub fn on_same_board(self, other: Self) -> Result<bool> {
        let mut on_same_board = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceOnSameBoard(
                self.0,
                other.0,
                &raw mut on_same_board,
            ))?;
        }
        Ok(on_same_board != 0)
    }

    pub fn compute_running_processes(self) -> Result<Vec<ProcessInfo>> {
        query_process_info_list(self, sys::nvmlDeviceGetComputeRunningProcesses)
    }

    /// Returns information about running processes on a device for the input context.
    ///
    /// For Hopper or newer fully supported devices.
    ///
    /// Returns information only about running processes, such as CUDA applications with active contexts.
    ///
    /// This wrapper performs the NVML size query internally and returns the matching process details as a [`Vec`].
    ///
    /// The `used_gpu_memory` field is all of the memory used by the application.
    /// The `used_gpu_cc_protected_memory` field is all of the protected memory used by the application.
    ///
    /// Keep in mind that information returned by this call is dynamic and the number of elements might change in time.
    /// The wrapper retries internally if NVML reports that more space is needed because new processes were spawned.
    ///
    /// In MIG mode, a physical device handle reports aggregate information only if the caller has appropriate privileges.
    /// Per-instance information can be queried by using specific MIG device handles.
    /// Querying per-instance information using MIG device handles is not supported if the device is in vGPU Host virtualization mode.
    /// Protected memory usage is currently not available in MIG mode or on Windows.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if the process list
    /// changes while the wrapper is fetching it, if NVML rejects the device,
    /// process mode, or output, if the query is unsupported, if the current
    /// process lacks permission, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn running_process_details(self, mode: ProcessMode) -> Result<Vec<ProcessDetail>> {
        let mut list = sys::nvmlProcessDetailList_t {
            version: struct_version::<sys::nvmlProcessDetailList_t>(1),
            mode: mode.into(),
            ..Default::default()
        };
        let status = unsafe { sys::nvmlDeviceGetRunningProcessDetailList(self.0, &raw mut list) };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && list.numProcArrayEntries == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut entries =
            vec![sys::nvmlProcessDetail_v1_t::default(); list.numProcArrayEntries as usize];
        list.procArray = entries.as_mut_ptr();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetRunningProcessDetailList(
                self.0,
                &raw mut list
            ))?;
        }
        entries.truncate(list.numProcArrayEntries as usize);
        Ok(entries.into_iter().map(Into::into).collect())
    }

    pub fn graphics_running_processes(self) -> Result<Vec<ProcessInfo>> {
        query_process_info_list(self, sys::nvmlDeviceGetGraphicsRunningProcesses)
    }

    pub fn mps_compute_running_processes(self) -> Result<Vec<ProcessInfo>> {
        query_process_info_list(self, sys::nvmlDeviceGetMPSComputeRunningProcesses)
    }

    /// Returns the current utilization and process ID.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// Reads recent utilization of GPU SM (3D/Compute), framebuffer, video encoder, and video decoder for processes running.
    /// This wrapper returns utilization values as a [`Vec`] of process samples.
    /// One utilization sample structure is returned per running process that had
    /// non-zero utilization during the last sample period.
    /// It includes the CPU timestamp at which the samples were recorded.
    /// Individual utilization values are returned as unsigned integer values.
    /// If no valid sample entries are found since `last_seen_timestamp`, [`Status::NotFound`] is returned.
    ///
    /// This wrapper performs the NVML size query internally and retries with the required capacity.
    ///
    /// On success, NVML reports the number of process utilization sample structures that were actually written.
    /// This may differ from a previously read value as instances are created or destroyed.
    ///
    /// `last_seen_timestamp` represents the CPU timestamp in microseconds at which utilization samples were last read.
    /// Use `0` to read utilization based on all samples maintained by the driver's internal sample buffer.
    /// Use a timestamp returned by a previous query to read utilization since that query.
    ///
    /// On MIG-enabled GPUs, querying process utilization is not currently supported.
    ///
    /// # Errors
    ///
    /// Returns an error if the device is inaccessible, if NVML rejects the
    /// handle, utilization buffer, or sampling timestamp, if the device does not
    /// support process utilization sampling, if NVML has not been initialized,
    /// or if NVML reports an unexpected failure. Missing sample entries are
    /// returned as an empty list.
    pub fn process_utilization(
        self,
        last_seen_timestamp: u64,
    ) -> Result<Vec<ProcessUtilizationSample>> {
        let mut count = 0;
        let status = unsafe {
            sys::nvmlDeviceGetProcessUtilization(
                self.0,
                ptr::null_mut(),
                &raw mut count,
                last_seen_timestamp,
            )
        };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status == sys::nvmlReturn_t::NVML_ERROR_NOT_FOUND {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut samples = vec![sys::nvmlProcessUtilizationSample_t::default(); count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetProcessUtilization(
                self.0,
                samples.as_mut_ptr(),
                &raw mut count,
                last_seen_timestamp,
            ))?;
        }
        samples.truncate(count as usize);
        Ok(samples.into_iter().map(Into::into).collect())
    }

    /// Returns the recent utilization and process ID for all running processes.
    ///
    /// For Maxwell or newer fully supported devices.
    ///
    /// Reads recent utilization of GPU SM (3D/Compute), framebuffer, video encoder, and video decoder, jpeg decoder, OFA (Optical Flow Accelerator) for all running processes.
    /// This wrapper returns utilization values as a [`Vec`] of process utilization records.
    /// One utilization sample structure is returned per running process that had
    /// non-zero utilization during the last sample period.
    /// It includes the CPU timestamp at which the samples were recorded.
    /// Individual utilization values are returned as unsigned integer values.
    ///
    /// This wrapper performs the NVML size query internally and retries with the required capacity.
    ///
    /// On success, NVML reports the number of process utilization info structures that were actually written.
    /// This may differ from a previously read value as instances are created or destroyed.
    ///
    /// `last_seen_timestamp` represents the CPU timestamp in microseconds at which utilization samples were last read.
    /// Use `0` to read utilization based on all samples maintained by the driver's internal sample buffer.
    /// Use a timestamp returned by a previous query to read utilization since that query.
    ///
    /// On MIG-enabled GPUs, querying process utilization is not currently supported.
    ///
    /// # Errors
    ///
    /// Returns an error if the installed NVML version does not support the
    /// request layout, if the device is inaccessible, if the process list
    /// changes while the wrapper is fetching it, if NVML rejects the query, if
    /// the device does not support process utilization sampling, if NVML has not
    /// been initialized, or if NVML reports an unexpected failure. Missing
    /// sample entries are returned as an empty list.
    pub fn processes_utilization(
        self,
        last_seen_timestamp: u64,
    ) -> Result<Vec<ProcessUtilizationInfo>> {
        let mut info = sys::nvmlProcessesUtilizationInfo_t {
            version: struct_version::<sys::nvmlProcessesUtilizationInfo_t>(1),
            lastSeenTimeStamp: last_seen_timestamp,
            processSamplesCount: 0,
            ..Default::default()
        };
        let status = unsafe { sys::nvmlDeviceGetProcessesUtilizationInfo(self.0, &raw mut info) };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && info.processSamplesCount == 0 {
            return Ok(Vec::new());
        }
        if status == sys::nvmlReturn_t::NVML_ERROR_NOT_FOUND {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut entries = vec![
            sys::nvmlProcessUtilizationInfo_v1_t::default();
            info.processSamplesCount as usize
        ];
        info.procUtilArray = entries.as_mut_ptr();
        unsafe {
            try_ffi!(sys::nvmlDeviceGetProcessesUtilizationInfo(
                self.0,
                &raw mut info
            ))?;
        }
        entries.truncate(info.processSamplesCount as usize);
        Ok(entries.into_iter().map(Into::into).collect())
    }

    /// Queries the state of per process accounting mode.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// See [`Device::accounting_stats`] for the reported accounting metrics.
    /// See [`sys::nvmlDeviceSetAccountingMode`].
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if the device does
    /// not support accounting mode, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn accounting_mode(self) -> Result<EnableState> {
        let mut mode = sys::nvmlEnableState_t::NVML_FEATURE_DISABLED;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetAccountingMode(self.0, &raw mut mode))?;
        }
        Ok(mode.into())
    }

    /// Queries process's accounting stats.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// Accounting stats capture GPU utilization and other statistics across the lifetime of a process.
    /// Accounting stats can be queried during the lifetime of the process and after its termination.
    /// The reported running time remains 0 while the process is still running and is updated to the actual duration after termination.
    /// Accounting stats are kept in a circular buffer, newly created processes overwrite information about old processes.
    ///
    /// The returned value includes the per-process accounting metrics exposed by NVML.
    /// Use [`Device::accounting_pids`] to list processes with available stats.
    ///
    /// * Accounting mode must be enabled.
    ///   See [`Device::accounting_mode`].
    /// * Only compute and graphics application stats can be queried.
    ///   Monitoring application stats cannot be queried because they do not contribute to GPU utilization.
    /// * With a PID collision, only stats for the latest process to terminate are reported.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle, process ID, or output, if no
    /// accounting stats exist for the process, if accounting is unsupported or
    /// disabled, if NVML has not been initialized, or if NVML reports an
    /// unexpected failure.
    pub fn accounting_stats(self, pid: crate::types::Pid) -> Result<AccountingStats> {
        unsafe {
            let mut stats = MaybeUninit::<sys::nvmlAccountingStats_t>::uninit();
            try_ffi!(sys::nvmlDeviceGetAccountingStats(
                self.0,
                pid.0,
                stats.as_mut_ptr()
            ))?;
            Ok(stats.assume_init().into())
        }
    }

    /// Returns processes that have accounting stats.
    /// Returned processes can be running or terminated.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// This wrapper queries the process count internally.
    /// It returns an empty list when no accounting processes are available.
    ///
    /// See [`Device::accounting_stats`] for the per-process metrics.
    ///
    /// With a PID collision, some processes may not be accessible before the circular buffer is full.
    ///
    /// # Errors
    ///
    /// Returns an error if the accounting PID list changes while the wrapper is
    /// fetching it, if NVML rejects the handle or count output, if accounting is
    /// unsupported or disabled, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn accounting_pids(self) -> Result<Vec<crate::types::Pid>> {
        let mut count = 0;
        let status =
            unsafe { sys::nvmlDeviceGetAccountingPids(self.0, &raw mut count, ptr::null_mut()) };
        if status == sys::nvmlReturn_t::NVML_SUCCESS && count == 0 {
            return Ok(Vec::new());
        }
        if status != sys::nvmlReturn_t::NVML_ERROR_INSUFFICIENT_SIZE {
            return Err(status.into());
        }

        let mut pids = vec![0u32; count as usize];
        unsafe {
            try_ffi!(sys::nvmlDeviceGetAccountingPids(
                self.0,
                &raw mut count,
                pids.as_mut_ptr(),
            ))?;
        }
        pids.truncate(count as usize);
        Ok(pids.into_iter().map(crate::types::Pid).collect())
    }

    /// Returns the number of processes that the circular buffer with accounting pids can hold.
    ///
    /// For Kepler or newer fully supported devices.
    ///
    /// This is the maximum number of processes with stored accounting information before
    /// information about the oldest processes is overwritten by newer process information.
    ///
    /// # Errors
    ///
    /// Returns an error if NVML rejects the handle or output, if accounting is
    /// unsupported or disabled, if NVML has not been initialized, or if NVML
    /// reports an unexpected failure.
    pub fn accounting_buffer_size(self) -> Result<u32> {
        let mut size = 0;
        unsafe {
            try_ffi!(sys::nvmlDeviceGetAccountingBufferSize(
                self.0,
                &raw mut size
            ))?;
        }
        Ok(size)
    }
}

fn field_id_for_perf_policy(perf_policy: PerfPolicyType) -> FieldId {
    match perf_policy {
        PerfPolicyType::Power => FieldId::PERF_POLICY_POWER,
        PerfPolicyType::Thermal => FieldId::PERF_POLICY_THERMAL,
        PerfPolicyType::SyncBoost => FieldId::PERF_POLICY_SYNC_BOOST,
        PerfPolicyType::BoardLimit => FieldId::PERF_POLICY_BOARD_LIMIT,
        PerfPolicyType::LowUtilization => FieldId::PERF_POLICY_LOW_UTILIZATION,
        PerfPolicyType::Reliability => FieldId::PERF_POLICY_RELIABILITY,
        PerfPolicyType::TotalAppClocks => FieldId::PERF_POLICY_TOTAL_APP_CLOCKS,
        PerfPolicyType::TotalBaseClocks => FieldId::PERF_POLICY_TOTAL_BASE_CLOCKS,
    }
}

fn field_sample_as_u64(sample: FieldSample) -> Result<u64> {
    Ok(match sample.result? {
        FieldValue::UnsignedInt(value) => u64::from(value),
        FieldValue::UnsignedLong(value) | FieldValue::UnsignedLongLong(value) => value,
        FieldValue::SignedInt(value) => u64::try_from(value).map_err(|_| Error::NegativeValue {
            name: "field sample".into(),
            value: i64::from(value),
        })?,
        FieldValue::SignedLongLong(value) => {
            u64::try_from(value).map_err(|_| Error::NegativeValue {
                name: "field sample".into(),
                value,
            })?
        }
        FieldValue::UnsignedShort(value) => u64::from(value),
        FieldValue::Double(_) => {
            return Err(Error::UnexpectedFieldValueType {
                name: "numeric field sample".into(),
                value: "double".into(),
            });
        }
    })
}