nvml-wrapper 0.13.0

A safe and ergonomic Rust wrapper for the NVIDIA Management Library
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
use std::{
    ffi::CStr,
    os::raw::{c_char, c_uint},
};

use ffi::bindings::{
    nvmlEnableState_enum_NVML_FEATURE_ENABLED, nvmlEncoderSessionInfo_t, nvmlFBCSessionInfo_t,
    nvmlFBCStats_t, nvmlVgpuCapability_t, nvmlVgpuInstance_t, nvmlVgpuLicenseInfo_st,
    nvmlVgpuMetadata_t, nvmlVgpuPlacementId_t, nvmlVgpuRuntimeState_t, nvmlVgpuTypeBar1Info_v1_t,
    nvmlVgpuTypeId_t, nvmlVgpuVmIdType_NVML_VGPU_VM_ID_DOMAIN_ID,
    nvmlVgpuVmIdType_NVML_VGPU_VM_ID_UUID, NVML_DEVICE_NAME_BUFFER_SIZE,
    NVML_DEVICE_UUID_BUFFER_SIZE, NVML_GRID_LICENSE_BUFFER_SIZE,
    NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE,
};
use static_assertions::assert_impl_all;

use crate::{
    enum_wrappers::vgpu::VmId,
    error::{nvml_sym, nvml_try, nvml_try_count, NvmlError},
    struct_wrappers::{
        device::{EncoderSessionInfo, FbcSessionInfo, FbcStats},
        vgpu::{Bar1Info, VgpuLicenseInfo, VgpuMetadata, VgpuPlacementId, VgpuRuntimeState},
    },
    structs::device::EncoderStats,
    Device,
};

#[derive(Debug)]
pub struct VgpuType<'dev> {
    id: nvmlVgpuTypeId_t,
    device: &'dev Device<'dev>,
}

assert_impl_all!(VgpuType: Send, Sync);

impl<'dev> VgpuType<'dev> {
    /// Create a new vGPU type wrapper.
    ///
    /// You probably don't need to use this yourself, but rather through
    /// [`Device::vgpu_supported_types`] and [`Device::vgpu_creatable_types`].
    pub fn new(device: &'dev Device, id: nvmlVgpuTypeId_t) -> Self {
        Self { id, device }
    }

    /// Access the `Device` this struct belongs to.
    ///
    pub fn device(&self) -> &'dev Device<'_> {
        self.device
    }

    /// Get the underlying vGPU type id.
    pub fn id(&self) -> nvmlVgpuTypeId_t {
        self.id
    }

    /// Retrieve the class of the vGPU type.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetClass")]
    pub fn class_name(&self) -> Result<String, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetClass.as_ref())?;

        unsafe {
            let mut size = NVML_DEVICE_NAME_BUFFER_SIZE;
            let mut buffer = vec![0; size as usize];

            nvml_try(sym(self.id, buffer.as_mut_ptr(), &mut size))?;

            let version_raw = CStr::from_ptr(buffer.as_ptr());
            Ok(version_raw.to_str()?.into())
        }
    }

    /// Retrieve license requirements for a vGPU type.
    ///
    /// The license type and version required to run the specified vGPU type is returned as an
    /// alphanumeric string, in the form "\<license name\>,\<version\>", for example
    /// "GRID-Virtual-PC,2.0". If a vGPU is runnable with* more than one type of license, the
    /// licenses are delimited by a semicolon, for example
    /// "GRID-Virtual-PC,2.0;GRID-Virtual-WS,2.0;GRID-Virtual-WS-Ext,2.0".
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InsufficientSize`, if the passed-in `size` is 0 (must be > 0)
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetLicense")]
    pub fn license(&self) -> Result<String, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetLicense.as_ref())?;

        unsafe {
            let mut buffer = vec![0; NVML_GRID_LICENSE_BUFFER_SIZE as usize];

            nvml_try(sym(self.id, buffer.as_mut_ptr(), buffer.len() as u32))?;

            let version_raw = CStr::from_ptr(buffer.as_ptr());
            Ok(version_raw.to_str()?.into())
        }
    }

    /// Retrieve the name of the vGPU type.
    ///
    /// The name is an alphanumeric string that denotes a particular vGPU, e.g. GRID M60-2Q.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetName")]
    pub fn name(&self) -> Result<String, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetName.as_ref())?;

        unsafe {
            let mut size = NVML_DEVICE_NAME_BUFFER_SIZE;
            let mut buffer = vec![0; size as usize];

            nvml_try(sym(self.id, buffer.as_mut_ptr(), &mut size))?;

            let version_raw = CStr::from_ptr(buffer.as_ptr());
            Ok(version_raw.to_str()?.into())
        }
    }

    /// Retrieve the requested capability for a given vGPU type. Refer to the
    /// `nvmlVgpuCapability_t` structure for the specific capabilities that can be
    /// queried.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetCapabilities")]
    pub fn capabilities(&self, capability: nvmlVgpuCapability_t) -> Result<bool, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetCapabilities.as_ref())?;

        let mut result: c_uint = 0;
        unsafe {
            nvml_try(sym(self.id, capability, &mut result))?;
        }
        Ok(result != 0)
    }

    /// Retrieve the device ID of the vGPU type.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetDeviceID")]
    pub fn device_id(&self) -> Result<(u64, u64), NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetDeviceID.as_ref())?;

        let (mut device_id, mut subsystem_id) = (0, 0);
        unsafe {
            nvml_try(sym(self.id, &mut device_id, &mut subsystem_id))?;
        }
        Ok((device_id, subsystem_id))
    }

    /// Retrieve the static frame rate limit value of the vGPU type.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotSupported`, if frame rate limiter is turned off for the vGPU type
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetFrameRateLimit")]
    pub fn frame_rate_limit(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuTypeGetFrameRateLimit
                .as_ref(),
        )?;

        let mut limit = 0;
        unsafe {
            nvml_try(sym(self.id, &mut limit))?;
        }
        Ok(limit)
    }

    /// Retrieve the vGPU framebuffer size in bytes.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetFramebufferSize")]
    pub fn framebuffer_size(&self) -> Result<u64, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuTypeGetFramebufferSize
                .as_ref(),
        )?;

        let mut size = 0;
        unsafe {
            nvml_try(sym(self.id, &mut size))?;
        }
        Ok(size)
    }

    /// Retrieve the GPU Instance Profile ID for the vGPU type. The API will return a valid GPU
    /// Instance Profile ID for the MIG capable vGPU types, else
    /// [`crate::ffi::bindings::INVALID_GPU_INSTANCE_PROFILE_ID`] is returned.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetGpuInstanceProfileId")]
    pub fn instance_profile_id(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuTypeGetGpuInstanceProfileId
                .as_ref(),
        )?;

        let mut profile_id = 0;
        unsafe {
            nvml_try(sym(self.id, &mut profile_id))?;
        }
        Ok(profile_id)
    }

    /// Retrieve the maximum number of vGPU instances creatable on a device for the vGPU type.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetMaxInstances")]
    pub fn max_instances(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetMaxInstances.as_ref())?;

        let mut max = 0;
        unsafe {
            nvml_try(sym(self.device.handle(), self.id, &mut max))?;
        }
        Ok(max)
    }

    /// Retrieve the maximum number of vGPU instances supported per VM for the vGPU type.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetMaxInstancesPerVm")]
    pub fn max_instances_per_vm(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuTypeGetMaxInstancesPerVm
                .as_ref(),
        )?;

        let mut max = 0;
        unsafe {
            nvml_try(sym(self.id, &mut max))?;
        }
        Ok(max)
    }

    /// Retrieve count of vGPU's supported display heads.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetNumDisplayHeads")]
    pub fn num_display_heads(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuTypeGetNumDisplayHeads
                .as_ref(),
        )?;

        let mut heads = 0;
        unsafe {
            nvml_try(sym(self.id, &mut heads))?;
        }
        Ok(heads)
    }

    /// Retrieve vGPU display head's maximum supported resolution.
    ///
    /// The `display_head` argument specifies the 0-based display index, the
    /// maximum being what [`VgpuType::num_display_heads`] returns.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg`, if this `Device` is invalid
    /// * `Unknown`, on any unexpected error
    ///
    /// # Device Support
    ///
    /// Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetResolution")]
    pub fn resolution(&self, display_head: u32) -> Result<(u32, u32), NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetResolution.as_ref())?;

        let (mut x, mut y) = (0, 0);
        unsafe {
            nvml_try(sym(self.id, display_head, &mut x, &mut y))?;
        }
        Ok((x, y))
    }

    /// Retrieve the BAR1 info for given vGPU type.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuTypeGetBAR1Info")]
    pub fn bar1_info(&self) -> Result<Bar1Info, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetBAR1Info.as_ref())?;
        let mut info: nvmlVgpuTypeBar1Info_v1_t;
        unsafe {
            info = std::mem::zeroed();
            nvml_try(sym(self.id, &mut info))?;
        }
        Ok(info.into())
    }

    /// Retrieve the static framebuffer reservation of the vGPU type in bytes
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    ///
    #[doc(alias = "nvmlVgpuTypeGetFbReservation")]
    pub fn fb_reservation(&self) -> Result<u64, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetFbReservation.as_ref())?;
        let mut res = 0;
        unsafe {
            nvml_try(sym(self.id, &mut res))?;
        }
        Ok(res)
    }

    /// Retrieve the static GSP heap size of the vGPU type in bytes
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    #[doc(alias = "nvmlVgpuTypeGetGspHeapSize")]
    pub fn gsp_heap_size(&self) -> Result<u64, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuTypeGetGspHeapSize.as_ref())?;
        let mut res = 0;
        unsafe {
            nvml_try(sym(self.id, &mut res))?;
        }
        Ok(res)
    }
}

pub struct VgpuInstance<'dev> {
    pub(crate) instance: nvmlVgpuInstance_t,
    device: &'dev Device<'dev>,
}

assert_impl_all!(VgpuInstance: Send, Sync);

impl<'dev> VgpuInstance<'dev> {
    /// Create a new vGPU instance wrapper from a raw vGPU instance ID.
    ///
    /// You probably don't need to use this yourself, but rather through
    /// `Device::active_vgpus` (Linux only).
    pub fn new(instance: nvmlVgpuInstance_t, device: &'dev Device<'dev>) -> Self {
        Self { instance, device }
    }

    /// Retrieve the VM ID associated with a vGPU instance.
    ///
    /// The VM ID is returned as a string, not exceeding 80 characters in length (including the NUL
    /// terminator). See nvmlConstants::NVML_DEVICE_UUID_BUFFER_SIZE.
    ///
    /// The format of the VM ID varies by platform, and is indicated by the type identifier returned
    /// in vmIdType.
    ///
    /// # Errors
    ///
    /// * `Uninitialized` if the library has not been successfully initialized
    /// * `NotFound` if self does not match a valid active vGPU instance on the system
    /// * `Unknown` on any unexpected error
    ///
    /// # Platform Support
    ///
    /// For Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetVmID")]
    pub fn vm_id(&self) -> Result<VmId, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetVmID.as_ref())?;
        let mut s = [0; NVML_DEVICE_UUID_BUFFER_SIZE as usize];
        let mut id_type = 0;
        let id = unsafe {
            nvml_try(sym(
                self.instance,
                s.as_mut_ptr(),
                NVML_DEVICE_UUID_BUFFER_SIZE,
                &mut id_type,
            ))?;
            CStr::from_ptr(s.as_ptr())
        };

        let id = id.to_str()?.to_string();
        Ok(match id_type {
            nvmlVgpuVmIdType_NVML_VGPU_VM_ID_DOMAIN_ID => VmId::Domain(id),
            nvmlVgpuVmIdType_NVML_VGPU_VM_ID_UUID => VmId::Uuid(id),
            _ => return Err(NvmlError::Unknown),
        })
    }

    /// Retrieve the framebuffer usage in bytes.
    ///
    /// Framebuffer usage is the amount of vGPU framebuffer memory that is currently in use by the VM
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg` if self is invalid
    /// * `NotFound` if self does not match a valid active vGPU instance on the system
    /// * `Unknown`, on any unexpected error
    ///
    /// # Platform Support
    ///
    /// For Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetFbUsage")]
    pub fn fb_usage(&self) -> Result<u64, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetFbUsage.as_ref())?;
        let mut usage = 0;
        unsafe {
            nvml_try(sym(self.instance, &mut usage))?;
        }
        Ok(usage)
    }

    /// Retrieve the vGPU type of a vGPU instance
    ///
    /// Returns the vGPU type ID of vgpu assigned to the vGPU instance.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `InvalidArg` if self is invalid
    /// * `NotFound` if self does not match a valid active vGPU instance on the system
    /// * `Unknown`, on any unexpected error
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices
    #[doc(alias = "nvmlVgpuInstanceGetType")]
    pub fn instance_type(&self) -> Result<VgpuType<'dev>, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetType.as_ref())?;
        let mut raw_type = 0;
        unsafe {
            nvml_try(sym(self.instance, &mut raw_type))?;
        }
        Ok(VgpuType::new(self.device, raw_type))
    }

    /// Get the list of process ids running on this vGPU instance for stats purpose
    ///
    /// see [`crate::device::Device::vgpu_accounting_pids`] for details
    #[doc(alias = "nvmlVgpuInstanceGetAccountingPids")]
    pub fn accounting_pids(&self) -> Result<Vec<u32>, NvmlError> {
        self.device.vgpu_accounting_pids(self.instance)
    }

    /// Clears accounting information of the vGPU instance that have already terminated.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NoPermission`, if the user doesn't have permission to perform this operation
    /// * `NotSupported`, if the vGPU doesn't support this feature or accounting mode is disabled
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices. Requires root/admin permissions.
    #[doc(alias = "nvmlVgpuInstanceClearAccountingPids")]
    pub fn clear_accounting_pids(&self) -> Result<(), NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceClearAccountingPids
                .as_ref(),
        )?;
        unsafe { nvml_try(sym(self.instance)) }
    }

    /// Queries the state of per process accounting mode on vGPU.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    /// * `NotSupported`, if the vGPU doesn't support this feature or accounting mode is disabled
    /// * `DriverNotLoaded`, driver is not running on the vGPU instance
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetAccountingMode")]
    pub fn accounting_mode(&self) -> Result<bool, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetAccountingMode
                .as_ref(),
        )?;
        let mut mode = 0;
        unsafe {
            nvml_try(sym(self.instance, &mut mode))?;
        }
        Ok(mode == nvmlEnableState_enum_NVML_FEATURE_ENABLED)
    }

    /// Retrieve the current ECC mode of vGPU instance.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    /// * `NotSupported`, if the vGPU doesn't support this feature or accounting mode is disabled
    #[doc(alias = "nvmlVgpuInstanceGetEccMode")]
    pub fn ecc_mode(&self) -> Result<bool, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetEccMode.as_ref())?;
        let mut mode = 0;
        unsafe {
            nvml_try(sym(self.instance, &mut mode))?;
        }
        Ok(mode == nvmlEnableState_enum_NVML_FEATURE_ENABLED)
    }

    /// Retrieve the encoder capacity of a vGPU instance, as a percentage of maximum encoder
    /// capacity with valid values in the range 0-100.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetEncoderCapacity")]
    pub fn encoder_capacity(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetEncoderCapacity
                .as_ref(),
        )?;
        let mut cap = 0;
        unsafe {
            nvml_try(sym(self.instance, &mut cap))?;
        }
        Ok(cap)
    }

    /// Retrieves information about all active encoder sessions on a vGPU Instance.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetEncoderSessions")]
    pub fn encoder_sessions(&self) -> Result<Vec<EncoderSessionInfo>, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetEncoderSessions
                .as_ref(),
        )?;
        let mut count = self.encoder_session_count()?;
        let mut raw_sessions: Vec<nvmlEncoderSessionInfo_t>;
        unsafe {
            raw_sessions = vec![std::mem::zeroed(); count as usize];
            nvml_try(sym(self.instance, &mut count, raw_sessions.as_mut_ptr()))?;
        };
        raw_sessions
            .into_iter()
            .map(EncoderSessionInfo::try_from)
            .collect()
    }

    /// Retrieves the current encoder statistics of a vGPU Instance
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetEncoderStats")]
    pub fn encoder_stats(&self) -> Result<EncoderStats, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetEncoderStats
                .as_ref(),
        )?;
        let mut session_count = self.encoder_session_count()?;
        let mut average_fps = 0;
        let mut average_latency = 0;
        unsafe {
            nvml_try(sym(
                self.instance,
                &mut session_count,
                &mut average_fps,
                &mut average_latency,
            ))?;
        };
        Ok(EncoderStats {
            session_count,
            average_fps,
            average_latency,
        })
    }

    /// Retrieves information about active frame buffer capture sessions on a vGPU Instance.
    ///
    /// > hResolution, vResolution, averageFPS and averageLatency data for a FBC session
    /// > returned in sessionInfo may be zero if there are no new frames captured since the
    /// > session started.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetFBCSessions")]
    pub fn fbc_sessions(&self) -> Result<Vec<FbcSessionInfo>, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetFBCSessions
                .as_ref(),
        )?;
        let mut session_count = 0;
        let mut info: Vec<nvmlFBCSessionInfo_t>;
        unsafe {
            nvml_try_count(sym(self.instance, &mut session_count, std::ptr::null_mut()))?;
            if session_count == 0 {
                return Ok(Vec::new());
            }
            info = vec![std::mem::zeroed(); session_count as usize];
            nvml_try(sym(self.instance, &mut session_count, info.as_mut_ptr()))?;
        };
        info.into_iter().map(FbcSessionInfo::try_from).collect()
    }

    /// Retrieves the active frame buffer capture sessions statistics of a vGPU Instance
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetFBCStats")]
    pub fn fbc_stats(&self) -> Result<FbcStats, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetFBCStats.as_ref())?;
        unsafe {
            let mut info: nvmlFBCStats_t = std::mem::zeroed();
            nvml_try(sym(self.instance, &mut info))?;
            Ok(FbcStats::from(info))
        }
    }

    /// Retrieve the frame rate limit set for the vGPU instance.
    ///
    /// Returns the value of the frame rate limit set for the vGPU instance
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotSupported`, if frame rate limiter is turned off for the vGPU type
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetFrameRateLimit")]
    pub fn frame_rate_limit(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetFrameRateLimit
                .as_ref(),
        )?;
        let mut limit = 0;
        unsafe {
            nvml_try(sym(self.instance, &mut limit))?;
        };
        Ok(limit)
    }

    /// Retrieve the GPU Instance ID for the given vGPU Instance. The API will return a valid GPU
    /// Instance ID for MIG backed vGPU Instance, else INVALID_GPU_INSTANCE_ID is returned.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetGpuInstanceId")]
    pub fn gpu_instance_id(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetGpuInstanceId
                .as_ref(),
        )?;
        let mut id = 0;
        unsafe {
            nvml_try(sym(self.instance, &mut id))?;
        };
        Ok(id)
    }

    /// Retrieves the PCI Id of the given vGPU Instance i.e. the PCI Id of the GPU as seen inside
    /// the VM.
    ///
    /// The vGPU PCI id is returned as "00000000:00:00.0" if NVIDIA driver is not installed on the
    /// vGPU instance.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    /// * `DriverNotLoaded`, driver is not running on the vGPU instance
    #[doc(alias = "nvmlVgpuInstanceGetGpuPciId")]
    pub fn gpu_pci_id(&self) -> Result<String, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetGpuPciId.as_ref())?;
        let mut buffer: Vec<c_char>;
        let mut count = 0;
        let raw_id = unsafe {
            nvml_try_count(sym(self.instance, [0; 1].as_mut_ptr(), &mut count))?;
            if count == 0 {
                return Ok(String::new());
            }
            buffer = vec![0; count as usize];
            nvml_try(sym(self.instance, buffer.as_mut_ptr(), &mut count))?;
            CStr::from_ptr(buffer.as_ptr())
        };
        Ok(raw_id.to_str()?.to_string())
    }

    /// Query the license information of the vGPU instance.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    /// * `DriverNotLoaded`, driver is not running on the vGPU instance
    #[cfg(feature = "legacy-functions")]
    #[doc(alias = "nvmlVgpuInstanceGetLicenseInfo")]
    pub fn license_info(&self) -> Result<VgpuLicenseInfo, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetLicenseInfo
                .as_ref(),
        )?;
        let mut info: nvmlVgpuLicenseInfo_st;

        unsafe {
            info = std::mem::zeroed();
            nvml_try(sym(self.instance, &mut info))?;
        };
        Ok(VgpuLicenseInfo::from(info))
    }

    /// Query the license information of the vGPU instance.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    /// * `DriverNotLoaded`, driver is not running on the vGPU instance
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetLicenseInfo_v2")]
    pub fn license_info_v2(&self) -> Result<VgpuLicenseInfo, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetLicenseInfo_v2
                .as_ref(),
        )?;
        let mut info: nvmlVgpuLicenseInfo_st;

        unsafe {
            info = std::mem::zeroed();
            nvml_try(sym(self.instance, &mut info))?;
        };
        Ok(VgpuLicenseInfo::from(info))
    }

    /// Retrieve the MDEV UUID of a vGPU instance.
    ///
    /// The MDEV UUID is a globally unique identifier of the mdev device assigned to the VM, and is
    /// returned as a 5-part hexadecimal string, not exceeding 80 characters in length (including
    /// the NULL terminator). MDEV UUID is displayed only on KVM platform.
    /// See nvmlConstants::NVML_DEVICE_UUID_BUFFER_SIZE.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    /// * `NotSupported`, on any hypervisor other than KVM
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetMdevUUID")]
    pub fn mdev_uuid(&self) -> Result<String, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetMdevUUID.as_ref())?;
        let mut buffer: [c_char; NVML_DEVICE_UUID_BUFFER_SIZE as usize] =
            [0; NVML_DEVICE_UUID_BUFFER_SIZE as usize];

        unsafe {
            nvml_try(sym(
                self.instance,
                buffer.as_mut_ptr(),
                NVML_DEVICE_UUID_BUFFER_SIZE,
            ))?;
            let raw_id = CStr::from_ptr(buffer.as_ptr());
            Ok(raw_id.to_str()?.to_string())
        }
    }

    /// Returns vGPU metadata structure for a running vGPU. The structure contains information
    /// about the vGPU and its associated VM such as the currently installed NVIDIA guest driver
    /// version, together with host driver version and an opaque data section containing internal
    /// state.
    ///
    /// May be called at any time for a vGPU instance. Some fields in the returned structure are
    /// dependent on information obtained from the guest VM, which may not yet have reached a state
    /// where that information is available.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    ///
    #[doc(alias = "nvmlVgpuInstanceGetMetadata")]
    pub fn metadata(&self) -> Result<VgpuMetadata, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetMetadata.as_ref())?;
        let mut byte_size = 0;
        unsafe {
            nvml_try_count(sym(self.instance, std::ptr::null_mut(), &mut byte_size))?;
            // The metadata is one variable-length structure: a fixed header
            // followed by an opaque payload. Over-allocate in whole
            // `nvmlVgpuMetadata_t`s so the buffer stays correctly aligned.
            let struct_size = std::mem::size_of::<nvmlVgpuMetadata_t>();
            let count = ((byte_size as usize + struct_size - 1) / struct_size).max(1);
            let mut buffer: Vec<nvmlVgpuMetadata_t> = vec![std::mem::zeroed(); count];
            let mut byte_size = (count * struct_size) as c_uint;
            nvml_try(sym(self.instance, buffer.as_mut_ptr(), &mut byte_size))?;
            VgpuMetadata::try_from(buffer[0])
        }
    }

    /// Query the placement ID of active vGPU instance.
    ///
    /// When in vGPU heterogeneous mode, this function returns a valid placement ID as
    /// [`VgpuPlacementId::id`], [`VgpuPlacementId::version`] is the version number
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    #[doc(alias = "nvmlVgpuInstanceGetPlacementId")]
    pub fn placement_id(&self) -> Result<VgpuPlacementId, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetPlacementId
                .as_ref(),
        )?;
        let mut raw_placement_id: nvmlVgpuPlacementId_t;
        unsafe {
            raw_placement_id = std::mem::zeroed();
            nvml_try(sym(self.instance, &mut raw_placement_id))?;
        }
        Ok(raw_placement_id.into())
    }

    /// Retrieve the currently used runtime state size of the vGPU instance
    ///
    /// This size represents the maximum in-memory data size utilized by a vGPU instance during
    /// standard operation. This measurement is exclusive of frame buffer (FB) data size assigned
    /// to the vGPU instance.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetRuntimeStateSize")]
    pub fn runtime_state_size(&self) -> Result<VgpuRuntimeState, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetRuntimeStateSize
                .as_ref(),
        )?;
        let mut raw_state: nvmlVgpuRuntimeState_t;
        unsafe {
            raw_state = std::mem::zeroed();
            nvml_try(sym(self.instance, &mut raw_state))?;
        }
        Ok(raw_state.into())
    }

    /// Retrieve the UUID of a vGPU instance.
    ///
    /// The UUID is a globally unique identifier associated with the vGPU, and is returned as a 5-part hexadecimal string
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetUUID")]
    pub fn uuid(&self) -> Result<String, NvmlError> {
        let sym = nvml_sym(self.device.nvml().lib.nvmlVgpuInstanceGetUUID.as_ref())?;
        let mut buffer: [c_char; NVML_DEVICE_UUID_BUFFER_SIZE as usize] =
            [0; NVML_DEVICE_UUID_BUFFER_SIZE as usize];

        unsafe {
            nvml_try(sym(
                self.instance,
                buffer.as_mut_ptr(),
                NVML_DEVICE_UUID_BUFFER_SIZE,
            ))?;
            let raw_id = CStr::from_ptr(buffer.as_ptr());
            Ok(raw_id.to_str()?.to_string())
        }
    }

    /// Retrieve the NVIDIA driver version installed in the VM associated with a vGPU.
    ///
    /// The version is returned as an alphanumeric string in the caller-supplied buffer version.
    /// This may be called at any time for a vGPU instance.
    ///
    /// The guest VM driver version is returned as "Not Available" if no NVIDIA driver is installed
    /// in the VM, or the VM has not yet booted to the point where the NVIDIA driver is loaded and
    /// initialized.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Kepler or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceGetVmDriverVersion")]
    pub fn driver_version(&self) -> Result<String, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetVmDriverVersion
                .as_ref(),
        )?;
        let mut buffer: [c_char; NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE as usize] =
            [0; NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE as usize];

        unsafe {
            nvml_try(sym(
                self.instance,
                buffer.as_mut_ptr(),
                NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE,
            ))?;
            let raw_id = CStr::from_ptr(buffer.as_ptr());
            Ok(raw_id.to_str()?.to_string())
        }
    }
    /// Set the encoder capacity of a vGPU instance, as a percentage of maximum encoder capacity with valid values in the range 0-100.
    ///
    /// # Errors
    ///
    /// * `Uninitialized`, if the library has not been successfully initialized
    /// * `NotFound`, if the vGPU does not match a valid active vGPU instance on the system
    ///
    /// # Platform Support
    ///
    /// For Maxwell or newer fully supported devices.
    #[doc(alias = "nvmlVgpuInstanceSetEncoderCapacity")]
    pub fn set_encoder_capacity(&self, capacity: u32) -> Result<(), NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceSetEncoderCapacity
                .as_ref(),
        )?;

        unsafe {
            nvml_try(sym(self.instance, capacity))?;
        }
        Ok(())
    }

    fn encoder_session_count(&self) -> Result<u32, NvmlError> {
        let sym = nvml_sym(
            self.device
                .nvml()
                .lib
                .nvmlVgpuInstanceGetEncoderSessions
                .as_ref(),
        )?;
        let mut count = 0;
        unsafe {
            nvml_try_count(sym(self.instance, &mut count, std::ptr::null_mut()))?;
        };
        Ok(count)
    }
}

impl<'dev> std::fmt::Debug for VgpuInstance<'dev> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VgpuInstance")
            .field("instance", &self.instance)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::test_utils::*;

    #[test]
    fn vgpu_type_class_name() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).class_name());
    }

    #[test]
    fn vgpu_type_license() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).license());
    }

    #[test]
    fn vgpu_type_name() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).name());
    }

    #[test]
    fn vgpu_type_device_id() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).device_id());
    }

    #[test]
    fn vgpu_type_frame_rate_limit() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).frame_rate_limit());
    }

    #[test]
    fn vgpu_type_framebuffer_size() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).framebuffer_size());
    }

    #[test]
    fn vgpu_type_instance_profile_id() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).instance_profile_id());
    }

    #[test]
    fn vgpu_type_max_instances() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).max_instances());
    }

    #[test]
    fn vgpu_type_max_instances_per_vm() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).max_instances_per_vm());
    }

    #[test]
    fn vgpu_type_num_display_heads() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).num_display_heads());
    }

    #[test]
    fn vgpu_type_resolution() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).resolution(1));
    }

    #[test]
    fn vgpu_type_get_bar1_info() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).bar1_info());
    }

    #[test]
    fn vgpu_type_get_fb_reservation() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).fb_reservation());
    }

    #[test]
    fn vgpu_type_get_gsp_heap_size() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuType::new(dev, 1).gsp_heap_size());
    }

    #[test]
    fn vgpu_instance_get_vm_id() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).vm_id());
    }

    #[test]
    fn vgpu_instance_get_fb_usage() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).fb_usage());
    }

    #[test]
    fn vgpu_instance_get_instance_type() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| {
            Ok(VgpuInstance::new(1, dev).instance_type()?.id)
        });
    }

    #[test]
    fn vgpu_instance_accounting_pids() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).accounting_pids());
    }

    #[test]
    fn vgpu_instance_clear_accounting_pids() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| {
            VgpuInstance::new(1, dev).clear_accounting_pids()
        });
    }

    #[test]
    fn vgpu_instance_get_accounting_mode() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).accounting_mode());
    }

    #[test]
    fn vgpu_instance_get_ecc_mode() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).ecc_mode());
    }

    #[test]
    fn vgpu_instance_get_encoder_capacity() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).encoder_capacity());
    }

    #[test]
    fn vgpu_instance_get_encoder_sessions() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).encoder_sessions());
    }

    #[test]
    fn vgpu_instance_get_encoder_stats() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).encoder_stats());
    }

    #[test]
    fn vgpu_instance_get_fbc_sessions() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).fbc_sessions());
    }

    #[test]
    fn vgpu_instance_get_fbc_stats() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).fbc_stats());
    }

    #[test]
    fn vgpu_instance_get_frame_rate_limit() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).frame_rate_limit());
    }

    #[test]
    fn vgpu_instance_get_gpu_instance_id() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).gpu_instance_id());
    }

    #[test]
    fn vgpu_instance_get_gpu_pci_id() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).gpu_pci_id());
    }

    #[test]
    #[cfg(feature = "legacy-functions")]
    fn vgpu_instance_get_license_info() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).license_info());
    }

    #[test]
    fn vgpu_instance_get_license_info_v2() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).license_info_v2());
    }

    #[test]
    fn vgpu_instance_get_mdev_uuid() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).mdev_uuid());
    }

    #[test]
    fn vgpu_instance_get_metadata() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).metadata());
    }

    #[test]
    fn vgpu_instance_get_placement_id() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).placement_id());
    }

    #[test]
    fn vgpu_instance_get_runtime_state_size() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| {
            VgpuInstance::new(1, dev).runtime_state_size()
        });
    }

    #[test]
    fn vgpu_instance_get_uuid() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).uuid());
    }

    #[test]
    fn vgpu_instance_get_driver_version() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| VgpuInstance::new(1, dev).driver_version());
    }

    #[test]
    fn vgpu_instance_set_encoder_capacity() {
        let nvml = nvml();
        test_with_device(1, &nvml, |dev| {
            VgpuInstance::new(1, dev).set_encoder_capacity(50)
        });
    }
}